ó m”þfc@ sªdZddlmZddlmZddlZddlZddlZddlZddgZ ej Z d„Z ej dej ejBƒZde fd „ƒYZdS( s+Rational, infinite-precision, real numbers.iÿÿÿÿ(tdivision(tDecimalNtFractiontgcdcC s"x|r|||}}qW|S(s¶Calculate the Greatest Common Divisor of a and b. Unless b==0, the result will have the same sign as b (so that when b is divided by it, the result comes out positive). ((tatb((s!/usr/lib64/python2.7/fractions.pyRs sC \A\s* # optional whitespace at the start, then (?P[-+]?) # an optional sign, then (?=\d|\.\d) # lookahead for digit or .digit (?P\d*) # numerator (possibly empty) (?: # followed by (?:/(?P\d+))? # an optional denominator | # or (?:\.(?P\d*))? # an optional fractional part (?:E(?P[-+]?\d+))? # and optional exponent ) \s*\Z # and optional whitespace to finish cB sßeZdZd'Zdd(d„Zed„ƒZed„ƒZdd„Z e d „ƒZ e d „ƒZ d „Z d „Zd „Zd„Zeeejƒ\ZZd„Zeeejƒ\ZZd„Zeeejƒ\ZZd„Zeeejƒ\ZZ eeej!ƒ\Z"Z#d„Z$d„Z%d„Z&d„Z'd„Z(d„Z)d„Z*d„Z+d„Z,d„Z-d„Z.d„Z/d„Z0d„Z1d „Z2d!„Z3d"„Z4d#„Z5d$„Z6d%„Z7d&„Z8RS()s]This class implements rational numbers. In the two-argument form of the constructor, Fraction(8, 6) will produce a rational number equivalent to 4/3. Both arguments must be Rational. The numerator defaults to 0 and the denominator defaults to 1 so that Fraction(3) == 3 and Fraction() == 0. Fractions can also be constructed from: - numeric strings similar to those accepted by the float constructor (for example, '-2.3' or '1e10') - strings of the form '123/456' - float and Decimal instances - other Rational instances (including integers) t _numeratort _denominatoric C s¦tt|ƒj|ƒ}|dkr t|tƒrO|j|_|j|_ |St|t ƒr‰tj |ƒ}|j|_|j |_ |St|t ƒrÃtj |ƒ}|j|_|j |_ |St|tƒrýtj|ƒ}|dkrtd|ƒ‚nt|jdƒpdƒ}|jdƒ}|r?t|ƒ}nœd}|jdƒ}|r‹dt|ƒ}||t|ƒ}||9}n|jdƒ} | rÛt| ƒ} | d krÉ|d| 9}qÛ|d| 9}n|jd ƒd kr | }q qZtd ƒ‚nNt|tƒrNt|tƒrN|j|j|j|j}}n td ƒ‚|d krytd|ƒ‚nt||ƒ} || |_|| |_ |S(s£Constructs a Fraction. Takes a string like '3/2' or '1.5', another Rational instance, a numerator/denominator pair, or a float. Examples -------- >>> Fraction(10, -8) Fraction(-5, 4) >>> Fraction(Fraction(1, 7), 5) Fraction(1, 35) >>> Fraction(Fraction(1, 7), Fraction(2, 3)) Fraction(3, 14) >>> Fraction('314') Fraction(314, 1) >>> Fraction('-35/4') Fraction(-35, 4) >>> Fraction('3.1415') # conversion from numeric string Fraction(6283, 2000) >>> Fraction('-47e-2') # string may include a decimal exponent Fraction(-47, 100) >>> Fraction(1.47) # direct construction from float (exact conversion) Fraction(6620291452234629, 4503599627370496) >>> Fraction(2.25) Fraction(9, 4) >>> Fraction(Decimal('1.47')) Fraction(147, 100) s Invalid literal for Fraction: %rtnumt0tdenomitdecimali texpitsignt-s2argument should be a string or a Rational instances+both arguments should be Rational instancessFraction(%s, 0)N(tsuperRt__new__tNonet isinstancetRationalt numeratorRt denominatorRtfloatt from_floatRt from_decimalt basestringt_RATIONAL_FORMATtmatcht ValueErrortinttgrouptlent TypeErrortZeroDivisionErrorR( tclsRRtselftvaluetmR R tscaleR tg((s!/usr/lib64/python2.7/fractions.pyRDsf                  cC st|tjƒr||ƒSt|tƒsStd|j|t|ƒjfƒ‚ntj|ƒsqtj |ƒrtd||jfƒ‚n||j ƒŒS(s‚Converts a finite float to a rational number, exactly. Beware that Fraction.from_float(0.3) != Fraction(3, 10). s.%s.from_float() only takes floats, not %r (%s)sCannot convert %r to %s.( RtnumberstIntegralRR t__name__ttypetmathtisnantisinftas_integer_ratio(R"tf((s!/usr/lib64/python2.7/fractions.pyR¨s "cC s ddlm}t|tjƒr7|t|ƒƒ}n7t||ƒsntd|j|t|ƒjfƒ‚n|j ƒs–td||jfƒ‚n|j ƒ\}}}tdj t t |ƒƒƒ}|rÙ| }n|dkr÷||d|ƒS||d| ƒSdS( sAConverts a finite Decimal instance to a rational number, exactly.iÿÿÿÿ(Rs2%s.from_decimal() only takes Decimals, not %r (%s)sCannot convert %s to %s.tii N(R RRR(R)RR R*R+t is_finitetas_tupletjointmaptstr(R"tdecRR tdigitsR ((s!/usr/lib64/python2.7/fractions.pyR¸s "   i@Bc C s1|dkrtdƒ‚n|j|kr4t|ƒSd\}}}}|j|j}}xmtrÈ||}|||} | |krŠPn|||||| f\}}}}||||}}q\W|||} t|| ||| |ƒ} t||ƒ} t| |ƒt| |ƒkr)| S| SdS(sWClosest Fraction to self with denominator at most max_denominator. >>> Fraction('3.141592653589793').limit_denominator(10) Fraction(22, 7) >>> Fraction('3.141592653589793').limit_denominator(100) Fraction(311, 99) >>> Fraction(4321, 8765).limit_denominator(10000) Fraction(4321, 8765) is$max_denominator should be at least 1iN(iiii(RRRRtTruetabs( R#tmax_denominatortp0tq0tp1tq1tntdRtq2tktbound1tbound2((s!/usr/lib64/python2.7/fractions.pytlimit_denominatorÎs&     & cC s|jS(N(R(R((s!/usr/lib64/python2.7/fractions.pyRscC s|jS(N(R(R((s!/usr/lib64/python2.7/fractions.pyR scC sd|j|jfS(s repr(self)sFraction(%s, %s)(RR(R#((s!/usr/lib64/python2.7/fractions.pyt__repr__ scC s4|jdkrt|jƒSd|j|jfSdS(s str(self)is%s/%sN(RR6R(R#((s!/usr/lib64/python2.7/fractions.pyt__str__s c sn‡‡fd†}dˆjd|_ˆj|_‡‡fd†}dˆjd|_ˆj|_||fS(sÓGenerates forward and reverse operators given a purely-rational operator and a function from the operator module. Use this like: __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op) In general, we want to implement the arithmetic operations so that mixed-mode operations either call an implementation whose author knew about the types of both arguments, or convert both to the nearest built in type and do the operation there. In Fraction, that means that we define __add__ and __radd__ as: def __add__(self, other): # Both types have numerators/denominator attributes, # so do the operation directly if isinstance(other, (int, long, Fraction)): return Fraction(self.numerator * other.denominator + other.numerator * self.denominator, self.denominator * other.denominator) # float and complex don't have those operations, but we # know about those types, so special case them. elif isinstance(other, float): return float(self) + other elif isinstance(other, complex): return complex(self) + other # Let the other type take over. return NotImplemented def __radd__(self, other): # radd handles more types than add because there's # nothing left to fall back to. if isinstance(other, Rational): return Fraction(self.numerator * other.denominator + other.numerator * self.denominator, self.denominator * other.denominator) elif isinstance(other, Real): return float(other) + float(self) elif isinstance(other, Complex): return complex(other) + complex(self) return NotImplemented There are 5 different cases for a mixed-type addition on Fraction. I'll refer to all of the above code that doesn't refer to Fraction, float, or complex as "boilerplate". 'r' will be an instance of Fraction, which is a subtype of Rational (r : Fraction <: Rational), and b : B <: Complex. The first three involve 'r + b': 1. If B <: Fraction, int, float, or complex, we handle that specially, and all is well. 2. If Fraction falls back to the boilerplate code, and it were to return a value from __add__, we'd miss the possibility that B defines a more intelligent __radd__, so the boilerplate should return NotImplemented from __add__. In particular, we don't handle Rational here, even though we could get an exact answer, in case the other type wants to do something special. 3. If B <: Fraction, Python tries B.__radd__ before Fraction.__add__. This is ok, because it was implemented with knowledge of Fraction, so it can handle those instances before delegating to Real or Complex. The next two situations describe 'b + r'. We assume that b didn't know about Fraction in its implementation, and that it uses similar boilerplate code: 4. If B <: Rational, then __radd_ converts both to the builtin rational type (hey look, that's us) and proceeds. 5. Otherwise, __radd__ tries to find the nearest common base ABC, and fall back to its builtin type. Since this class doesn't subclass a concrete type, there's no implementation to fall back to, so we need to try as hard as possible to return an actual value, or the user will get a TypeError. c sqt|tttfƒr%ˆ||ƒSt|tƒrGˆt|ƒ|ƒSt|tƒriˆt|ƒ|ƒStSdS(N(RRtlongRRtcomplextNotImplemented(RR(tfallback_operatortmonomorphic_operator(s!/usr/lib64/python2.7/fractions.pytforwardhs t__c szt|tƒrˆ||ƒSt|tjƒrGˆt|ƒt|ƒƒSt|tjƒrrˆt|ƒt|ƒƒStSdS(N(RRR(tRealRtComplexRJRK(RR(RLRM(s!/usr/lib64/python2.7/fractions.pytreversets t__r(R*t__doc__(RMRLRNRR((RLRMs!/usr/lib64/python2.7/fractions.pyt_operator_fallbackssP    cC s/t|j|j|j|j|j|jƒS(sa + b(RRR(RR((s!/usr/lib64/python2.7/fractions.pyt_addƒscC s/t|j|j|j|j|j|jƒS(sa - b(RRR(RR((s!/usr/lib64/python2.7/fractions.pyt_sub‹scC s!t|j|j|j|jƒS(sa * b(RRR(RR((s!/usr/lib64/python2.7/fractions.pyt_mul“scC s!t|j|j|j|jƒS(sa / b(RRR(RR((s!/usr/lib64/python2.7/fractions.pyt_div™scC s8||}t|tƒr'|j|jStj|ƒSdS(sa // bN(RRRRR,tfloor(RRtdiv((s!/usr/lib64/python2.7/fractions.pyt __floordiv__¡s cC s8||}t|tƒr'|j|jStj|ƒSdS(sa // bN(RRRRR,RZ(RRR[((s!/usr/lib64/python2.7/fractions.pyt __rfloordiv__­s cC s||}|||S(sa % b((RRR[((s!/usr/lib64/python2.7/fractions.pyt__mod__¹s cC s||}|||S(sa % b((RRR[((s!/usr/lib64/python2.7/fractions.pyt__rmod__¾s cC s—t|tƒr…|jdkrn|j}|dkrNt|j||j|ƒSt|j| |j| ƒSq“t|ƒt|ƒSnt|ƒ|SdS(s¾a ** b If b is not an integer, the result will be a float or complex since roots are generally irrational. If b is an integer, the result will be rational. iiN(RRRRRRRR(RRtpower((s!/usr/lib64/python2.7/fractions.pyt__pow__Ãs   cC sw|jdkr)|jdkr)||jSt|tƒrOt|j|jƒ|S|jdkri||jS|t|ƒS(sa ** bii(RRRRRRRR(RR((s!/usr/lib64/python2.7/fractions.pyt__rpow__Ûs  cC st|j|jƒS(s++a: Coerces a subclass instance to Fraction(RRR(R((s!/usr/lib64/python2.7/fractions.pyt__pos__éscC st|j |jƒS(s-a(RRR(R((s!/usr/lib64/python2.7/fractions.pyt__neg__íscC stt|jƒ|jƒS(sabs(a)(RR:RR(R((s!/usr/lib64/python2.7/fractions.pyt__abs__ñscC s1|jdkr|j |j S|j|jSdS(strunc(a)iN(RR(R((s!/usr/lib64/python2.7/fractions.pyt __trunc__õscC sX|jdkrt|jƒS|t|ƒkr>tt|ƒƒSt|j|jfƒSdS(sŒhash(self) Tricky because values that are exactly representable as a float must have the same hash as that float. iN(RthashRR(R#((s!/usr/lib64/python2.7/fractions.pyt__hash__üs  cC s³t|tƒr1|j|jko0|j|jkSt|tjƒr^|jdkr^|j }nt|t ƒr«t j |ƒs‹t j |ƒr•d|kS||j|ƒkSntSdS(sa == bigN(RRRRRRR(RQtimagtrealRR,R-R.RRK(RR((s!/usr/lib64/python2.7/fractions.pyt__eq__s!  cC s©t|tƒr0||j|j|j|jƒSt|tƒrNtdƒ‚nt|tƒr¡t j |ƒs{t j |ƒrˆ|d|ƒS|||j |ƒƒSnt SdS(scHelper for comparison operators, for internal use only. Implement comparison between a Rational instance `self`, and either another Rational instance or a float `other`. If `other` is not a Rational instance or a float, return NotImplemented. `op` should be one of the six standard comparison operators. s3no ordering relation is defined for complex numbersgN(RRRRRRRJR RR,R-R.RRK(R#tothertop((s!/usr/lib64/python2.7/fractions.pyt_richcmp"s  cC s|j|tjƒS(sa < b(Rntoperatortlt(RR((s!/usr/lib64/python2.7/fractions.pyt__lt__<scC s|j|tjƒS(sa > b(RnRotgt(RR((s!/usr/lib64/python2.7/fractions.pyt__gt__@scC s|j|tjƒS(sa <= b(RnRotle(RR((s!/usr/lib64/python2.7/fractions.pyt__le__DscC s|j|tjƒS(sa >= b(RnRotge(RR((s!/usr/lib64/python2.7/fractions.pyt__ge__HscC s |jdkS(sa != 0i(R(R((s!/usr/lib64/python2.7/fractions.pyt __nonzero__LscC s|jt|ƒffS(N(t __class__R6(R#((s!/usr/lib64/python2.7/fractions.pyt __reduce__RscC s,t|ƒtkr|S|j|j|jƒS(N(R+RRyRR(R#((s!/usr/lib64/python2.7/fractions.pyt__copy__UscC s,t|ƒtkr|S|j|j|jƒS(N(R+RRyRR(R#tmemo((s!/usr/lib64/python2.7/fractions.pyt __deepcopy__Zs(s _numerators _denominatorN(9R*t __module__RTt __slots__RRt classmethodRRRFtpropertyRRRGRHRURVRotaddt__add__t__radd__RWtsubt__sub__t__rsub__RXtmult__mul__t__rmul__RYttruedivt __truediv__t __rtruediv__R[t__div__t__rdiv__R\R]R^R_RaRbRcRdReRfRhRkRnRqRsRuRwRxRzR{R}(((s!/usr/lib64/python2.7/fractions.pyR,sRd 7   k                      (RTt __future__RR RR,R(Rotret__all__RRtcompiletVERBOSEt IGNORECASERR(((s!/usr/lib64/python2.7/fractions.pyts