mirror of
https://github.com/RGBCube/serenity
synced 2025-07-27 09:37:34 +00:00
AK: Add Statistics helper
This patch adds a helper to AK which allows for basic statistical analysis of values. The median algorithm is very naive and slow, but it works.
This commit is contained in:
parent
60d43d6969
commit
dcf06a4f40
1 changed files with 60 additions and 0 deletions
60
AK/Statistics.h
Normal file
60
AK/Statistics.h
Normal file
|
@ -0,0 +1,60 @@
|
||||||
|
/*
|
||||||
|
* 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(); }
|
||||||
|
|
||||||
|
// 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 {};
|
||||||
|
};
|
||||||
|
|
||||||
|
}
|
Loading…
Add table
Add a link
Reference in a new issue