Skip to content

Instantly share code, notes, and snippets.

@tschnz
Created December 14, 2022 17:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tschnz/8070f1773b93ceb74eb3a12b2e549dbe to your computer and use it in GitHub Desktop.
Save tschnz/8070f1773b93ceb74eb3a12b2e549dbe to your computer and use it in GitHub Desktop.
Create centered & normalized 1D gaussian kernel aka normal distribution function aka probability density function
template <typename T>
T norm_pdf(T x, T mu, T sigma)
{
static const T inv_sqrt_2pi = static_cast<T>(0.3989422804014327); // Precomputed 1/sqrt(2*PI) to avoid sqrt()
T a = (x - mu) / sigma;
return inv_sqrt_2pi / sigma * std::exp(-T(0.5) * a * a);
}
template <typename T>
void generateCenteredNormPdf(std::vector<T>& density)
{
size_t n = density.size(); // Number of steps
T mu = static_cast<T>(0.0); // Mu is always 0 centered
T half_size = static_cast<T>(floor(n / 2.0)); // Half the size of our array
T sigma = static_cast<T>(half_size / 3.0); // Adjust our sigma dependent on the vector size to always stay within +/- 3 sigma
T sum = 0.0; // For normalization
T step_size = static_cast<T>(1.0); // How fast we run away from the center
for (size_t i = 0; i < n; i++)
{
density[i] = norm_pdf(static_cast<T>(step_size * (i - half_size)), mu, sigma);
sum += density[i];
}
// Make up for any energy loss during calculation (sum should already be very close to 1.0)
for (size_t j = 0; j < n; j++)
{
density[j] /= sum;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment