赞
踩
采用蒙特卡罗方法求解π值。
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()))
玩了一个 抛点数特别多的版本,以我的笔记本电脑性能还运行了这么久。
pi值是10000000000
pi值是3.1416024552
运行时间是:6169.62848s
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。