可以使用莱布尼茨级数公式计算 $\pi$ 的代码如下:
import math
def calculate_pi(threshold):
"""
Calculate pi using the Leibniz formula.
The calculation stops when the absolute value of the last term is less than the given threshold.
"""
pi = 0
i = 0
term = 1
while abs(term) > threshold:
pi += term
i += 2
term = -term * 4 / i