PageRenderTime 49ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/fractions.py

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