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