計算多項式 f(x) = 1 + Σ(xi/i) (i=1..m) 時,直接調用 pow() 與使用秦九韶算法(Horner 規則)的性能差距驚人。本文通過 C++ 實測數據,直觀展示算法優化的威力。
double Fn1(double x) {
double f = 1.0;
for (int i = 1; i <= m; i++) {
f += pow(x, i) / i; // 每次調用 pow,重複計算 x^i
}
return f;
}
double Fn2(double x) {
double f = 0.0;
for (int i = m; i >= 1; i--) {
f = f * x + 1.0 / i; // 利用上一次結果,僅一次乘法
}
return f * x + 1.0;
}
原理:f(x) = 1 + x/1 + x²/2 + ... + xm/m 重寫為遞推形式,消除冪次運算。
x = 0.9,m 從 100 到 109clock() 精度約毫秒#include#include #include #define m 1000000000 // 修改此處測試不同規模 using namespace std; double Fn1(double x); double Fn2(double x); int main() { double x = 0.9; clock_t start, stop; start = clock(); cout << Fn1(x) << endl; stop = clock(); cout << "Fn1 time: " << double(stop-start)/CLOCKS_PER_SEC << "s" << endl; start = clock(); cout << Fn2(x) << endl; stop = clock(); cout << "Fn2 time: " << double(stop-start)/CLOCKS_PER_SEC << "s" << endl; return 0; }
| m (項數) | Fn1 pow() 耗時 | Fn2 秦九韶 耗時 | 加速比 |
|---|---|---|---|
| 100 | 0.001s | 0.000s | — |
| 1,000 | 0.001s | 0.000s | — |
| 10,000 | 0.003s | 0.000s | — |
| 100,000 | 0.015s | 0.001s | 15x |
| 1,000,000 | 0.157s | 0.005s | 31x |
| 10,000,000 | 1.619s | 0.049s | 33x |
| 100,000,000 | 17.955s | 0.472s | 38x |
| 1,000,000,000 | 191.608s | 4.706s | 41x |
| 算法 | 時間複雜度 | 空間複雜度 | 關鍵操作 |
|---|---|---|---|
| pow() 直接求和 | O(m · log i) ≈ O(m log m) | O(1) | 每項調用 pow(),內部指數運算 |
| 秦九韶算法 | O(m) | O(1) | 每項 1 次乘法 + 1 次加法 |