求pi时可以采用蒙特卡罗的方法:随机向单位圆中和正方形中抛洒大量点,计算每个点到圆心的距离从而判断该点在圆内或圆外,用圆内的点数除以总点数。
输入:随机抛出的点数
处理:计算每个点到圆心的距离,统计在圆内的点的数量
输出:pi值
求pi的python程序为:
from random import random
from math import sqrt
from time import perf_counter
DARTS = 1000
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(pi))
print("运行时间是:{:.5f}s".format(perf_counter()))
标签:hits,perf,random,计算,点数,import,pi From: https://www.cnblogs.com/guowenye/p/17798595.html