1. 使用内置的`math`模块,通过`math.pi`属性获取圆周率的值。
import math
pi = math.pi
print(pi) 输出圆周率的近似值
2. 如果你需要更精确的圆周率值,可以使用`decimal`模块中的`Decimal`类型,通过设置精度来获得圆周率的精确值。
from decimal import Decimal, getcontext
getcontext().prec = 50 设置精度为50位小数
pi_exact = Decimal(0)
for _ in range():
pi_exact += Decimal(1) / Decimal() 2
pi_exact = pi_exact * 4
print(pi_exact) 输出圆周率的精确值
3. 你还可以使用蒙特卡罗方法来估算圆周率。
import random
def estimate_pi(num_points):
points_inside_circle = 0
for _ in range(num_points):
x = random.uniform(0, 1)
y = random.uniform(0, 1)
if x2 + y2 <= 1:
points_inside_circle += 1
pi_estimate = 4 * points_inside_circle / num_points
return pi_estimate
num_points =
pi_approx = estimate_pi(num_points)
print("Approximated value of pi:", pi_approx) 输出圆周率的近似值
以上是几种在Python中引用圆周率的方法