tfrexp1.nim 1.4 KB

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