NfodZddlmZddlZddlZddlZddlZddlZdgZej j Z ej j Z ejdejejzZGddejZdS)z/Fraction, infinite-precision, rational numbers.DecimalNFractiona \A\s* # optional whitespace at the start, (?P[-+]?) # an optional sign, then (?=\d|\.\d) # lookahead for digit or .digit (?P\d*|\d+(_\d+)*) # numerator (possibly empty) (?: # followed by (?:/(?P\d+(_\d+)*))? # an optional denominator | # or (?:\.(?Pd*|\d+(_\d+)*))? # an optional fractional part (?:E(?P[-+]?\d+(_\d+)*))? # and optional exponent ) \s*\Z # and optional whitespace to finish cleZdZdZdZd.ddfd ZedZed Zd Z d/d Z e d Z e dZ dZdZdZdZeeej\ZZdZeeej\ZZdZeeej\ZZdZeeej\Z Z!dZ"ee"ej#\Z$Z%dZ&ee&e'\Z(Z)dZ*ee*ej+\Z,Z-dZ.dZ/dZ0dZ1dZ2ej3fdZ4dZ5d Z6d!Z7d0d"Z8d#Z9d$Z:d%Z;d&Zd)Z?d*Z@d+ZAd,ZBd-ZCxZDS)1ra]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)  _numerator _denominatorrNT _normalizectt||}|t|tur||_d|_|St|tj r|j |_|j |_|St|ttfr#|\|_|_|St|tr/t |}|t%d|zt |dpd}|d}|rt |}nd}|d}|rB|dd }d t+|z}||zt |z}||z}|d } | r't | } | d kr |d | zz}n |d | zz}|d dkr| }nt-dt|tcxurt|urnnnbt|tj r9t|tj r|j |j z|j |j z}}nt-d|d krt/d|z|r(t1j||} |d kr| } || z}|| z}||_||_|S)aConstructs 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) Nz Invalid literal for Fraction: %rnum0denomdecimal_ exprsign-z2argument should be a string or a Rational instancez+both arguments should be Rational instanceszFraction(%s, 0))superr__new__typeintrr isinstancenumbersRational numerator denominatorfloatras_integer_ratiostr_RATIONAL_FORMATmatch ValueErrorgroupreplacelen TypeErrorZeroDivisionErrormathgcd) clsrr r selfmrrscalerg __class__s /usr/lib/python3.11/fractions.pyrzFraction.__new__>s->Xs##++C00  I#%%"+$%! Iw'788( :"+"5$-$9! Iw'788# :5>5O5O5Q5Q2!2 Is++ :$**9559$%G%.&/000 5#66 ((4"%e**KK"#Kggi00G-")//#r":": "CLL 0$-$5G $D #u, ''%..C4!#hh!88%S0II'2t83K776??c))!* I !9:::)__ 8 8 8 8tK'8'8 8 8 8 8 8 G$455 2 {G$4 5 5 2#k&==% (==#II 122 2 !  #$5 $ABB B  K00AQB !OI A K#' c t|tjr ||St|ts/t |jd|dt |jd||S)zConverts a finite float to a rational number, exactly. Beware that Fraction.from_float(0.3) != Fraction(3, 10). z%.from_float() only takes floats, not  ())rrIntegralr!r*__name__rr")r.fs r4 from_floatzFraction.from_floats a) * * A3q66MAu%% A \\\111d1gg.>.>.>@AA AsA&&(())r5c  ddlm}t|tjr|t |}n?t||s/t |jd|dt|jd|| S)zAConverts a finite Decimal instance to a rational number, exactly.rrz).from_decimal() only takes Decimals, not r7r8) rrrrr9rr*r:rr")r.decrs r4 from_decimalzFraction.from_decimals $##### c7+ , , 9'#c((##CCC)) 9sssDII$6$6$6899 9sC((**++r5c|j|jfS)zReturn the integer ratio as a tuple. Return a tuple of two integers, whose ratio is equal to the Fraction and with a positive denominator. rr/s r4r"zFraction.as_integer_ratios !233r5@Bc|dkrtd|j|krt|Sd\}}}}|j|j}} ||z}|||zz} | |krn|||||zz| f\}}}}||||zz }}0||z |z} t|| |zz|| |zz} t||} t | |z t | |z kr| S| S)aWClosest 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) r z$max_denominator should be at least 1)rr r r)r&r rrabs) r/max_denominatorp0q0p1q1ndaq2kbound1bound2s r4limit_denominatorzFraction.limit_denominators@ Q  CDD D   / /D>> !#BB 11 1AAbDBO##R"Wb0NBBa!eqA  R " $"QrT'2ad7++"b!! v}  VD[!1!1 1 1MMr5c|jSN)rrLs r4rzFraction.numerators |r5c|jSrS)r rTs r4r zFraction.denominators ~r5c@|jjd|jd|jdS)z repr(self)(z, r8)r3r:rr rAs r4__repr__zFraction.__repr__ s0#~666#0A0A0AC Cr5cb|jdkrt|jS|jd|jS)z str(self)r /)r r#rrAs r4__str__zFraction.__str__s7   ! !t'' '"ooot/@/@A Ar5cfd}djzdz|_j|_fd}djzdz|_j|_||fS)aGenerates 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. ct|ttfr ||St|trt||St|trt ||St SrS)rrrr!complexNotImplemented)rLbfallback_operatormonomorphic_operators r4forwardz-Fraction._operator_fallbacks..forwardes!c8_-- &++Aq111Au%% &((q1555Aw'' &((Q777%%r5__c^t|tjr ||St|tjr&t |t |St|tjr&t |t |StSrS)rrrRealr!Complexr^r_)r`rLrarbs r4reversez-Fraction._operator_fallbacks..reverseqs!W-.. &++Aq111Aw|,, &((q588<<<Aw// &((WQZZ@@@%%r5__r)r:__doc__)rbrarcrhs`` r4_operator_fallbackszFraction._operator_fallbackss` & & & & & & "3"<?? UHUBG,,,,r5cj|j|j}}t|j|z|j|zz||zS)za % b)r rr)rLr`rprrs r4_modz Fraction._mods6 Br)akB.>?bIIIr5ct|tjr|jdkr|j}|dkr"t |j|z|j|zdS|jdkr$t |j| z|j| zdSt |j | z|j | zdSt|t|zSt||zS)za ** 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. r rFr ) rrrr rrrr r!)rLr`powers r4__pow__zFraction.__pow__s a) * * !}!! A::#ALE$9$%Ne$;/46666\Q&&#ANuf$<$%LUF$:/46666$an_%$?&'l]v$=/46666 Qxx588++88q= r5c|jdkr|jdkr ||jzSt|tjrt |j|j|zS|jdkr ||jzS|t|zS)za ** br r) r rrrrrrr r!)r`rLs r4__rpow__zFraction.__rpow__;s >Q  1<1#4#4 $ $ a) * * =AK771< < >Q   $ $E!HH}r5c:t|j|jdS)z++a: Coerces a subclass instance to FractionFr rrr rTs r4__pos__zFraction.__pos__Is anGGGGr5c<t|j |jdS)z-aFr rrTs r4__neg__zFraction.__neg__Ms q~%HHHHr5cTtt|j|jdS)zabs(a)Fr )rrDrr rTs r4__abs__zFraction.__abs__Qs#AL))1>eLLLLr5c||jdkr||j |jz S||j|jzS)zint(a)rr)rL_indexs r4__int__zFraction.__int__UsF 1 1r5c |j|jzS)z math.floor(a)rrTs r4 __floor__zFraction.__floor__cs{am++r5c$|j |jz S)z math.ceil(a)rrTs r4__ceil__zFraction.__ceil__gs+.//r5cZ|Pt|j|j\}}|dz|jkr|S|dz|jkr|dzS|dzdkr|S|dzSdt|z}|dkr t t ||z|St t ||z |zS)z?round(self, ndigits) Rounds half toward even. Nr rr)rrr rDrround)r/ndigitsfloor remaindershifts r4 __round__zFraction.__round__ls ?%dnd6FGG E91}t/// Q!111qy a qy CLL  Q;;E$,//77 7E$,//%788 8r5c t|jdt}ttt |j|z}n#t $r t}YnwxYw|jdkr|n| }|dkrdn|S)z hash(self)r)powr _PyHASH_MODULUShashrDrr& _PyHASH_INF)r/dinvhash_results r4__hash__zFraction.__hash__s <t("o>>D(c$/2233d:;;EE'   EEE (/Q..UFr\\rrv-sAA#"A#ct|tur|j|ko |jdkSt |t jr |j|jko|j|jkSt |t j r|j dkr|j }t |trGtj|stj|rd|kS|||kSt"S)za == br r)rrrr rrrrr rgimagrealr!r,isnanisinfr<r_rs r4__eq__zFraction.__eq__s 77c>><1$<1)< < a) * * 5LAK/4Nam3 5 a ) ) afkkA a   "z!}} , 1  ,axALLOO++" !r5c`t|tjr&||j|jz|j|jzSt|trStj |stj |r |d|S||| |StS)acHelper 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. r) rrrrr r rr!r,rrr<r_)r/otherops r4_richcmpzFraction._richcmps eW- . . ;2do(99'%/9;; ; eU # # "z%   8DJu$5$5 8r#u~~%r$ 6 6777! !r5cB||tjS)za < b)roperatorltrs r4__lt__zFraction.__lt__zz!X[)))r5cB||tjS)za > b)rrgtrs r4__gt__zFraction.__gt__rr5cB||tjS)za <= b)rrlers r4__le__zFraction.__le__rr5cB||tjS)za >= b)rrgers r4__ge__zFraction.__ge__rr5c*t|jS)za != 0)boolrrTs r4__bool__zFraction.__bool__sAL!!!r5c,|j|j|jffSrS)r3rr rAs r4 __reduce__zFraction.__reduce__s$2C DEEr5cvt|tkr|S||j|jSrSrrr3rr rAs r4__copy__zFraction.__copy__1 :: ! !K~~dot/@AAAr5cvt|tkr|S||j|jSrSr)r/memos r4 __deepcopy__zFraction.__deepcopy__rr5)rN)rBrS)Er: __module__ __qualname__rj __slots__r classmethodr<r?r"rQpropertyrr rXr[rkrvradd__add____radd__rysub__sub____rsub__r|mul__mul____rmul__r~truediv __truediv__ __rtruediv__rfloordiv __floordiv__ __rfloordiv__rr __divmod__ __rdivmod__rmod__mod____rmod__rrrrrindexrrrrrrrrrrrrrrrr __classcell__)r3s@r4rr&s(/Ih$hhhhhhhT * *[ * , ,[ ,4445555nXXCCC BBBi i i ^ C C C,+D(,??GX C C C,+D(,??GX < < <,+D(,??GX000$!4 3D(:J K KKNNN#6"5iAR"S"SL---- 21'6BBJ JJJ ,+D(,??GX!!!<   HHHIIIMMM#.::::222,,,000 99992...B"""*""",************"""FFFBBB BBBBBBBr5)rjrrr,rrresys__all__ hash_infomodulusrinfrcompileVERBOSE IGNORECASEr$rrr5r4rs65  , -'m 2: Z"- ! !N BN BN BN BN BwN BN BN BN BN Br5