我用python中的montecarlo方法编制了一个程序来近似pi的值:
import random
import math
N_tot = 0
N_hits = 0
centerX = 0.5
centerY = 0.5
# precision = input('input number of decimals for approximation: ')
def inside_circle(randomX,randomY):
if(math.sqrt((centerX-randomX)**2+(centerY-randomY)**2)<=0.5):
return True
else:
return False
def estimate_pi():
N_tot = 0
N_hits = 0
for i in range(0,100000):
if(inside_circle(random.random(),random.random())==True):
N_hits = N_hits+1
N_tot = N_tot+1
else:
N_tot = N_tot+1
result = N_hits/N_tot
return result
print(estimate_pi())
当我运行这个,控制台打印0.0,我不知道为什么?请帮帮我,谢谢!你知道吗
如果您在python2中运行这个函数,
N_hits/N_tot
被视为整数除法。使用float(N_hits)/N_tot
应该可以。你知道吗顺便说一句,这里的近似值不是π,而是π/4,因为你在圆的右上角。乘以4得到正确的结果。你知道吗
相关问题 更多 >
编程相关推荐