13#include <gsl/gsl_multifit.h>
21class ChebyshevPolyFitImpl {
23 explicit ChebyshevPolyFitImpl(
const size_t order) : m_order(order) {}
25 std::vector<double> fit(
const std::vector<double> &x,
const std::vector<double> &y,
const std::vector<double> &w);
35std::vector<double> ChebyshevPolyFitImpl::fit(
const std::vector<double> &
x,
const std::vector<double> &
y,
36 const std::vector<double> &w) {
37 assert(
x.size() ==
y.size());
38 assert(
y.size() == w.size());
40 const size_t npts(
y.size()), degp1(m_order + 1);
41 const double xmin(
x.front()), xmax(
x.back());
45 gsl_matrix *MX = gsl_matrix_alloc(npts, degp1);
46 auto *yw = gsl_vector_alloc(npts);
47 ChebyshevPolynomial chebyp;
48 for (
size_t i = 0; i < npts; ++i) {
51 const auto xbar = ((xi - xmin) - (xmax - xi)) / (xmax - xmin);
52 gsl_vector_set(yw, i, wi *
y[i]);
53 for (
size_t j = 0; j < degp1; ++j) {
54 gsl_matrix_set(MX, i, j, wi * chebyp(j, xbar));
59 auto *c = gsl_vector_alloc(degp1);
60 auto *cov = gsl_matrix_alloc(degp1, degp1);
61 auto *work = gsl_multifit_linear_alloc(npts, degp1);
63 gsl_multifit_linear(MX, yw, c, cov, &chisq, work);
67 gsl_multifit_linear_free(work);
69 std::vector<double> coeffs(c->data, c->data + degp1);
102 const std::vector<double> &wgts) {
103 return m_impl->fit(xs, ys, wgts);
~ChebyshevPolyFit()
Destructor.
std::vector< double > operator()(const std::vector< double > &xs, const std::vector< double > &ys, const std::vector< double > &wgts)
Find coefficients of polynomial that minimizes the sum of the squares of the residuals: e_r = w_r(y_r...
ChebyshevPolyFit(const size_t n)
Constructor.
std::unique_ptr< ChebyshevPolyFitImpl > m_impl