Skip to content

Instantly share code, notes, and snippets.

@jeancroy
Created September 11, 2018 02:13
Show Gist options
  • Save jeancroy/bfca4cf12a6a20eea9c0f1aa4f2d377e to your computer and use it in GitHub Desktop.
Save jeancroy/bfca4cf12a6a20eea9c0f1aa4f2d377e to your computer and use it in GitHub Desktop.
// 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