python 5种方法计算圆周率(python怎么算圆周率)

python 5种方法计算圆周率(python怎么算圆周率)

首页维修大全综合更新时间:2024-05-05 02:05:14

python 5种方法计算圆周率

以下是使用Python计算圆周率的五种方法:

1、使用圆的半径计算圆周率:

import math

radius = 5

circumference = 2 * math.pi * radius

pi = circumference / (2 * radius)

print(pi)

2、使用圆的直径计算圆周率:

import math

diameter = 10

pi = math.pi * (diameter ** 2) / (2 * diameter)

print(pi)

3、使用蒙特卡罗方法估算圆周率:

import random

num_trials = 1000000

count_inside = 0

for i in range(num_trials):

    x = random.uniform(-1, 1)

    y = random.uniform(-1, 1)

    if x ** 2 + y ** 2 <= 1:

        count_inside += 1

pi = 4 * count_inside / num_trials

print(pi)

4、使用莱布尼茨级数估算圆周率:

import math

num_terms = 1000000

pi = 0

for i in range(num_terms):

    term = (-1) ** i / (2 * i + 1)

    pi += term

pi = 4 * pi

print(pi)

5、使用查普曼公式估算圆周率:

import math

num_terms = 1000000

pi = 0

for i in range(num_terms):

    term = (4 * (i ** 2)) / (8 * i + 1)

    pi += term

pi = pi * math.sqrt(8)

print(pi)

以上五种方法分别使用了不同的算法来计算或估算圆周率,具体实现细节可以根据需要进行调整。

from sys import stdout

scale = 10000

maxarr = 2800

arrinit = 2000

carry = 0

arr = [arrinit] * (maxarr + 1)

for i in xrange(maxarr, 1, -14):

total = 0

for j in xrange(i, 0, -1):

total = (total * j) + (scale * arr[j])

arr[j] = total % ((j * 2) - 1)

total = total / ((j * 2) - 1)

stdout.write("%04d" % (carry + (total / scale)))

carry = total % scale

大家还看了
也许喜欢
更多栏目

© 2021 3dmxku.com,All Rights Reserved.