[英]Using Monte Carlo method in python
我正在處理下圖中所寫問題的第一個版本。 我使用rand
命令生成了一個隨機點,並測試了該點是否在圓圈內。 我的代碼是否接受蒙特卡洛函數的數量作為輸入值? 我相信我已經選擇了N
,點數足夠小所以我不會耗盡內存。 此外,當我運行此代碼時,它運行沒有任何錯誤,但圖形不會顯示。 在我可能出錯的地方尋求幫助。
import numpy as np
import matplotlib.pyplot as plt
from random import random
xinside = []
yinside = []
xoutside = []
youtside = []
insidecircle = 0
totalpoints = 10**3
for _ in range(totalpoints):
x = random()
y = random()
if x**2+y**2 <= 1:
insidecircle += 1
xinside.append(x)
yinside.append(y)
else:
xoutside.append(x)
youtside.append(y)
fig, ax = plt.subplots()
ax.set_aspect('equal')
ax.scatter(xinside, yinside, color='g', marker='s')
ax.scatter(xoutside, youtside, color='r', marker='s')
fig.show()
圖中沒有顯示是神秘的,也許嘗試plt.show()
。 或者,您可以使用savefig
保存繪圖。 這是代碼的第一部分的一個工作函數(只是修改問題中的已發布代碼)以及所需的輸出圖。
import numpy as np
import matplotlib.pyplot as plt
from random import random
def monte_carlo(n_points):
xin, yin, xout, yout = [[] for _ in range(4)] # Defining all 4 lists together
insidecircle = 0
for _ in range(n_points):
x = random()
y = random()
if x**2+y**2 <= 1:
insidecircle += 1
xin.append(x)
yin.append(y)
else:
xout.append(x)
yout.append(y)
print ("The estimated value of Pi for N = %d is %.4f" %(n_points, 4*insidecircle/n_points))
fig, ax = plt.subplots()
ax.set_aspect('equal')
ax.scatter(xin, yin, color='g', marker='o', s=4)
ax.scatter(xout, yout, color='r', marker='o', s=4)
plt.savefig('monte_carlo.png')
n_points = 10**4
monte_carlo(n_points)
> The estimated value of Pi for N = 10000 is 3.1380
矢量化方法如果在函數中排除print
語句,則可以將其稱為單行。 我把時間分析作為你的功課
import numpy as np
import matplotlib.pyplot as plt
def monte_carlo(n_points, x, y):
pi_vec = 4*(x**2 + y**2 <= 1).sum()/n_points
print ("The estimated value of Pi for N = %d is %.4f" %(n_points, pi_vec))
# Generate points
n_points = 10**4
x = np.random.random(n_points)
y = np.random.random(n_points)
# x = [random() for _ in range(n_points)] # alternative way to define x
# y = [random() for _ in range(n_points)] # alternative way to define y
# Call function
monte_carlo(n_points, x, y)
> The estimated value of Pi for N = 10000 is 3.1284
或者,您可以通過使用單個x和y點數組來消除兩個變量x
和y
,如下所示:
pts = np.random.uniform(0, 1, 2*n_points).reshape((n_points, 2))
monte_carlo(n_points, pts) # Function will be def monte_carlo(n_points, pts):
並在功能上使用
pi_vec = 4*(pts[:,0]**2 + pts[:,1]**2 <= 1).sum()/n_points
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.