"Calculating Pi" python

Topic: There are many formulas for calculating pi in history. Among them, Gregory and Leibniz discovered the following formula:
pai = 4
(1-1/3+1/5-1/7 …
this formula is simple and It is beautiful, but it has a fly in the ointment. It converges too slowly.
If we round to two decimal places, then: the
cumulative 1 item is: 4.00, the
cumulative 2 items are: 2.67, the
cumulative 3 items are: 3.47
...
Please write it out What is the cumulative number of 100 items (rounded to two decimal places).
Note: Only fill in the decimal number itself, do not fill in any extra description or explanation text.
*

Idea 1: Recursion

def func(n):
    sum = 0
    if n==1:
        return 4
    else:
        return   4*(-1)**(n-1)/(2*n-1) + func(n-1)

print(round(func(100),2))


3.13

Idea 2: for loop

sum = 0
for n in range(1,101):
    if n%2==0:
        sum = sum -4/(2*n-1)

    else:
        sum = sum+4/(2*n-1)

print(round(sum,2))


3.13

Guess you like

Origin blog.csdn.net/weixin_53776140/article/details/112994288