已知函数表如下: x 0.4 0.55 0.8 0.9 1 y 0.41075 0.57515 0.88811 1.02652 1.17520 请写出用拉格朗日插值多项式函数值的c语言和c++代码
时间: 2024-02-14 18:08:45 浏览: 114
数值分析拉格朗日插值C++代码
以下是用拉格朗日插值多项式求解函数值的C语言代码:
```c
#include <stdio.h>
double lagrange_interpolation(double x[], double y[], int n, double xi);
int main()
{
double x[] = {0.4, 0.55, 0.8, 0.9, 1};
double y[] = {0.41075, 0.57515, 0.88811, 1.02652, 1.17520};
double xi = 0.6;
double yi = lagrange_interpolation(x, y, 5, xi);
printf("f(%lf) = %lf\n", xi, yi);
return 0;
}
double lagrange_interpolation(double x[], double y[], int n, double xi)
{
double result = 0;
for (int i = 0; i < n; i++)
{
double term = y[i];
for (int j = 0; j < n; j++)
{
if (j != i)
{
term *= (xi - x[j]) / (x[i] - x[j]);
}
}
result += term;
}
return result;
}
```
以下是用拉格朗日插值多项式求解函数值的C++代码:
```c++
#include <iostream>
using namespace std;
double lagrange_interpolation(double x[], double y[], int n, double xi);
int main()
{
double x[] = {0.4, 0.55, 0.8, 0.9, 1};
double y[] = {0.41075, 0.57515, 0.88811, 1.02652, 1.17520};
double xi = 0.6;
double yi = lagrange_interpolation(x, y, 5, xi);
cout << "f(" << xi << ") = " << yi << endl;
return 0;
}
double lagrange_interpolation(double x[], double y[], int n, double xi)
{
double result = 0;
for (int i = 0; i < n; i++)
{
double term = y[i];
for (int j = 0; j < n; j++)
{
if (j != i)
{
term *= (xi - x[j]) / (x[i] - x[j]);
}
}
result += term;
}
return result;
}
```
阅读全文