fractions.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  1. # Originally contributed by Sjoerd Mullender.
  2. # Significantly modified by Jeffrey Yasskin <jyasskin at gmail.com>.
  3. """Fraction, infinite-precision, rational numbers."""
  4. from decimal import Decimal
  5. import math
  6. import numbers
  7. import operator
  8. import re
  9. import sys
  10. __all__ = ['Fraction']
  11. # Constants related to the hash implementation; hash(x) is based
  12. # on the reduction of x modulo the prime _PyHASH_MODULUS.
  13. _PyHASH_MODULUS = sys.hash_info.modulus
  14. # Value to be used for rationals that reduce to infinity modulo
  15. # _PyHASH_MODULUS.
  16. _PyHASH_INF = sys.hash_info.inf
  17. _RATIONAL_FORMAT = re.compile(r"""
  18. \A\s* # optional whitespace at the start,
  19. (?P<sign>[-+]?) # an optional sign, then
  20. (?=\d|\.\d) # lookahead for digit or .digit
  21. (?P<num>\d*|\d+(_\d+)*) # numerator (possibly empty)
  22. (?: # followed by
  23. (?:/(?P<denom>\d+(_\d+)*))? # an optional denominator
  24. | # or
  25. (?:\.(?P<decimal>d*|\d+(_\d+)*))? # an optional fractional part
  26. (?:E(?P<exp>[-+]?\d+(_\d+)*))? # and optional exponent
  27. )
  28. \s*\Z # and optional whitespace to finish
  29. """, re.VERBOSE | re.IGNORECASE)
  30. class Fraction(numbers.Rational):
  31. """This class implements rational numbers.
  32. In the two-argument form of the constructor, Fraction(8, 6) will
  33. produce a rational number equivalent to 4/3. Both arguments must
  34. be Rational. The numerator defaults to 0 and the denominator
  35. defaults to 1 so that Fraction(3) == 3 and Fraction() == 0.
  36. Fractions can also be constructed from:
  37. - numeric strings similar to those accepted by the
  38. float constructor (for example, '-2.3' or '1e10')
  39. - strings of the form '123/456'
  40. - float and Decimal instances
  41. - other Rational instances (including integers)
  42. """
  43. __slots__ = ('_numerator', '_denominator')
  44. # We're immutable, so use __new__ not __init__
  45. def __new__(cls, numerator=0, denominator=None, *, _normalize=True):
  46. """Constructs a Rational.
  47. Takes a string like '3/2' or '1.5', another Rational instance, a
  48. numerator/denominator pair, or a float.
  49. Examples
  50. --------
  51. >>> Fraction(10, -8)
  52. Fraction(-5, 4)
  53. >>> Fraction(Fraction(1, 7), 5)
  54. Fraction(1, 35)
  55. >>> Fraction(Fraction(1, 7), Fraction(2, 3))
  56. Fraction(3, 14)
  57. >>> Fraction('314')
  58. Fraction(314, 1)
  59. >>> Fraction('-35/4')
  60. Fraction(-35, 4)
  61. >>> Fraction('3.1415') # conversion from numeric string
  62. Fraction(6283, 2000)
  63. >>> Fraction('-47e-2') # string may include a decimal exponent
  64. Fraction(-47, 100)
  65. >>> Fraction(1.47) # direct construction from float (exact conversion)
  66. Fraction(6620291452234629, 4503599627370496)
  67. >>> Fraction(2.25)
  68. Fraction(9, 4)
  69. >>> Fraction(Decimal('1.47'))
  70. Fraction(147, 100)
  71. """
  72. self = super(Fraction, cls).__new__(cls)
  73. if denominator is None:
  74. if type(numerator) is int:
  75. self._numerator = numerator
  76. self._denominator = 1
  77. return self
  78. elif isinstance(numerator, numbers.Rational):
  79. self._numerator = numerator.numerator
  80. self._denominator = numerator.denominator
  81. return self
  82. elif isinstance(numerator, (float, Decimal)):
  83. # Exact conversion
  84. self._numerator, self._denominator = numerator.as_integer_ratio()
  85. return self
  86. elif isinstance(numerator, str):
  87. # Handle construction from strings.
  88. m = _RATIONAL_FORMAT.match(numerator)
  89. if m is None:
  90. raise ValueError('Invalid literal for Fraction: %r' %
  91. numerator)
  92. numerator = int(m.group('num') or '0')
  93. denom = m.group('denom')
  94. if denom:
  95. denominator = int(denom)
  96. else:
  97. denominator = 1
  98. decimal = m.group('decimal')
  99. if decimal:
  100. decimal = decimal.replace('_', '')
  101. scale = 10**len(decimal)
  102. numerator = numerator * scale + int(decimal)
  103. denominator *= scale
  104. exp = m.group('exp')
  105. if exp:
  106. exp = int(exp)
  107. if exp >= 0:
  108. numerator *= 10**exp
  109. else:
  110. denominator *= 10**-exp
  111. if m.group('sign') == '-':
  112. numerator = -numerator
  113. else:
  114. raise TypeError("argument should be a string "
  115. "or a Rational instance")
  116. elif type(numerator) is int is type(denominator):
  117. pass # *very* normal case
  118. elif (isinstance(numerator, numbers.Rational) and
  119. isinstance(denominator, numbers.Rational)):
  120. numerator, denominator = (
  121. numerator.numerator * denominator.denominator,
  122. denominator.numerator * numerator.denominator
  123. )
  124. else:
  125. raise TypeError("both arguments should be "
  126. "Rational instances")
  127. if denominator == 0:
  128. raise ZeroDivisionError('Fraction(%s, 0)' % numerator)
  129. if _normalize:
  130. g = math.gcd(numerator, denominator)
  131. if denominator < 0:
  132. g = -g
  133. numerator //= g
  134. denominator //= g
  135. self._numerator = numerator
  136. self._denominator = denominator
  137. return self
  138. @classmethod
  139. def from_float(cls, f):
  140. """Converts a finite float to a rational number, exactly.
  141. Beware that Fraction.from_float(0.3) != Fraction(3, 10).
  142. """
  143. if isinstance(f, numbers.Integral):
  144. return cls(f)
  145. elif not isinstance(f, float):
  146. raise TypeError("%s.from_float() only takes floats, not %r (%s)" %
  147. (cls.__name__, f, type(f).__name__))
  148. return cls(*f.as_integer_ratio())
  149. @classmethod
  150. def from_decimal(cls, dec):
  151. """Converts a finite Decimal instance to a rational number, exactly."""
  152. from decimal import Decimal
  153. if isinstance(dec, numbers.Integral):
  154. dec = Decimal(int(dec))
  155. elif not isinstance(dec, Decimal):
  156. raise TypeError(
  157. "%s.from_decimal() only takes Decimals, not %r (%s)" %
  158. (cls.__name__, dec, type(dec).__name__))
  159. return cls(*dec.as_integer_ratio())
  160. def as_integer_ratio(self):
  161. """Return the integer ratio as a tuple.
  162. Return a tuple of two integers, whose ratio is equal to the
  163. Fraction and with a positive denominator.
  164. """
  165. return (self._numerator, self._denominator)
  166. def limit_denominator(self, max_denominator=1000000):
  167. """Closest Fraction to self with denominator at most max_denominator.
  168. >>> Fraction('3.141592653589793').limit_denominator(10)
  169. Fraction(22, 7)
  170. >>> Fraction('3.141592653589793').limit_denominator(100)
  171. Fraction(311, 99)
  172. >>> Fraction(4321, 8765).limit_denominator(10000)
  173. Fraction(4321, 8765)
  174. """
  175. # Algorithm notes: For any real number x, define a *best upper
  176. # approximation* to x to be a rational number p/q such that:
  177. #
  178. # (1) p/q >= x, and
  179. # (2) if p/q > r/s >= x then s > q, for any rational r/s.
  180. #
  181. # Define *best lower approximation* similarly. Then it can be
  182. # proved that a rational number is a best upper or lower
  183. # approximation to x if, and only if, it is a convergent or
  184. # semiconvergent of the (unique shortest) continued fraction
  185. # associated to x.
  186. #
  187. # To find a best rational approximation with denominator <= M,
  188. # we find the best upper and lower approximations with
  189. # denominator <= M and take whichever of these is closer to x.
  190. # In the event of a tie, the bound with smaller denominator is
  191. # chosen. If both denominators are equal (which can happen
  192. # only when max_denominator == 1 and self is midway between
  193. # two integers) the lower bound---i.e., the floor of self, is
  194. # taken.
  195. if max_denominator < 1:
  196. raise ValueError("max_denominator should be at least 1")
  197. if self._denominator <= max_denominator:
  198. return Fraction(self)
  199. p0, q0, p1, q1 = 0, 1, 1, 0
  200. n, d = self._numerator, self._denominator
  201. while True:
  202. a = n//d
  203. q2 = q0+a*q1
  204. if q2 > max_denominator:
  205. break
  206. p0, q0, p1, q1 = p1, q1, p0+a*p1, q2
  207. n, d = d, n-a*d
  208. k = (max_denominator-q0)//q1
  209. bound1 = Fraction(p0+k*p1, q0+k*q1)
  210. bound2 = Fraction(p1, q1)
  211. if abs(bound2 - self) <= abs(bound1-self):
  212. return bound2
  213. else:
  214. return bound1
  215. @property
  216. def numerator(a):
  217. return a._numerator
  218. @property
  219. def denominator(a):
  220. return a._denominator
  221. def __repr__(self):
  222. """repr(self)"""
  223. return '%s(%s, %s)' % (self.__class__.__name__,
  224. self._numerator, self._denominator)
  225. def __str__(self):
  226. """str(self)"""
  227. if self._denominator == 1:
  228. return str(self._numerator)
  229. else:
  230. return '%s/%s' % (self._numerator, self._denominator)
  231. def _operator_fallbacks(monomorphic_operator, fallback_operator):
  232. """Generates forward and reverse operators given a purely-rational
  233. operator and a function from the operator module.
  234. Use this like:
  235. __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op)
  236. In general, we want to implement the arithmetic operations so
  237. that mixed-mode operations either call an implementation whose
  238. author knew about the types of both arguments, or convert both
  239. to the nearest built in type and do the operation there. In
  240. Fraction, that means that we define __add__ and __radd__ as:
  241. def __add__(self, other):
  242. # Both types have numerators/denominator attributes,
  243. # so do the operation directly
  244. if isinstance(other, (int, Fraction)):
  245. return Fraction(self.numerator * other.denominator +
  246. other.numerator * self.denominator,
  247. self.denominator * other.denominator)
  248. # float and complex don't have those operations, but we
  249. # know about those types, so special case them.
  250. elif isinstance(other, float):
  251. return float(self) + other
  252. elif isinstance(other, complex):
  253. return complex(self) + other
  254. # Let the other type take over.
  255. return NotImplemented
  256. def __radd__(self, other):
  257. # radd handles more types than add because there's
  258. # nothing left to fall back to.
  259. if isinstance(other, numbers.Rational):
  260. return Fraction(self.numerator * other.denominator +
  261. other.numerator * self.denominator,
  262. self.denominator * other.denominator)
  263. elif isinstance(other, Real):
  264. return float(other) + float(self)
  265. elif isinstance(other, Complex):
  266. return complex(other) + complex(self)
  267. return NotImplemented
  268. There are 5 different cases for a mixed-type addition on
  269. Fraction. I'll refer to all of the above code that doesn't
  270. refer to Fraction, float, or complex as "boilerplate". 'r'
  271. will be an instance of Fraction, which is a subtype of
  272. Rational (r : Fraction <: Rational), and b : B <:
  273. Complex. The first three involve 'r + b':
  274. 1. If B <: Fraction, int, float, or complex, we handle
  275. that specially, and all is well.
  276. 2. If Fraction falls back to the boilerplate code, and it
  277. were to return a value from __add__, we'd miss the
  278. possibility that B defines a more intelligent __radd__,
  279. so the boilerplate should return NotImplemented from
  280. __add__. In particular, we don't handle Rational
  281. here, even though we could get an exact answer, in case
  282. the other type wants to do something special.
  283. 3. If B <: Fraction, Python tries B.__radd__ before
  284. Fraction.__add__. This is ok, because it was
  285. implemented with knowledge of Fraction, so it can
  286. handle those instances before delegating to Real or
  287. Complex.
  288. The next two situations describe 'b + r'. We assume that b
  289. didn't know about Fraction in its implementation, and that it
  290. uses similar boilerplate code:
  291. 4. If B <: Rational, then __radd_ converts both to the
  292. builtin rational type (hey look, that's us) and
  293. proceeds.
  294. 5. Otherwise, __radd__ tries to find the nearest common
  295. base ABC, and fall back to its builtin type. Since this
  296. class doesn't subclass a concrete type, there's no
  297. implementation to fall back to, so we need to try as
  298. hard as possible to return an actual value, or the user
  299. will get a TypeError.
  300. """
  301. def forward(a, b):
  302. if isinstance(b, (int, Fraction)):
  303. return monomorphic_operator(a, b)
  304. elif isinstance(b, float):
  305. return fallback_operator(float(a), b)
  306. elif isinstance(b, complex):
  307. return fallback_operator(complex(a), b)
  308. else:
  309. return NotImplemented
  310. forward.__name__ = '__' + fallback_operator.__name__ + '__'
  311. forward.__doc__ = monomorphic_operator.__doc__
  312. def reverse(b, a):
  313. if isinstance(a, numbers.Rational):
  314. # Includes ints.
  315. return monomorphic_operator(a, b)
  316. elif isinstance(a, numbers.Real):
  317. return fallback_operator(float(a), float(b))
  318. elif isinstance(a, numbers.Complex):
  319. return fallback_operator(complex(a), complex(b))
  320. else:
  321. return NotImplemented
  322. reverse.__name__ = '__r' + fallback_operator.__name__ + '__'
  323. reverse.__doc__ = monomorphic_operator.__doc__
  324. return forward, reverse
  325. # Rational arithmetic algorithms: Knuth, TAOCP, Volume 2, 4.5.1.
  326. #
  327. # Assume input fractions a and b are normalized.
  328. #
  329. # 1) Consider addition/subtraction.
  330. #
  331. # Let g = gcd(da, db). Then
  332. #
  333. # na nb na*db ± nb*da
  334. # a ± b == -- ± -- == ------------- ==
  335. # da db da*db
  336. #
  337. # na*(db//g) ± nb*(da//g) t
  338. # == ----------------------- == -
  339. # (da*db)//g d
  340. #
  341. # Now, if g > 1, we're working with smaller integers.
  342. #
  343. # Note, that t, (da//g) and (db//g) are pairwise coprime.
  344. #
  345. # Indeed, (da//g) and (db//g) share no common factors (they were
  346. # removed) and da is coprime with na (since input fractions are
  347. # normalized), hence (da//g) and na are coprime. By symmetry,
  348. # (db//g) and nb are coprime too. Then,
  349. #
  350. # gcd(t, da//g) == gcd(na*(db//g), da//g) == 1
  351. # gcd(t, db//g) == gcd(nb*(da//g), db//g) == 1
  352. #
  353. # Above allows us optimize reduction of the result to lowest
  354. # terms. Indeed,
  355. #
  356. # g2 = gcd(t, d) == gcd(t, (da//g)*(db//g)*g) == gcd(t, g)
  357. #
  358. # t//g2 t//g2
  359. # a ± b == ----------------------- == ----------------
  360. # (da//g)*(db//g)*(g//g2) (da//g)*(db//g2)
  361. #
  362. # is a normalized fraction. This is useful because the unnormalized
  363. # denominator d could be much larger than g.
  364. #
  365. # We should special-case g == 1 (and g2 == 1), since 60.8% of
  366. # randomly-chosen integers are coprime:
  367. # https://en.wikipedia.org/wiki/Coprime_integers#Probability_of_coprimality
  368. # Note, that g2 == 1 always for fractions, obtained from floats: here
  369. # g is a power of 2 and the unnormalized numerator t is an odd integer.
  370. #
  371. # 2) Consider multiplication
  372. #
  373. # Let g1 = gcd(na, db) and g2 = gcd(nb, da), then
  374. #
  375. # na*nb na*nb (na//g1)*(nb//g2)
  376. # a*b == ----- == ----- == -----------------
  377. # da*db db*da (db//g1)*(da//g2)
  378. #
  379. # Note, that after divisions we're multiplying smaller integers.
  380. #
  381. # Also, the resulting fraction is normalized, because each of
  382. # two factors in the numerator is coprime to each of the two factors
  383. # in the denominator.
  384. #
  385. # Indeed, pick (na//g1). It's coprime with (da//g2), because input
  386. # fractions are normalized. It's also coprime with (db//g1), because
  387. # common factors are removed by g1 == gcd(na, db).
  388. #
  389. # As for addition/subtraction, we should special-case g1 == 1
  390. # and g2 == 1 for same reason. That happens also for multiplying
  391. # rationals, obtained from floats.
  392. def _add(a, b):
  393. """a + b"""
  394. na, da = a.numerator, a.denominator
  395. nb, db = b.numerator, b.denominator
  396. g = math.gcd(da, db)
  397. if g == 1:
  398. return Fraction(na * db + da * nb, da * db, _normalize=False)
  399. s = da // g
  400. t = na * (db // g) + nb * s
  401. g2 = math.gcd(t, g)
  402. if g2 == 1:
  403. return Fraction(t, s * db, _normalize=False)
  404. return Fraction(t // g2, s * (db // g2), _normalize=False)
  405. __add__, __radd__ = _operator_fallbacks(_add, operator.add)
  406. def _sub(a, b):
  407. """a - b"""
  408. na, da = a.numerator, a.denominator
  409. nb, db = b.numerator, b.denominator
  410. g = math.gcd(da, db)
  411. if g == 1:
  412. return Fraction(na * db - da * nb, da * db, _normalize=False)
  413. s = da // g
  414. t = na * (db // g) - nb * s
  415. g2 = math.gcd(t, g)
  416. if g2 == 1:
  417. return Fraction(t, s * db, _normalize=False)
  418. return Fraction(t // g2, s * (db // g2), _normalize=False)
  419. __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub)
  420. def _mul(a, b):
  421. """a * b"""
  422. na, da = a.numerator, a.denominator
  423. nb, db = b.numerator, b.denominator
  424. g1 = math.gcd(na, db)
  425. if g1 > 1:
  426. na //= g1
  427. db //= g1
  428. g2 = math.gcd(nb, da)
  429. if g2 > 1:
  430. nb //= g2
  431. da //= g2
  432. return Fraction(na * nb, db * da, _normalize=False)
  433. __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul)
  434. def _div(a, b):
  435. """a / b"""
  436. # Same as _mul(), with inversed b.
  437. na, da = a.numerator, a.denominator
  438. nb, db = b.numerator, b.denominator
  439. g1 = math.gcd(na, nb)
  440. if g1 > 1:
  441. na //= g1
  442. nb //= g1
  443. g2 = math.gcd(db, da)
  444. if g2 > 1:
  445. da //= g2
  446. db //= g2
  447. n, d = na * db, nb * da
  448. if d < 0:
  449. n, d = -n, -d
  450. return Fraction(n, d, _normalize=False)
  451. __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv)
  452. def _floordiv(a, b):
  453. """a // b"""
  454. return (a.numerator * b.denominator) // (a.denominator * b.numerator)
  455. __floordiv__, __rfloordiv__ = _operator_fallbacks(_floordiv, operator.floordiv)
  456. def _divmod(a, b):
  457. """(a // b, a % b)"""
  458. da, db = a.denominator, b.denominator
  459. div, n_mod = divmod(a.numerator * db, da * b.numerator)
  460. return div, Fraction(n_mod, da * db)
  461. __divmod__, __rdivmod__ = _operator_fallbacks(_divmod, divmod)
  462. def _mod(a, b):
  463. """a % b"""
  464. da, db = a.denominator, b.denominator
  465. return Fraction((a.numerator * db) % (b.numerator * da), da * db)
  466. __mod__, __rmod__ = _operator_fallbacks(_mod, operator.mod)
  467. def __pow__(a, b):
  468. """a ** b
  469. If b is not an integer, the result will be a float or complex
  470. since roots are generally irrational. If b is an integer, the
  471. result will be rational.
  472. """
  473. if isinstance(b, numbers.Rational):
  474. if b.denominator == 1:
  475. power = b.numerator
  476. if power >= 0:
  477. return Fraction(a._numerator ** power,
  478. a._denominator ** power,
  479. _normalize=False)
  480. elif a._numerator >= 0:
  481. return Fraction(a._denominator ** -power,
  482. a._numerator ** -power,
  483. _normalize=False)
  484. else:
  485. return Fraction((-a._denominator) ** -power,
  486. (-a._numerator) ** -power,
  487. _normalize=False)
  488. else:
  489. # A fractional power will generally produce an
  490. # irrational number.
  491. return float(a) ** float(b)
  492. else:
  493. return float(a) ** b
  494. def __rpow__(b, a):
  495. """a ** b"""
  496. if b._denominator == 1 and b._numerator >= 0:
  497. # If a is an int, keep it that way if possible.
  498. return a ** b._numerator
  499. if isinstance(a, numbers.Rational):
  500. return Fraction(a.numerator, a.denominator) ** b
  501. if b._denominator == 1:
  502. return a ** b._numerator
  503. return a ** float(b)
  504. def __pos__(a):
  505. """+a: Coerces a subclass instance to Fraction"""
  506. return Fraction(a._numerator, a._denominator, _normalize=False)
  507. def __neg__(a):
  508. """-a"""
  509. return Fraction(-a._numerator, a._denominator, _normalize=False)
  510. def __abs__(a):
  511. """abs(a)"""
  512. return Fraction(abs(a._numerator), a._denominator, _normalize=False)
  513. def __int__(a, _index=operator.index):
  514. """int(a)"""
  515. if a._numerator < 0:
  516. return _index(-(-a._numerator // a._denominator))
  517. else:
  518. return _index(a._numerator // a._denominator)
  519. def __trunc__(a):
  520. """math.trunc(a)"""
  521. if a._numerator < 0:
  522. return -(-a._numerator // a._denominator)
  523. else:
  524. return a._numerator // a._denominator
  525. def __floor__(a):
  526. """math.floor(a)"""
  527. return a.numerator // a.denominator
  528. def __ceil__(a):
  529. """math.ceil(a)"""
  530. # The negations cleverly convince floordiv to return the ceiling.
  531. return -(-a.numerator // a.denominator)
  532. def __round__(self, ndigits=None):
  533. """round(self, ndigits)
  534. Rounds half toward even.
  535. """
  536. if ndigits is None:
  537. floor, remainder = divmod(self.numerator, self.denominator)
  538. if remainder * 2 < self.denominator:
  539. return floor
  540. elif remainder * 2 > self.denominator:
  541. return floor + 1
  542. # Deal with the half case:
  543. elif floor % 2 == 0:
  544. return floor
  545. else:
  546. return floor + 1
  547. shift = 10**abs(ndigits)
  548. # See _operator_fallbacks.forward to check that the results of
  549. # these operations will always be Fraction and therefore have
  550. # round().
  551. if ndigits > 0:
  552. return Fraction(round(self * shift), shift)
  553. else:
  554. return Fraction(round(self / shift) * shift)
  555. def __hash__(self):
  556. """hash(self)"""
  557. # To make sure that the hash of a Fraction agrees with the hash
  558. # of a numerically equal integer, float or Decimal instance, we
  559. # follow the rules for numeric hashes outlined in the
  560. # documentation. (See library docs, 'Built-in Types').
  561. try:
  562. dinv = pow(self._denominator, -1, _PyHASH_MODULUS)
  563. except ValueError:
  564. # ValueError means there is no modular inverse.
  565. hash_ = _PyHASH_INF
  566. else:
  567. # The general algorithm now specifies that the absolute value of
  568. # the hash is
  569. # (|N| * dinv) % P
  570. # where N is self._numerator and P is _PyHASH_MODULUS. That's
  571. # optimized here in two ways: first, for a non-negative int i,
  572. # hash(i) == i % P, but the int hash implementation doesn't need
  573. # to divide, and is faster than doing % P explicitly. So we do
  574. # hash(|N| * dinv)
  575. # instead. Second, N is unbounded, so its product with dinv may
  576. # be arbitrarily expensive to compute. The final answer is the
  577. # same if we use the bounded |N| % P instead, which can again
  578. # be done with an int hash() call. If 0 <= i < P, hash(i) == i,
  579. # so this nested hash() call wastes a bit of time making a
  580. # redundant copy when |N| < P, but can save an arbitrarily large
  581. # amount of computation for large |N|.
  582. hash_ = hash(hash(abs(self._numerator)) * dinv)
  583. result = hash_ if self._numerator >= 0 else -hash_
  584. return -2 if result == -1 else result
  585. def __eq__(a, b):
  586. """a == b"""
  587. if type(b) is int:
  588. return a._numerator == b and a._denominator == 1
  589. if isinstance(b, numbers.Rational):
  590. return (a._numerator == b.numerator and
  591. a._denominator == b.denominator)
  592. if isinstance(b, numbers.Complex) and b.imag == 0:
  593. b = b.real
  594. if isinstance(b, float):
  595. if math.isnan(b) or math.isinf(b):
  596. # comparisons with an infinity or nan should behave in
  597. # the same way for any finite a, so treat a as zero.
  598. return 0.0 == b
  599. else:
  600. return a == a.from_float(b)
  601. else:
  602. # Since a doesn't know how to compare with b, let's give b
  603. # a chance to compare itself with a.
  604. return NotImplemented
  605. def _richcmp(self, other, op):
  606. """Helper for comparison operators, for internal use only.
  607. Implement comparison between a Rational instance `self`, and
  608. either another Rational instance or a float `other`. If
  609. `other` is not a Rational instance or a float, return
  610. NotImplemented. `op` should be one of the six standard
  611. comparison operators.
  612. """
  613. # convert other to a Rational instance where reasonable.
  614. if isinstance(other, numbers.Rational):
  615. return op(self._numerator * other.denominator,
  616. self._denominator * other.numerator)
  617. if isinstance(other, float):
  618. if math.isnan(other) or math.isinf(other):
  619. return op(0.0, other)
  620. else:
  621. return op(self, self.from_float(other))
  622. else:
  623. return NotImplemented
  624. def __lt__(a, b):
  625. """a < b"""
  626. return a._richcmp(b, operator.lt)
  627. def __gt__(a, b):
  628. """a > b"""
  629. return a._richcmp(b, operator.gt)
  630. def __le__(a, b):
  631. """a <= b"""
  632. return a._richcmp(b, operator.le)
  633. def __ge__(a, b):
  634. """a >= b"""
  635. return a._richcmp(b, operator.ge)
  636. def __bool__(a):
  637. """a != 0"""
  638. # bpo-39274: Use bool() because (a._numerator != 0) can return an
  639. # object which is not a bool.
  640. return bool(a._numerator)
  641. # support for pickling, copy, and deepcopy
  642. def __reduce__(self):
  643. return (self.__class__, (self._numerator, self._denominator))
  644. def __copy__(self):
  645. if type(self) == Fraction:
  646. return self # I'm immutable; therefore I am my own clone
  647. return self.__class__(self._numerator, self._denominator)
  648. def __deepcopy__(self, memo):
  649. if type(self) == Fraction:
  650. return self # My components are also immutable
  651. return self.__class__(self._numerator, self._denominator)