random.monkey2 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. Namespace std.random
  2. #rem
  3. Random number generator is based on the xorshift128plus:
  4. https://en.wikipedia.org/wiki/Xorshift
  5. #end
  6. Private
  7. Global state0:ULong=1234
  8. Global state1:ULong=5678
  9. Public
  10. #rem monkeydoc Seeds the random number generator.
  11. @param seed The seed value.
  12. #end
  13. Function SeedRnd( seed:ULong )
  14. state0=seed
  15. state1=seed
  16. RndULong()
  17. RndULong()
  18. End
  19. #rem monkeydoc Generates a random unsigned long value.
  20. This is the core function used by all other functions in the random namespace that generate random numbers.
  21. @return A random unsigned long value.
  22. #end
  23. Function RndULong:ULong()
  24. Local s1:=state0
  25. Local s0:=state1
  26. state0=s0
  27. s1~=s1 Shl 23
  28. s1~=s1 Shr 17
  29. s1~=s0
  30. s1~=s0 Shr 26
  31. state1=s1
  32. Return s1+s0
  33. End
  34. #rem monkeydoc Generates a random double value.
  35. When used with no parameters, returns a random double value in the range 0 (inclusive) to 1 (exclusive).
  36. When used with one parameter, returns a random double value in the range 0 (inclusive) to `max` (exclusive).
  37. When used with two parameters, returns a random double value in the range `min` (inclusive) to `max` (exclusive).
  38. @param min Minimum value to return.
  39. @param max Maximum value to return.
  40. #end
  41. Function Rnd:Double()
  42. Return Double( RndULong() & ULong( $1fffffffffffff ) ) / Double( $20000000000000 )
  43. End
  44. Function Rnd:Double( max:Double )
  45. Return Rnd()*max
  46. End
  47. Function Rnd:Double( min:Double,max:Double )
  48. Return Rnd(max-min)+min
  49. End