1 基于C++实现线性插值
代码如下。
#include <iostream>
#include <vector>
class LinearInterpolation {
public:
void SetValues(const std::vector<double>& v1, std::vector<double>& v2);
double Interpolation(double x) const;
private:
std::vector<double> x_values;
std::vector<double> y_values;
};
void LinearInterpolation::SetValues(const std::vector<double>& v1, std::vector<double>& v2) {
x_values = v1;
y_values = v2;
}
double LinearInterpolation::Interpolation(double x) const {
double y, k;
int i = 0, n = x_values.size(), m = y_values.size();
if (n != m) {
std::cout << "Error: invalid number of points" << std::endl;
return 0.0;
}
while (i < n && x > x_values[i]) {
i++;
}
if (i == 0) {
y = y_values[0];
} else if (i == n) {
y = y_values[n - 1];
} else {
k = (y_values[i] - y_values[i - 1]) / (x_values[i] - x_values[i - 1]);
y = y_values[i - 1] + k * (x - x_values[i - 1]);
}
return y;
}
int main() {
LinearInterpolation linear_interpolation;
std::vector<double> x_data = {1.0, 3.0, 5.0, 7.0, 9.0};
std::vector<double> y_data = {2.0, 4.0, 6.0, 8.0, 10.0};
linear_interpolation.SetValues(x_data, y_data);
double x = 2.0;
double y = linear_interpolation.Interpolation(x);
std::cout << "result: " << y << std::endl;
return 0;
}
2 基于C++实现牛顿插值
代码如下。
#include <iostream>
#include <vector>
class NewtonInterpolation {
public:
void SetValues(const std::vector<double>& v1, const std::vector<d