用C语言写一个拉格朗日插值算法
时间: 2023-12-29 11:48:14 浏览: 77
好的,以下是一个简单的用 C 语言实现的拉格朗日插值算法:
```c
#include <stdio.h>
double interpolate(double x[], double y[], int n, double x0) {
double sum = 0.0;
for (int i = 0; i < n; i++) {
double prod = y[i];
for (int j = 0; j < n; j++) {
if (i != j) {
prod *= (x0 - x[j]) / (x[i] - x[j]);
}
}
sum += prod;
}
return sum;
}
int main() {
double x[] = {1.0, 2.0, 3.0, 4.0, 5.0};
double y[] = {1.0, 8.0, 27.0, 64.0, 125.0};
double x0 = 2.5;
int n = 5;
double result = interpolate(x, y, n, x0);
printf("The interpolated value for x=%lf is %lf.\n", x0, result);
}
```
输出结果为:
```
The interpolated value for x=2.500000 is 15.625000.
```
希望以上代码可以对您有所帮助。现在,您有什么其它问题吗?
阅读全文