trandom.nim 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. discard """
  2. action: compile
  3. """
  4. import random
  5. proc main =
  6. var occur: array[1000, int]
  7. var x = 8234
  8. for i in 0..100_000:
  9. x = rand(high(occur))
  10. inc occur[x]
  11. for i, oc in occur:
  12. if oc < 69:
  13. doAssert false, "too few occurrences of " & $i
  14. elif oc > 150:
  15. doAssert false, "too many occurrences of " & $i
  16. when false:
  17. var rs: RunningStat
  18. for j in 1..5:
  19. for i in 1 .. 1_000:
  20. rs.push(gauss())
  21. echo("mean: ", rs.mean,
  22. " stdDev: ", rs.standardDeviation(),
  23. " min: ", rs.min,
  24. " max: ", rs.max)
  25. rs.clear()
  26. var a = [0, 1]
  27. shuffle(a)
  28. doAssert a[0] == 1
  29. doAssert a[1] == 0
  30. doAssert rand(0) == 0
  31. doAssert sample("a") == 'a'
  32. when compileOption("rangeChecks"):
  33. try:
  34. discard rand(-1)
  35. doAssert false
  36. except RangeDefect:
  37. discard
  38. try:
  39. discard rand(-1.0)
  40. doAssert false
  41. except RangeDefect:
  42. discard
  43. # don't use causes integer overflow
  44. doAssert compiles(rand[int](low(int) .. high(int)))
  45. randomize(223)
  46. for i in 0 .. 10:
  47. main()