#include <stdio.h>
const int n = 2;
typedef struct
{
double x;
double y;
} Point;//现在可以用Point作为类型声明新的结构体变量
void print_points(int n, Point *points)
{
for (int i = 0; i <= n; i++)
{
printf("(%lf, %lf)\n", points[i].x, points[i].y);
}
}
int main()
{
Point points[] = {{11, 0.190809}, {12, 0.207912}, {13, 0.224951}};//points[n+1] : x0, x1, ..., xn
printf("Interpolation point: \n");
print_points(n, points);
double x = 11.5;
printf("Calculate the function value at x = %lf\n", x);
double diff[n+1];
for (int i = 0; i <= n; i++)//diff[i] = points[i].y
{
diff[i] = points[i].y;
}
for (int i = 0; i < n; i++)//diff[i] = f[x0, x1, ..., xi]
{
for (int j = n; j > i; j--)
{
diff[j] = (diff[j] - diff[j-1])/(points[j].x - points[j-1-i].x);
}
}
double temp = 1;
double newton = diff[0];
//calculte N_n(x) = f(x0) + (x - x0)f[x0, x1] + ... + (x - x0)(x - x1)...(x - x_n-1)f[x0, x1, ..., xn]
for (int i = 0; i < n; i++)
{
temp = temp * (x - points[i].x);
newton = newton + temp * diff[i+1];
}
printf("N_n(%lf) = %lf\n", x, newton);
return 0;
}