trationals.nim 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. import std/[rationals, math]
  2. import std/assertions
  3. template main() =
  4. var
  5. z = Rational[int](num: 0, den: 1)
  6. o = initRational(num = 1, den = 1)
  7. a = initRational(1, 2)
  8. b = -1 // -2
  9. m1 = -1 // 1
  10. tt = 10 // 2
  11. doAssert a == a
  12. doAssert a - a == z
  13. doAssert a + b == o
  14. doAssert a / b == o
  15. doAssert a * b == 1 // 4
  16. doAssert 3 / a == 6 // 1
  17. doAssert a / 3 == 1 // 6
  18. doAssert tt * z == z
  19. doAssert 10 * a == tt
  20. doAssert a * 10 == tt
  21. doAssert tt / 10 == a
  22. doAssert a - m1 == 3 // 2
  23. doAssert a + m1 == -1 // 2
  24. doAssert m1 + tt == 16 // 4
  25. doAssert m1 - tt == 6 // -1
  26. doAssert z < o
  27. doAssert z <= o
  28. doAssert z == z
  29. doAssert cmp(z, o) < 0
  30. doAssert cmp(o, z) > 0
  31. doAssert o == o
  32. doAssert o >= o
  33. doAssert not(o > o)
  34. doAssert cmp(o, o) == 0
  35. doAssert cmp(z, z) == 0
  36. doAssert hash(o) == hash(o)
  37. doAssert a == b
  38. doAssert a >= b
  39. doAssert not(b > a)
  40. doAssert cmp(a, b) == 0
  41. doAssert hash(a) == hash(b)
  42. var x = 1 // 3
  43. x *= 5 // 1
  44. doAssert x == 5 // 3
  45. x += 2 // 9
  46. doAssert x == 17 // 9
  47. x -= 9 // 18
  48. doAssert x == 25 // 18
  49. x /= 1 // 2
  50. doAssert x == 50 // 18
  51. var y = 1 // 3
  52. y *= 4
  53. doAssert y == 4 // 3
  54. y += 5
  55. doAssert y == 19 // 3
  56. y -= 2
  57. doAssert y == 13 // 3
  58. y /= 9
  59. doAssert y == 13 // 27
  60. doAssert toRational(5) == 5 // 1
  61. doAssert abs(toFloat(y) - 0.4814814814814815) < 1.0e-7
  62. doAssert toInt(z) == 0
  63. when sizeof(int) == 8:
  64. doAssert toRational(0.98765432) == 2111111029 // 2137499919
  65. doAssert toRational(PI) == 817696623 // 260280919
  66. when sizeof(int) == 4:
  67. doAssert toRational(0.98765432) == 80 // 81
  68. doAssert toRational(PI) == 355 // 113
  69. doAssert toRational(0.1) == 1 // 10
  70. doAssert toRational(0.9) == 9 // 10
  71. doAssert toRational(0.0) == 0 // 1
  72. doAssert toRational(-0.25) == 1 // -4
  73. doAssert toRational(3.2) == 16 // 5
  74. doAssert toRational(0.33) == 33 // 100
  75. doAssert toRational(0.22) == 11 // 50
  76. doAssert toRational(10.0) == 10 // 1
  77. doAssert (1 // 1) div (3 // 10) == 3
  78. doAssert (-1 // 1) div (3 // 10) == -3
  79. doAssert (3 // 10) mod (1 // 1) == 3 // 10
  80. doAssert (-3 // 10) mod (1 // 1) == -3 // 10
  81. doAssert floorDiv(1 // 1, 3 // 10) == 3
  82. doAssert floorDiv(-1 // 1, 3 // 10) == -4
  83. doAssert floorMod(3 // 10, 1 // 1) == 3 // 10
  84. doAssert floorMod(-3 // 10, 1 // 1) == 7 // 10
  85. when sizeof(int) == 8:
  86. doAssert almostEqual(PI.toRational.toFloat, PI)
  87. static: main()
  88. main()