Blue Bridge Cup Daily Question (15): Leibniz calculates Pi (python)

Topic:

There are many formulas for calculating the pi ratio in history. Among them, Gregory and Leibniz discovered the following formula:
pai = 4*(1-1/3+1/5-1/7 …)
See
this formula in the figure Simple and beautiful, but it has a flaw in it, it converges too slowly.
If we round to the nearest two decimal places, then:
Accumulate 1 item is: 4.00
Accumulate 2 items is: 2.67
Accumulate 3 items is: 3.47
. . .
Please write down the total of 100 items (rounded to two decimal places).
Note: Only fill in the decimal itself, do not fill in any redundant description or explanatory text.

Insert picture description here
Solution_1:

Directly separate the addition and subtraction operations.
Add the cases of 1, 5, 9, etc. Subtract the cases of
3, 7, 11, etc., and
finally round to two decimal places.

Code_1:

a = 0

for i in range(1, 200, 4):
    a += (4 / i)

for j in range(3, 200, 4):
    a -= (4 / j)

print(round(a, 2))

Solution_2:

Using the recursive algorithm,
first judge the situation
of addition and subtraction, and then continue to recurse i + 2 and add and subtract ans respectively.
Finally, the benchmark condition is met (i is 197 for the 100th item) and the output is output after two decimal places.

Code_2:

def circle(i, ans):
    if i == 197:
        return round(ans, 2)
    if (i + 1) / 2 % 2 == 1:
        return circle(i + 2, ans + 4 / i)
    elif (i + 1) / 2 % 2 == 0:
        return circle(i + 2, ans - 4 / i)


print(circle(1, 0))

Answer:

3.13

Guess you like

Origin blog.csdn.net/weixin_50791900/article/details/113000567