Alexandria 2.31.0
SDC-CH common library for the Euclid project
Loading...
Searching...
No Matches
LinearRegression.cpp
Go to the documentation of this file.
1/*
2 * Copyright (C) 2012-2021 Euclid Science Ground Segment
3 *
4 * This library is free software; you can redistribute it and/or modify it under
5 * the terms of the GNU Lesser General Public License as published by the Free
6 * Software Foundation; either version 3.0 of the License, or (at your option)
7 * any later version.
8 *
9 * This library is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
12 * details.
13 *
14 * You should have received a copy of the GNU Lesser General Public License
15 * along with this library; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17 */
18
21
22namespace Euclid {
23namespace MathUtils {
24
26 if (x.size() != y.size()) {
27 throw Elements::Exception("linearRegression: x and y vectors must have the same size");
28 }
29 if (x.empty()) {
30 throw Elements::Exception("linearRegression: Can not do a regression over empty vectors");
31 }
32
33 double mean_x = 0;
34 double mean_y = 0;
35
36 for (std::size_t index = 0; index < x.size(); ++index) {
37 mean_x += x[index];
38 mean_y += y[index];
39 }
40
41 mean_x /= static_cast<double>(x.size());
42 mean_y /= static_cast<double>(x.size());
43
44 double nom = 0.0;
45 double denom = 0.0;
46 for (std::size_t index = 0; index < x.size(); ++index) {
47 nom += (x[index] - mean_x) * (y[index] - mean_y);
48 denom += (x[index] - mean_x) * (x[index] - mean_x);
49 }
50
51 double a = nom / denom;
52 double b = mean_y - a * mean_x;
53
54 return std::make_pair(a, b);
55}
56
57} // namespace MathUtils
58} // namespace Euclid
T empty(T... args)
T make_pair(T... args)
std::pair< double, double > linearRegression(const std::vector< double > &x, const std::vector< double > &y)
std::array< std::vector< double >, N > Coordinates
Used to pass the grid coordinates to interpn. Internally will make a copy of the required values.
T size(T... args)