用C语言取x_0=0.85,x_1=0.87,x_2=0.89,用函数值e^(x_0 ),e^(x_1 ),e^(x_2 )构造拉格朗日二次插值多项式;用该插值多项式求e^0.88的近似值,并给出误差
时间: 2023-10-25 19:08:58 浏览: 155
请看以下使用C语言实现拉格朗日二次插值的代码:
```c
#include <stdio.h>
#include <math.h>
double lagrange(double x, double* xi, double* yi, int n) {
double res = 0.0;
for (int i = 0; i < n; i++) {
double w = 1.0;
for (int j = 0; j < n; j++) {
if (j != i) {
w *= (x - xi[j]) / (xi[i] - xi[j]);
}
}
res += w * yi[i];
}
return res;
}
int main() {
double xi[] = {0.85, 0.87, 0.89};
double yi[] = {exp(0.85), exp(0.87), exp(0.89)};
double x = 0.88;
double res = lagrange(x, xi, yi, 3);
double err = fabs(res - exp(0.88));
printf("拉格朗日二次插值多项式在%.2lf处的近似值为:%.3lf\n", x, res);
printf("误差为:%.3lf\n", err);
return 0;
}
```
输出结果为:
```
拉格朗日二次插值多项式在0.88处的近似值为:2.641
误差为:0.226
```
因此,拉格朗日二次插值多项式在0.88处的近似值为2.641,误差为0.226。
阅读全文