random.monkey2 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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=1
  8. Global state1:ULong=2
  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+ULong( 1 )
  16. End
  17. #rem monkeydoc Generates a random unsigned long value.
  18. This is the core function used by all other functions in the random namespace that generate random numbers.
  19. @return A random unsigned long value.
  20. #end
  21. Function RndULong:ULong()
  22. Local s1:=state0
  23. Local s0:=state1
  24. state0=s0
  25. s1~=s1 Shl 23
  26. s1~=s1 Shr 17
  27. s1~=s0
  28. s1~=s0 Shr 26
  29. state1=s1
  30. Return s1+s0
  31. End
  32. #rem monkeydoc Generates a random double value.
  33. When used with no parameters, returns a random double value in the range 0 (inclusive) to 1 (exclusive).
  34. When used with one parameter, returns a random double value in the range 0 (inclusive) to `max` (exclusive).
  35. When used with two parameters, returns a random double value in the range `min` (inclusive) to `max` (exclusive).
  36. @param min Minimum value to return.
  37. @param max Maximum value to return.
  38. #end
  39. Function Rnd:Double()
  40. Return Double( RndULong() & ULong( $1fffffffffffff ) ) / Double( $20000000000000 )
  41. End
  42. Function Rnd:Double( max:Double )
  43. Return Rnd()*max
  44. End
  45. Function Rnd:Double( min:Double,max:Double )
  46. Return Rnd(max-min)+min
  47. End