blob: 2208997bbc0198929953b1ceb4daa5b773438725 [file] [log] [blame]
Adrià Vilanova Martínezf19ea432024-01-23 20:20:52 +01001// Copyright 2019 The Chromium Authors
Copybara854996b2021-09-07 19:36:02 +00002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// Get parameter of generated line using linear regression formula,
6// using last n data points of values.
7export function linearRegression(values, n) {
8 let sumValues = 0;
9 let indices = 0;
10 let sqIndices = 0;
11 let multiply = 0;
12 let temp;
13 for (let i = 0; i < n; i++) {
14 temp = values[values.length-n+i];
15 sumValues += temp;
16 indices += i;
17 sqIndices += i * i;
18 multiply += i * temp;
19 }
20 // Calculate linear regression formula for values.
21 const slope = (n * multiply - sumValues * indices) /
22 (n * sqIndices - indices * indices);
23 const intercept = (sumValues * sqIndices - indices * multiply) /
24 (n * sqIndices - indices * indices);
25 return [slope, intercept];
26}