nextafter.py 551 B

1234567891011121314151617181920212223
  1. import imp
  2. try:
  3. # if module 'numpy' exists, use it
  4. found = imp.find_module('numpy')
  5. nextafter = imp.load_module('numpy', *found).nextafter
  6. except ImportError:
  7. import math
  8. # this ad-hoc implementation won't always give the exact same result as the C implementation used by numpy, but it's good enough for our purposes
  9. def nextafter(x, y):
  10. m,e = math.frexp(x)
  11. exp = e - 53
  12. if exp < -1022 or m == 0.0:
  13. exp = -1022
  14. epsilon = math.ldexp(1.0, exp)
  15. if y > x:
  16. return x + epsilon
  17. elif y < x:
  18. return x - epsilon
  19. else:
  20. return x