hash(self)
(self)
| 643 | return Fraction(round(self / shift) * shift) |
| 644 | |
| 645 | def __hash__(self): |
| 646 | """hash(self)""" |
| 647 | |
| 648 | # To make sure that the hash of a Fraction agrees with the hash |
| 649 | # of a numerically equal integer, float or Decimal instance, we |
| 650 | # follow the rules for numeric hashes outlined in the |
| 651 | # documentation. (See library docs, 'Built-in Types'). |
| 652 | |
| 653 | try: |
| 654 | dinv = pow(self._denominator, -1, _PyHASH_MODULUS) |
| 655 | except ValueError: |
| 656 | # ValueError means there is no modular inverse. |
| 657 | hash_ = _PyHASH_INF |
| 658 | else: |
| 659 | # The general algorithm now specifies that the absolute value of |
| 660 | # the hash is |
| 661 | # (|N| * dinv) % P |
| 662 | # where N is self._numerator and P is _PyHASH_MODULUS. That's |
| 663 | # optimized here in two ways: first, for a non-negative int i, |
| 664 | # hash(i) == i % P, but the int hash implementation doesn't need |
| 665 | # to divide, and is faster than doing % P explicitly. So we do |
| 666 | # hash(|N| * dinv) |
| 667 | # instead. Second, N is unbounded, so its product with dinv may |
| 668 | # be arbitrarily expensive to compute. The final answer is the |
| 669 | # same if we use the bounded |N| % P instead, which can again |
| 670 | # be done with an int hash() call. If 0 <= i < P, hash(i) == i, |
| 671 | # so this nested hash() call wastes a bit of time making a |
| 672 | # redundant copy when |N| < P, but can save an arbitrarily large |
| 673 | # amount of computation for large |N|. |
| 674 | hash_ = hash(hash(abs(self._numerator)) * dinv) |
| 675 | result = hash_ if self._numerator >= 0 else -hash_ |
| 676 | return -2 if result == -1 else result |
| 677 | |
| 678 | def __eq__(a, b): |
| 679 | """a == b""" |