C++:三次B样条插值
发现的一个可以实现三次B样条的库,可以更加专注于项目的代码实现,提高编程效率。
#include <iostream>
#include <vector>
#include <boost/math/interpolators/cubic_b_spline.hpp>
int main() {
// 给定控制点
std::vector<double> x = {1, 2, 3, 4, 5, 6, 7};
std::vector<double> y = {1, 2, 3, 4, 5, 6, 7};
// 创建三次B样条插值器
double t0 = 0; // 起始参数
double dt = 1; // 步长
auto x_interpolator = boost::math::cubic_b_spline<double>(x.begin(), x.end(), t0, dt);
auto y_interpolator = boost::math::cubic_b_spline<double>(y.begin(), y.end(), t0, dt);
// 生成100个插值点
int num_points = 100;
std::vector<std::pair<double, double>> interpolated_points;
for (int i = 0; i < num_points; ++i) {
// 均匀取值
double t = t0 + i * (static_cast<double>(x.size()-1) / (num_points - 1));
double interpolated_x = x_interpolator(t);
double interpolated_y = y_interpolator(t);
interpolated_points.emplace_back(interpolated_x, interpolated_y);
}
// 输出插值点
for (const auto& point : interpolated_points) {
std::cout << "(" << point.first << ", " << point.second << ")\n";
}
return 0;
}