floats.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. # coding=utf-8
  2. #
  3. # This file is part of Hypothesis, which may be found at
  4. # https://github.com/HypothesisWorks/hypothesis-python
  5. #
  6. # Most of this work is copyright (C) 2013-2018 David R. MacIver
  7. # (david@drmaciver.com), but it contains contributions by others. See
  8. # CONTRIBUTING.rst for a full list of people who may hold copyright, and
  9. # consult the git log if you need to determine who owns an individual
  10. # contribution.
  11. #
  12. # This Source Code Form is subject to the terms of the Mozilla Public License,
  13. # v. 2.0. If a copy of the MPL was not distributed with this file, You can
  14. # obtain one at http://mozilla.org/MPL/2.0/.
  15. #
  16. # END HEADER
  17. from __future__ import division, print_function, absolute_import
  18. import math
  19. from hypothesis.internal.compat import struct_pack, struct_unpack
  20. def sign(x):
  21. try:
  22. return math.copysign(1.0, x)
  23. except TypeError:
  24. raise TypeError('Expected float but got %r of type %s' % (
  25. x, type(x).__name__
  26. ))
  27. def is_negative(x):
  28. return sign(x) < 0
  29. def count_between_floats(x, y):
  30. assert x <= y
  31. if is_negative(x):
  32. if is_negative(y):
  33. return float_to_int(x) - float_to_int(y) + 1
  34. else:
  35. return count_between_floats(x, -0.0) + count_between_floats(0.0, y)
  36. else:
  37. assert not is_negative(y)
  38. return float_to_int(y) - float_to_int(x) + 1
  39. def float_to_int(value):
  40. return (
  41. struct_unpack(b'!Q', struct_pack(b'!d', value))[0]
  42. )
  43. def int_to_float(value):
  44. return (
  45. struct_unpack(b'!d', struct_pack(b'!Q', value))[0]
  46. )