RandomExtensions.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using System;
  2. namespace NLangDetect.Core.Extensions
  3. {
  4. public static class RandomExtensions
  5. {
  6. private const double _Epsilon = 2.22044604925031E-15;
  7. private static readonly object _mutex = new object();
  8. private static double _nextNextGaussian;
  9. private static bool _hasNextNextGaussian;
  10. /// <summary>
  11. /// Returns the next pseudorandom, Gaussian ("normally") distributed double value with mean 0.0 and standard deviation 1.0 from this random number generator's sequence.
  12. /// The general contract of nextGaussian is that one double value, chosen from (approximately) the usual normal distribution with mean 0.0 and standard deviation 1.0, is pseudorandomly generated and returned.
  13. /// </summary>
  14. /// <remarks>
  15. /// Taken from: http://download.oracle.com/javase/6/docs/api/java/util/Random.html (nextGaussian())
  16. /// </remarks>
  17. public static double NextGaussian(this Random random)
  18. {
  19. lock (_mutex)
  20. {
  21. if (_hasNextNextGaussian)
  22. {
  23. _hasNextNextGaussian = false;
  24. return _nextNextGaussian;
  25. }
  26. double v1, v2, s;
  27. do
  28. {
  29. v1 = 2.0 * random.NextDouble() - 1.0; // between -1.0 and 1.0
  30. v2 = 2.0 * random.NextDouble() - 1.0; // between -1.0 and 1.0
  31. s = v1 * v1 + v2 * v2;
  32. }
  33. while (s >= 1.0 || Math.Abs(s - 0.0) < _Epsilon);
  34. double multiplier = Math.Sqrt(-2.0 * Math.Log(s) / s);
  35. _nextNextGaussian = v2 * multiplier;
  36. _hasNextNextGaussian = true;
  37. return v1 * multiplier;
  38. }
  39. }
  40. }
  41. }