当前位置:   article > 正文

采用蒙特卡罗方法求解π值_用蒙特卡罗方法求解pi的值

用蒙特卡罗方法求解pi的值

采用蒙特卡罗方法求解π值。
Python 3.8.8版本。

#----计算pi的值----
from random import random
from math import sqrt
from time import perf_counter   #新版本需要用这个。
DARTS=10000000000  #抛点数
hits=0.0
perf_counter()
for i in range(1,DARTS+1):
    x,y=random(),random()
    dist=sqrt(x**2+y**2)
    if dist<=1.0:
        hits=hits+1
pi=4*(hits/DARTS)
print("pi值是{}".format(DARTS))
print("pi值是{}".format(pi))
print("运行时间是:{:.5f}s".format(perf_counter()))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

玩了一个 抛点数特别多的版本,以我的笔记本电脑性能还运行了这么久。

 
pi值是10000000000
pi值是3.1416024552
运行时间是:6169.62848s
  • 1
  • 2
  • 3
  • 4
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/729919
推荐阅读
相关标签
  

闽ICP备14008679号