尝试使用这个while循环计算pi,但是一旦达到3.14就无法弄清楚如何阻止它,它只会无限地继续
import turtle
import math
import random
t = turtle.Turtle()
wn = turtle.Screen()
wn.setworldcoordinates(-400,-400,400,400)
t.pu()
t.speed(0)
t.goto(0,-400)
t.pd()
t.color("blue")
t.circle(400)
t.color("orange")
hits=0.0
numdarts =0
eps=0.01
actPi=3.1415
estPi=3
error=abs(actPi-estPi)
while abs(error) >= eps:
randx=random.uniform(-1,1)
randy=random.uniform(-1,1)
if (randx**2+ randy**2)<1:
hits+=1.0
numdarts+=1
estPi=(hits/numdarts)
error=abs(actPi-estPi)
t.pu()
t.goto(400*randx,400*randy)
t.pd()
t.dot()
print 4*(hits/numdarts)
wn.exitonclick()
我不知道如何让循环停在3.14
答案 0 :(得分:1)
实际上,你的method of calculating pi should converge to pi/4。你需要将estPi乘以4:
estPi = 4*hits/numdarts
编辑:我刚看到你在最后一次印刷中考虑到了这一点!我想你在计算错误时忘了添加它:)