fractions.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990
  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 functools
  6. import math
  7. import numbers
  8. import operator
  9. import re
  10. import sys
  11. __all__ = ['Fraction']
  12. # Constants related to the hash implementation; hash(x) is based
  13. # on the reduction of x modulo the prime _PyHASH_MODULUS.
  14. _PyHASH_MODULUS = sys.hash_info.modulus
  15. # Value to be used for rationals that reduce to infinity modulo
  16. # _PyHASH_MODULUS.
  17. _PyHASH_INF = sys.hash_info.inf
  18. @functools.lru_cache(maxsize = 1 << 14)
  19. def _hash_algorithm(numerator, denominator):
  20. # To make sure that the hash of a Fraction agrees with the hash
  21. # of a numerically equal integer, float or Decimal instance, we
  22. # follow the rules for numeric hashes outlined in the
  23. # documentation. (See library docs, 'Built-in Types').
  24. try:
  25. dinv = pow(denominator, -1, _PyHASH_MODULUS)
  26. except ValueError:
  27. # ValueError means there is no modular inverse.
  28. hash_ = _PyHASH_INF
  29. else:
  30. # The general algorithm now specifies that the absolute value of
  31. # the hash is
  32. # (|N| * dinv) % P
  33. # where N is self._numerator and P is _PyHASH_MODULUS. That's
  34. # optimized here in two ways: first, for a non-negative int i,
  35. # hash(i) == i % P, but the int hash implementation doesn't need
  36. # to divide, and is faster than doing % P explicitly. So we do
  37. # hash(|N| * dinv)
  38. # instead. Second, N is unbounded, so its product with dinv may
  39. # be arbitrarily expensive to compute. The final answer is the
  40. # same if we use the bounded |N| % P instead, which can again
  41. # be done with an int hash() call. If 0 <= i < P, hash(i) == i,
  42. # so this nested hash() call wastes a bit of time making a
  43. # redundant copy when |N| < P, but can save an arbitrarily large
  44. # amount of computation for large |N|.
  45. hash_ = hash(hash(abs(numerator)) * dinv)
  46. result = hash_ if numerator >= 0 else -hash_
  47. return -2 if result == -1 else result
  48. _RATIONAL_FORMAT = re.compile(r"""
  49. \A\s* # optional whitespace at the start,
  50. (?P<sign>[-+]?) # an optional sign, then
  51. (?=\d|\.\d) # lookahead for digit or .digit
  52. (?P<num>\d*|\d+(_\d+)*) # numerator (possibly empty)
  53. (?: # followed by
  54. (?:\s*/\s*(?P<denom>\d+(_\d+)*))? # an optional denominator
  55. | # or
  56. (?:\.(?P<decimal>\d*|\d+(_\d+)*))? # an optional fractional part
  57. (?:E(?P<exp>[-+]?\d+(_\d+)*))? # and optional exponent
  58. )
  59. \s*\Z # and optional whitespace to finish
  60. """, re.VERBOSE | re.IGNORECASE)
  61. # Helpers for formatting
  62. def _round_to_exponent(n, d, exponent, no_neg_zero=False):
  63. """Round a rational number to the nearest multiple of a given power of 10.
  64. Rounds the rational number n/d to the nearest integer multiple of
  65. 10**exponent, rounding to the nearest even integer multiple in the case of
  66. a tie. Returns a pair (sign: bool, significand: int) representing the
  67. rounded value (-1)**sign * significand * 10**exponent.
  68. If no_neg_zero is true, then the returned sign will always be False when
  69. the significand is zero. Otherwise, the sign reflects the sign of the
  70. input.
  71. d must be positive, but n and d need not be relatively prime.
  72. """
  73. if exponent >= 0:
  74. d *= 10**exponent
  75. else:
  76. n *= 10**-exponent
  77. # The divmod quotient is correct for round-ties-towards-positive-infinity;
  78. # In the case of a tie, we zero out the least significant bit of q.
  79. q, r = divmod(n + (d >> 1), d)
  80. if r == 0 and d & 1 == 0:
  81. q &= -2
  82. sign = q < 0 if no_neg_zero else n < 0
  83. return sign, abs(q)
  84. def _round_to_figures(n, d, figures):
  85. """Round a rational number to a given number of significant figures.
  86. Rounds the rational number n/d to the given number of significant figures
  87. using the round-ties-to-even rule, and returns a triple
  88. (sign: bool, significand: int, exponent: int) representing the rounded
  89. value (-1)**sign * significand * 10**exponent.
  90. In the special case where n = 0, returns a significand of zero and
  91. an exponent of 1 - figures, for compatibility with formatting.
  92. Otherwise, the returned significand satisfies
  93. 10**(figures - 1) <= significand < 10**figures.
  94. d must be positive, but n and d need not be relatively prime.
  95. figures must be positive.
  96. """
  97. # Special case for n == 0.
  98. if n == 0:
  99. return False, 0, 1 - figures
  100. # Find integer m satisfying 10**(m - 1) <= abs(n)/d <= 10**m. (If abs(n)/d
  101. # is a power of 10, either of the two possible values for m is fine.)
  102. str_n, str_d = str(abs(n)), str(d)
  103. m = len(str_n) - len(str_d) + (str_d <= str_n)
  104. # Round to a multiple of 10**(m - figures). The significand we get
  105. # satisfies 10**(figures - 1) <= significand <= 10**figures.
  106. exponent = m - figures
  107. sign, significand = _round_to_exponent(n, d, exponent)
  108. # Adjust in the case where significand == 10**figures, to ensure that
  109. # 10**(figures - 1) <= significand < 10**figures.
  110. if len(str(significand)) == figures + 1:
  111. significand //= 10
  112. exponent += 1
  113. return sign, significand, exponent
  114. # Pattern for matching float-style format specifications;
  115. # supports 'e', 'E', 'f', 'F', 'g', 'G' and '%' presentation types.
  116. _FLOAT_FORMAT_SPECIFICATION_MATCHER = re.compile(r"""
  117. (?:
  118. (?P<fill>.)?
  119. (?P<align>[<>=^])
  120. )?
  121. (?P<sign>[-+ ]?)
  122. (?P<no_neg_zero>z)?
  123. (?P<alt>\#)?
  124. # A '0' that's *not* followed by another digit is parsed as a minimum width
  125. # rather than a zeropad flag.
  126. (?P<zeropad>0(?=[0-9]))?
  127. (?P<minimumwidth>0|[1-9][0-9]*)?
  128. (?P<thousands_sep>[,_])?
  129. (?:\.(?P<precision>0|[1-9][0-9]*))?
  130. (?P<presentation_type>[eEfFgG%])
  131. """, re.DOTALL | re.VERBOSE).fullmatch
  132. class Fraction(numbers.Rational):
  133. """This class implements rational numbers.
  134. In the two-argument form of the constructor, Fraction(8, 6) will
  135. produce a rational number equivalent to 4/3. Both arguments must
  136. be Rational. The numerator defaults to 0 and the denominator
  137. defaults to 1 so that Fraction(3) == 3 and Fraction() == 0.
  138. Fractions can also be constructed from:
  139. - numeric strings similar to those accepted by the
  140. float constructor (for example, '-2.3' or '1e10')
  141. - strings of the form '123/456'
  142. - float and Decimal instances
  143. - other Rational instances (including integers)
  144. """
  145. __slots__ = ('_numerator', '_denominator')
  146. # We're immutable, so use __new__ not __init__
  147. def __new__(cls, numerator=0, denominator=None):
  148. """Constructs a Rational.
  149. Takes a string like '3/2' or '1.5', another Rational instance, a
  150. numerator/denominator pair, or a float.
  151. Examples
  152. --------
  153. >>> Fraction(10, -8)
  154. Fraction(-5, 4)
  155. >>> Fraction(Fraction(1, 7), 5)
  156. Fraction(1, 35)
  157. >>> Fraction(Fraction(1, 7), Fraction(2, 3))
  158. Fraction(3, 14)
  159. >>> Fraction('314')
  160. Fraction(314, 1)
  161. >>> Fraction('-35/4')
  162. Fraction(-35, 4)
  163. >>> Fraction('3.1415') # conversion from numeric string
  164. Fraction(6283, 2000)
  165. >>> Fraction('-47e-2') # string may include a decimal exponent
  166. Fraction(-47, 100)
  167. >>> Fraction(1.47) # direct construction from float (exact conversion)
  168. Fraction(6620291452234629, 4503599627370496)
  169. >>> Fraction(2.25)
  170. Fraction(9, 4)
  171. >>> Fraction(Decimal('1.47'))
  172. Fraction(147, 100)
  173. """
  174. self = super(Fraction, cls).__new__(cls)
  175. if denominator is None:
  176. if type(numerator) is int:
  177. self._numerator = numerator
  178. self._denominator = 1
  179. return self
  180. elif isinstance(numerator, numbers.Rational):
  181. self._numerator = numerator.numerator
  182. self._denominator = numerator.denominator
  183. return self
  184. elif isinstance(numerator, (float, Decimal)):
  185. # Exact conversion
  186. self._numerator, self._denominator = numerator.as_integer_ratio()
  187. return self
  188. elif isinstance(numerator, str):
  189. # Handle construction from strings.
  190. m = _RATIONAL_FORMAT.match(numerator)
  191. if m is None:
  192. raise ValueError('Invalid literal for Fraction: %r' %
  193. numerator)
  194. numerator = int(m.group('num') or '0')
  195. denom = m.group('denom')
  196. if denom:
  197. denominator = int(denom)
  198. else:
  199. denominator = 1
  200. decimal = m.group('decimal')
  201. if decimal:
  202. decimal = decimal.replace('_', '')
  203. scale = 10**len(decimal)
  204. numerator = numerator * scale + int(decimal)
  205. denominator *= scale
  206. exp = m.group('exp')
  207. if exp:
  208. exp = int(exp)
  209. if exp >= 0:
  210. numerator *= 10**exp
  211. else:
  212. denominator *= 10**-exp
  213. if m.group('sign') == '-':
  214. numerator = -numerator
  215. else:
  216. raise TypeError("argument should be a string "
  217. "or a Rational instance")
  218. elif type(numerator) is int is type(denominator):
  219. pass # *very* normal case
  220. elif (isinstance(numerator, numbers.Rational) and
  221. isinstance(denominator, numbers.Rational)):
  222. numerator, denominator = (
  223. numerator.numerator * denominator.denominator,
  224. denominator.numerator * numerator.denominator
  225. )
  226. else:
  227. raise TypeError("both arguments should be "
  228. "Rational instances")
  229. if denominator == 0:
  230. raise ZeroDivisionError('Fraction(%s, 0)' % numerator)
  231. g = math.gcd(numerator, denominator)
  232. if denominator < 0:
  233. g = -g
  234. numerator //= g
  235. denominator //= g
  236. self._numerator = numerator
  237. self._denominator = denominator
  238. return self
  239. @classmethod
  240. def from_float(cls, f):
  241. """Converts a finite float to a rational number, exactly.
  242. Beware that Fraction.from_float(0.3) != Fraction(3, 10).
  243. """
  244. if isinstance(f, numbers.Integral):
  245. return cls(f)
  246. elif not isinstance(f, float):
  247. raise TypeError("%s.from_float() only takes floats, not %r (%s)" %
  248. (cls.__name__, f, type(f).__name__))
  249. return cls._from_coprime_ints(*f.as_integer_ratio())
  250. @classmethod
  251. def from_decimal(cls, dec):
  252. """Converts a finite Decimal instance to a rational number, exactly."""
  253. from decimal import Decimal
  254. if isinstance(dec, numbers.Integral):
  255. dec = Decimal(int(dec))
  256. elif not isinstance(dec, Decimal):
  257. raise TypeError(
  258. "%s.from_decimal() only takes Decimals, not %r (%s)" %
  259. (cls.__name__, dec, type(dec).__name__))
  260. return cls._from_coprime_ints(*dec.as_integer_ratio())
  261. @classmethod
  262. def _from_coprime_ints(cls, numerator, denominator, /):
  263. """Convert a pair of ints to a rational number, for internal use.
  264. The ratio of integers should be in lowest terms and the denominator
  265. should be positive.
  266. """
  267. obj = super(Fraction, cls).__new__(cls)
  268. obj._numerator = numerator
  269. obj._denominator = denominator
  270. return obj
  271. def is_integer(self):
  272. """Return True if the Fraction is an integer."""
  273. return self._denominator == 1
  274. def as_integer_ratio(self):
  275. """Return a pair of integers, whose ratio is equal to the original Fraction.
  276. The ratio is in lowest terms and has a positive denominator.
  277. """
  278. return (self._numerator, self._denominator)
  279. def limit_denominator(self, max_denominator=1000000):
  280. """Closest Fraction to self with denominator at most max_denominator.
  281. >>> Fraction('3.141592653589793').limit_denominator(10)
  282. Fraction(22, 7)
  283. >>> Fraction('3.141592653589793').limit_denominator(100)
  284. Fraction(311, 99)
  285. >>> Fraction(4321, 8765).limit_denominator(10000)
  286. Fraction(4321, 8765)
  287. """
  288. # Algorithm notes: For any real number x, define a *best upper
  289. # approximation* to x to be a rational number p/q such that:
  290. #
  291. # (1) p/q >= x, and
  292. # (2) if p/q > r/s >= x then s > q, for any rational r/s.
  293. #
  294. # Define *best lower approximation* similarly. Then it can be
  295. # proved that a rational number is a best upper or lower
  296. # approximation to x if, and only if, it is a convergent or
  297. # semiconvergent of the (unique shortest) continued fraction
  298. # associated to x.
  299. #
  300. # To find a best rational approximation with denominator <= M,
  301. # we find the best upper and lower approximations with
  302. # denominator <= M and take whichever of these is closer to x.
  303. # In the event of a tie, the bound with smaller denominator is
  304. # chosen. If both denominators are equal (which can happen
  305. # only when max_denominator == 1 and self is midway between
  306. # two integers) the lower bound---i.e., the floor of self, is
  307. # taken.
  308. if max_denominator < 1:
  309. raise ValueError("max_denominator should be at least 1")
  310. if self._denominator <= max_denominator:
  311. return Fraction(self)
  312. p0, q0, p1, q1 = 0, 1, 1, 0
  313. n, d = self._numerator, self._denominator
  314. while True:
  315. a = n//d
  316. q2 = q0+a*q1
  317. if q2 > max_denominator:
  318. break
  319. p0, q0, p1, q1 = p1, q1, p0+a*p1, q2
  320. n, d = d, n-a*d
  321. k = (max_denominator-q0)//q1
  322. # Determine which of the candidates (p0+k*p1)/(q0+k*q1) and p1/q1 is
  323. # closer to self. The distance between them is 1/(q1*(q0+k*q1)), while
  324. # the distance from p1/q1 to self is d/(q1*self._denominator). So we
  325. # need to compare 2*(q0+k*q1) with self._denominator/d.
  326. if 2*d*(q0+k*q1) <= self._denominator:
  327. return Fraction._from_coprime_ints(p1, q1)
  328. else:
  329. return Fraction._from_coprime_ints(p0+k*p1, q0+k*q1)
  330. @property
  331. def numerator(a):
  332. return a._numerator
  333. @property
  334. def denominator(a):
  335. return a._denominator
  336. def __repr__(self):
  337. """repr(self)"""
  338. return '%s(%s, %s)' % (self.__class__.__name__,
  339. self._numerator, self._denominator)
  340. def __str__(self):
  341. """str(self)"""
  342. if self._denominator == 1:
  343. return str(self._numerator)
  344. else:
  345. return '%s/%s' % (self._numerator, self._denominator)
  346. def __format__(self, format_spec, /):
  347. """Format this fraction according to the given format specification."""
  348. # Backwards compatiblility with existing formatting.
  349. if not format_spec:
  350. return str(self)
  351. # Validate and parse the format specifier.
  352. match = _FLOAT_FORMAT_SPECIFICATION_MATCHER(format_spec)
  353. if match is None:
  354. raise ValueError(
  355. f"Invalid format specifier {format_spec!r} "
  356. f"for object of type {type(self).__name__!r}"
  357. )
  358. elif match["align"] is not None and match["zeropad"] is not None:
  359. # Avoid the temptation to guess.
  360. raise ValueError(
  361. f"Invalid format specifier {format_spec!r} "
  362. f"for object of type {type(self).__name__!r}; "
  363. "can't use explicit alignment when zero-padding"
  364. )
  365. fill = match["fill"] or " "
  366. align = match["align"] or ">"
  367. pos_sign = "" if match["sign"] == "-" else match["sign"]
  368. no_neg_zero = bool(match["no_neg_zero"])
  369. alternate_form = bool(match["alt"])
  370. zeropad = bool(match["zeropad"])
  371. minimumwidth = int(match["minimumwidth"] or "0")
  372. thousands_sep = match["thousands_sep"]
  373. precision = int(match["precision"] or "6")
  374. presentation_type = match["presentation_type"]
  375. trim_zeros = presentation_type in "gG" and not alternate_form
  376. trim_point = not alternate_form
  377. exponent_indicator = "E" if presentation_type in "EFG" else "e"
  378. # Round to get the digits we need, figure out where to place the point,
  379. # and decide whether to use scientific notation. 'point_pos' is the
  380. # relative to the _end_ of the digit string: that is, it's the number
  381. # of digits that should follow the point.
  382. if presentation_type in "fF%":
  383. exponent = -precision
  384. if presentation_type == "%":
  385. exponent -= 2
  386. negative, significand = _round_to_exponent(
  387. self._numerator, self._denominator, exponent, no_neg_zero)
  388. scientific = False
  389. point_pos = precision
  390. else: # presentation_type in "eEgG"
  391. figures = (
  392. max(precision, 1)
  393. if presentation_type in "gG"
  394. else precision + 1
  395. )
  396. negative, significand, exponent = _round_to_figures(
  397. self._numerator, self._denominator, figures)
  398. scientific = (
  399. presentation_type in "eE"
  400. or exponent > 0
  401. or exponent + figures <= -4
  402. )
  403. point_pos = figures - 1 if scientific else -exponent
  404. # Get the suffix - the part following the digits, if any.
  405. if presentation_type == "%":
  406. suffix = "%"
  407. elif scientific:
  408. suffix = f"{exponent_indicator}{exponent + point_pos:+03d}"
  409. else:
  410. suffix = ""
  411. # String of output digits, padded sufficiently with zeros on the left
  412. # so that we'll have at least one digit before the decimal point.
  413. digits = f"{significand:0{point_pos + 1}d}"
  414. # Before padding, the output has the form f"{sign}{leading}{trailing}",
  415. # where `leading` includes thousands separators if necessary and
  416. # `trailing` includes the decimal separator where appropriate.
  417. sign = "-" if negative else pos_sign
  418. leading = digits[: len(digits) - point_pos]
  419. frac_part = digits[len(digits) - point_pos :]
  420. if trim_zeros:
  421. frac_part = frac_part.rstrip("0")
  422. separator = "" if trim_point and not frac_part else "."
  423. trailing = separator + frac_part + suffix
  424. # Do zero padding if required.
  425. if zeropad:
  426. min_leading = minimumwidth - len(sign) - len(trailing)
  427. # When adding thousands separators, they'll be added to the
  428. # zero-padded portion too, so we need to compensate.
  429. leading = leading.zfill(
  430. 3 * min_leading // 4 + 1 if thousands_sep else min_leading
  431. )
  432. # Insert thousands separators if required.
  433. if thousands_sep:
  434. first_pos = 1 + (len(leading) - 1) % 3
  435. leading = leading[:first_pos] + "".join(
  436. thousands_sep + leading[pos : pos + 3]
  437. for pos in range(first_pos, len(leading), 3)
  438. )
  439. # We now have a sign and a body. Pad with fill character if necessary
  440. # and return.
  441. body = leading + trailing
  442. padding = fill * (minimumwidth - len(sign) - len(body))
  443. if align == ">":
  444. return padding + sign + body
  445. elif align == "<":
  446. return sign + body + padding
  447. elif align == "^":
  448. half = len(padding) // 2
  449. return padding[:half] + sign + body + padding[half:]
  450. else: # align == "="
  451. return sign + padding + body
  452. def _operator_fallbacks(monomorphic_operator, fallback_operator):
  453. """Generates forward and reverse operators given a purely-rational
  454. operator and a function from the operator module.
  455. Use this like:
  456. __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op)
  457. In general, we want to implement the arithmetic operations so
  458. that mixed-mode operations either call an implementation whose
  459. author knew about the types of both arguments, or convert both
  460. to the nearest built in type and do the operation there. In
  461. Fraction, that means that we define __add__ and __radd__ as:
  462. def __add__(self, other):
  463. # Both types have numerators/denominator attributes,
  464. # so do the operation directly
  465. if isinstance(other, (int, Fraction)):
  466. return Fraction(self.numerator * other.denominator +
  467. other.numerator * self.denominator,
  468. self.denominator * other.denominator)
  469. # float and complex don't have those operations, but we
  470. # know about those types, so special case them.
  471. elif isinstance(other, float):
  472. return float(self) + other
  473. elif isinstance(other, complex):
  474. return complex(self) + other
  475. # Let the other type take over.
  476. return NotImplemented
  477. def __radd__(self, other):
  478. # radd handles more types than add because there's
  479. # nothing left to fall back to.
  480. if isinstance(other, numbers.Rational):
  481. return Fraction(self.numerator * other.denominator +
  482. other.numerator * self.denominator,
  483. self.denominator * other.denominator)
  484. elif isinstance(other, Real):
  485. return float(other) + float(self)
  486. elif isinstance(other, Complex):
  487. return complex(other) + complex(self)
  488. return NotImplemented
  489. There are 5 different cases for a mixed-type addition on
  490. Fraction. I'll refer to all of the above code that doesn't
  491. refer to Fraction, float, or complex as "boilerplate". 'r'
  492. will be an instance of Fraction, which is a subtype of
  493. Rational (r : Fraction <: Rational), and b : B <:
  494. Complex. The first three involve 'r + b':
  495. 1. If B <: Fraction, int, float, or complex, we handle
  496. that specially, and all is well.
  497. 2. If Fraction falls back to the boilerplate code, and it
  498. were to return a value from __add__, we'd miss the
  499. possibility that B defines a more intelligent __radd__,
  500. so the boilerplate should return NotImplemented from
  501. __add__. In particular, we don't handle Rational
  502. here, even though we could get an exact answer, in case
  503. the other type wants to do something special.
  504. 3. If B <: Fraction, Python tries B.__radd__ before
  505. Fraction.__add__. This is ok, because it was
  506. implemented with knowledge of Fraction, so it can
  507. handle those instances before delegating to Real or
  508. Complex.
  509. The next two situations describe 'b + r'. We assume that b
  510. didn't know about Fraction in its implementation, and that it
  511. uses similar boilerplate code:
  512. 4. If B <: Rational, then __radd_ converts both to the
  513. builtin rational type (hey look, that's us) and
  514. proceeds.
  515. 5. Otherwise, __radd__ tries to find the nearest common
  516. base ABC, and fall back to its builtin type. Since this
  517. class doesn't subclass a concrete type, there's no
  518. implementation to fall back to, so we need to try as
  519. hard as possible to return an actual value, or the user
  520. will get a TypeError.
  521. """
  522. def forward(a, b):
  523. if isinstance(b, Fraction):
  524. return monomorphic_operator(a, b)
  525. elif isinstance(b, int):
  526. return monomorphic_operator(a, Fraction(b))
  527. elif isinstance(b, float):
  528. return fallback_operator(float(a), b)
  529. elif isinstance(b, complex):
  530. return fallback_operator(complex(a), b)
  531. else:
  532. return NotImplemented
  533. forward.__name__ = '__' + fallback_operator.__name__ + '__'
  534. forward.__doc__ = monomorphic_operator.__doc__
  535. def reverse(b, a):
  536. if isinstance(a, numbers.Rational):
  537. # Includes ints.
  538. return monomorphic_operator(Fraction(a), b)
  539. elif isinstance(a, numbers.Real):
  540. return fallback_operator(float(a), float(b))
  541. elif isinstance(a, numbers.Complex):
  542. return fallback_operator(complex(a), complex(b))
  543. else:
  544. return NotImplemented
  545. reverse.__name__ = '__r' + fallback_operator.__name__ + '__'
  546. reverse.__doc__ = monomorphic_operator.__doc__
  547. return forward, reverse
  548. # Rational arithmetic algorithms: Knuth, TAOCP, Volume 2, 4.5.1.
  549. #
  550. # Assume input fractions a and b are normalized.
  551. #
  552. # 1) Consider addition/subtraction.
  553. #
  554. # Let g = gcd(da, db). Then
  555. #
  556. # na nb na*db ± nb*da
  557. # a ± b == -- ± -- == ------------- ==
  558. # da db da*db
  559. #
  560. # na*(db//g) ± nb*(da//g) t
  561. # == ----------------------- == -
  562. # (da*db)//g d
  563. #
  564. # Now, if g > 1, we're working with smaller integers.
  565. #
  566. # Note, that t, (da//g) and (db//g) are pairwise coprime.
  567. #
  568. # Indeed, (da//g) and (db//g) share no common factors (they were
  569. # removed) and da is coprime with na (since input fractions are
  570. # normalized), hence (da//g) and na are coprime. By symmetry,
  571. # (db//g) and nb are coprime too. Then,
  572. #
  573. # gcd(t, da//g) == gcd(na*(db//g), da//g) == 1
  574. # gcd(t, db//g) == gcd(nb*(da//g), db//g) == 1
  575. #
  576. # Above allows us optimize reduction of the result to lowest
  577. # terms. Indeed,
  578. #
  579. # g2 = gcd(t, d) == gcd(t, (da//g)*(db//g)*g) == gcd(t, g)
  580. #
  581. # t//g2 t//g2
  582. # a ± b == ----------------------- == ----------------
  583. # (da//g)*(db//g)*(g//g2) (da//g)*(db//g2)
  584. #
  585. # is a normalized fraction. This is useful because the unnormalized
  586. # denominator d could be much larger than g.
  587. #
  588. # We should special-case g == 1 (and g2 == 1), since 60.8% of
  589. # randomly-chosen integers are coprime:
  590. # https://en.wikipedia.org/wiki/Coprime_integers#Probability_of_coprimality
  591. # Note, that g2 == 1 always for fractions, obtained from floats: here
  592. # g is a power of 2 and the unnormalized numerator t is an odd integer.
  593. #
  594. # 2) Consider multiplication
  595. #
  596. # Let g1 = gcd(na, db) and g2 = gcd(nb, da), then
  597. #
  598. # na*nb na*nb (na//g1)*(nb//g2)
  599. # a*b == ----- == ----- == -----------------
  600. # da*db db*da (db//g1)*(da//g2)
  601. #
  602. # Note, that after divisions we're multiplying smaller integers.
  603. #
  604. # Also, the resulting fraction is normalized, because each of
  605. # two factors in the numerator is coprime to each of the two factors
  606. # in the denominator.
  607. #
  608. # Indeed, pick (na//g1). It's coprime with (da//g2), because input
  609. # fractions are normalized. It's also coprime with (db//g1), because
  610. # common factors are removed by g1 == gcd(na, db).
  611. #
  612. # As for addition/subtraction, we should special-case g1 == 1
  613. # and g2 == 1 for same reason. That happens also for multiplying
  614. # rationals, obtained from floats.
  615. def _add(a, b):
  616. """a + b"""
  617. na, da = a._numerator, a._denominator
  618. nb, db = b._numerator, b._denominator
  619. g = math.gcd(da, db)
  620. if g == 1:
  621. return Fraction._from_coprime_ints(na * db + da * nb, da * db)
  622. s = da // g
  623. t = na * (db // g) + nb * s
  624. g2 = math.gcd(t, g)
  625. if g2 == 1:
  626. return Fraction._from_coprime_ints(t, s * db)
  627. return Fraction._from_coprime_ints(t // g2, s * (db // g2))
  628. __add__, __radd__ = _operator_fallbacks(_add, operator.add)
  629. def _sub(a, b):
  630. """a - b"""
  631. na, da = a._numerator, a._denominator
  632. nb, db = b._numerator, b._denominator
  633. g = math.gcd(da, db)
  634. if g == 1:
  635. return Fraction._from_coprime_ints(na * db - da * nb, da * db)
  636. s = da // g
  637. t = na * (db // g) - nb * s
  638. g2 = math.gcd(t, g)
  639. if g2 == 1:
  640. return Fraction._from_coprime_ints(t, s * db)
  641. return Fraction._from_coprime_ints(t // g2, s * (db // g2))
  642. __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub)
  643. def _mul(a, b):
  644. """a * b"""
  645. na, da = a._numerator, a._denominator
  646. nb, db = b._numerator, b._denominator
  647. g1 = math.gcd(na, db)
  648. if g1 > 1:
  649. na //= g1
  650. db //= g1
  651. g2 = math.gcd(nb, da)
  652. if g2 > 1:
  653. nb //= g2
  654. da //= g2
  655. return Fraction._from_coprime_ints(na * nb, db * da)
  656. __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul)
  657. def _div(a, b):
  658. """a / b"""
  659. # Same as _mul(), with inversed b.
  660. nb, db = b._numerator, b._denominator
  661. if nb == 0:
  662. raise ZeroDivisionError('Fraction(%s, 0)' % db)
  663. na, da = a._numerator, a._denominator
  664. g1 = math.gcd(na, nb)
  665. if g1 > 1:
  666. na //= g1
  667. nb //= g1
  668. g2 = math.gcd(db, da)
  669. if g2 > 1:
  670. da //= g2
  671. db //= g2
  672. n, d = na * db, nb * da
  673. if d < 0:
  674. n, d = -n, -d
  675. return Fraction._from_coprime_ints(n, d)
  676. __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv)
  677. def _floordiv(a, b):
  678. """a // b"""
  679. return (a.numerator * b.denominator) // (a.denominator * b.numerator)
  680. __floordiv__, __rfloordiv__ = _operator_fallbacks(_floordiv, operator.floordiv)
  681. def _divmod(a, b):
  682. """(a // b, a % b)"""
  683. da, db = a.denominator, b.denominator
  684. div, n_mod = divmod(a.numerator * db, da * b.numerator)
  685. return div, Fraction(n_mod, da * db)
  686. __divmod__, __rdivmod__ = _operator_fallbacks(_divmod, divmod)
  687. def _mod(a, b):
  688. """a % b"""
  689. da, db = a.denominator, b.denominator
  690. return Fraction((a.numerator * db) % (b.numerator * da), da * db)
  691. __mod__, __rmod__ = _operator_fallbacks(_mod, operator.mod)
  692. def __pow__(a, b):
  693. """a ** b
  694. If b is not an integer, the result will be a float or complex
  695. since roots are generally irrational. If b is an integer, the
  696. result will be rational.
  697. """
  698. if isinstance(b, numbers.Rational):
  699. if b.denominator == 1:
  700. power = b.numerator
  701. if power >= 0:
  702. return Fraction._from_coprime_ints(a._numerator ** power,
  703. a._denominator ** power)
  704. elif a._numerator > 0:
  705. return Fraction._from_coprime_ints(a._denominator ** -power,
  706. a._numerator ** -power)
  707. elif a._numerator == 0:
  708. raise ZeroDivisionError('Fraction(%s, 0)' %
  709. a._denominator ** -power)
  710. else:
  711. return Fraction._from_coprime_ints((-a._denominator) ** -power,
  712. (-a._numerator) ** -power)
  713. else:
  714. # A fractional power will generally produce an
  715. # irrational number.
  716. return float(a) ** float(b)
  717. elif isinstance(b, (float, complex)):
  718. return float(a) ** b
  719. else:
  720. return NotImplemented
  721. def __rpow__(b, a):
  722. """a ** b"""
  723. if b._denominator == 1 and b._numerator >= 0:
  724. # If a is an int, keep it that way if possible.
  725. return a ** b._numerator
  726. if isinstance(a, numbers.Rational):
  727. return Fraction(a.numerator, a.denominator) ** b
  728. if b._denominator == 1:
  729. return a ** b._numerator
  730. return a ** float(b)
  731. def __pos__(a):
  732. """+a: Coerces a subclass instance to Fraction"""
  733. return Fraction._from_coprime_ints(a._numerator, a._denominator)
  734. def __neg__(a):
  735. """-a"""
  736. return Fraction._from_coprime_ints(-a._numerator, a._denominator)
  737. def __abs__(a):
  738. """abs(a)"""
  739. return Fraction._from_coprime_ints(abs(a._numerator), a._denominator)
  740. def __int__(a, _index=operator.index):
  741. """int(a)"""
  742. if a._numerator < 0:
  743. return _index(-(-a._numerator // a._denominator))
  744. else:
  745. return _index(a._numerator // a._denominator)
  746. def __trunc__(a):
  747. """math.trunc(a)"""
  748. if a._numerator < 0:
  749. return -(-a._numerator // a._denominator)
  750. else:
  751. return a._numerator // a._denominator
  752. def __floor__(a):
  753. """math.floor(a)"""
  754. return a._numerator // a._denominator
  755. def __ceil__(a):
  756. """math.ceil(a)"""
  757. # The negations cleverly convince floordiv to return the ceiling.
  758. return -(-a._numerator // a._denominator)
  759. def __round__(self, ndigits=None):
  760. """round(self, ndigits)
  761. Rounds half toward even.
  762. """
  763. if ndigits is None:
  764. d = self._denominator
  765. floor, remainder = divmod(self._numerator, d)
  766. if remainder * 2 < d:
  767. return floor
  768. elif remainder * 2 > d:
  769. return floor + 1
  770. # Deal with the half case:
  771. elif floor % 2 == 0:
  772. return floor
  773. else:
  774. return floor + 1
  775. shift = 10**abs(ndigits)
  776. # See _operator_fallbacks.forward to check that the results of
  777. # these operations will always be Fraction and therefore have
  778. # round().
  779. if ndigits > 0:
  780. return Fraction(round(self * shift), shift)
  781. else:
  782. return Fraction(round(self / shift) * shift)
  783. def __hash__(self):
  784. """hash(self)"""
  785. return _hash_algorithm(self._numerator, self._denominator)
  786. def __eq__(a, b):
  787. """a == b"""
  788. if type(b) is int:
  789. return a._numerator == b and a._denominator == 1
  790. if isinstance(b, numbers.Rational):
  791. return (a._numerator == b.numerator and
  792. a._denominator == b.denominator)
  793. if isinstance(b, numbers.Complex) and b.imag == 0:
  794. b = b.real
  795. if isinstance(b, float):
  796. if math.isnan(b) or math.isinf(b):
  797. # comparisons with an infinity or nan should behave in
  798. # the same way for any finite a, so treat a as zero.
  799. return 0.0 == b
  800. else:
  801. return a == a.from_float(b)
  802. else:
  803. # Since a doesn't know how to compare with b, let's give b
  804. # a chance to compare itself with a.
  805. return NotImplemented
  806. def _richcmp(self, other, op):
  807. """Helper for comparison operators, for internal use only.
  808. Implement comparison between a Rational instance `self`, and
  809. either another Rational instance or a float `other`. If
  810. `other` is not a Rational instance or a float, return
  811. NotImplemented. `op` should be one of the six standard
  812. comparison operators.
  813. """
  814. # convert other to a Rational instance where reasonable.
  815. if isinstance(other, numbers.Rational):
  816. return op(self._numerator * other.denominator,
  817. self._denominator * other.numerator)
  818. if isinstance(other, float):
  819. if math.isnan(other) or math.isinf(other):
  820. return op(0.0, other)
  821. else:
  822. return op(self, self.from_float(other))
  823. else:
  824. return NotImplemented
  825. def __lt__(a, b):
  826. """a < b"""
  827. return a._richcmp(b, operator.lt)
  828. def __gt__(a, b):
  829. """a > b"""
  830. return a._richcmp(b, operator.gt)
  831. def __le__(a, b):
  832. """a <= b"""
  833. return a._richcmp(b, operator.le)
  834. def __ge__(a, b):
  835. """a >= b"""
  836. return a._richcmp(b, operator.ge)
  837. def __bool__(a):
  838. """a != 0"""
  839. # bpo-39274: Use bool() because (a._numerator != 0) can return an
  840. # object which is not a bool.
  841. return bool(a._numerator)
  842. # support for pickling, copy, and deepcopy
  843. def __reduce__(self):
  844. return (self.__class__, (self._numerator, self._denominator))
  845. def __copy__(self):
  846. if type(self) == Fraction:
  847. return self # I'm immutable; therefore I am my own clone
  848. return self.__class__(self._numerator, self._denominator)
  849. def __deepcopy__(self, memo):
  850. if type(self) == Fraction:
  851. return self # My components are also immutable
  852. return self.__class__(self._numerator, self._denominator)