当前位置:   article > 正文

Python中计算圆周率的n种方法_用python计算π的值

用python计算π的值

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

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

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

pi = 4 * math.atan(1)
print(pi)
  • 1
  • 2
  • 3
  • 4
  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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  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
  • 2
  • 3
  • 4
  1. 使用Python的内置库mpmath进行高精度计算
from mpmath import pi

print(pi)
  • 1
  • 2
  • 3
  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位
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

以上就是使用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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  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位
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

以上就是使用Python计算π的多种方法,包括使用数学库中的常量和公式、级数展开公式、蒙特卡洛方法、高斯公式以及无限级数等。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/424044
推荐阅读
相关标签
  

闽ICP备14008679号