Python中计算圆周率的方法汇总(方法合集)

Python中计算圆周率的n种方法
使用math库中的pi常量

import math
pi = math.pi
print(pi)

使用π的计算公式:4*arctan(1)

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))

使用高斯公式计算π(仅适用于偶数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为例

使用Python的内置库mpmath进行高精度计算

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位

使用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计算π的多种方法,包括使用数学库中的常量和公式、级数展开公式、蒙特卡洛方法、高斯公式以及无限级数等。

到此这篇关于Python中计算圆周率的n种方法的文章就介绍到这了,更多相关Python计算圆周率内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持vb.net教程C#教程python教程SQL教程access 2010教程xin3721自学网

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值