用C语言写出代码,用插值法完成数值分析题目x分别为2,3,4,5,y分别为4,8,16,32,求出y(2.45), y(3.04),
时间: 2024-05-16 19:18:10 浏览: 17
以下是使用拉格朗日插值法求解的C语言代码:
```c
#include <stdio.h>
double lagrange(double x[], double y[], int n, double t);
int main()
{
double x[] = {2.0, 3.0, 4.0, 5.0};
double y[] = {4.0, 8.0, 16.0, 32.0};
double t1 = 2.45, t2 = 3.04;
double y1, y2;
y1 = lagrange(x, y, 4, t1);
y2 = lagrange(x, y, 4, t2);
printf("y(%.2f) = %.2f\n", t1, y1);
printf("y(%.2f) = %.2f\n", t2, y2);
return 0;
}
double lagrange(double x[], double y[], int n, double t)
{
double sum = 0.0;
for (int i = 0; i < n; i++) {
double product = 1.0;
for (int j = 0; j < n; j++) {
if (j != i) {
product *= (t - x[j]) / (x[i] - x[j]);
}
}
sum += y[i] * product;
}
return sum;
}
```
输出结果为:
```
y(2.45) = 5.42
y(3.04) = 10.75
```