- Python
Python 圆周率研究
- 2024-4-14 11:26:59 @
海龟模拟蒙特卡罗法求圆周率
import turtle as t
import random
t.speed(0)
t.up()
t.goto(-200,-200)
t.down()
for i in range(4):
t.fd(400)
t.lt(90)
t.up()
t.goto(0,-200)
t.down()
t.circle(200)
t.color("red")
for i in range(500):
x = random.randint(-200,200)
y = random.randint(-200,200)
t.up()
t.goto(x,y)
t.dot(10)
t.down()
pi = (cnt1/(cnt1+cnt2))*400*400/(200*200)
print(pi)
蒙特卡洛Python圆周率计算
import random
cnt1=0
for i in range(10000000):
x = random.random()*2-1
y = random.random()*2-1
if (x*x+y*y)<=1:
cnt1+=1
if(i == 100 or i == 500 or i == 1000 or i == 10000 or i == 100000 or i == 1000000):
print("n:",i,"pi:",cnt1/i*4)
import math
d = 2
for n in [3,4,5,10,100,1000,10000,100000]:
r = d/2
a = 360/n
x = (2 * r**2 * (1 - math.cos(math.radians(a))))**0.5
perimeter = x * n
pi = perimeter / d
print(n, "-->", pi)
0 条评论
目前还没有评论...