3.141 或 3.142)$$\pi = 4 \times \left(1 - \frac{1}{3} + \frac{1}{5} - \frac{1}{7} + \frac{1}{9} - \cdots \right) = 4 \sum_{k=0}^{\infty} \frac{(-1)^k}{2k+1}$$
收斂較慢,需約 2000 項達到 1e-3 精度,遞迴深度可能超過堆疊限制。
$$\frac{\pi}{4} = 4 \arctan\frac{1}{5} - \arctan\frac{1}{239}$$
$$\arctan x = \sum_{k=0}^{\infty} \frac{(-1)^k x^{2k+1}}{2k+1}, \quad |x| \le 1$$
收斂極快,僅需 ~10 項即達 1e-15 精度,極適合遞迴實現。
#include
#include
/* 遞迴計算 arctan(x) 級數前 n 項
x: 角度值 (1/5 或 1/239)
n: 當前項索引 (從 0 開始)
max_n: 最大項數
返回:級數和 */
double arctan_rec(double x, int n, int max_n) {
if (n > max_n) return 0.0;
double term = pow(-1, n) * pow(x, 2*n + 1) / (2*n + 1);
return term + arctan_rec(x, n + 1, max_n);
}
int main() {
const double x1 = 1.0/5.0;
const double x2 = 1.0/239.0;
const int terms = 10; // 10 項足夠雙精度收斂
double a1 = arctan_rec(x1, 0, terms);
double a2 = arctan_rec(x2, 0, terms);
double pi = 4 * (4 * a1 - a2);
printf("π ≈ %.10f\n", pi); // 3.1415926536
printf("小數點後三位:%.3f\n", pi); // 3.142 (四捨五入)
return 0;
}
n > max_n 返回 0,保證有限遞迴深度(此處 11 層)。terms=10 時誤差 < 1e-15,遠超 1e-3 需求。
#include
#include
int hit_rec(int total, int hits, int n) {
if (n == 0) return hits;
double x = (double)rand() / RAND_MAX;
double y = (double)rand() / RAND_MAX;
return hit_rec(total, hits + (x*x + y*y <= 1.0), n - 1);
}
int main() {
srand(time(NULL));
const int N = 1000000;
int hits = hit_rec(N, 0, N);
double pi = 4.0 * hits / N;
printf("Monte Carlo π ≈ %.5f\n", pi);
return 0;
}
※ 蒙地卡羅法需大量遞迴(百萬層),實務上會棧溢位,僅供算法理解參考。
採用 馬青公式 + 遞迴級數求和 是滿足「無迴圈、高精度、堆疊安全」的最佳解法。最佳回答雖提供參考連結,但未給出完整可編譯代碼,本文補全了工程級實現。