92 lines
2.1 KiB
C++
92 lines
2.1 KiB
C++
/*
|
||
* © 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 NORMAL_H
|
||
#define NORMAL_H
|
||
|
||
#include <cmath>
|
||
#include <random>
|
||
#include "../random/RandomGenerator.h"
|
||
#include "../../Assertions.h"
|
||
|
||
namespace Distribution {
|
||
|
||
/** normal distribution */
|
||
template <typename T> class Normal {
|
||
|
||
private:
|
||
|
||
const T mu;
|
||
const T sigma;
|
||
const T _a;
|
||
|
||
Random::RandomGenerator gen;
|
||
std::normal_distribution<T> dist;
|
||
|
||
public:
|
||
|
||
/** ctor */
|
||
Normal(const T mu, const T sigma) :
|
||
mu(mu), sigma(sigma), _a(1.0 / (sigma * std::sqrt(2.0 * M_PI))), gen(RANDOM_SEED), dist(mu,sigma) {
|
||
}
|
||
|
||
/** ctor with seed */
|
||
Normal(const T mu, const T sigma, const uint32_t seed) :
|
||
mu(mu), sigma(sigma), _a(1.0 / (sigma * std::sqrt(2.0 * M_PI))), gen(seed), dist(mu,sigma) {
|
||
}
|
||
|
||
/** mu = 0, sigma = 1 */
|
||
static Normal unit() {
|
||
return Normal(0,1);
|
||
}
|
||
|
||
/** do not allow copy. this will not work as expected for std::normal_distribution when using draw() ?! */
|
||
//Normal(const Normal& o) = delete;
|
||
|
||
/** get probability for the given value */
|
||
T getProbability(const T val) const {
|
||
const T b = -0.5 * ((val-mu)/sigma) * ((val-mu)/sigma);
|
||
return _a * std::exp(b);
|
||
}
|
||
|
||
/** get a normally distributed random number */
|
||
T draw() {
|
||
return dist(gen);
|
||
}
|
||
|
||
/** set the seed to use */
|
||
void setSeed(const long seed) {
|
||
gen.seed(seed);
|
||
}
|
||
|
||
/** get the mean value */
|
||
const T getMu() {
|
||
return this->mu;
|
||
}
|
||
|
||
/** get the standard deviation */
|
||
const T getSigma() {
|
||
return this->sigma;
|
||
}
|
||
|
||
/** get the probability for the given value */
|
||
static T getProbability(const T mu, const T sigma, const T val) {
|
||
Assert::isTrue(sigma > 0, "sigma must be >= 0");
|
||
const T a = 1.0 / (sigma * std::sqrt(2.0 * M_PI));
|
||
const T b = -0.5 * ((val-mu)/sigma) * ((val-mu)/sigma);
|
||
return a * std::exp(b);
|
||
}
|
||
|
||
};
|
||
|
||
}
|
||
|
||
#endif // NORMAL_H
|