Loops 多次运行函数并打印每次单独运行的结果
嘿,我是个新手,在运行蒙特卡罗模拟和打印结果时遇到了问题:Loops 多次运行函数并打印每次单独运行的结果,loops,python-3.x,montecarlo,Loops,Python 3.x,Montecarlo,嘿,我是个新手,在运行蒙特卡罗模拟和打印结果时遇到了问题: 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)
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()
随机导入
输入数学
def computePI(抛出):
投掷=100
半径=1
ontarget=0
偏离目标=0
numthrows=0
当抛出量小于10000000时:
当numthrows<抛出时:
x=随机均匀(-1.0,1.0)
y=随机均匀(-1.0,1.0)
hyp=数学形下(x,y)
如果hyp您的问题是空白:
1) 您需要缩进computePi
的主体。如果使用IDLE,这很简单:突出显示主体并使用Ctrl+[
2) 您需要缩进main
3) 对文件底部的main()
的最后一次调用前面不应该有空格
我做了这些更改,它按照预期运行(尽管pi的近似值不是特别好)
编辑时:computePi
的逻辑不太合理。请尝试以下版本:
def computePI(throws):
radius = 1
ontarget = 0
offtarget = 0
numthrows = 0
for throw in range(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
pi = (ontarget/throws)*4
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函数有什么问题吗?我如何在每次运行computePI函数时更改“throws”值?@AlanHao看看这个版本是否工作得更好——你需要throws
变量来计算主循环的执行次数。好的。那么main()中定义的变量可以在其他函数中使用,但反之亦然?在computePi
中没有使用main
中的变量。您可以将throws
的值从main
传递到computePi
-但是computePi的范围中的变量throws
与throws
中的变量不同在main
中。您的代码不使用任何非局部变量。main
和computePi
之间的唯一通信是通过显式传递和返回值。
Num = 100 Calculated Pi = 3.4 Difference = -0.141593
Num = 1000 Calculated Pi = 3.124 Difference = +0.082407
Num = 10000 Calculated Pi = 3.106 Difference = -0.001593
Num = 100000 Calculated Pi = 3.13428 Difference = +0.012247
Num = 1000000 Calculated Pi = 3.14062 Difference = -0.000737
Num = 10000000 Calculated Pi = 3.14187 Difference = +0.000475