2015-10-04 69 views
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函数?

回答

0

你的问题是空白:

1)你必须要缩进的computePi身体。如果您正在使用IDLE这是很容易:突出身体和使用Ctrl + [

2)您需要的main

3)最后调用身体缩进到main()在文件的底部应该不会有在它前面的一个空间。

我做了这些改变,它按预期运行(尽管对pi的近似值并不特别好)。

On编辑:您的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 
+0

是不是有什么毛病computePI功能?每次运行computePI函数时,如何更改“throws”值? –

+0

@AlanHao看看这个版本是否工作得更好 - 你需要你的'throws'变量来计算主循环的执行次数 –

+0

Ohh没关系。所以在main()中定义的变量可以用在其他函数中,但反过来它不起作用? –