ž ¦ÿfùYc@s»dZddlmZddlZddlZddlZddlZddlZddgZdd„Z ej j Z ej j ZejdejejBƒZGdd„dejƒZdS( u+Fraction, infinite-precision, real numbers.i(uDecimalNuFractionugcdcCs"x|r|||}}qW|S(u¶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). ((uaub((u./opt/alt/python33/lib64/python3.3/fractions.pyugcds uC \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 csf|EeZdZdZdPZddQ‡fdd†Zedd„ƒZed d „ƒZ d d d „Z e dd„ƒZ e dd„ƒZ dd„Zdd„Zdd„Zdd„Zeeejƒ\ZZdd„Zeeejƒ\ZZdd„Zeeejƒ\ZZdd„Zeeejƒ\Z Z!d d!„Z"d"d#„Z#d$d%„Z$d&d'„Z%d(d)„Z&d*d+„Z'd,d-„Z(d.d/„Z)d0d1„Z*d2d3„Z+d4d5„Z,d6d7„Z-dQd8d9„Z.d:d;„Z/d<d=„Z0d>d?„Z1d@dA„Z2dBdC„Z3dDdE„Z4dFdG„Z5dHdI„Z6dJdK„Z7dLdM„Z8dNdO„Z9‡S(RuFractionu]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) u _numeratoru _denominatoric s¯tt|ƒj|ƒ}|dkrt|tjƒrR|j|_|j |_ |St|t ƒrŒtj |ƒ}|j|_|j |_ |St|t ƒrÆtj|ƒ}|j|_|j |_ |St|tƒrtj|ƒ}|dkrtd|ƒ‚nt|jdƒpdƒ}|jdƒ}|rBt|ƒ}nœd}|jdƒ}|rŽdt|ƒ}||t|ƒ}||9}n|jdƒ} | rÞt| ƒ} | d krÌ|d| 9}qÞ|d| 9}n|jd ƒd kr | }q qctd ƒ‚nTt|tjƒrWt|tjƒrW|j|j |j|j }}n td ƒ‚|d kr‚td|ƒ‚nt||ƒ} || |_|| |_ |S(u£Constructs a Rational. 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) u Invalid literal for Fraction: %runumu0udenomiudecimali uexpiusignu-u2argument should be a string or a Rational instanceu+both arguments should be Rational instancesuFraction(%s, 0)N(usuperuFractionu__new__uNoneu isinstanceunumbersuRationalu numeratoru _numeratoru denominatoru _denominatorufloatu from_floatuDecimalu from_decimalustru_RATIONAL_FORMATumatchu ValueErroruintugroupulenu TypeErroruZeroDivisionErrorugcd( uclsu numeratoru denominatoruselfuvalueumudenomudecimaluscaleuexpug(u __class__(u./opt/alt/python33/lib64/python3.3/fractions.pyu__new__Isf                  uFraction.__new__cCst|tjƒr||ƒSt|tƒsStd|j|t|ƒjfƒ‚ntj|ƒsqtj |ƒrtd||jfƒ‚n||j ƒŒS(u‚Converts a finite float to a rational number, exactly. Beware that Fraction.from_float(0.3) != Fraction(3, 10). u.%s.from_float() only takes floats, not %r (%s)uCannot convert %r to %s.( u isinstanceunumbersuIntegralufloatu TypeErroru__name__utypeumathuisnanuisinfuas_integer_ratio(uclsuf((u./opt/alt/python33/lib64/python3.3/fractions.pyu from_float­s "uFraction.from_floatcCs 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(uAConverts a finite Decimal instance to a rational number, exactly.i(uDecimalu2%s.from_decimal() only takes Decimals, not %r (%s)uCannot convert %s to %s.ui N(udecimaluDecimalu isinstanceunumbersuIntegraluintu TypeErroru__name__utypeu is_finiteuas_tupleujoinumapustr(uclsudecuDecimalusignudigitsuexp((u./opt/alt/python33/lib64/python3.3/fractions.pyu from_decimal½s "   uFraction.from_decimali@Bc Cs*|dkrtdƒ‚n|j|kr4t|ƒSd\}}}}|j|j}}xf||}|||} | |kr„Pn|||||| f\}}}}||||}}q\|||} t|| ||| |ƒ} t||ƒ} t| |ƒt| |ƒkr"| S| SdS(uWClosest 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) iu$max_denominator should be at least 1iN(iiii(u ValueErroru _denominatoruFractionu _numeratoruabs( uselfumax_denominatorup0uq0up1uq1unuduauq2ukubound1ubound2((u./opt/alt/python33/lib64/python3.3/fractions.pyulimit_denominatorÓs&    & uFraction.limit_denominatorcCs|jS(N(u _numerator(ua((u./opt/alt/python33/lib64/python3.3/fractions.pyu numerator suFraction.numeratorcCs|jS(N(u _denominator(ua((u./opt/alt/python33/lib64/python3.3/fractions.pyu denominatorsuFraction.denominatorcCsd|j|jfS(u repr(self)uFraction(%s, %s)(u _numeratoru _denominator(uself((u./opt/alt/python33/lib64/python3.3/fractions.pyu__repr__suFraction.__repr__cCs4|jdkrt|jƒSd|j|jfSdS(u str(self)iu%s/%sN(u _denominatorustru _numerator(uself((u./opt/alt/python33/lib64/python3.3/fractions.pyu__str__s uFraction.__str__cst‡‡fdd†}dˆjd|_ˆj|_‡‡fdd†}dˆjd|_ˆj|_||fS(uÕ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, 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, numbers.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. csnt|ttfƒr"ˆ||ƒSt|tƒrDˆt|ƒ|ƒSt|tƒrfˆt|ƒ|ƒStSdS(N(u isinstanceuintuFractionufloatucomplexuNotImplemented(uaub(ufallback_operatorumonomorphic_operator(u./opt/alt/python33/lib64/python3.3/fractions.pyuforwardms u-Fraction._operator_fallbacks..forwardu__cs}t|tjƒrˆ||ƒSt|tjƒrJˆt|ƒt|ƒƒSt|tjƒruˆt|ƒt|ƒƒStSdS(N(u isinstanceunumbersuRationaluRealufloatuComplexucomplexuNotImplemented(ubua(ufallback_operatorumonomorphic_operator(u./opt/alt/python33/lib64/python3.3/fractions.pyureverseys u-Fraction._operator_fallbacks..reverseu__r(u__name__u__doc__(umonomorphic_operatorufallback_operatoruforwardureverse((ufallback_operatorumonomorphic_operatoru./opt/alt/python33/lib64/python3.3/fractions.pyu_operator_fallbackssP    uFraction._operator_fallbackscCs/t|j|j|j|j|j|jƒS(ua + b(uFractionu numeratoru denominator(uaub((u./opt/alt/python33/lib64/python3.3/fractions.pyu_addˆsu Fraction._addcCs/t|j|j|j|j|j|jƒS(ua - b(uFractionu numeratoru denominator(uaub((u./opt/alt/python33/lib64/python3.3/fractions.pyu_subsu Fraction._subcCs!t|j|j|j|jƒS(ua * b(uFractionu numeratoru denominator(uaub((u./opt/alt/python33/lib64/python3.3/fractions.pyu_mul˜su Fraction._mulcCs!t|j|j|j|jƒS(ua / b(uFractionu numeratoru denominator(uaub((u./opt/alt/python33/lib64/python3.3/fractions.pyu_divžsu Fraction._divcCstj||ƒS(ua // b(umathufloor(uaub((u./opt/alt/python33/lib64/python3.3/fractions.pyu __floordiv__¥suFraction.__floordiv__cCstj||ƒS(ua // b(umathufloor(ubua((u./opt/alt/python33/lib64/python3.3/fractions.pyu __rfloordiv__©suFraction.__rfloordiv__cCs||}|||S(ua % b((uaubudiv((u./opt/alt/python33/lib64/python3.3/fractions.pyu__mod__­s uFraction.__mod__cCs||}|||S(ua % b((ubuaudiv((u./opt/alt/python33/lib64/python3.3/fractions.pyu__rmod__²s uFraction.__rmod__cCsšt|tjƒrˆ|jdkrq|j}|dkrQt|j||j|ƒSt|j| |j| ƒSq–t|ƒt|ƒSnt|ƒ|SdS(u¾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( u isinstanceunumbersuRationalu denominatoru numeratoruFractionu _numeratoru _denominatorufloat(uaubupower((u./opt/alt/python33/lib64/python3.3/fractions.pyu__pow__·s   uFraction.__pow__cCsz|jdkr)|jdkr)||jSt|tjƒrRt|j|jƒ|S|jdkrl||jS|t|ƒS(ua ** bii( u _denominatoru _numeratoru isinstanceunumbersuRationaluFractionu numeratoru denominatorufloat(ubua((u./opt/alt/python33/lib64/python3.3/fractions.pyu__rpow__Ïs  uFraction.__rpow__cCst|j|jƒS(u++a: Coerces a subclass instance to Fraction(uFractionu _numeratoru _denominator(ua((u./opt/alt/python33/lib64/python3.3/fractions.pyu__pos__ÝsuFraction.__pos__cCst|j |jƒS(u-a(uFractionu _numeratoru _denominator(ua((u./opt/alt/python33/lib64/python3.3/fractions.pyu__neg__ásuFraction.__neg__cCstt|jƒ|jƒS(uabs(a)(uFractionuabsu _numeratoru _denominator(ua((u./opt/alt/python33/lib64/python3.3/fractions.pyu__abs__åsuFraction.__abs__cCs1|jdkr|j |j S|j|jSdS(utrunc(a)iN(u _numeratoru _denominator(ua((u./opt/alt/python33/lib64/python3.3/fractions.pyu __trunc__ésuFraction.__trunc__cCs|j|jS(uWill be math.floor(a) in 3.0.(u numeratoru denominator(ua((u./opt/alt/python33/lib64/python3.3/fractions.pyu __floor__ðsuFraction.__floor__cCs|j |j S(uWill be math.ceil(a) in 3.0.(u numeratoru denominator(ua((u./opt/alt/python33/lib64/python3.3/fractions.pyu__ceil__ôsuFraction.__ceil__cCsÇ|dkrxt|j|jƒ\}}|d|jkr>|S|d|jkrY|dS|ddkrm|S|dSndt|ƒ}|dkr«tt||ƒ|ƒStt||ƒ|ƒSdS(uOWill be round(self, ndigits) in 3.0. Rounds half toward even. iiii N(uNoneudivmodu numeratoru denominatoruabsuFractionuround(uselfundigitsuflooru remainderushift((u./opt/alt/python33/lib64/python3.3/fractions.pyu __round__ùs   uFraction.__round__cCslt|jtdtƒ}|s(t}nt|jƒ|t}|dkrQ|n| }|dkrhdS|S(u hash(self)iiiiÿÿÿÿiþÿÿÿ(upowu _denominatoru_PyHASH_MODULUSu _PyHASH_INFuabsu _numerator(uselfudinvuhash_uresult((u./opt/alt/python33/lib64/python3.3/fractions.pyu__hash__s  uFraction.__hash__cCs¶t|tjƒr4|j|jko3|j|jkSt|tjƒra|jdkra|j }nt|t ƒr®t j |ƒsŽt j |ƒr˜d|kS||j|ƒkSntSdS(ua == bigN(u isinstanceunumbersuRationalu _numeratoru numeratoru _denominatoru denominatoruComplexuimagurealufloatumathuisnanuisinfu from_floatuNotImplemented(uaub((u./opt/alt/python33/lib64/python3.3/fractions.pyu__eq__(s!  uFraction.__eq__cCsŽt|tjƒr3||j|j|j|jƒSt|tƒr†tj |ƒs`tj |ƒrm|d|ƒS|||j |ƒƒSnt SdS(ucHelper 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. gN( u isinstanceunumbersuRationalu _numeratoru denominatoru _denominatoru numeratorufloatumathuisnanuisinfu from_floatuNotImplemented(uselfuotheruop((u./opt/alt/python33/lib64/python3.3/fractions.pyu_richcmp;s  uFraction._richcmpcCs|j|tjƒS(ua < b(u_richcmpuoperatorult(uaub((u./opt/alt/python33/lib64/python3.3/fractions.pyu__lt__QsuFraction.__lt__cCs|j|tjƒS(ua > b(u_richcmpuoperatorugt(uaub((u./opt/alt/python33/lib64/python3.3/fractions.pyu__gt__UsuFraction.__gt__cCs|j|tjƒS(ua <= b(u_richcmpuoperatorule(uaub((u./opt/alt/python33/lib64/python3.3/fractions.pyu__le__YsuFraction.__le__cCs|j|tjƒS(ua >= b(u_richcmpuoperatoruge(uaub((u./opt/alt/python33/lib64/python3.3/fractions.pyu__ge__]suFraction.__ge__cCs |jdkS(ua != 0i(u _numerator(ua((u./opt/alt/python33/lib64/python3.3/fractions.pyu__bool__asuFraction.__bool__cCs|jt|ƒffS(N(u __class__ustr(uself((u./opt/alt/python33/lib64/python3.3/fractions.pyu __reduce__gsuFraction.__reduce__cCs,t|ƒtkr|S|j|j|jƒS(N(utypeuFractionu __class__u _numeratoru _denominator(uself((u./opt/alt/python33/lib64/python3.3/fractions.pyu__copy__jsuFraction.__copy__cCs,t|ƒtkr|S|j|j|jƒS(N(utypeuFractionu __class__u _numeratoru _denominator(uselfumemo((u./opt/alt/python33/lib64/python3.3/fractions.pyu __deepcopy__osuFraction.__deepcopy__(u _numeratoru _denominatorN(:u__name__u __module__u __qualname__u__doc__u __slots__uNoneu__new__u classmethodu from_floatu from_decimalulimit_denominatorupropertyu numeratoru denominatoru__repr__u__str__u_operator_fallbacksu_adduoperatoruaddu__add__u__radd__u_subusubu__sub__u__rsub__u_mulumulu__mul__u__rmul__u_divutruedivu __truediv__u __rtruediv__u __floordiv__u __rfloordiv__u__mod__u__rmod__u__pow__u__rpow__u__pos__u__neg__u__abs__u __trunc__u __floor__u__ceil__u __round__u__hash__u__eq__u_richcmpu__lt__u__gt__u__le__u__ge__u__bool__u __reduce__u__copy__u __deepcopy__(u __locals__((u __class__u./opt/alt/python33/lib64/python3.3/fractions.pyuFraction1sVd7   k                          (u__doc__udecimaluDecimalumathunumbersuoperatorureusysu__all__ugcdu hash_infoumodulusu_PyHASH_MODULUSuinfu _PyHASH_INFucompileuVERBOSEu IGNORECASEu_RATIONAL_FORMATuRationaluFraction(((u./opt/alt/python33/lib64/python3.3/fractions.pyus