用montecarlo方法绘制Pi

2024-05-15 15:05:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我可以通过Python使用不同的数据点来计算pi的值。但对于每一次重复,我想绘制散点图,如下所示: enter image description here

我使用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)

Tags: 数据方法代码infromimportforpi
3条回答

根据您的代码进行构建,这可能会让您开始:

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的this answer

如果您得到有关后端的错误,请使用以下方法:

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

它将把后端设置为TkAgg,TkAgg使用Tkinter用户界面工具包

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

enter image description here

进一步阐述Robbie的代码:

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

相关问题 更多 >