random.monkey2 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. Namespace std.random
  2. Private
  3. Global state0:ULong=1234
  4. Global state1:ULong=~1234|1
  5. Function rotl:ULong( x:ULong,k:Int )
  6. Return (x Shl k) | (x Shr (64-k))
  7. End
  8. Public
  9. #rem monkeydoc Seeds the random number generator.
  10. @param seed The seed value.
  11. #end
  12. Function SeedRnd( seed:ULong )
  13. state0=seed*2|1
  14. state1=~state0|1
  15. RndULong()
  16. RndULong()
  17. End
  18. #rem monkeydoc Generates a random unsigned long value.
  19. This is the core function used by all other functions in the random namespace that generate random numbers.
  20. The algorithm currently used is 'xoroshiro128+'.
  21. @return A random unsigned long value.
  22. #end
  23. Function RndULong:ULong()
  24. Local s0:=state0
  25. Local s1:=state1
  26. s1~=s0
  27. state0=rotl( s0,55 ) ~ s1 ~ (s1 Shl 14)
  28. state1=rotl( s1,36 )
  29. return state0+state1
  30. End
  31. #rem monkeydoc Generates a random double value.
  32. When used with no parameters, returns a random double value in the range 0 (inclusive) to 1 (exclusive).
  33. When used with one parameter, returns a random double value in the range 0 (inclusive) to `max` (exclusive).
  34. When used with two parameters, returns a random double value in the range `min` (inclusive) to `max` (exclusive).
  35. @param min Minimum value to return.
  36. @param max Maximum value to return.
  37. #end
  38. Function Rnd:Double()
  39. Local x:=RndULong(),y:ULong=$3ff
  40. Local t:ULong=(y Shl 52) | (x Shr 12)
  41. Return (Cast<Double Ptr>( Varptr t ))[0]-1
  42. End
  43. Function Rnd:Double( max:Double )
  44. Return Rnd()*max
  45. End
  46. Function Rnd:Double( min:Double,max:Double )
  47. Return Rnd(max-min)+min
  48. End