Plan 9 from Bell Labs’s /usr/web/sources/contrib/stallion/root/sys/lib/python2.7/fractions.pyo

Copyright © 2021 Plan 9 Foundation.
Distributed under the MIT License.
Download the Plan 9 distribution.


�`^c@ s�dZddlmZddlmZddlZddlZddlZddlZddgZ	ej
Z
d�Zej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/sys/lib/python2.7/fractions.pyRs	sC
    \A\s*                      # optional whitespace at the start, then
    (?P<sign>[-+]?)            # an optional sign, then
    (?=\d|\.\d)                # lookahead for digit or .digit
    (?P<num>\d*)               # numerator (possibly empty)
    (?:                        # followed by
       (?:/(?P<denom>\d+))?    # an optional denominator
    |                          # or
       (?:\.(?P<decimal>\d*))? # an optional fractional part
       (?:E(?P<exp>[-+]?\d+))? # and optional exponent
    )
    \s*\Z                      # and optional whitespace to finish
cB s�eZdZd'Zdd(d�Zed��Zed��Zdd�Z	e
d	��Ze
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_denominatoricC s�tt|�j|�}|dkrt|t�rO|j|_|j|_	|St|t
�r�tj|�}|j|_|j	|_	|St|t�r�tj
|�}|j|_|j	|_	|St|t�r�j|�}|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
�dkr	|}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	numeratorRtdenominatorRtfloatt
from_floatRtfrom_decimalt
basestringt_RATIONAL_FORMATtmatcht
ValueErrortinttgrouptlent	TypeErrortZeroDivisionErrorR(tclsRRtselftvaluetmR
RtscaleRtg((s/sys/lib/python2.7/fractions.pyRDsf





cC s�t|tj�r||�St|t�sStd|j|t|�jf��ntj|�sqtj	|�r�td||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/sys/lib/python2.7/fractions.pyR�s
"cC s
ddlm}t|tj�r7|t|��}n7t||�sntd|j|t|�jf��n|j	�s�td||jf��n|j
�\}}}tdjt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(RRRR(R)RR R*R+t	is_finitetas_tupletjointmaptstr(R"tdecRR
tdigitsR((s/sys/lib/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/sys/lib/python2.7/fractions.pytlimit_denominator�s& 
	
& cC s|jS(N(R(R((s/sys/lib/python2.7/fractions.pyRscC s|jS(N(R(R((s/sys/lib/python2.7/fractions.pyR	scC sd|j|jfS(s
repr(self)sFraction(%s, %s)(RR(R#((s/sys/lib/python2.7/fractions.pyt__repr__
scC s4|jdkrt|j�Sd|j|jfSdS(s	str(self)is%s/%sN(RR6R(R#((s/sys/lib/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/sys/lib/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/sys/lib/python2.7/fractions.pytreversets
t__r(R*t__doc__(RMRLRNRR((RLRMs/sys/lib/python2.7/fractions.pyt_operator_fallbackssP	
cC s/t|j|j|j|j|j|j�S(sa + b(RRR(RR((s/sys/lib/python2.7/fractions.pyt_add�scC s/t|j|j|j|j|j|j�S(sa - b(RRR(RR((s/sys/lib/python2.7/fractions.pyt_sub�scC s!t|j|j|j|j�S(sa * b(RRR(RR((s/sys/lib/python2.7/fractions.pyt_mul�scC s!t|j|j|j|j�S(sa / b(RRR(RR((s/sys/lib/python2.7/fractions.pyt_div�scC s8||}t|t�r'|j|jStj|�SdS(sa // bN(RRRRR,tfloor(RRtdiv((s/sys/lib/python2.7/fractions.pyt__floordiv__�s
cC s8||}t|t�r'|j|jStj|�SdS(sa // bN(RRRRR,RZ(RRR[((s/sys/lib/python2.7/fractions.pyt
__rfloordiv__�s
cC s||}|||S(sa % b((RRR[((s/sys/lib/python2.7/fractions.pyt__mod__�s
cC s||}|||S(sa % b((RRR[((s/sys/lib/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/sys/lib/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/sys/lib/python2.7/fractions.pyt__rpow__�scC st|j|j�S(s++a: Coerces a subclass instance to Fraction(RRR(R((s/sys/lib/python2.7/fractions.pyt__pos__�scC st|j|j�S(s-a(RRR(R((s/sys/lib/python2.7/fractions.pyt__neg__�scC stt|j�|j�S(sabs(a)(RR:RR(R((s/sys/lib/python2.7/fractions.pyt__abs__�scC s1|jdkr|j|jS|j|jSdS(strunc(a)iN(RR(R((s/sys/lib/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/sys/lib/python2.7/fractions.pyt__hash__�s

cC s�t|t�r1|j|jko0|j|jkSt|tj�r^|jdkr^|j	}nt|t
�r�tj|�s�tj
|�r�d|kS||j|�kSntSdS(sa == bigN(RRRRRRR(RQtimagtrealRR,R-R.RRK(RR((s/sys/lib/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/sys/lib/python2.7/fractions.pyt_richcmp"s
cC s|j|tj�S(sa < b(Rntoperatortlt(RR((s/sys/lib/python2.7/fractions.pyt__lt__<scC s|j|tj�S(sa > b(RnRotgt(RR((s/sys/lib/python2.7/fractions.pyt__gt__@scC s|j|tj�S(sa <= b(RnRotle(RR((s/sys/lib/python2.7/fractions.pyt__le__DscC s|j|tj�S(sa >= b(RnRotge(RR((s/sys/lib/python2.7/fractions.pyt__ge__HscC s
|jdkS(sa != 0i(R(R((s/sys/lib/python2.7/fractions.pyt__nonzero__LscC s|jt|�ffS(N(t	__class__R6(R#((s/sys/lib/python2.7/fractions.pyt
__reduce__RscC s,t|�tkr|S|j|j|j�S(N(R+RRyRR(R#((s/sys/lib/python2.7/fractions.pyt__copy__UscC s,t|�tkr|S|j|j|j�S(N(R+RRyRR(R#tmemo((s/sys/lib/python2.7/fractions.pyt__deepcopy__Zs(s
_numerators_denominatorN(9R*t
__module__RTt	__slots__RRtclassmethodRRRFtpropertyRRRGRHRURVRotaddt__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/sys/lib/python2.7/fractions.pyR,sRd7			k																								(RTt
__future__RRRR,R(Rotret__all__RRtcompiletVERBOSEt
IGNORECASERR(((s/sys/lib/python2.7/fractions.pyt<module>s		

Bell Labs OSI certified Powered by Plan 9

(Return to Plan 9 Home Page)

Copyright © 2021 Plan 9 Foundation. All Rights Reserved.
Comments to [email protected].