// implement the function fit_least_squares public Box<double[][], Double, Matrix> fit_least_squares(double[][] points, Function[] f) { Box<double[][], Double, Matrix> container = new Box<double[][], Double, Matrix>(); int prow = points.length; int flen = f.length; Matrix A = new Matrix(prow, flen); Matrix b = new Matrix(prow, 1); for (int i = 0; i < prow; i++) { double weight = 0.0; if (points[i].length > 2) { weight = 1.0 / points[i][2]; } else { weight = 1.0; } double val = weight * points[i][1]; b.setitem(i, 0, val); for (int j = 0; j < flen; j++) { double val2 = weight * f[j].apply(points[i][0]); A.setitem(i, j, val2); } } Matrix c = ((A.transpose().mul(A)).inverse()).mul(A.transpose().mul(b)); Matrix chi = A.mul(c).add(b.neg()); double chi2 = Math.pow(chi.norm(2), 2); double x = 1.0; Matrix fitting_f = eval_fitting_function(f, c, x); container.setT(c.as_list()); container.setU(chi2); container.setV(fitting_f); return container; }