normal.h 918 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. #pragma once
  2. #include <cmath>
  3. // sometimes we need stateless normal distribution...
  4. /*
  5. * normal distribution with Box-Muller transform
  6. * http://www.design.caltech.edu/erik/Misc/Gaussian.html
  7. */
  8. template <typename T, typename TRng>
  9. static inline T StdNormalDistribution(TRng&& rng) noexcept {
  10. T x;
  11. T y;
  12. T r;
  13. do {
  14. x = (T)rng.GenRandReal1() * T(2) - T(1);
  15. y = (T)rng.GenRandReal1() * T(2) - T(1);
  16. r = x * x + y * y;
  17. } while (r > T(1) || r <= T(0));
  18. return x * std::sqrt(-T(2) * std::log(r) / r);
  19. }
  20. template <typename T, typename TRng>
  21. static inline T NormalDistribution(TRng&& rng, T m, T d) noexcept {
  22. return StdNormalDistribution<T>(rng) * d + m;
  23. }
  24. // specialized for float, double, long double
  25. template <class T>
  26. T StdNormalRandom() noexcept;
  27. template <class T>
  28. static inline T NormalRandom(T m, T d) noexcept {
  29. return StdNormalRandom<T>() * d + m;
  30. }