flatten 20260225
This commit is contained in:
86
tjp/core/math/mean.hpp
Executable file
86
tjp/core/math/mean.hpp
Executable file
@@ -0,0 +1,86 @@
|
||||
//
|
||||
// Math.hpp
|
||||
// amoeba
|
||||
//
|
||||
// Created by Timothy Prepscius on 12/30/16.
|
||||
// Copyright © 2016 Timothy Prepscius. All rights reserved.
|
||||
//
|
||||
|
||||
#pragma once
|
||||
|
||||
namespace tjp::core::math {
|
||||
|
||||
template<typename T>
|
||||
struct Mean_SumDivide
|
||||
{
|
||||
T t = zero<T>();
|
||||
size_t count = 0;
|
||||
|
||||
void add(const T &v)
|
||||
{
|
||||
t = t + v;
|
||||
count++;
|
||||
}
|
||||
|
||||
T mean() const
|
||||
{
|
||||
return t / count;
|
||||
}
|
||||
};
|
||||
|
||||
// https://www.geeksforgeeks.org/program-for-average-of-an-array-without-running-into-overflow/
|
||||
template<typename T>
|
||||
struct Mean_AddDivide
|
||||
{
|
||||
T t = zero<T>();
|
||||
size_t count = 0;
|
||||
|
||||
void add(const T &v)
|
||||
{
|
||||
++count;
|
||||
t = t + (v - t) / (count);
|
||||
}
|
||||
|
||||
T mean() const
|
||||
{
|
||||
return t / count;
|
||||
}
|
||||
} ;
|
||||
|
||||
// https://www.geeksforgeeks.org/compute-average-two-numbers-without-overflow/
|
||||
template<typename T>
|
||||
struct Mean_AddDivideMod
|
||||
{
|
||||
T t = zero<T>();
|
||||
size_t count = 0;
|
||||
|
||||
void add(const T &v)
|
||||
{
|
||||
++count;
|
||||
t = t + (v - t) / (count);
|
||||
}
|
||||
|
||||
T mean() const
|
||||
{
|
||||
return t / count;
|
||||
}
|
||||
} ;
|
||||
|
||||
template<typename T, typename U>
|
||||
auto mean_(const U &u)
|
||||
{
|
||||
T t;
|
||||
for (auto &v: u)
|
||||
t.add(v);
|
||||
|
||||
return t.mean();
|
||||
}
|
||||
|
||||
template<typename U>
|
||||
auto mean(const U &u)
|
||||
{
|
||||
return mean_<Mean_SumDivide<typename U::value_type>>(u);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
Reference in New Issue
Block a user