/Lib/fractions.py

http://unladen-swallow.googlecode.com/ · Python · 539 lines · 399 code · 36 blank · 104 comment · 52 complexity · 98bd91be206ca244fdda81b6ae682a85 MD5 · raw file

  1. # Originally contributed by Sjoerd Mullender.
  2. # Significantly modified by Jeffrey Yasskin <jyasskin at gmail.com>.
  3. """Rational, infinite-precision, real numbers."""
  4. from __future__ import division
  5. import math
  6. import numbers
  7. import operator
  8. import re
  9. __all__ = ['Fraction', 'gcd']
  10. Rational = numbers.Rational
  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. while b:
  17. a, b = b, a%b
  18. return a
  19. _RATIONAL_FORMAT = re.compile(r"""
  20. \A\s* # optional whitespace at the start, then
  21. (?P<sign>[-+]?) # an optional sign, then
  22. (?=\d|\.\d) # lookahead for digit or .digit
  23. (?P<num>\d*) # numerator (possibly empty)
  24. (?: # followed by an optional
  25. /(?P<denom>\d+) # / and denominator
  26. | # or
  27. \.(?P<decimal>\d*) # decimal point and fractional part
  28. )?
  29. \s*\Z # and optional whitespace to finish
  30. """, re.VERBOSE)
  31. class Fraction(Rational):
  32. """This class implements rational numbers.
  33. Fraction(8, 6) will produce a rational number equivalent to
  34. 4/3. Both arguments must be Integral. The numerator defaults to 0
  35. and the denominator defaults to 1 so that Fraction(3) == 3 and
  36. Fraction() == 0.
  37. Fractions can also be constructed from strings of the form
  38. '[-+]?[0-9]+((/|.)[0-9]+)?', optionally surrounded by spaces.
  39. """
  40. __slots__ = ('_numerator', '_denominator')
  41. # We're immutable, so use __new__ not __init__
  42. def __new__(cls, numerator=0, denominator=1):
  43. """Constructs a Fraction.
  44. Takes a string like '3/2' or '1.5', another Fraction, or a
  45. numerator/denominator pair.
  46. """
  47. self = super(Fraction, cls).__new__(cls)
  48. if type(numerator) not in (int, long) and denominator == 1:
  49. if isinstance(numerator, basestring):
  50. # Handle construction from strings.
  51. input = numerator
  52. m = _RATIONAL_FORMAT.match(input)
  53. if m is None:
  54. raise ValueError('Invalid literal for Fraction: %r' % input)
  55. numerator = m.group('num')
  56. decimal = m.group('decimal')
  57. if decimal:
  58. # The literal is a decimal number.
  59. numerator = int(numerator + decimal)
  60. denominator = 10**len(decimal)
  61. else:
  62. # The literal is an integer or fraction.
  63. numerator = int(numerator)
  64. # Default denominator to 1.
  65. denominator = int(m.group('denom') or 1)
  66. if m.group('sign') == '-':
  67. numerator = -numerator
  68. elif isinstance(numerator, Rational):
  69. # Handle copies from other rationals. Integrals get
  70. # caught here too, but it doesn't matter because
  71. # denominator is already 1.
  72. other_rational = numerator
  73. numerator = other_rational.numerator
  74. denominator = other_rational.denominator
  75. if denominator == 0:
  76. raise ZeroDivisionError('Fraction(%s, 0)' % numerator)
  77. numerator = operator.index(numerator)
  78. denominator = operator.index(denominator)
  79. g = gcd(numerator, denominator)
  80. self._numerator = numerator // g
  81. self._denominator = denominator // g
  82. return self
  83. @classmethod
  84. def from_float(cls, f):
  85. """Converts a finite float to a rational number, exactly.
  86. Beware that Fraction.from_float(0.3) != Fraction(3, 10).
  87. """
  88. if isinstance(f, numbers.Integral):
  89. return cls(f)
  90. elif not isinstance(f, float):
  91. raise TypeError("%s.from_float() only takes floats, not %r (%s)" %
  92. (cls.__name__, f, type(f).__name__))
  93. if math.isnan(f) or math.isinf(f):
  94. raise TypeError("Cannot convert %r to %s." % (f, cls.__name__))
  95. return cls(*f.as_integer_ratio())
  96. @classmethod
  97. def from_decimal(cls, dec):
  98. """Converts a finite Decimal instance to a rational number, exactly."""
  99. from decimal import Decimal
  100. if isinstance(dec, numbers.Integral):
  101. dec = Decimal(int(dec))
  102. elif not isinstance(dec, Decimal):
  103. raise TypeError(
  104. "%s.from_decimal() only takes Decimals, not %r (%s)" %
  105. (cls.__name__, dec, type(dec).__name__))
  106. if not dec.is_finite():
  107. # Catches infinities and nans.
  108. raise TypeError("Cannot convert %s to %s." % (dec, cls.__name__))
  109. sign, digits, exp = dec.as_tuple()
  110. digits = int(''.join(map(str, digits)))
  111. if sign:
  112. digits = -digits
  113. if exp >= 0:
  114. return cls(digits * 10 ** exp)
  115. else:
  116. return cls(digits, 10 ** -exp)
  117. def limit_denominator(self, max_denominator=1000000):
  118. """Closest Fraction to self with denominator at most max_denominator.
  119. >>> Fraction('3.141592653589793').limit_denominator(10)
  120. Fraction(22, 7)
  121. >>> Fraction('3.141592653589793').limit_denominator(100)
  122. Fraction(311, 99)
  123. >>> Fraction(1234, 5678).limit_denominator(10000)
  124. Fraction(1234, 5678)
  125. """
  126. # Algorithm notes: For any real number x, define a *best upper
  127. # approximation* to x to be a rational number p/q such that:
  128. #
  129. # (1) p/q >= x, and
  130. # (2) if p/q > r/s >= x then s > q, for any rational r/s.
  131. #
  132. # Define *best lower approximation* similarly. Then it can be
  133. # proved that a rational number is a best upper or lower
  134. # approximation to x if, and only if, it is a convergent or
  135. # semiconvergent of the (unique shortest) continued fraction
  136. # associated to x.
  137. #
  138. # To find a best rational approximation with denominator <= M,
  139. # we find the best upper and lower approximations with
  140. # denominator <= M and take whichever of these is closer to x.
  141. # In the event of a tie, the bound with smaller denominator is
  142. # chosen. If both denominators are equal (which can happen
  143. # only when max_denominator == 1 and self is midway between
  144. # two integers) the lower bound---i.e., the floor of self, is
  145. # taken.
  146. if max_denominator < 1:
  147. raise ValueError("max_denominator should be at least 1")
  148. if self._denominator <= max_denominator:
  149. return Fraction(self)
  150. p0, q0, p1, q1 = 0, 1, 1, 0
  151. n, d = self._numerator, self._denominator
  152. while True:
  153. a = n//d
  154. q2 = q0+a*q1
  155. if q2 > max_denominator:
  156. break
  157. p0, q0, p1, q1 = p1, q1, p0+a*p1, q2
  158. n, d = d, n-a*d
  159. k = (max_denominator-q0)//q1
  160. bound1 = Fraction(p0+k*p1, q0+k*q1)
  161. bound2 = Fraction(p1, q1)
  162. if abs(bound2 - self) <= abs(bound1-self):
  163. return bound2
  164. else:
  165. return bound1
  166. @property
  167. def numerator(a):
  168. return a._numerator
  169. @property
  170. def denominator(a):
  171. return a._denominator
  172. def __repr__(self):
  173. """repr(self)"""
  174. return ('Fraction(%s, %s)' % (self._numerator, self._denominator))
  175. def __str__(self):
  176. """str(self)"""
  177. if self._denominator == 1:
  178. return str(self._numerator)
  179. else:
  180. return '%s/%s' % (self._numerator, self._denominator)
  181. def _operator_fallbacks(monomorphic_operator, fallback_operator):
  182. """Generates forward and reverse operators given a purely-rational
  183. operator and a function from the operator module.
  184. Use this like:
  185. __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op)
  186. In general, we want to implement the arithmetic operations so
  187. that mixed-mode operations either call an implementation whose
  188. author knew about the types of both arguments, or convert both
  189. to the nearest built in type and do the operation there. In
  190. Fraction, that means that we define __add__ and __radd__ as:
  191. def __add__(self, other):
  192. # Both types have numerators/denominator attributes,
  193. # so do the operation directly
  194. if isinstance(other, (int, long, Fraction)):
  195. return Fraction(self.numerator * other.denominator +
  196. other.numerator * self.denominator,
  197. self.denominator * other.denominator)
  198. # float and complex don't have those operations, but we
  199. # know about those types, so special case them.
  200. elif isinstance(other, float):
  201. return float(self) + other
  202. elif isinstance(other, complex):
  203. return complex(self) + other
  204. # Let the other type take over.
  205. return NotImplemented
  206. def __radd__(self, other):
  207. # radd handles more types than add because there's
  208. # nothing left to fall back to.
  209. if isinstance(other, Rational):
  210. return Fraction(self.numerator * other.denominator +
  211. other.numerator * self.denominator,
  212. self.denominator * other.denominator)
  213. elif isinstance(other, Real):
  214. return float(other) + float(self)
  215. elif isinstance(other, Complex):
  216. return complex(other) + complex(self)
  217. return NotImplemented
  218. There are 5 different cases for a mixed-type addition on
  219. Fraction. I'll refer to all of the above code that doesn't
  220. refer to Fraction, float, or complex as "boilerplate". 'r'
  221. will be an instance of Fraction, which is a subtype of
  222. Rational (r : Fraction <: Rational), and b : B <:
  223. Complex. The first three involve 'r + b':
  224. 1. If B <: Fraction, int, float, or complex, we handle
  225. that specially, and all is well.
  226. 2. If Fraction falls back to the boilerplate code, and it
  227. were to return a value from __add__, we'd miss the
  228. possibility that B defines a more intelligent __radd__,
  229. so the boilerplate should return NotImplemented from
  230. __add__. In particular, we don't handle Rational
  231. here, even though we could get an exact answer, in case
  232. the other type wants to do something special.
  233. 3. If B <: Fraction, Python tries B.__radd__ before
  234. Fraction.__add__. This is ok, because it was
  235. implemented with knowledge of Fraction, so it can
  236. handle those instances before delegating to Real or
  237. Complex.
  238. The next two situations describe 'b + r'. We assume that b
  239. didn't know about Fraction in its implementation, and that it
  240. uses similar boilerplate code:
  241. 4. If B <: Rational, then __radd_ converts both to the
  242. builtin rational type (hey look, that's us) and
  243. proceeds.
  244. 5. Otherwise, __radd__ tries to find the nearest common
  245. base ABC, and fall back to its builtin type. Since this
  246. class doesn't subclass a concrete type, there's no
  247. implementation to fall back to, so we need to try as
  248. hard as possible to return an actual value, or the user
  249. will get a TypeError.
  250. """
  251. def forward(a, b):
  252. if isinstance(b, (int, long, Fraction)):
  253. return monomorphic_operator(a, b)
  254. elif isinstance(b, float):
  255. return fallback_operator(float(a), b)
  256. elif isinstance(b, complex):
  257. return fallback_operator(complex(a), b)
  258. else:
  259. return NotImplemented
  260. forward.__name__ = '__' + fallback_operator.__name__ + '__'
  261. forward.__doc__ = monomorphic_operator.__doc__
  262. def reverse(b, a):
  263. if isinstance(a, Rational):
  264. # Includes ints.
  265. return monomorphic_operator(a, b)
  266. elif isinstance(a, numbers.Real):
  267. return fallback_operator(float(a), float(b))
  268. elif isinstance(a, numbers.Complex):
  269. return fallback_operator(complex(a), complex(b))
  270. else:
  271. return NotImplemented
  272. reverse.__name__ = '__r' + fallback_operator.__name__ + '__'
  273. reverse.__doc__ = monomorphic_operator.__doc__
  274. return forward, reverse
  275. def _add(a, b):
  276. """a + b"""
  277. return Fraction(a.numerator * b.denominator +
  278. b.numerator * a.denominator,
  279. a.denominator * b.denominator)
  280. __add__, __radd__ = _operator_fallbacks(_add, operator.add)
  281. def _sub(a, b):
  282. """a - b"""
  283. return Fraction(a.numerator * b.denominator -
  284. b.numerator * a.denominator,
  285. a.denominator * b.denominator)
  286. __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub)
  287. def _mul(a, b):
  288. """a * b"""
  289. return Fraction(a.numerator * b.numerator, a.denominator * b.denominator)
  290. __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul)
  291. def _div(a, b):
  292. """a / b"""
  293. return Fraction(a.numerator * b.denominator,
  294. a.denominator * b.numerator)
  295. __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv)
  296. __div__, __rdiv__ = _operator_fallbacks(_div, operator.div)
  297. def __floordiv__(a, b):
  298. """a // b"""
  299. # Will be math.floor(a / b) in 3.0.
  300. div = a / b
  301. if isinstance(div, Rational):
  302. # trunc(math.floor(div)) doesn't work if the rational is
  303. # more precise than a float because the intermediate
  304. # rounding may cross an integer boundary.
  305. return div.numerator // div.denominator
  306. else:
  307. return math.floor(div)
  308. def __rfloordiv__(b, a):
  309. """a // b"""
  310. # Will be math.floor(a / b) in 3.0.
  311. div = a / b
  312. if isinstance(div, Rational):
  313. # trunc(math.floor(div)) doesn't work if the rational is
  314. # more precise than a float because the intermediate
  315. # rounding may cross an integer boundary.
  316. return div.numerator // div.denominator
  317. else:
  318. return math.floor(div)
  319. def __mod__(a, b):
  320. """a % b"""
  321. div = a // b
  322. return a - b * div
  323. def __rmod__(b, a):
  324. """a % b"""
  325. div = a // b
  326. return a - b * div
  327. def __pow__(a, b):
  328. """a ** b
  329. If b is not an integer, the result will be a float or complex
  330. since roots are generally irrational. If b is an integer, the
  331. result will be rational.
  332. """
  333. if isinstance(b, Rational):
  334. if b.denominator == 1:
  335. power = b.numerator
  336. if power >= 0:
  337. return Fraction(a._numerator ** power,
  338. a._denominator ** power)
  339. else:
  340. return Fraction(a._denominator ** -power,
  341. a._numerator ** -power)
  342. else:
  343. # A fractional power will generally produce an
  344. # irrational number.
  345. return float(a) ** float(b)
  346. else:
  347. return float(a) ** b
  348. def __rpow__(b, a):
  349. """a ** b"""
  350. if b._denominator == 1 and b._numerator >= 0:
  351. # If a is an int, keep it that way if possible.
  352. return a ** b._numerator
  353. if isinstance(a, Rational):
  354. return Fraction(a.numerator, a.denominator) ** b
  355. if b._denominator == 1:
  356. return a ** b._numerator
  357. return a ** float(b)
  358. def __pos__(a):
  359. """+a: Coerces a subclass instance to Fraction"""
  360. return Fraction(a._numerator, a._denominator)
  361. def __neg__(a):
  362. """-a"""
  363. return Fraction(-a._numerator, a._denominator)
  364. def __abs__(a):
  365. """abs(a)"""
  366. return Fraction(abs(a._numerator), a._denominator)
  367. def __trunc__(a):
  368. """trunc(a)"""
  369. if a._numerator < 0:
  370. return -(-a._numerator // a._denominator)
  371. else:
  372. return a._numerator // a._denominator
  373. def __hash__(self):
  374. """hash(self)
  375. Tricky because values that are exactly representable as a
  376. float must have the same hash as that float.
  377. """
  378. # XXX since this method is expensive, consider caching the result
  379. if self._denominator == 1:
  380. # Get integers right.
  381. return hash(self._numerator)
  382. # Expensive check, but definitely correct.
  383. if self == float(self):
  384. return hash(float(self))
  385. else:
  386. # Use tuple's hash to avoid a high collision rate on
  387. # simple fractions.
  388. return hash((self._numerator, self._denominator))
  389. def __eq__(a, b):
  390. """a == b"""
  391. if isinstance(b, Rational):
  392. return (a._numerator == b.numerator and
  393. a._denominator == b.denominator)
  394. if isinstance(b, numbers.Complex) and b.imag == 0:
  395. b = b.real
  396. if isinstance(b, float):
  397. return a == a.from_float(b)
  398. else:
  399. # XXX: If b.__eq__ is implemented like this method, it may
  400. # give the wrong answer after float(a) changes a's
  401. # value. Better ways of doing this are welcome.
  402. return float(a) == b
  403. def _subtractAndCompareToZero(a, b, op):
  404. """Helper function for comparison operators.
  405. Subtracts b from a, exactly if possible, and compares the
  406. result with 0 using op, in such a way that the comparison
  407. won't recurse. If the difference raises a TypeError, returns
  408. NotImplemented instead.
  409. """
  410. if isinstance(b, numbers.Complex) and b.imag == 0:
  411. b = b.real
  412. if isinstance(b, float):
  413. b = a.from_float(b)
  414. try:
  415. # XXX: If b <: Real but not <: Rational, this is likely
  416. # to fall back to a float. If the actual values differ by
  417. # less than MIN_FLOAT, this could falsely call them equal,
  418. # which would make <= inconsistent with ==. Better ways of
  419. # doing this are welcome.
  420. diff = a - b
  421. except TypeError:
  422. return NotImplemented
  423. if isinstance(diff, Rational):
  424. return op(diff.numerator, 0)
  425. return op(diff, 0)
  426. def __lt__(a, b):
  427. """a < b"""
  428. return a._subtractAndCompareToZero(b, operator.lt)
  429. def __gt__(a, b):
  430. """a > b"""
  431. return a._subtractAndCompareToZero(b, operator.gt)
  432. def __le__(a, b):
  433. """a <= b"""
  434. return a._subtractAndCompareToZero(b, operator.le)
  435. def __ge__(a, b):
  436. """a >= b"""
  437. return a._subtractAndCompareToZero(b, operator.ge)
  438. def __nonzero__(a):
  439. """a != 0"""
  440. return a._numerator != 0
  441. # support for pickling, copy, and deepcopy
  442. def __reduce__(self):
  443. return (self.__class__, (str(self),))
  444. def __copy__(self):
  445. if type(self) == Fraction:
  446. return self # I'm immutable; therefore I am my own clone
  447. return self.__class__(self._numerator, self._denominator)
  448. def __deepcopy__(self, memo):
  449. if type(self) == Fraction:
  450. return self # My components are also immutable
  451. return self.__class__(self._numerator, self._denominator)