mersenne.nim 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2015 Nim Contributors
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. type
  10. MersenneTwister* = object
  11. mt: array[0..623, uint32]
  12. index: int
  13. proc newMersenneTwister*(seed: uint32): MersenneTwister =
  14. result.index = 0
  15. result.mt[0] = seed
  16. for i in 1'u32 .. 623'u32:
  17. result.mt[i] = (0x6c078965'u32 * (result.mt[i-1] xor
  18. (result.mt[i-1] shr 30'u32)) + i)
  19. proc generateNumbers(m: var MersenneTwister) =
  20. for i in 0..623:
  21. var y = (m.mt[i] and 0x80000000'u32) +
  22. (m.mt[(i+1) mod 624] and 0x7fffffff'u32)
  23. m.mt[i] = m.mt[(i+397) mod 624] xor uint32(y shr 1'u32)
  24. if (y mod 2'u32) != 0:
  25. m.mt[i] = m.mt[i] xor 0x9908b0df'u32
  26. proc getNum*(m: var MersenneTwister): uint32 =
  27. ## Returns the next pseudo random number ranging from 0 to high(uint32)
  28. if m.index == 0:
  29. generateNumbers(m)
  30. result = m.mt[m.index]
  31. m.index = (m.index + 1) mod m.mt.len
  32. result = result xor (result shr 11'u32)
  33. result = result xor ((result shl 7'u32) and 0x9d2c5680'u32)
  34. result = result xor ((result shl 15'u32) and 0xefc60000'u32)
  35. result = result xor (result shr 18'u32)
  36. # Test
  37. when not defined(testing) and isMainModule:
  38. var mt = newMersenneTwister(2525)
  39. for i in 0..99:
  40. echo mt.getNum