trationals.nim 2.4 KB

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