Audacity 3.2.0
Functions
LinearFit.h File Reference
#include <cassert>
#include <numeric>
#include <utility>
#include <vector>
Include dependency graph for LinearFit.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

template<typename X , typename Y , typename W = double>
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. More...
 

Function Documentation

◆ LinearFit()

template<typename X , typename Y , typename W = double>
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.


Audacity: A Digital Audio Editor

LinearFit.h

Matthieu Hodgkinson

Precondition
x and y have equal size
w is empty or has the same size as x and y

Definition at line 26 of file LinearFit.h.

27 {})
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}

Referenced by TEST_CASE().

Here is the caller graph for this function: