一般拉格朗日插值多項式:
2.1如圖拉格朗日多項式插值結果,預測不準
2.2如圖,擬合曲線兩端出現鉅變,出現龍格現象。
2.3此拉格朗日插值多項式不是數據的好模型,由於被插值區間數據較少,出現龍格現象。
2.4如圖,前 4 個數據點的三次多項式估計 1998 年世界石油產量爲74.258(桶/天),Runge 現象不會出現。
c++程序源代碼:
//拉格朗日多項式插值,龍格現象,高等數值計算
//開發人員:chenshuai 開發日期:2019.11.5 郵箱:[email protected]
#include "pch.h"
#include <iostream>
#include <math.h>
using namespace std;
#define num 3 //擬合多項式次數
#include <vector>
#include <fstream>//文件輸入/輸出流
#include <iomanip> //參數化輸入/輸出
double Lagrange(double x, vector<double>x_i, vector<double>y_i);//定義拉格朗日插值函數
double Lagrange(double x,vector<double>x_i,vector<double>y_i)
{
int n = size(x_i);
double ln_x = 0, w_i = 1.0;
for (int k = 0; k <n; k++)
{
w_i = 1;
for (int j = 0; j <n; j++)
{
if (k != j)
w_i = w_i * (x - x_i[j]) / (x_i[k] - x_i[j]);
}
ln_x = ln_x + w_i * y_i[k];
}
return ln_x;
}
int main()
{
/*vector<double>x_i = {1994, 1995,1996,1997,1998,1999,2000,2001,2002,2003 };
vector<double>y_i = { 67.052,68.008,69.803,72.024,73.4,72.063,74.669,74.487,74.065,76.777 };*/
vector<double>x_i = { 1994, 1995,1996,1997 };
vector<double>y_i = { 67.052,68.008,69.803,72.024};
double x=1998,y=0;
int n = 50;//插值等分數
y = Lagrange(x, x_i, y_i);
cout << "1998年的石油產量=" << fixed << setprecision(4) << setw(8) << y << endl;
ofstream out("插值結果.dat");
for (int i = 0; i <= num; i++)
{
out << fixed << setprecision(4) << setw(12) << x_i[i] << fixed << setprecision(4) << setw(15) << y_i[i] << endl;
}
for (int i = 0; i < n; i++)
{
x = 1994 + double(1997 - 1994) / (n - 1)*i;
cout << x << endl;
y= Lagrange(x, x_i, y_i);
out << fixed << setprecision(4) << setw(12) << x<< fixed << setprecision(4) << setw(15) << y<< endl;
}
out.close();
}