Wrapper function to do polynomial fits with gsl I have two arrays of double, say x and y containing some physical data.
I would like to find the best-fitting polynomial function at a given order:

\$y=pol_n(x)=c_0 + c_1*x + c_2*x^2 + ... + c_n * x^n\$

and return the coefficients (\$c\$) in an std::vector. There are no constraints on the function interface. The GNU Scientific Library, gsl, contains some handy functions to properly do the maths, however those functions are in plain old C. I have encapsulated them in this piece of C++ code:

std::vector&lt;double&gt; gsl_polynomial_fit(const double * const data_x,
                                       const double * const data_y,
                                       const int n, const int order,
                                       double &amp; chisq) {
  gsl_vector *y, *c;
  gsl_matrix *X, *cov;
  y = gsl_vector_alloc (n);
  c = gsl_vector_alloc (order+1);
  X   = gsl_matrix_alloc (n, order+1);
  cov = gsl_matrix_alloc (order+1, order+1);

  for (int i = 0; i &lt; n; i++) {
    for (int j = 0; j &lt; order+1; j++) {  
      gsl_matrix_set (X, i, j, pow(data_x[i],j));
    }
    gsl_vector_set (y, i, data_y[i]);
  }

  gsl_multifit_linear_workspace * work = gsl_multifit_linear_alloc (n, order+1);
  gsl_multifit_linear (X, y, c, cov, &amp;chisq, work);
  gsl_multifit_linear_free (work);

  std::vector&lt;double&gt; vc;
  for (int i = 0; i &lt; order+1; i++) {
    vc.push_back(gsl_vector_get(c,i));
  }

  gsl_vector_free (y);
  gsl_vector_free (c);
  gsl_matrix_free (X);
  gsl_matrix_free (cov);

  return vc;
}


Although it is pretty much self-contained it doesn't look very safe. With speed and code clarity in mind, what could be done to improve it?
One issue is numerical stability. Although the GSL uses stable routines, the problem of fitting a polynomial in the monomial basis is so ill-conditioned (especially for large ranges in x and large (eg 50) degree), that you risk getting significant errors. Unless you really, really need the coefficients in this basis then I think you should use another basis, for example Legendre or Chebycheff polynomials. This will mean that any code that uses the coefficients will need to know how to do so, but the evaluation is in fact almost as efficient as evaluation in the polynomial basis.