[英]Monte Carlo dart simulator
我一直在嘗試使用Python 3中的Monte Carlo模擬制作飛鏢模擬器。到目前為止,我已經編寫了以下代碼:
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
,我們可以用以下方法解決:
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)))
話雖這么說,該程序仍然是不正確的:它為Pi提供了0.773
輸出,這顯然是錯誤的。
主要問題是采樣:您想要生成-1和1之間的數字,但是想要生成-1和3之間的數字。在距離計算中,然后使用x-1
和y-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
(盡管在某些模擬中它可能當然會有所不同)。
兩個問題:
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)))
由於您無法在數字中添加字符串
除此之外-我不確定計算是否正確-但這將是另一個問題。
除了已經確定的字符串到整數問題之外,如果將x
和y
邊界設置為[-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
-loop:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.