This repository has been archived on 2020-04-08. You can view files and clone it, but cannot push or open issues or pull requests.
Files
Indoor/math/distribution/LUT.h
2018-10-25 11:50:12 +02:00

93 lines
2.0 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
* © Copyright 2014 Urheberrechtshinweis
* Alle Rechte vorbehalten / All Rights Reserved
*
* Programmcode ist urheberrechtlich geschuetzt.
* Das Urheberrecht liegt, soweit nicht ausdruecklich anders gekennzeichnet, bei Frank Ebner.
* Keine Verwendung ohne explizite Genehmigung.
* (vgl. § 106 ff UrhG / § 97 UrhG)
*/
#ifndef LUT_H
#define LUT_H
#include <vector>
#include "../Math.h"
#include "../DrawList.h"
namespace Distribution {
template <typename Scalar> class LUT {
private:
Scalar min;
Scalar max;
Scalar diff;
/** number of samples between min and max */
int numSamples;
/** the look-up-table */
std::vector<Scalar> samples;
public:
/** ctor */
template <typename Distribution> LUT(const Distribution dist, const Scalar min, const Scalar max, const int numSamples) :
min(min), max(max), diff(max-min), numSamples(numSamples) {
buildLUT(dist);
}
/** get the probability of val from the LUT */
Scalar getProbability(const Scalar val) const {
int idx = ((val - min) * numSamples / diff);
idx = Math::clamp(0, numSamples-1, idx);
return samples[idx];
}
/** get a DrawList for this LUT to draw random values out of it */
DrawList<Scalar> getDrawList() {
DrawList<Scalar> dl;
for (int idx = 0; idx < (int) samples.size(); ++idx) {
const Scalar val = idxToVal(idx);
const Scalar prob = samples[idx];
dl.add(val, prob);
}
return dl;
}
protected:
/** convert value [min:max] to index [0:numSamples] */
inline int valToIdx(const Scalar val) const {
return ((val - min) * numSamples / diff);
}
/** convert index [0:numSamples] to value [min:max] */
inline Scalar idxToVal(const int idx) const {
return min + (idx * diff / numSamples);
}
private:
/** build the look-up-table */
template <typename Distribution> void buildLUT(const Distribution dist) {
samples.resize(numSamples);
for (int idx = 0; idx < numSamples; ++idx) {
const Scalar val = min + (idx * diff / numSamples);
samples[idx] = dist.getProbability(val);
}
}
};
}
#endif // LUT_H