1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#[allow(unused_imports)]
use statistics::stat::*;
#[allow(unused_imports)]
use structure::matrix::*;
#[allow(unused_imports)]
use structure::polynomial::*;
#[allow(unused_imports)]
use structure::vector::*;
pub fn least_square(node_x: Vector, node_y: Vector) -> Polynomial {
let l = node_x.len();
assert_eq!(l, node_y.len());
let mut x_bar = 0f64;
let mut t_bar = 0f64;
let mut xt_bar = 0f64;
let mut x_sq_bar = 0f64;
for i in 0..l {
let x = node_x[i];
let t = node_y[i];
x_bar += x;
t_bar += t;
xt_bar += x * t;
x_sq_bar += x * x;
}
x_bar /= l as f64;
t_bar /= l as f64;
xt_bar /= l as f64;
x_sq_bar /= l as f64;
let x_bar_sq = x_bar.clone() * x_bar.clone();
let x_bar_t_bar = x_bar.clone() * t_bar.clone();
let w1 = (xt_bar - x_bar_t_bar) / (x_sq_bar - x_bar_sq);
let w0 = t_bar - w1 * x_bar;
Polynomial::new(vec![w1, w0])
}