tynbl.github.io

蒙特卡洛计算圆周率pi

from __future__ import division
import random
import time

num = 1
for j in range(2, 10):
    startT = time.clock()
    # 落入圆内计数
    counter = 0
    # 往正方形中扔了 10 的 j 次方次
    for i in range(10 ** j):
        x = random.uniform(-1, 1)
        y = random.uniform(-1, 1)
        # 落入了圆内
        if x**2 + y**2 < 1:
            counter += 1
    endT = time.clock()
    print(num)
    print('pi: {0}'.format(4 * (counter / 10 ** j)))
    print('时间:{0}'.format(endT - startT))
    print()
    num += 1
1
pi: 3.12
时间:0.0004917938844788995

2
pi: 3.196
时间:0.006825671469711056

3
pi: 3.1572
时间:0.0472306017247853

4
pi: 3.13796
时间:0.3023685648770216

5
pi: 3.140912
时间:2.3969991164815956

6
pi: 3.1422756
时间:24.567880813110627

7
pi: 3.14168144
时间:246.5710466827861




---------------------------------------------------------------------------

KeyboardInterrupt                         Traceback (most recent call last)

<ipython-input-1-5105396dc295> in <module>()
     11     for i in range(10 ** j):
     12         x = random.uniform(-1, 1)
---> 13         y = random.uniform(-1, 1)
     14         # 落入了圆内
     15         if x**2 + y**2 < 1:


d:\python34\lib\random.py in uniform(self, a, b)
    342     def uniform(self, a, b):
    343         "Get a random number in the range [a, b) or [a, b] depending on rounding."
--> 344         return a + (b-a) * self.random()
    345 
    346 ## -------------------- triangular --------------------


KeyboardInterrupt: