fractions.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  1. # Originally contributed by Sjoerd Mullender.
  2. # Significantly modified by Jeffrey Yasskin <jyasskin at gmail.com>.
  3. """Fraction, infinite-precision, real 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, then
  19. (?P<sign>[-+]?) # an optional sign, then
  20. (?=\d|\.\d) # lookahead for digit or .digit
  21. (?P<num>\d*) # numerator (possibly empty)
  22. (?: # followed by
  23. (?:/(?P<denom>\d+))? # an optional denominator
  24. | # or
  25. (?:\.(?P<decimal>\d*))? # an optional fractional part
  26. (?:E(?P<exp>[-+]?\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. scale = 10**len(decimal)
  101. numerator = numerator * scale + int(decimal)
  102. denominator *= scale
  103. exp = m.group('exp')
  104. if exp:
  105. exp = int(exp)
  106. if exp >= 0:
  107. numerator *= 10**exp
  108. else:
  109. denominator *= 10**-exp
  110. if m.group('sign') == '-':
  111. numerator = -numerator
  112. else:
  113. raise TypeError("argument should be a string "
  114. "or a Rational instance")
  115. elif type(numerator) is int is type(denominator):
  116. pass # *very* normal case
  117. elif (isinstance(numerator, numbers.Rational) and
  118. isinstance(denominator, numbers.Rational)):
  119. numerator, denominator = (
  120. numerator.numerator * denominator.denominator,
  121. denominator.numerator * numerator.denominator
  122. )
  123. else:
  124. raise TypeError("both arguments should be "
  125. "Rational instances")
  126. if denominator == 0:
  127. raise ZeroDivisionError('Fraction(%s, 0)' % numerator)
  128. if _normalize:
  129. g = math.gcd(numerator, denominator)
  130. if denominator < 0:
  131. g = -g
  132. numerator //= g
  133. denominator //= g
  134. self._numerator = numerator
  135. self._denominator = denominator
  136. return self
  137. @classmethod
  138. def from_float(cls, f):
  139. """Converts a finite float to a rational number, exactly.
  140. Beware that Fraction.from_float(0.3) != Fraction(3, 10).
  141. """
  142. if isinstance(f, numbers.Integral):
  143. return cls(f)
  144. elif not isinstance(f, float):
  145. raise TypeError("%s.from_float() only takes floats, not %r (%s)" %
  146. (cls.__name__, f, type(f).__name__))
  147. return cls(*f.as_integer_ratio())
  148. @classmethod
  149. def from_decimal(cls, dec):
  150. """Converts a finite Decimal instance to a rational number, exactly."""
  151. from decimal import Decimal
  152. if isinstance(dec, numbers.Integral):
  153. dec = Decimal(int(dec))
  154. elif not isinstance(dec, Decimal):
  155. raise TypeError(
  156. "%s.from_decimal() only takes Decimals, not %r (%s)" %
  157. (cls.__name__, dec, type(dec).__name__))
  158. return cls(*dec.as_integer_ratio())
  159. def as_integer_ratio(self):
  160. """Return the integer ratio as a tuple.
  161. Return a tuple of two integers, whose ratio is equal to the
  162. Fraction and with a positive denominator.
  163. """
  164. return (self._numerator, self._denominator)
  165. def limit_denominator(self, max_denominator=1000000):
  166. """Closest Fraction to self with denominator at most max_denominator.
  167. >>> Fraction('3.141592653589793').limit_denominator(10)
  168. Fraction(22, 7)
  169. >>> Fraction('3.141592653589793').limit_denominator(100)
  170. Fraction(311, 99)
  171. >>> Fraction(4321, 8765).limit_denominator(10000)
  172. Fraction(4321, 8765)
  173. """
  174. # Algorithm notes: For any real number x, define a *best upper
  175. # approximation* to x to be a rational number p/q such that:
  176. #
  177. # (1) p/q >= x, and
  178. # (2) if p/q > r/s >= x then s > q, for any rational r/s.
  179. #
  180. # Define *best lower approximation* similarly. Then it can be
  181. # proved that a rational number is a best upper or lower
  182. # approximation to x if, and only if, it is a convergent or
  183. # semiconvergent of the (unique shortest) continued fraction
  184. # associated to x.
  185. #
  186. # To find a best rational approximation with denominator <= M,
  187. # we find the best upper and lower approximations with
  188. # denominator <= M and take whichever of these is closer to x.
  189. # In the event of a tie, the bound with smaller denominator is
  190. # chosen. If both denominators are equal (which can happen
  191. # only when max_denominator == 1 and self is midway between
  192. # two integers) the lower bound---i.e., the floor of self, is
  193. # taken.
  194. if max_denominator < 1:
  195. raise ValueError("max_denominator should be at least 1")
  196. if self._denominator <= max_denominator:
  197. return Fraction(self)
  198. p0, q0, p1, q1 = 0, 1, 1, 0
  199. n, d = self._numerator, self._denominator
  200. while True:
  201. a = n//d
  202. q2 = q0+a*q1
  203. if q2 > max_denominator:
  204. break
  205. p0, q0, p1, q1 = p1, q1, p0+a*p1, q2
  206. n, d = d, n-a*d
  207. k = (max_denominator-q0)//q1
  208. bound1 = Fraction(p0+k*p1, q0+k*q1)
  209. bound2 = Fraction(p1, q1)
  210. if abs(bound2 - self) <= abs(bound1-self):
  211. return bound2
  212. else:
  213. return bound1
  214. @property
  215. def numerator(a):
  216. return a._numerator
  217. @property
  218. def denominator(a):
  219. return a._denominator
  220. def __repr__(self):
  221. """repr(self)"""
  222. return '%s(%s, %s)' % (self.__class__.__name__,
  223. self._numerator, self._denominator)
  224. def __str__(self):
  225. """str(self)"""
  226. if self._denominator == 1:
  227. return str(self._numerator)
  228. else:
  229. return '%s/%s' % (self._numerator, self._denominator)
  230. def _operator_fallbacks(monomorphic_operator, fallback_operator):
  231. """Generates forward and reverse operators given a purely-rational
  232. operator and a function from the operator module.
  233. Use this like:
  234. __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op)
  235. In general, we want to implement the arithmetic operations so
  236. that mixed-mode operations either call an implementation whose
  237. author knew about the types of both arguments, or convert both
  238. to the nearest built in type and do the operation there. In
  239. Fraction, that means that we define __add__ and __radd__ as:
  240. def __add__(self, other):
  241. # Both types have numerators/denominator attributes,
  242. # so do the operation directly
  243. if isinstance(other, (int, Fraction)):
  244. return Fraction(self.numerator * other.denominator +
  245. other.numerator * self.denominator,
  246. self.denominator * other.denominator)
  247. # float and complex don't have those operations, but we
  248. # know about those types, so special case them.
  249. elif isinstance(other, float):
  250. return float(self) + other
  251. elif isinstance(other, complex):
  252. return complex(self) + other
  253. # Let the other type take over.
  254. return NotImplemented
  255. def __radd__(self, other):
  256. # radd handles more types than add because there's
  257. # nothing left to fall back to.
  258. if isinstance(other, numbers.Rational):
  259. return Fraction(self.numerator * other.denominator +
  260. other.numerator * self.denominator,
  261. self.denominator * other.denominator)
  262. elif isinstance(other, Real):
  263. return float(other) + float(self)
  264. elif isinstance(other, Complex):
  265. return complex(other) + complex(self)
  266. return NotImplemented
  267. There are 5 different cases for a mixed-type addition on
  268. Fraction. I'll refer to all of the above code that doesn't
  269. refer to Fraction, float, or complex as "boilerplate". 'r'
  270. will be an instance of Fraction, which is a subtype of
  271. Rational (r : Fraction <: Rational), and b : B <:
  272. Complex. The first three involve 'r + b':
  273. 1. If B <: Fraction, int, float, or complex, we handle
  274. that specially, and all is well.
  275. 2. If Fraction falls back to the boilerplate code, and it
  276. were to return a value from __add__, we'd miss the
  277. possibility that B defines a more intelligent __radd__,
  278. so the boilerplate should return NotImplemented from
  279. __add__. In particular, we don't handle Rational
  280. here, even though we could get an exact answer, in case
  281. the other type wants to do something special.
  282. 3. If B <: Fraction, Python tries B.__radd__ before
  283. Fraction.__add__. This is ok, because it was
  284. implemented with knowledge of Fraction, so it can
  285. handle those instances before delegating to Real or
  286. Complex.
  287. The next two situations describe 'b + r'. We assume that b
  288. didn't know about Fraction in its implementation, and that it
  289. uses similar boilerplate code:
  290. 4. If B <: Rational, then __radd_ converts both to the
  291. builtin rational type (hey look, that's us) and
  292. proceeds.
  293. 5. Otherwise, __radd__ tries to find the nearest common
  294. base ABC, and fall back to its builtin type. Since this
  295. class doesn't subclass a concrete type, there's no
  296. implementation to fall back to, so we need to try as
  297. hard as possible to return an actual value, or the user
  298. will get a TypeError.
  299. """
  300. def forward(a, b):
  301. if isinstance(b, (int, Fraction)):
  302. return monomorphic_operator(a, b)
  303. elif isinstance(b, float):
  304. return fallback_operator(float(a), b)
  305. elif isinstance(b, complex):
  306. return fallback_operator(complex(a), b)
  307. else:
  308. return NotImplemented
  309. forward.__name__ = '__' + fallback_operator.__name__ + '__'
  310. forward.__doc__ = monomorphic_operator.__doc__
  311. def reverse(b, a):
  312. if isinstance(a, numbers.Rational):
  313. # Includes ints.
  314. return monomorphic_operator(a, b)
  315. elif isinstance(a, numbers.Real):
  316. return fallback_operator(float(a), float(b))
  317. elif isinstance(a, numbers.Complex):
  318. return fallback_operator(complex(a), complex(b))
  319. else:
  320. return NotImplemented
  321. reverse.__name__ = '__r' + fallback_operator.__name__ + '__'
  322. reverse.__doc__ = monomorphic_operator.__doc__
  323. return forward, reverse
  324. def _add(a, b):
  325. """a + b"""
  326. da, db = a.denominator, b.denominator
  327. return Fraction(a.numerator * db + b.numerator * da,
  328. da * db)
  329. __add__, __radd__ = _operator_fallbacks(_add, operator.add)
  330. def _sub(a, b):
  331. """a - b"""
  332. da, db = a.denominator, b.denominator
  333. return Fraction(a.numerator * db - b.numerator * da,
  334. da * db)
  335. __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub)
  336. def _mul(a, b):
  337. """a * b"""
  338. return Fraction(a.numerator * b.numerator, a.denominator * b.denominator)
  339. __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul)
  340. def _div(a, b):
  341. """a / b"""
  342. return Fraction(a.numerator * b.denominator,
  343. a.denominator * b.numerator)
  344. __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv)
  345. def _floordiv(a, b):
  346. """a // b"""
  347. return (a.numerator * b.denominator) // (a.denominator * b.numerator)
  348. __floordiv__, __rfloordiv__ = _operator_fallbacks(_floordiv, operator.floordiv)
  349. def _divmod(a, b):
  350. """(a // b, a % b)"""
  351. da, db = a.denominator, b.denominator
  352. div, n_mod = divmod(a.numerator * db, da * b.numerator)
  353. return div, Fraction(n_mod, da * db)
  354. __divmod__, __rdivmod__ = _operator_fallbacks(_divmod, divmod)
  355. def _mod(a, b):
  356. """a % b"""
  357. da, db = a.denominator, b.denominator
  358. return Fraction((a.numerator * db) % (b.numerator * da), da * db)
  359. __mod__, __rmod__ = _operator_fallbacks(_mod, operator.mod)
  360. def __pow__(a, b):
  361. """a ** b
  362. If b is not an integer, the result will be a float or complex
  363. since roots are generally irrational. If b is an integer, the
  364. result will be rational.
  365. """
  366. if isinstance(b, numbers.Rational):
  367. if b.denominator == 1:
  368. power = b.numerator
  369. if power >= 0:
  370. return Fraction(a._numerator ** power,
  371. a._denominator ** power,
  372. _normalize=False)
  373. elif a._numerator >= 0:
  374. return Fraction(a._denominator ** -power,
  375. a._numerator ** -power,
  376. _normalize=False)
  377. else:
  378. return Fraction((-a._denominator) ** -power,
  379. (-a._numerator) ** -power,
  380. _normalize=False)
  381. else:
  382. # A fractional power will generally produce an
  383. # irrational number.
  384. return float(a) ** float(b)
  385. else:
  386. return float(a) ** b
  387. def __rpow__(b, a):
  388. """a ** b"""
  389. if b._denominator == 1 and b._numerator >= 0:
  390. # If a is an int, keep it that way if possible.
  391. return a ** b._numerator
  392. if isinstance(a, numbers.Rational):
  393. return Fraction(a.numerator, a.denominator) ** b
  394. if b._denominator == 1:
  395. return a ** b._numerator
  396. return a ** float(b)
  397. def __pos__(a):
  398. """+a: Coerces a subclass instance to Fraction"""
  399. return Fraction(a._numerator, a._denominator, _normalize=False)
  400. def __neg__(a):
  401. """-a"""
  402. return Fraction(-a._numerator, a._denominator, _normalize=False)
  403. def __abs__(a):
  404. """abs(a)"""
  405. return Fraction(abs(a._numerator), a._denominator, _normalize=False)
  406. def __trunc__(a):
  407. """trunc(a)"""
  408. if a._numerator < 0:
  409. return -(-a._numerator // a._denominator)
  410. else:
  411. return a._numerator // a._denominator
  412. def __floor__(a):
  413. """math.floor(a)"""
  414. return a.numerator // a.denominator
  415. def __ceil__(a):
  416. """math.ceil(a)"""
  417. # The negations cleverly convince floordiv to return the ceiling.
  418. return -(-a.numerator // a.denominator)
  419. def __round__(self, ndigits=None):
  420. """round(self, ndigits)
  421. Rounds half toward even.
  422. """
  423. if ndigits is None:
  424. floor, remainder = divmod(self.numerator, self.denominator)
  425. if remainder * 2 < self.denominator:
  426. return floor
  427. elif remainder * 2 > self.denominator:
  428. return floor + 1
  429. # Deal with the half case:
  430. elif floor % 2 == 0:
  431. return floor
  432. else:
  433. return floor + 1
  434. shift = 10**abs(ndigits)
  435. # See _operator_fallbacks.forward to check that the results of
  436. # these operations will always be Fraction and therefore have
  437. # round().
  438. if ndigits > 0:
  439. return Fraction(round(self * shift), shift)
  440. else:
  441. return Fraction(round(self / shift) * shift)
  442. def __hash__(self):
  443. """hash(self)"""
  444. # To make sure that the hash of a Fraction agrees with the hash
  445. # of a numerically equal integer, float or Decimal instance, we
  446. # follow the rules for numeric hashes outlined in the
  447. # documentation. (See library docs, 'Built-in Types').
  448. try:
  449. dinv = pow(self._denominator, -1, _PyHASH_MODULUS)
  450. except ValueError:
  451. # ValueError means there is no modular inverse.
  452. hash_ = _PyHASH_INF
  453. else:
  454. # The general algorithm now specifies that the absolute value of
  455. # the hash is
  456. # (|N| * dinv) % P
  457. # where N is self._numerator and P is _PyHASH_MODULUS. That's
  458. # optimized here in two ways: first, for a non-negative int i,
  459. # hash(i) == i % P, but the int hash implementation doesn't need
  460. # to divide, and is faster than doing % P explicitly. So we do
  461. # hash(|N| * dinv)
  462. # instead. Second, N is unbounded, so its product with dinv may
  463. # be arbitrarily expensive to compute. The final answer is the
  464. # same if we use the bounded |N| % P instead, which can again
  465. # be done with an int hash() call. If 0 <= i < P, hash(i) == i,
  466. # so this nested hash() call wastes a bit of time making a
  467. # redundant copy when |N| < P, but can save an arbitrarily large
  468. # amount of computation for large |N|.
  469. hash_ = hash(hash(abs(self._numerator)) * dinv)
  470. result = hash_ if self._numerator >= 0 else -hash_
  471. return -2 if result == -1 else result
  472. def __eq__(a, b):
  473. """a == b"""
  474. if type(b) is int:
  475. return a._numerator == b and a._denominator == 1
  476. if isinstance(b, numbers.Rational):
  477. return (a._numerator == b.numerator and
  478. a._denominator == b.denominator)
  479. if isinstance(b, numbers.Complex) and b.imag == 0:
  480. b = b.real
  481. if isinstance(b, float):
  482. if math.isnan(b) or math.isinf(b):
  483. # comparisons with an infinity or nan should behave in
  484. # the same way for any finite a, so treat a as zero.
  485. return 0.0 == b
  486. else:
  487. return a == a.from_float(b)
  488. else:
  489. # Since a doesn't know how to compare with b, let's give b
  490. # a chance to compare itself with a.
  491. return NotImplemented
  492. def _richcmp(self, other, op):
  493. """Helper for comparison operators, for internal use only.
  494. Implement comparison between a Rational instance `self`, and
  495. either another Rational instance or a float `other`. If
  496. `other` is not a Rational instance or a float, return
  497. NotImplemented. `op` should be one of the six standard
  498. comparison operators.
  499. """
  500. # convert other to a Rational instance where reasonable.
  501. if isinstance(other, numbers.Rational):
  502. return op(self._numerator * other.denominator,
  503. self._denominator * other.numerator)
  504. if isinstance(other, float):
  505. if math.isnan(other) or math.isinf(other):
  506. return op(0.0, other)
  507. else:
  508. return op(self, self.from_float(other))
  509. else:
  510. return NotImplemented
  511. def __lt__(a, b):
  512. """a < b"""
  513. return a._richcmp(b, operator.lt)
  514. def __gt__(a, b):
  515. """a > b"""
  516. return a._richcmp(b, operator.gt)
  517. def __le__(a, b):
  518. """a <= b"""
  519. return a._richcmp(b, operator.le)
  520. def __ge__(a, b):
  521. """a >= b"""
  522. return a._richcmp(b, operator.ge)
  523. def __bool__(a):
  524. """a != 0"""
  525. # bpo-39274: Use bool() because (a._numerator != 0) can return an
  526. # object which is not a bool.
  527. return bool(a._numerator)
  528. # support for pickling, copy, and deepcopy
  529. def __reduce__(self):
  530. return (self.__class__, (str(self),))
  531. def __copy__(self):
  532. if type(self) == Fraction:
  533. return self # I'm immutable; therefore I am my own clone
  534. return self.__class__(self._numerator, self._denominator)
  535. def __deepcopy__(self, memo):
  536. if type(self) == Fraction:
  537. return self # My components are also immutable
  538. return self.__class__(self._numerator, self._denominator)