x f(x)
=======================
{-1.0 , 0.3679}
{0.0 , 1.0000}
{1.0 , 2.7183}
{2.0 , 7.3891}
並且計算 {-0.5 , 0.5 , 1.2 , 1.5 ,1.8 , 2.5}的值
程式
// C program for implementation of Lagrange's Interpolation
#include <stdio.h>
#include <math.h>
// To represent a data point corresponding to x and y = f(x)
typedef struct f
{
double x , y;
} Data;
// function to interpolate the given data points using Lagrange's formula
// xi corresponds to the new data point whose value is to be obtained
// n represents the number of known data points
double interpolate(Data f[], double xi, int n)
{
double result = 0; // Initialize result
for (int i=0; i<n; i++)
{
// Compute individual terms of above formula
double term = f[i].y;
//printf("%0.3lf\n",term);
for (int j=0;j<n;j++)
{
if (j !=i )
{
term = term* (xi - f[j].x)/ (f[i].x - f[j].x);
//printf("%0.1lf %0.1lf \n",f[i].x , f[j].x);
//printf("%0.3lf\n",term);
}
}
// Add current term to result
result += term;
}
return result;
}
// driver function to check the program
int main()
{
// creating an array of 4 known data points
Data f[]={ {-1.0, 0.3679} , {0.0 , 1.0000} , {1.0, 2.7183} ,{2.0, 7.3891}};
double xb[]= {-0.5 , 0.5 , 1.2 , 1.5 ,1.8 , 2.5};
// Using the interpolate function to obtain a data point
// corresponding to x=1.5
int n1=6;
for (int k=0; k<n1; k++)
{
double xa=xb[k];
printf("%3.1lf----",xa);
double result1= interpolate(f, xa, 4);
printf("Value of Pn(%3.1lf) is : %3.5lf\n",xa,result1);
printf("Value of f(%3.1lf) is : %3.5lf\n",xa,exp(xa));
printf("The e(x) = f(x)-Pn(x) is : %3.5lf\n\n", (exp(xa)-result1));
}
return 0;
}
輸出畫面
-0.5----Value of Pn(-0.5) is : 0.66482
Value of f(-0.5) is : 0.60653
The e(x) = f(x)-Pn(x) is : -0.05829
0.5----Value of Pn(0.5) is : 1.60673
Value of f(0.5) is : 1.64872
The e(x) = f(x)-Pn(x) is : 0.04199
1.2----Value of Pn(1.2) is : 3.35654
Value of f(1.2) is : 3.32012
The e(x) = f(x)-Pn(x) is : -0.03642
1.5----Value of Pn(1.5) is : 4.56799
Value of f(1.5) is : 4.48169
The e(x) = f(x)-Pn(x) is : -0.08630
1.8----Value of Pn(1.8) is : 6.12916
Value of f(1.8) is : 6.04965
The e(x) = f(x)-Pn(x) is : -0.07951
2.5----Value of Pn(2.5) is : 11.41491
Value of f(2.5) is : 12.18249
The e(x) = f(x)-Pn(x) is : 0.76759
...Program finished with exit code 0
Press ENTER to exit console.
沒有留言:
張貼留言