分段插值,分段二次插值,拉格朗日插值C++代码
时间: 2023-06-28 22:10:56 浏览: 272
以下是分段插值、分段二次插值和拉格朗日插值的C++代码示例:
分段插值:
```cpp
#include <iostream>
using namespace std;
int main() {
int x[] = {1, 2, 3, 4, 5}; // x 值
int y[] = {1, 4, 9, 16, 25}; // y 值
int n = 5;
int x0 = 3; // 待插值点
int i;
for (i = 0; i < n-1; i++) {
if (x[i] <= x0 && x0 <= x[i+1]) { // 找到待插值点所在区间
break;
}
}
double k = (y[i+1] - y[i]) / (double)(x[i+1] - x[i]); // 斜率
double b = y[i] - k * x[i]; // 截距
double y0 = k * x0 + b; // 插值结果
cout << "f(" << x0 << ") = " << y0 << endl; // 输出结果
return 0;
}
```
分段二次插值:
```cpp
#include <iostream>
using namespace std;
int main() {
int x[] = {1, 2, 3, 4, 5}; // x 值
int y[] = {1, 4, 9, 16, 25}; // y 值
int n = 5;
int x0 = 3; // 待插值点
int i;
for (i = 0; i < n-1; i++) {
if (x[i] <= x0 && x0 <= x[i+1]) { // 找到待插值点所在区间
break;
}
}
double k1, k2, b1, b2;
if (i == 0) { // 特判第一段
k1 = (y[i+1] - y[i]) / (double)(x[i+1] - x[i]);
b1 = y[i] - k1 * x[i];
k2 = (y[i+2] - y[i+1]) / (double)(x[i+2] - x[i+1]);
b2 = y[i+1] - k2 * x[i+1];
} else if (i == n-2) { // 特判最后一段
k1 = (y[i-1] - y[i-2]) / (double)(x[i-1] - x[i-2]);
b1 = y[i-1] - k1 * x[i-1];
k2 = (y[i] - y[i-1]) / (double)(x[i] - x[i-1]);
b2 = y[i] - k2 * x[i];
} else { // 一般情况
k1 = (y[i] - y[i-1]) / (double)(x[i] - x[i-1]);
b1 = y[i] - k1 * x[i];
k2 = (y[i+2] - y[i+1]) / (double)(x[i+2] - x[i+1]);
b2 = y[i+1] - k2 * x[i+1];
}
double a = (k2 - k1) / (double)(2 * (x[i+1] - x[i])); // 二次项系数
double b = k1 - 2 * a * x[i]; // 一次项系数
double c = y[i] - a * x[i] * x[i] - b * x[i]; // 常数项系数
double y0 = a * x0 * x0 + b * x0 + c; // 插值结果
cout << "f(" << x0 << ") = " << y0 << endl; // 输出结果
return 0;
}
```
拉格朗日插值:
```cpp
#include <iostream>
using namespace std;
int main() {
int x[] = {1, 2, 3, 4, 5}; // x 值
int y[] = {1, 4, 9, 16, 25}; // y 值
int n = 5;
int x0 = 3; // 待插值点
double y0 = 0;
for (int i = 0; i < n; i++) {
double li = 1;
for (int j = 0; j < n; j++) {
if (i != j) {
li *= (x0 - x[j]) / (double)(x[i] - x[j]);
}
}
y0 += y[i] * li;
}
cout << "f(" << x0 << ") = " << y0 << endl; // 输出结果
return 0;
}
```
阅读全文