Monte Carlo算法画π
# encoding=utf8
import matplotlib.pyplot as plt
import random
def get_random_point(N):
x0 = []
y0 = []
x1 = []
y1 = []
for index in range(1, N):
x = random.random()
y = random.random()
if x * x + y * y < 1:
x0.append(x)
y0.append(y)
else:
x1.append(x)
y1.append(y)
return (x0, y0, x1, y1)
def plot_pi():
for N in [100, 1000, 10000, 100000]:
(x0, y0, x1, y1) = get_random_point(N)
plt.figure(N, figsize=(7, 7))
plt.plot(x0, y0, 'b.', x1, y1, 'r.')
plt.title('N = {}'.format(N))
plt.show()
if __name__ == "__main__":
plot_pi()
pass