def dynamic_programming_for_pi(target_pi=3.1415926, threshold=1e-7): """ Approximates the value of π using the Leibniz formula for π. Parameters: - target_pi: 設置目標 pi 和精度閾值 - threshold: 控制逼近的精確度 Returns: - pi_approx: The approximated value of π. - terms_used: The number of terms used to reach the approximation. """ n = 1 # 初始項數 pi_approx = 4.0 # dp[0] 的值 previous_sum = 1.0 # 第一項的值 terms = [1.0] # 記錄每一項的值 while abs(pi_approx - target_pi) >= threshold: # 計算第 n 項,使用動態累積和 if n < len(terms): term = terms[n] else: term = ((-1) ** n) / (2 * n + 1) terms.append(term) previous_sum += term pi_approx = 4 * previous_sum n += 1 # 增加項數