供应商管理系统毕设实战:SpringBoot+Vue全栈开发指南
2026/10/2 21:50:03
基于C++语言编写牛顿插值多项式算法,计算下面例题:
代码:
#include <iostream> #include <vector> #include <iomanip> #include <cmath> using namespace std; // 牛顿插值法计算函数 double newtonInterpolation(const vector<double>& x, const vector<double>& y, double target_x) { int n = x.size(); // 构建差商表,使用二维vector,初始化为0 // diff_quotient[i][j] 表示从节点 i 开始的 j 阶差商 vector<vector<double>> diff_quotient(n, vector<double>(n, 0.0)); // 1. 初始化0阶差商(即函数值本身) for (int i = 0; i < n; ++i) { diff_quotient[i][0] = y[i]; } // 2. 计算1阶到n-1阶差商 // 按照图片表格的列方向进行计算 for (int j = 1; j < n; ++j) { // j代表阶数 for (int i = 0; i < n - j; ++i) { // i代表行索引 diff_quotient[i][j] = (diff_quotient[i + 1][j - 1] - diff_quotient[i][j - 1]) / (x[i + j] - x[i]); } } // 3. 打印差商表(模仿你提供的第二张图) cout << "================ 差商表 ================" << endl; cout << setw(6) << "xk" << setw(12) << "f(xk)" << setw(12) << "一阶" << setw(12) << "二阶" << setw(12) << "三阶" << endl; for (int i = 0; i < n; ++i) { cout << setw(6) << fixed << setprecision(2) << x[i]; for (int j = 0; j < n - i; ++j) { cout << setw(12) << fixed << setprecision(5) << diff_quotient[i][j]; } cout << endl; } cout << "=========================================" << endl; // 4. 根据牛顿插值公式计算目标值 // N(x) = f[x0] + f[x0,x1](x-x0) + f[x0,x1,x2](x-x0)(x-x1) + ... double result = diff_quotient[0][0]; // 第一项 f[x0] double term = 1.0; for (int i = 1; i < n; ++i) { term *= (target_x - x[i - 1]); // 累乘 (x - x0)(x - x1)... result += diff_quotient[0][i] * term; // 加上对应的差商乘以累乘项 } return result; } int main() { // 输入题目给定数据 vector<double> x = { 0.40, 0.55, 0.65, 0.80 }; vector<double> y = { 0.41075, 0.57815, 0.69675, 0.88811 }; double target_x = 0.596; cout << "已知节点: "; for (double val : x) cout << val << " "; cout << "\n对应函数值: "; for (double val : y) cout << val << " "; cout << "\n\n目标插值点 x = " << target_x << endl << endl; // 执行牛顿插值 double result = newtonInterpolation(x, y, target_x); // 输出最终结果 cout << "最终计算结果: f(" << target_x << ") ≈ " << fixed << setprecision(6) << result << endl; cout << "(注:由于浮点数精度限制,手工计算与程序计算结果可能存在微小尾数差异,属正常现象)" << endl; return 0; }运行结果: