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

时间:2015-10-04 13:22:56

标签: 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)
        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函数?

1 个答案:

答案 0 :(得分:0)

您的问题是空白区域:

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