|
|
|
|
|
by dxbydt
4291 days ago
|
|
you have to divide by n.Here - def pointInsideCircle = {val (z,w) = (0.5,0.5);val (x,y) = (math.random,math.random); if ((x-z)*(x-z)+(w-y)*(w-y) < 0.25) 1 else 0;}
(1 to 1000).map{x=> pointInsideCircle}.sum*4/1000.0
scala> 3.132
(1 to 1000000).map{x=>pointInsideCircle}.sum*4/1000000.0
scala> 3.141612
So as n goes from 1000 to a million, your pi accuracy has improved from 3.13 to 3.1416. As Chris Stuccio pointed out elsewhere on this page, this thing converges O(N^{-1/2} ie. very slowly.You can try Buffon's needle if you want something much faster. |
|