蒙特卡洛飞镖模拟器

时间:2017-10-22 21:34:17

标签: python python-3.x montecarlo

我一直在尝试使用Python 3中的蒙特卡罗模拟制作飞镖模拟器。到目前为止,我编写了以下代码:

import random
import math

n = (input("Enter the number of darts you have. "))
count = 1
circleval = 0
squareval = 0
while count <= n:
    y = 2*random.random()*2-1
    x = 2*random.random()*2-1
    if math.sqrt((x-1)**2+(y-1)**2)<=1:
        circleval+=1
        squareval+=1
    else:
        squareval+=1
    count+=1

print("Pi is " + 4*(1.*circleval/squareval))

但是,当我运行此命令时,我会收到以下错误消息:

TypeError: '<=' not supported between instances of 'int' and 'str'

3 个答案:

答案 0 :(得分:2)

这不起作用的主要原因是:

n = (input("Enter the number of darts you have. "))

会将一个字符串放入n,我们可以用以下方法解决:

n = int(input("Enter the number of darts you have. "))

print("Pi is " + 4*(1.*circleval/squareval))

需要一个字符串,但是你没有提供一个字符串,我们可以用:

解决这个问题
print("Pi is " + str(4*(1.*circleval/squareval)))

但话虽如此,该程序仍然是错误的:它给出0.773作为Pi的输出,这显然是错误的。

主要问题是您的采样:您希望生成介于-1和1之间的数字,但是您生成介于-1和3之间的数字。在距离计算中,您可以使用x-1y-1将它转移到-2到2域,但仍然太大。此外,代码不是很优雅。

from random import random

n = int(input("Enter the number of darts you have. "))
c = 0
for i in range(n):
    x = 2*random()-1
    y = 2*random()-1
    if x*x + y*y <= 1:
        c += 1
print("Pi is %s" % (4.0*c/n))

对于n=100000,这给了我3.14368(尽管在几次模拟之间可能会有所不同)。

答案 1 :(得分:1)

两个问题:

n = input("Enter the number of darts you have. "))

应该是:

n = int(input("Enter the number of darts you have. "))

(因为您希望将n视为整数)

print("Pi is " + 4*(1.*circleval/squareval))

应该是:

print("Pi is " + str(4*(1.*circleval/squareval)))

由于您无法将字符串添加到数字

除此之外 - 我不确定计算是否正确 - 但那将是另一个问题。

答案 2 :(得分:1)

除了已识别的字符串到整数问题之外,如果您将xy范围设置为[-1,1],您可能会发现这更简单。
另外,考虑使用Numpy:

import numpy as np

n = int(input("Enter the number of darts you have. "))
count = 1
circleval = 0
squareval = 0
while count <= n:
    y = np.random.uniform(low=-1, high=1)
    x = np.random.uniform(low=-1, high=1)
    if np.sqrt(x**2 + y**2) <= 1:
        circleval+=1
        squareval+=1
    else:
        squareval+=1
    count+=1

print("Pi is", 4*(1.*circleval/squareval))

输出:

Enter the number of darts you have. 1000000
Pi is 3.142168

注意:
- 您不需要跟踪squareval,您只需使用n
- 您可以使用Numpy的矢量化操作跳过while - 循环:

area = 4
n = int(input("Enter the number of darts you have. "))

X = np.random.uniform(low=-1, high=1, size=n)  
Y = np.random.uniform(low=-1, high=1, size=n)   

dist = np.sqrt(X**2+Y**2);  

in_circle = np.sum(dist < 1.0)

print("Pi is", area * in_circle/n)