(1 , 0.0) (2 , 0.693) (3 , 1.099)
x f(x)
==================
1.0 0.0
2.0 0.693
3.0 1.099
===================
程式
// 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.0} , {2.0 , 0.693} , {3.0, 1.099} };
// Using the interpolate function to obtain a data point
// corresponding to x=3
double result1= interpolate(f, 1.5, 3);
printf("Value of f(3) is : %3.5lf",result1);
return 0;
}
輸出畫面
0.000
1.0 2.0
0.000
1.0 3.0
0.000
0.693
2.0 1.0
0.346
2.0 3.0
0.520
1.099
3.0 1.0
0.275
3.0 2.0
-0.137
Value of f(3) is : 0.38237
...Program finished with exit code 0
Press ENTER to exit console.
沒有留言:
張貼留言