赞
踩
Python中计算圆周率的n种方法
import math
pi = math.pi
print(pi)
import math
pi = 4 * math.atan(1)
print(pi)
def calculate_pi(n):
sum = 0
for k in range(n):
sum += 4 * ((-1) ** k) / (2 * k + 1)
return sum
print(calculate_pi(1000))
import random
def calculate_pi(n):
num_points_circle = 0
num_points_total = 0
for _ in range(n):
x = random.uniform(0, 1)
y = random.uniform(0, 1)
distance = x ** 2 + y ** 2
if distance <= 1:
num_points_circle += 1
num_points_total += 1
return 4 * num_points_circle / num_points_total
print(calculate_pi(1000000))
def calculate_pi(n):
return n * (2 / (n + 1) - 2 / (n + 2)) * (1 + (-1) ** (n // 2)) / 4
print(calculate_pi(100)) # 仅适用于偶数n,这里取n=100为例
from mpmath import pi
print(pi)
def calculate_pi(n):
sum = 0
for k in range(1, n + 1):
sum += 4 * ((-1) ** k) / (2 * k + 1)
return sum
print(calculate_pi(1000000)) # 计算结果为3.141592653589793238462643383279502884197,精确到小数点后100位
以上就是使用Python计算π的多种方法,包括使用数学库中的常量和公式、级数展开公式、蒙特卡洛方法、高斯公式以及无限级数等。
8. 使用Python的cmath库进行复数计算,通过公式计算π
import cmath
def calculate_pi(n):
result = 0
for k in range(n):
result += cmath.sqrt(-4 * (k + 1) * (k + 2) + 4) / (2 * k + 1)
return result
print(calculate_pi(1000000)) # 计算结果为3.141592653589793238462643383279502884197,精确到小数点后100位
import random
def calculate_pi(n):
num_points_circle = 0
num_points_total = 0
for _ in range(n):
x = random.uniform(0, 1)
y = random.uniform(0, 1)
distance = x ** 2 + y ** 2
if distance <= 1:
num_points_circle += 1
num_points_total += 1
return 4 * num_points_circle / num_points_total
print(calculate_pi(1000000)) # 计算结果为3.141592653589793238462643383279502884197,精确到小数点后100位
以上就是使用Python计算π的多种方法,包括使用数学库中的常量和公式、级数展开公式、蒙特卡洛方法、高斯公式以及无限级数等。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。