怎么用python做计算_input函数python

怎么用python做计算_input函数python在 Python 中 计算圆周率 可以通过多种方法实现 下面是一些常见的方法 BBP 公式法 pythonfrom math import log sqrt def approximate pi bbp places 10 pi 0 n 1 while True term 1 n 2 n 1 pi term log 16

在Python中,计算圆周率(π)可以通过多种方法实现,下面是一些常见的方法:

BBP公式法

python

from math import log, sqrt

def approximate_pi_bbp(places=10):

pi = 0

n = 1

while True:

term = (-1) n / (2 * n + 1)

pi += term * log(16) / log(4)

pi = pi / n

if abs(pi * 4 - 3) < 10 (-places):

break

n += 1

return pi * 4

print(approximate_pi_bbp(places))

蒙特卡罗方法

python

import random

import time

from tqdm import tqdm

def estimate_pi_montecarlo(num_samples):

inside_circle = 0

for _ in range(num_samples):

x, y = random.random(), random.random()

if x2 + y2 <= 1:

inside_circle += 1

return 4 * inside_circle / num_samples

DARTS =

hits = 0.0

start = time.perf_counter()

for _ in tqdm(range(DARTS)):

x, y = random.random(), random.random()

if x2 + y2 <= 1.0:

hits += 1

pi = 4 * (hits / DARTS)

print("圆周率值是: {:.10f}, 运行时间是: {:.5f}s".format(pi, time.perf_counter() - start))

逼近法

python

import math

def approximate_pi_approximation(n):

return 4 * sum(1 / (2 * i + 1) for i in range(n))

for n in [3, 4, 5, 10, 100, 1000, 10000, ]:

print(n, "-->", approximate_pi_approximation(n))

使用math库

python

import math

print("Python中的π是:", math.pi)

以上方法都可以用来计算圆周率,其中蒙特卡罗方法通过随机采样来估计π的值,而其他方法则基于数学公式。你可以根据需要的精度选择合适的方法。

如果你需要更精确的计算,并且想要看到计算进度,可以使用`tqdm`库来显示进度条。

编程小号
上一篇 2026-03-19 14:32
下一篇 2026-03-19 14:26

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/71347.html