fractions.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  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 limit_denominator(self, max_denominator=1000000):
  182. """Closest Fraction to self with denominator at most max_denominator.
  183. >>> Fraction('3.141592653589793').limit_denominator(10)
  184. Fraction(22, 7)
  185. >>> Fraction('3.141592653589793').limit_denominator(100)
  186. Fraction(311, 99)
  187. >>> Fraction(4321, 8765).limit_denominator(10000)
  188. Fraction(4321, 8765)
  189. """
  190. # Algorithm notes: For any real number x, define a *best upper
  191. # approximation* to x to be a rational number p/q such that:
  192. #
  193. # (1) p/q >= x, and
  194. # (2) if p/q > r/s >= x then s > q, for any rational r/s.
  195. #
  196. # Define *best lower approximation* similarly. Then it can be
  197. # proved that a rational number is a best upper or lower
  198. # approximation to x if, and only if, it is a convergent or
  199. # semiconvergent of the (unique shortest) continued fraction
  200. # associated to x.
  201. #
  202. # To find a best rational approximation with denominator <= M,
  203. # we find the best upper and lower approximations with
  204. # denominator <= M and take whichever of these is closer to x.
  205. # In the event of a tie, the bound with smaller denominator is
  206. # chosen. If both denominators are equal (which can happen
  207. # only when max_denominator == 1 and self is midway between
  208. # two integers) the lower bound---i.e., the floor of self, is
  209. # taken.
  210. if max_denominator < 1:
  211. raise ValueError("max_denominator should be at least 1")
  212. if self._denominator <= max_denominator:
  213. return Fraction(self)
  214. p0, q0, p1, q1 = 0, 1, 1, 0
  215. n, d = self._numerator, self._denominator
  216. while True:
  217. a = n//d
  218. q2 = q0+a*q1
  219. if q2 > max_denominator:
  220. break
  221. p0, q0, p1, q1 = p1, q1, p0+a*p1, q2
  222. n, d = d, n-a*d
  223. k = (max_denominator-q0)//q1
  224. bound1 = Fraction(p0+k*p1, q0+k*q1)
  225. bound2 = Fraction(p1, q1)
  226. if abs(bound2 - self) <= abs(bound1-self):
  227. return bound2
  228. else:
  229. return bound1
  230. @property
  231. def numerator(a):
  232. return a._numerator
  233. @property
  234. def denominator(a):
  235. return a._denominator
  236. def __repr__(self):
  237. """repr(self)"""
  238. return '%s(%s, %s)' % (self.__class__.__name__,
  239. self._numerator, self._denominator)
  240. def __str__(self):
  241. """str(self)"""
  242. if self._denominator == 1:
  243. return str(self._numerator)
  244. else:
  245. return '%s/%s' % (self._numerator, self._denominator)
  246. def _operator_fallbacks(monomorphic_operator, fallback_operator):
  247. """Generates forward and reverse operators given a purely-rational
  248. operator and a function from the operator module.
  249. Use this like:
  250. __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op)
  251. In general, we want to implement the arithmetic operations so
  252. that mixed-mode operations either call an implementation whose
  253. author knew about the types of both arguments, or convert both
  254. to the nearest built in type and do the operation there. In
  255. Fraction, that means that we define __add__ and __radd__ as:
  256. def __add__(self, other):
  257. # Both types have numerators/denominator attributes,
  258. # so do the operation directly
  259. if isinstance(other, (int, Fraction)):
  260. return Fraction(self.numerator * other.denominator +
  261. other.numerator * self.denominator,
  262. self.denominator * other.denominator)
  263. # float and complex don't have those operations, but we
  264. # know about those types, so special case them.
  265. elif isinstance(other, float):
  266. return float(self) + other
  267. elif isinstance(other, complex):
  268. return complex(self) + other
  269. # Let the other type take over.
  270. return NotImplemented
  271. def __radd__(self, other):
  272. # radd handles more types than add because there's
  273. # nothing left to fall back to.
  274. if isinstance(other, numbers.Rational):
  275. return Fraction(self.numerator * other.denominator +
  276. other.numerator * self.denominator,
  277. self.denominator * other.denominator)
  278. elif isinstance(other, Real):
  279. return float(other) + float(self)
  280. elif isinstance(other, Complex):
  281. return complex(other) + complex(self)
  282. return NotImplemented
  283. There are 5 different cases for a mixed-type addition on
  284. Fraction. I'll refer to all of the above code that doesn't
  285. refer to Fraction, float, or complex as "boilerplate". 'r'
  286. will be an instance of Fraction, which is a subtype of
  287. Rational (r : Fraction <: Rational), and b : B <:
  288. Complex. The first three involve 'r + b':
  289. 1. If B <: Fraction, int, float, or complex, we handle
  290. that specially, and all is well.
  291. 2. If Fraction falls back to the boilerplate code, and it
  292. were to return a value from __add__, we'd miss the
  293. possibility that B defines a more intelligent __radd__,
  294. so the boilerplate should return NotImplemented from
  295. __add__. In particular, we don't handle Rational
  296. here, even though we could get an exact answer, in case
  297. the other type wants to do something special.
  298. 3. If B <: Fraction, Python tries B.__radd__ before
  299. Fraction.__add__. This is ok, because it was
  300. implemented with knowledge of Fraction, so it can
  301. handle those instances before delegating to Real or
  302. Complex.
  303. The next two situations describe 'b + r'. We assume that b
  304. didn't know about Fraction in its implementation, and that it
  305. uses similar boilerplate code:
  306. 4. If B <: Rational, then __radd_ converts both to the
  307. builtin rational type (hey look, that's us) and
  308. proceeds.
  309. 5. Otherwise, __radd__ tries to find the nearest common
  310. base ABC, and fall back to its builtin type. Since this
  311. class doesn't subclass a concrete type, there's no
  312. implementation to fall back to, so we need to try as
  313. hard as possible to return an actual value, or the user
  314. will get a TypeError.
  315. """
  316. def forward(a, b):
  317. if isinstance(b, (int, Fraction)):
  318. return monomorphic_operator(a, b)
  319. elif isinstance(b, float):
  320. return fallback_operator(float(a), b)
  321. elif isinstance(b, complex):
  322. return fallback_operator(complex(a), b)
  323. else:
  324. return NotImplemented
  325. forward.__name__ = '__' + fallback_operator.__name__ + '__'
  326. forward.__doc__ = monomorphic_operator.__doc__
  327. def reverse(b, a):
  328. if isinstance(a, numbers.Rational):
  329. # Includes ints.
  330. return monomorphic_operator(a, b)
  331. elif isinstance(a, numbers.Real):
  332. return fallback_operator(float(a), float(b))
  333. elif isinstance(a, numbers.Complex):
  334. return fallback_operator(complex(a), complex(b))
  335. else:
  336. return NotImplemented
  337. reverse.__name__ = '__r' + fallback_operator.__name__ + '__'
  338. reverse.__doc__ = monomorphic_operator.__doc__
  339. return forward, reverse
  340. def _add(a, b):
  341. """a + b"""
  342. da, db = a.denominator, b.denominator
  343. return Fraction(a.numerator * db + b.numerator * da,
  344. da * db)
  345. __add__, __radd__ = _operator_fallbacks(_add, operator.add)
  346. def _sub(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. __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub)
  352. def _mul(a, b):
  353. """a * b"""
  354. return Fraction(a.numerator * b.numerator, a.denominator * b.denominator)
  355. __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul)
  356. def _div(a, b):
  357. """a / b"""
  358. return Fraction(a.numerator * b.denominator,
  359. a.denominator * b.numerator)
  360. __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv)
  361. def __floordiv__(a, b):
  362. """a // b"""
  363. return math.floor(a / b)
  364. def __rfloordiv__(b, a):
  365. """a // b"""
  366. return math.floor(a / b)
  367. def __mod__(a, b):
  368. """a % b"""
  369. div = a // b
  370. return a - b * div
  371. def __rmod__(b, a):
  372. """a % b"""
  373. div = a // b
  374. return a - b * div
  375. def __pow__(a, b):
  376. """a ** b
  377. If b is not an integer, the result will be a float or complex
  378. since roots are generally irrational. If b is an integer, the
  379. result will be rational.
  380. """
  381. if isinstance(b, numbers.Rational):
  382. if b.denominator == 1:
  383. power = b.numerator
  384. if power >= 0:
  385. return Fraction(a._numerator ** power,
  386. a._denominator ** power,
  387. _normalize=False)
  388. elif a._numerator >= 0:
  389. return Fraction(a._denominator ** -power,
  390. a._numerator ** -power,
  391. _normalize=False)
  392. else:
  393. return Fraction((-a._denominator) ** -power,
  394. (-a._numerator) ** -power,
  395. _normalize=False)
  396. else:
  397. # A fractional power will generally produce an
  398. # irrational number.
  399. return float(a) ** float(b)
  400. else:
  401. return float(a) ** b
  402. def __rpow__(b, a):
  403. """a ** b"""
  404. if b._denominator == 1 and b._numerator >= 0:
  405. # If a is an int, keep it that way if possible.
  406. return a ** b._numerator
  407. if isinstance(a, numbers.Rational):
  408. return Fraction(a.numerator, a.denominator) ** b
  409. if b._denominator == 1:
  410. return a ** b._numerator
  411. return a ** float(b)
  412. def __pos__(a):
  413. """+a: Coerces a subclass instance to Fraction"""
  414. return Fraction(a._numerator, a._denominator, _normalize=False)
  415. def __neg__(a):
  416. """-a"""
  417. return Fraction(-a._numerator, a._denominator, _normalize=False)
  418. def __abs__(a):
  419. """abs(a)"""
  420. return Fraction(abs(a._numerator), a._denominator, _normalize=False)
  421. def __trunc__(a):
  422. """trunc(a)"""
  423. if a._numerator < 0:
  424. return -(-a._numerator // a._denominator)
  425. else:
  426. return a._numerator // a._denominator
  427. def __floor__(a):
  428. """Will be math.floor(a) in 3.0."""
  429. return a.numerator // a.denominator
  430. def __ceil__(a):
  431. """Will be math.ceil(a) in 3.0."""
  432. # The negations cleverly convince floordiv to return the ceiling.
  433. return -(-a.numerator // a.denominator)
  434. def __round__(self, ndigits=None):
  435. """Will be round(self, ndigits) in 3.0.
  436. Rounds half toward even.
  437. """
  438. if ndigits is None:
  439. floor, remainder = divmod(self.numerator, self.denominator)
  440. if remainder * 2 < self.denominator:
  441. return floor
  442. elif remainder * 2 > self.denominator:
  443. return floor + 1
  444. # Deal with the half case:
  445. elif floor % 2 == 0:
  446. return floor
  447. else:
  448. return floor + 1
  449. shift = 10**abs(ndigits)
  450. # See _operator_fallbacks.forward to check that the results of
  451. # these operations will always be Fraction and therefore have
  452. # round().
  453. if ndigits > 0:
  454. return Fraction(round(self * shift), shift)
  455. else:
  456. return Fraction(round(self / shift) * shift)
  457. def __hash__(self):
  458. """hash(self)"""
  459. # XXX since this method is expensive, consider caching the result
  460. # In order to make sure that the hash of a Fraction agrees
  461. # with the hash of a numerically equal integer, float or
  462. # Decimal instance, we follow the rules for numeric hashes
  463. # outlined in the documentation. (See library docs, 'Built-in
  464. # Types').
  465. # dinv is the inverse of self._denominator modulo the prime
  466. # _PyHASH_MODULUS, or 0 if self._denominator is divisible by
  467. # _PyHASH_MODULUS.
  468. dinv = pow(self._denominator, _PyHASH_MODULUS - 2, _PyHASH_MODULUS)
  469. if not dinv:
  470. hash_ = _PyHASH_INF
  471. else:
  472. hash_ = abs(self._numerator) * dinv % _PyHASH_MODULUS
  473. result = hash_ if self >= 0 else -hash_
  474. return -2 if result == -1 else result
  475. def __eq__(a, b):
  476. """a == b"""
  477. if type(b) is int:
  478. return a._numerator == b and a._denominator == 1
  479. if isinstance(b, numbers.Rational):
  480. return (a._numerator == b.numerator and
  481. a._denominator == b.denominator)
  482. if isinstance(b, numbers.Complex) and b.imag == 0:
  483. b = b.real
  484. if isinstance(b, float):
  485. if math.isnan(b) or math.isinf(b):
  486. # comparisons with an infinity or nan should behave in
  487. # the same way for any finite a, so treat a as zero.
  488. return 0.0 == b
  489. else:
  490. return a == a.from_float(b)
  491. else:
  492. # Since a doesn't know how to compare with b, let's give b
  493. # a chance to compare itself with a.
  494. return NotImplemented
  495. def _richcmp(self, other, op):
  496. """Helper for comparison operators, for internal use only.
  497. Implement comparison between a Rational instance `self`, and
  498. either another Rational instance or a float `other`. If
  499. `other` is not a Rational instance or a float, return
  500. NotImplemented. `op` should be one of the six standard
  501. comparison operators.
  502. """
  503. # convert other to a Rational instance where reasonable.
  504. if isinstance(other, numbers.Rational):
  505. return op(self._numerator * other.denominator,
  506. self._denominator * other.numerator)
  507. if isinstance(other, float):
  508. if math.isnan(other) or math.isinf(other):
  509. return op(0.0, other)
  510. else:
  511. return op(self, self.from_float(other))
  512. else:
  513. return NotImplemented
  514. def __lt__(a, b):
  515. """a < b"""
  516. return a._richcmp(b, operator.lt)
  517. def __gt__(a, b):
  518. """a > b"""
  519. return a._richcmp(b, operator.gt)
  520. def __le__(a, b):
  521. """a <= b"""
  522. return a._richcmp(b, operator.le)
  523. def __ge__(a, b):
  524. """a >= b"""
  525. return a._richcmp(b, operator.ge)
  526. def __bool__(a):
  527. """a != 0"""
  528. # bpo-39274: Use bool() because (a._numerator != 0) can return an
  529. # object which is not a bool.
  530. return bool(a._numerator)
  531. # support for pickling, copy, and deepcopy
  532. def __reduce__(self):
  533. return (self.__class__, (str(self),))
  534. def __copy__(self):
  535. if type(self) == Fraction:
  536. return self # I'm immutable; therefore I am my own clone
  537. return self.__class__(self._numerator, self._denominator)
  538. def __deepcopy__(self, memo):
  539. if type(self) == Fraction:
  540. return self # My components are also immutable
  541. return self.__class__(self._numerator, self._denominator)