插值法是一种数学方法,用于通过已知的离散数据点来估计未知的连续函数值。在C++中,可以使用以下代码实现插值法:
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
double interpolate(double x, vector<double>& x_values, vector<double>& y_values) {
int n = x_values.size();
if (n == 0) {
return NAN; // No interpolation possible
}
int lower = 0, upper = n - 1;
while (lower <= upper) {
int i = lower + (upper - lower) / 2;
if (x_values[i] == x) {
return y_values[i]; // Exact match
} else if (x_values[i] < x) {
lower = i + 1; // Search in the right half
} else {
upper = i - 1; // Search in the left half
}
}
// Interpolate between the two closest points
int i = lower - 1;
int j = lower;
double alpha = (x - x_value