Julia 笔记(1)
function myfunc() num = 100000000 sum=0 for i=1:num if rand()^2+rand()^2<=1 sum+=1 end end print(4*sum/num) end @time myfunc()
输出结果
3.1416062 2.223351 seconds (182.41 k allocations: 9.508 MiB)
function myfunc() num = 100000000 x=rand(num) y=rand(num) sum_pi=0 z = x.^2+y.^2 sum_pi = sum((i<=1 ? 1 : 0) for i in z) print(4*sum_pi/num) end @time myfunc()
输出结果
3.14153128 29.991045 seconds (866.35 k allocations: 3.768 GiB, 1.74% gc time)
说明内存是此次计算的瓶颈。
补充3月21日
function myfunc()
local num=100000000
sum_pi = ( (rand()^2+rand()^2)<=1 ? 1 : 0 for i =1:num)
end
这个更精简的写法居然耗时5.4秒,是第一种的写法的一倍耗时.
function myfunc()
local num=100000000
sum_pi=0
for i=1:num
sum_pi += (rand()^2+rand()^2)<=1 ? 1 : 0
end
end
这样写的话即只要1.8秒的耗时
可见直接用循环语句进行加和是效率最高的