首页 > 其他分享 >求π

求π

时间:2023-10-29 21:55:34浏览次数:41  
标签: perf format random DARTS print import

利用蒙特卡罗方法求解π的值

 

from random import random
from math import sqrt
from time import perf_counter
print("3107")
DARTS = 100000000
hits = 0.0
n = 1
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
    if i == DARTS * 0.01 * n:
        print("\r{}% [{}->]".format(n,'*'*n),end='')
        n += 1
pi = 4 * (hits/DARTS)
print("\nπ的值是:{}.".format(pi))
print("运行时间为:{}.".format(perf_counter()))

 

标签:,perf,format,random,DARTS,print,import
From: https://www.cnblogs.com/zyqdfp/p/17796590.html

相关文章