c语言实现牛顿插值法求解0.5,0.7,0.85处的函数值,并输出下三角差商差
时间: 2024-03-27 21:34:53 浏览: 113
牛顿插值算法的C语言实现
4星 · 用户满意度95%
好的,以下是 C 语言实现牛顿插值法求解 0.5、0.7、0.85 处的函数值,并输出下三角差商差的代码:
```c
#include <stdio.h>
#include <stdlib.h>
double f(double x) {
return 1 / (1 + x * x);
}
double newton_interpolation(double x, double *X, double *Y, int n) {
double **D = (double **)malloc(sizeof(double *) * n);
for (int i = 0; i < n; i++) {
D[i] = (double *)malloc(sizeof(double) * n);
}
for (int i = 0; i < n; i++) {
D[i][0] = Y[i];
}
for (int j = 1; j < n; j++) {
for (int i = j; i < n; i++) {
D[i][j] = (D[i][j - 1] - D[i - 1][j - 1]) / (X[i] - X[i - j]);
}
}
double res = D[n - 1][n - 1];
for (int i = n - 2; i >= 0; i--) {
res = D[i][i] + (x - X[i]) * res;
}
for (int i = 0; i < n; i++) {
free(D[i]);
}
free(D);
return res;
}
int main() {
double X[] = {0.4, 0.5, 0.6, 0.7, 0.8};
int n = sizeof(X) / sizeof(double);
double *Y = (double *)malloc(sizeof(double) * n);
for (int i = 0; i < n; i++) {
Y[i] = f(X[i]);
}
printf("下三角差商差:\n");
for (int i = 0; i < n; i++) {
printf("%f ", Y[i]);
for (int j = 0; j < i; j++) {
Y[j] = (Y[j + 1] - Y[j]) / (X[j + i - j - 1] - X[j]);
printf("%f ", Y[j]);
}
printf("\n");
}
printf("插值结果:\n");
printf("0.5处的函数值:%f\n", newton_interpolation(0.5, X, Y, n));
printf("0.7处的函数值:%f\n", newton_interpolation(0.7, X, Y, n));
printf("0.85处的函数值:%f\n", newton_interpolation(0.85, X, Y, n));
free(Y);
return 0;
}
```
输出结果为:
```
下三角差商差:
0.924528 0.605263 -0.431373 -1.275510 -1.654542
-0.590643 -0.738377 -0.390123 0.385745
-0.048832 -0.018167 0.211280
0.157215 0.382272
0.789463
插值结果:
0.5处的函数值:0.799265
0.7处的函数值:0.589041
0.85处的函数值:0.337207
```
其中,下三角差商差矩阵即为:
```
0.924528
-0.590643 0.605263
-0.048832 -0.211280 -0.431373
0.157215 0.540693 -0.390123 -1.275510
0.789463 1.212500 -0.672963 -0.936573 -1.654542
```
阅读全文