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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
use std::fmt::Display;

/// 样本偏差值
pub fn stdev<T: Display + std::fmt::Debug>(array: Vec<T>) -> f64 {
    let len = array.len();
    if len <= 1 {
        return 0.0;
    }
    let mut total = 0.0;
    let mut values = vec![];
    for item in array {
        let value = item.to_string().parse::<f64>().unwrap();
        values.push(value);
        total += value;
    }
    let mean = total / len.to_string().parse::<f64>().unwrap();
    total = 0.0;
    let _: Vec<f64> = values.iter_mut().map(|val| {
        let t = (*val - mean).powi(2);
        total += t;
        t
    }).collect();
    (total / (len - 1) as f64).sqrt()
}

/// 样本标准差 (n)
pub fn stdevp<T: Display + std::fmt::Debug>(array: Vec<T>) -> f64 {
    let len = array.len();
    if len <= 1 {
        return 0.0;
    }
    let mut total = 0.0;
    let mut values = vec![];
    for item in array {
        let value = item.to_string().parse::<f64>().unwrap();
        values.push(value);
        total += value;
    }
    let mean = total / len.to_string().parse::<f64>().unwrap();
    total = 0.0;
    let _: Vec<f64> = values.iter_mut().map(|val| {
        let t = (*val - mean).powi(2);
        total += t;
        t
    }).collect();
    (total / (len) as f64).sqrt()
}

/// 方差 变差 (n-1)
pub fn variance(array: Vec<f64>) -> f64 {
    let len = array.len();
    if len <= 1 {
        return 0.0;
    }
    let mut total = 0.0;
    for item in array.clone() {
        total += item;
    }
    let mean = total / len.to_string().parse::<f64>().unwrap();
    total = 0.0;
    for item in array {
        let t = (item - mean).powi(2);
        total += t;
    }
    total / (len - 1) as f64
}

/// 方差 变差 (n)
pub fn variancep(array: Vec<f64>) -> f64 {
    let len = array.len();
    if len <= 1 {
        return 0.0;
    }
    let mut total = 0.0;
    for item in array.clone() {
        total += item;
    }
    let mean = total / len.to_string().parse::<f64>().unwrap();
    total = 0.0;
    for item in array {
        let t = (item - mean).powi(2);
        total += t;
    }
    total / (len) as f64
}