多次运行一个函数,并为每次单独运行打印结果



嘿,我是一个新手,我在运行蒙特卡罗模拟和打印结果时遇到了麻烦:

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。是否有一种方法来运行computePI函数每次while循环在main()函数循环?

你的问题是留白:

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()

代码现在给出了相当合理的近似pi:

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

最新更新