Monte Carlo 飞镖模拟器

Monte Carlo dart simulator

我一直在尝试使用Python中的Monte Carlo模拟制作飞镖模拟器 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'

两期:

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

因为您不能将字符串添加到数字

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

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

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

会将一个字符串放入n,我们可以这样解决:

n = <b>int</b>(input("Enter the number of darts you have. "))

和:

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

需要一个字符串,但您没有提供,我们可以解决这个问题:

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

但话虽如此,该程序仍然不正确:它给出 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(尽管在几次模拟之间它可能会有所不同)。

除了已经确定的字符串到整数问题之外,如果将 xy 边界设置为 [-1,1].[=25=,您可能会发现这更简单] 另外,考虑使用 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)