25template <
typename X,
typename Y,
typename W =
double>
27 const std::vector<X>& x,
const std::vector<Y>& y, std::vector<W> w = {})
29 assert(x.size() == y.size() && (w.empty() || w.size() == y.size()));
31 w = std::vector<W>(y.size(), 1);
34 const double xwMean = std::inner_product(x.begin(), x.end(), w.begin(), 0.) /
35 std::accumulate(w.begin(), w.end(), 0.);
36 const double ywMean = std::inner_product(y.begin(), y.end(), w.begin(), 0.) /
37 std::accumulate(w.begin(), w.end(), 0.);
40 const double numerator = std::inner_product(
41 x.begin(), x.end(), y.begin(), 0., std::plus<>(),
42 [&](X xi, Y yi) { return w[n++] * (xi - xwMean) * (yi - ywMean); });
45 const double denominator = std::inner_product(
46 x.begin(), x.end(), x.begin(), 0., std::plus<>(),
47 [&](X xi, X) { return w[n++] * (xi - xwMean) * (xi - xwMean); });
50 const double a = numerator / denominator;
51 const double b = ywMean - a * xwMean;
53 return std::make_pair(a, b);
std::pair< double, double > LinearFit(const std::vector< X > &x, const std::vector< Y > &y, std::vector< W > w={})
Linear least-square fit of a set of points y located at x, with optional weights w.