已知函数表如下: x 0.4 0.55 0.8 0.9 1 y 0.41075 0.57515 0.88811 1.02652 1.17520 请写出用拉格朗日插值多项式求0.5,0.7,0.85三处的函数值的c语言和c++代码
时间: 2024-02-14 19:08:45 浏览: 160
以下是用拉格朗日插值多项式求解函数值的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 x1 = 0.5;
double x2 = 0.7;
double x3 = 0.85;
double y1 = lagrange_interpolation(x, y, 5, x1);
double y2 = lagrange_interpolation(x, y, 5, x2);
double y3 = lagrange_interpolation(x, y, 5, x3);
printf("f(0.5) = %lf\n", y1);
printf("f(0.7) = %lf\n", y2);
printf("f(0.85) = %lf\n", y3);
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 x1 = 0.5;
double x2 = 0.7;
double x3 = 0.85;
double y1 = lagrange_interpolation(x, y, 5, x1);
double y2 = lagrange_interpolation(x, y, 5, x2);
double y3 = lagrange_interpolation(x, y, 5, x3);
cout << "f(0.5) = " << y1 << endl;
cout << "f(0.7) = " << y2 << endl;
cout << "f(0.85) = " << y3 << 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;
}
```
阅读全文