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

Running a function multiple times and printing the results for each separate run

嘿,所以我比较新,在 运行 进行 Monte Carlo 模拟和打印结果时遇到了问题:

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

所以我认为Monte Carlo函数(computePI)是正确的。我正在尝试 运行 Monte Carlo 值 100、1000、100000、1000000 的函数和 10000000.Is 每次 while 循环时 运行 computePI 函数在 main() 函数循环中?

你的问题是白space:

1) 您需要缩进 computePi 的正文。如果您使用的是 IDLE,这很简单:突出显示正文并使用 Ctrl + [

2) 您需要缩进 main

的正文

3) 文件底部对 main() 的最终调用前面不应有 space。

我进行了这些更改,结果 运行 符合预期(尽管 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