tfrexp1.nim 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. discard """
  2. matrix: "--mm:refc; --mm:orc"
  3. targets: "js c cpp"
  4. """
  5. import std/math
  6. import std/assertions
  7. const manualTest = false
  8. when manualTest:
  9. import strformat
  10. proc frexp_test(lo, hi, step: float64) =
  11. var exp: int
  12. var frac: float64
  13. var eps = 1e-15.float64
  14. var x:float64 = lo
  15. while x <= hi:
  16. frac = frexp(x.float, exp)
  17. let rslt = pow(2.0, float(exp)) * frac
  18. doAssert(abs(rslt - x) < eps)
  19. when manualTest:
  20. echo fmt("x: {x:10.3f} exp: {exp:4d} frac: {frac:24.20f} check: {$(abs(rslt - x) < eps):-5s} {rslt: 9.3f}")
  21. x += step
  22. when manualTest:
  23. var exp: int
  24. var frac: float64
  25. for flval in [1.7976931348623157e+308, -1.7976931348623157e+308, # max, min float64
  26. 3.4028234663852886e+38, -3.4028234663852886e+38, # max, min float32
  27. 4.9406564584124654e-324, -4.9406564584124654e-324, # smallest/largest positive/negative float64
  28. 1.4012984643248171e-45, -1.4012984643248171e-45, # smallest/largest positive/negative float32
  29. 2.2250738585072014e-308, 1.1754943508222875e-38]: # smallest normal float64/float32
  30. frac = frexp(flval, exp)
  31. echo fmt("{flval:25.16e}, {exp: 6d}, {frac: .20f} {frac * pow(2.0, float(exp)): .20e}")
  32. frexp_test(-1000.0, 1000.0, 0.0125)
  33. else:
  34. frexp_test(-200000.0, 200000.0, 0.125)
  35. doAssert frexp(8.0) == (0.5, 4)
  36. doAssert frexp(-8.0) == (-0.5, 4)
  37. doAssert frexp(0.0) == (0.0, 0)
  38. block:
  39. var x: int
  40. doAssert frexp(5.0, x) == 0.625
  41. doAssert x == 3