Leibniz series is a classic method for calculating pi, and its formula is as follows:
π/4 = 1 - 1/3 + 1/5 - 1/7 + 1/9 - ...
This formula approximates the value of π by continuously accumulating finite terms;
Sample code
The following is a Python sample code that uses the Leibniz formula to calculate pi:
def estimate_pi(num_terms):
pi_estimate = 0.0
sign = 1
for i in range(num_terms):
term = 1.0 / (2 * i + 1)
pi_estimate += sign * term
sign *= -1
return 4.0 * pi_estimate
# 调用函数进行估算,num_terms为级数项数
print(estimate_pi(1000000))
By adjusting the value of num_terms
, we can improve the accuracy of our approximation of pi; although the Leibniz series converges slowly, it provides a simple and intuitive way to calculate π.