fixed issues with random walks
This commit is contained in:
94
math/stats/Histogram.h
Normal file
94
math/stats/Histogram.h
Normal file
@@ -0,0 +1,94 @@
|
||||
#ifndef STATS_HISTOGRAM_H
|
||||
#define STATS_HISTOGRAM_H
|
||||
|
||||
#define WITH_DEBUG_PLOT
|
||||
|
||||
#ifdef WITH_DEBUG_PLOT
|
||||
#include <KLib/misc/gnuplot/Gnuplot.h>
|
||||
#include <KLib/misc/gnuplot/GnuplotPlot.h>
|
||||
#include <KLib/misc/gnuplot/GnuplotPlotElementLines.h>
|
||||
#endif
|
||||
|
||||
#include <vector>
|
||||
|
||||
namespace Stats {
|
||||
|
||||
template <typename Scalar> class Histogram {
|
||||
|
||||
#ifdef WITH_DEBUG_PLOT
|
||||
K::Gnuplot gp;
|
||||
K::GnuplotPlot plot;
|
||||
K::GnuplotPlotElementLines lines;
|
||||
#endif
|
||||
|
||||
Scalar min;
|
||||
Scalar max;
|
||||
int bins;
|
||||
int cnt = 0;
|
||||
|
||||
std::vector<Scalar> counts;
|
||||
|
||||
public:
|
||||
|
||||
/** ctor */
|
||||
Histogram(Scalar min, Scalar max, int bins) : min(min), max(max), bins(bins) {
|
||||
|
||||
clear();
|
||||
|
||||
#ifdef WITH_DEBUG_PLOT
|
||||
plot.add(&lines);
|
||||
#endif
|
||||
|
||||
}
|
||||
|
||||
int count() const {
|
||||
return cnt;
|
||||
}
|
||||
|
||||
void add(const Scalar x) {
|
||||
const int idx = binIdx(x);
|
||||
counts.at(idx) += 1;
|
||||
++cnt;
|
||||
if (cnt % 200 == 0) {showPlot();}
|
||||
}
|
||||
|
||||
void clear() {
|
||||
counts.clear();
|
||||
counts.resize(bins);
|
||||
cnt = 0;
|
||||
}
|
||||
|
||||
#ifdef WITH_DEBUG_PLOT
|
||||
void showPlot() {
|
||||
|
||||
lines.clear();
|
||||
|
||||
lines.add(K::GnuplotPoint2(-1,0));
|
||||
for (size_t idx = 0; idx < counts.size(); ++idx) {
|
||||
const Scalar val = binValue(idx);
|
||||
const Scalar sum = counts[idx];
|
||||
const K::GnuplotPoint2 gp2(val, sum);
|
||||
lines.add(gp2);
|
||||
}
|
||||
|
||||
gp.draw(plot);
|
||||
gp.flush();
|
||||
|
||||
}
|
||||
#endif
|
||||
|
||||
private:
|
||||
|
||||
int binIdx(const Scalar val) const {
|
||||
return (val - min) / (max-min) * bins;
|
||||
}
|
||||
|
||||
Scalar binValue(const int idx) {
|
||||
return idx * (max-min) + min;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif // STATS_HISTOGRAM_H
|
||||
Reference in New Issue
Block a user