[問題] 迴圈加速

作者: Serenede (Serenede)   2014-12-21 00:27:29
sav = 0; iter = 10000000;
For[i = 1, i <= iter, i++,
If[Random[]^2 < 1/2, sav = sav + 1;]
] // Timing
2 sav/iter // N
這樣居然也算了23秒,覺得有點太久,請問要怎樣寫才會快呢?
作者: biglion ( )   2014-12-21 00:57:00
Nest[UnitStep[(1/2-Random[]^2)]+#&,0,10000000]
作者: sunev (Veritas)   2014-12-21 07:02:00
RandomVariate[NormalDistribution[1/Sqrt[2], 1/Sqrt[12]//Sqrt[10000000]]]
作者: chungyuandye (養花種魚數月亮賞星星)   2014-12-21 07:36:00
AbsoluteTiming@Total@NestList[If[Random[]^2<0.5,1,0]&,0,iter]

Links booklink

Contact Us: admin [ a t ] ucptt.com