首页
学习
活动
专区
圈层
工具
发布

#python# Monte Carlo算法画π

Monte Carlo算法画π

代码语言:javascript
复制
# 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
下一篇
举报
领券