使用蒙特卡罗方法绘制Pi

时间:2017-04-30 06:49:08

标签: 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)

4 个答案:

答案 0 :(得分:4)

如果您收到有关后端的错误,请使用以下命令:

GT-S5830

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

GT-S5830i

enter image description here

答案 1 :(得分:3)

进一步阐述罗比的代码:

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

答案 2 :(得分:0)

从您的代码构建,这可能会让您入门:

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

答案 3 :(得分:0)

这里是hiro主人公代码的一种变体,使用random.uniform()允许-1.0到1.0之间的随机数,允许绘制所有点,而不仅仅是1/4(不是最优雅的)代码,但完全可以了解Monte Carlo Simulation的基础知识):

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

Plot of points inside and outside the circle