[問題] 迴圈加速

看板Mathematica作者 (Serenede)時間9年前 (2014/12/21 00:27), 9年前編輯推噓2(203)
留言5則, 3人參與, 最新討論串1/2 (看更多)
sav = 0; iter = 10000000; For[i = 1, i <= iter, i++, If[Random[]^2 < 1/2, sav = sav + 1;] ] // Timing 2 sav/iter // N 這樣居然也算了23秒,覺得有點太久,請問要怎樣寫才會快呢? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.26.112.191 ※ 文章網址: http://www.ptt.cc/bbs/Mathematica/M.1419092852.A.941.html ※ 編輯: Serenede (114.26.112.191), 12/21/2014 00:39:59

12/21 00:57, , 1F
Nest[UnitStep[(1/2-Random[]^2)]+#&,0,10000000]
12/21 00:57, 1F

12/21 07:02, , 2F
RandomVariate[NormalDistribution[1/Sqrt[2], 1/Sqrt[12]/
12/21 07:02, 2F

12/21 07:02, , 3F
/Sqrt[10000000]]]
12/21 07:02, 3F

12/21 07:36, , 4F
AbsoluteTiming@Total@NestList[If[Random[]^2<0.5,
12/21 07:36, 4F

12/21 07:36, , 5F
1,0]&,0,iter]
12/21 07:36, 5F
文章代碼(AID): #1KbQDqb1 (Mathematica)
討論串 (同標題文章)
以下文章回應了本文
完整討論串 (本文為第 1 之 2 篇):
文章代碼(AID): #1KbQDqb1 (Mathematica)