0
嘿,所以我是比较新,我有运行蒙特卡罗模拟的麻烦和打印结果:运行功能,多次打印,并为每个独立的运行结果
import random
import math
def computePI(throws):
throws = 100
radius = 1
ontarget = 0
offtarget = 0
numthrows = 0
while throws < 10000000:
while numthrows < throws:
x = random.uniform(-1.0,1.0)
y = random.uniform(-1.0,1.0)
hyp = math.hypot(x,y)
if hyp <= radius:
ontarget += 1
numthrows+=1
else:
offtarget += 1
numthrows+=1
continue
pi = (ontarget/throws)*4
throws *= 10
return(pi)
def main():
throws = 100
while throws <= 10000000:
difference = computePI(throws) - math.pi
print('{first} {last}'.format(first="Num =", last=throws),end = " ")
print('{first} {last}'.format(first="Calculated Pi =", last=computePI(throws)),end = " ")
if difference < 0:
print('{first} {last}'.format(first="Difference =", last=round(difference,6)))
if difference > 0:
print('{first} +{last}'.format(first="Difference =", last=round(difference,6)))
throws *= 10
main()
所以我认为,蒙特卡洛函数(computePI)是正确的。我试图运行蒙特卡洛函数的值为100,1000,100000,1000000和10000000.是否有一种方法可以在main()函数循环中的while循环中运行computePI函数?
是不是有什么毛病computePI功能?每次运行computePI函数时,如何更改“throws”值? –
@AlanHao看看这个版本是否工作得更好 - 你需要你的'throws'变量来计算主循环的执行次数 –
Ohh没关系。所以在main()中定义的变量可以用在其他函数中,但反过来它不起作用? –