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