Adrià Vilanova MartÃnez | f19ea43 | 2024-01-23 20:20:52 +0100 | [diff] [blame] | 1 | // Copyright 2019 The Chromium Authors |
Copybara | 854996b | 2021-09-07 19:36:02 +0000 | [diff] [blame] | 2 | // 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. |
| 7 | export 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 | } |