fork download
  1. import numpy as np
  2.  
  3. # 生成10的6次方個隨機點
  4. npts = 10**6
  5. points = np.random.rand(npts, 2)
  6.  
  7. # 計算點到原點的距離
  8. distances = np.sqrt(points[:,0]**2 + points[:,1]**2)
  9.  
  10. # 計算落在1/4單位圓內的點的數量
  11. nins = np.sum(distances <= 1)
  12.  
  13. # 蒙地卡羅方法計算圓周率
  14. estimate = 4 * nins / npts
  15.  
  16. print("%.4f" % estimate)
Success #stdin #stdout 0.84s 71236KB
stdin
Standard input is empty
stdout
3.1416