#include <stdio.h>
#include <math.h>
double f(double x) {
return 1 / (1 + pow(x, 2));
}
double lagrangeInterpolation(double x[], double y[], int n, double point) {
double result = 0.0;
for (int i = 0; i <= n; i++) {
double term = y[i];
for (int j = 0; j <= n; j++) {
if (j != i) {
term *= (point - x[j]) / (x[i] - x[j]);
}
}
result += term;
}
return result;
}
double linearInterpolation(double x[], double y[], int n, double point) {
int i;
for (i = 0; i < n; i++) {
if (point >= x[i] && point <= x[i + 1]) {
break;
}
}
double slope = (y[i + 1] - y[i]) / (x[i + 1] - x[i]);
double result = y[i] + slope * (point - x[i]);
return result;
}
int main() {
double x[12]; // 11个等距插值节点
double y[12]; // 对应节点的函数值
double interval = 10.0 / 10.0; // 区间长度
double point1 = 0.5; // 预测点1
double point2 = 4.5; // 预测点2
// 计算插值节点和函数值
for (int i = 0; i <= 10; i++) {
x[i] = -5.0 + i * interval;
y[i] = f(x[i]);
}
// 计算拉格朗日插值并比较精确值和误差
double lagrangeResult1 = lagrangeInterpolation(x, y, 10, point1);
double lagrangeResult2 = lagrangeInterpolation(x, y, 10, point2);
double exactResult1 = f(point1);
double exactResult2 = f(point2);
double lagrangeError1 = fabs(lagrangeResult1 - exactResult1);
double lagrangeError2 = fabs(lagrangeResult2 - exactResult2);
printf("拉格朗日插值结果:\n");
printf("预测点 %.1f 的近似函数值:%.6f,精确值:%.6f,误差:%.6f\n", point1, lagrangeResult1, exactResult1, lagrangeError1);
printf("预测点 %.1f 的近似函数值:%.6f,精确值:%.6f,误差:%.6f\n", point2, lagrangeResult2, exactResult2, lagrangeError2);
// 计算分段线性插值并比较精确值和误差
double linearResult1 = linearInterpolation(x, y, 10, point1);
double linearResult2 = linearInterpolation(x, y, 10, point2);
double linearError1 = fabs(linearResult1 - exactResult1);
double linearError2 = fabs(linearResult2 - exactResult2);
printf("分段线性插值结果:\n");
printf("预测点 %.1f 的近似函数值:%.6f,精确值:%.6f,误差:%.6f\n", point1, linearResult1, exactResult1, linearError1);
printf("预测点 %.1f 的近似函数值:%.6f,精确值:%.6f,误差:%.6f\n", point2, linearResult2, exactResult2, linearError2);
return 0;
}