blob: a74400fb05e7f5e193ad44da620006e339234e4a (
plain)
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
|
/*
* Copyright (c) 2021, Tobias Christiansen <tobyase@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/Math.h>
#include <AK/QuickSort.h>
#include <AK/StdLibExtraDetails.h>
#include <AK/Vector.h>
namespace AK {
template<typename T = float>
requires(IsArithmetic<T>) class Statistics {
public:
Statistics() = default;
~Statistics() = default;
void add(T const& value)
{
// FIXME: Check for an overflow
m_sum += value;
m_values.append(value);
}
T const sum() const { return m_sum; }
float average() const { return (float)sum() / size(); }
T const min() const
{
T minimum = m_values[0];
for (T number : values()) {
if (number < minimum) {
minimum = number;
}
}
return minimum;
}
T const max() const
{
T maximum = m_values[0];
for (T number : values()) {
if (number > maximum) {
maximum = number;
}
}
return maximum;
}
// FIXME: Implement a better algorithm
T const median()
{
quick_sort(m_values);
return m_values.at(size() / 2);
}
float standard_deviation() const { return sqrt(variance()); }
float variance() const
{
float summation = 0;
float avg = average();
for (T number : values()) {
float difference = (float)number - avg;
summation += (difference * difference);
}
summation = summation / size();
return summation;
}
Vector<T> const& values() const { return m_values; }
size_t size() const { return m_values.size(); }
private:
Vector<T> m_values;
T m_sum {};
};
}
|