簡體   English   中英

使用蒙特卡洛方法繪制Pi

[英]Plotting Pi using Monte Carlo Method

我可以使用Python使用不同的數據點評估pi的值。 但是對於每個重復,我想繪制散點圖,如下所示: 在此處輸入圖片說明

我的使用monte carlo方法查找pi的python代碼是:

from random import *
from math import sqrt
inside=0
n=10**6
for i in range(0,n):
    x=random()
    y=random()
    if sqrt(x*x+y*y)<=1:
        inside+=1
pi=4*inside/n
print (pi)

如果您發現有關后端的錯誤,請使用以下命令:

import matplotlib as mp
mp.use('Tkagg')

它將使用Tkinter用戶界面工具包將后端設置為TkAgg。

import numpy as np
import matplotlib.pyplot as plt

n=1e3
x = 1-2*np.random.random(int(n))
y = 1-2.*np.random.random(int(n))
insideX,  insideY  = x[(x*x+y*y)<=1],y[(x*x+y*y)<=1]
outsideX, outsideY = x[(x*x+y*y)>1],y[(x*x+y*y)>1]

fig, ax = plt.subplots(1)
ax.scatter(insideX, insideY, c='b', alpha=0.8, edgecolor=None)
ax.scatter(outsideX, outsideY, c='r', alpha=0.8, edgecolor=None)
ax.set_aspect('equal')
fig.show()

在此處輸入圖片說明

要進一步詳細說明羅比的代碼:

import numpy as np
import matplotlib.pyplot as plt

n = 1000
xy = np.random.uniform(-1, 1, 2 * n).reshape((2, n))
in_marker = xy[0]**2 + xy[1]**2 <= 1
pi = np.sum(in_marker) / n * 4
in_xy = xy[:, in_marker]
out_xy = xy[:, ~in_marker]


fig, ax = plt.subplots(1)
ax.scatter(*in_xy,c='b')
ax.scatter(*out_xy,c='r')
ax.set_aspect('equal')
fig.show()

根據您的代碼進行構建,這可以幫助您入門:

import matplotlib.pyplot as plt

from random import random

inside = 0
n = 10**3

x_inside = []
y_inside = []
x_outside = []
y_outside = []

for _ in range(n):
    x = random()
    y = random()
    if x**2+y**2 <= 1:
        inside += 1
        x_inside.append(x)
        y_inside.append(y)
    else:
        x_outside.append(x)
        y_outside.append(y)

pi = 4*inside/n
print(pi)

fig, ax = plt.subplots()
ax.set_aspect('equal')
ax.scatter(x_inside, y_inside, color='g', marker='s')
ax.scatter(x_outside, y_outside, color='r', marker='s')
fig.show()

雖然我更喜歡從一開始就使用numpy的答案 ...

這是hiro主人公代碼的一種變體,使用random.uniform()允許-1.0到1.0之間的隨機數,允許繪制所有點,而不僅僅是1/4(不是最優雅的代碼,明確說明了蒙特卡洛模擬的基礎知識):

import matplotlib.pyplot as plt
import random

inside = 0
n = 10**3

x_inside = []
y_inside = []
x_outside = []
y_outside = []

for _ in range(n):
    x = random.uniform(-1.0,1.0)
    y = random.uniform(-1.0,1.0)
    if x**2+y**2 <= 1:
        inside += 1
        x_inside.append(x)
        y_inside.append(y)
    else:
        x_outside.append(x)
        y_outside.append(y)

為了估計pi,圓中的點對應於包圍它的圓的面積(pi * radius ^ 2),總點對應於包圍它的正方形的面積(2 * radius)^ 2。 因此,這轉化為:

(圓中的點)/(總點)=(pi *半徑^ 2)/(2 *半徑)^ 2

求解pi,方程變為:

pi = 4 *(圈中的點數)/(總點數)

pi = 4*inside/n
print(pi)

繪制圓內外的點:

fig, ax = plt.subplots()
ax.set_aspect('equal')
ax.scatter(x_inside, y_inside, color='g', marker='s')
ax.scatter(x_outside, y_outside, color='r', marker='s')
fig.show()

圓內外的點圖

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM