Audacity 3.2.0
LinearFit.h
Go to the documentation of this file.
1/* SPDX-License-Identifier: GPL-2.0-or-later */
2/*!********************************************************************
3
4 Audacity: A Digital Audio Editor
5
6 LinearFit.h
7
8 Matthieu Hodgkinson
9
10**********************************************************************/
11
12#pragma once
13#include <cassert>
14#include <numeric>
15#include <utility>
16#include <vector>
17
25template <typename X, typename Y, typename W = double>
26std::pair<double, double> LinearFit(
27 const std::vector<X>& x, const std::vector<Y>& y, std::vector<W> w = {})
28{
29 assert(x.size() == y.size() && (w.empty() || w.size() == y.size()));
30 if (w.empty())
31 w = std::vector<W>(y.size(), 1);
32
33 // Calculate weighted means
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.);
38
39 auto n = 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); });
43
44 n = 0;
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); });
48
49 // Calculate slope (a) and intercept (b)
50 const double a = numerator / denominator;
51 const double b = ywMean - a * xwMean;
52
53 return std::make_pair(a, b);
54}
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.
Definition: LinearFit.h:26