Created
September 11, 2018 02:13
-
-
Save jeancroy/bfca4cf12a6a20eea9c0f1aa4f2d377e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Sample from a normal distribution, truncated between -1 and 1 | |
double MultiObjectiveCompactDifferentialEvolution::sampleValue(double mu, double sigma) { | |
if (sigma < 1e-8) // Should avoid infinity error below | |
return mu; | |
try { | |
double sqrt2Sigma = SQRT_2 * sigma; | |
double erfMuNeg = boost::math::erf((mu - 1) / sqrt2Sigma); | |
double erfMuPlus = boost::math::erf((mu + 1) / sqrt2Sigma); | |
double u = randreal(); | |
double C = - boost::math::erf((mu + 1) / sqrt2Sigma) / (erfMuNeg - erfMuPlus); | |
return mu - sqrt2Sigma * boost::math::erf_inv((u - C) * (erfMuNeg - erfMuPlus)); | |
} catch (exception& e) { | |
cerr << "ERROR: Sampling method failed! mu: " << mu << ", sigma: " << sigma << ". Got: " << e.what() << endl; | |
} | |
return mu; // Safer guess | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How to generate normal number inside [a,b[ ?
The basic idea is to generate a Gaussian number, test interval and retry.
This will break under 2 conditions:
To address (1) we need a process able to generate random number that's aware of [a,b]
To get there we flip the role, 1st we generate a uniform number inside [a,b] then reject if inconsistent with normal statistics.
To address (2) we'll use an algorithm used to simulate tail. (therefore whether [a,b[ pass by the mean will be an important question)
Some algorithm use both a and b to scale the problem, those are slower but uniform in speed & still faster than blind luck.
Some will generate from [a,inf[ then check b after the fact, where that strategy work they can be the fastest (but it'll still fail if too narrow)