fractions.py 24 KB

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