站点图标 AI技术聚合

Python中计算圆周率的n种方法

Python中计算圆周率的n种方法

  1. 使用math库中的pi常量
import math

pi = math.pi
print(pi)
  1. 使用π的计算公式:4*arctan(1)
import math

pi = 4 * math.atan(1)
print(pi)
  1. 使用级数展开公式计算π
def calculate_pi(n):
    sum = 0
    for k in range(n):
        sum += 4 * ((-1) ** k) / (2 * k + 1)
    return sum

print(calculate_pi(1000))
  1. 使用蒙特卡洛方法计算π
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))
  1. 使用高斯公式计算π(仅适用于偶数n)
def calculate_pi(n):
    return n * (2 / (n + 1) - 2 / (n + 2)) * (1 + (-1) ** (n // 2)) / 4

print(calculate_pi(100))  # 仅适用于偶数n,这里取n=100为例
  1. 使用Python的内置库mpmath进行高精度计算
from mpmath import pi

print(pi)
  1. 使用无限级数进行π的近似计算
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位
  1. 使用Python的内置库random进行随机数生成,通过蒙特卡洛方法计算π
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计算π的多种方法,包括使用数学库中的常量和公式、级数展开公式、蒙特卡洛方法、高斯公式以及无限级数等。

版权声明:本文为博主作者:实相无相原创文章,版权归属原作者,如果侵权,请联系我们删除!

原文链接:https://blog.csdn.net/weixin_46121540/article/details/135101076

退出移动版