Edit File by line
/home/barbar84/www/wp-conte.../plugins/sujqvwi/ShExBy/shex_roo.../proc/self/root/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 as_integer_ratio(self):
[218] Fix | Delete
"""Return the integer ratio as a tuple.
[219] Fix | Delete
[220] Fix | Delete
Return a tuple of two integers, whose ratio is equal to the
[221] Fix | Delete
Fraction and with a positive denominator.
[222] Fix | Delete
"""
[223] Fix | Delete
return (self._numerator, self._denominator)
[224] Fix | Delete
[225] Fix | Delete
def limit_denominator(self, max_denominator=1000000):
[226] Fix | Delete
"""Closest Fraction to self with denominator at most max_denominator.
[227] Fix | Delete
[228] Fix | Delete
>>> Fraction('3.141592653589793').limit_denominator(10)
[229] Fix | Delete
Fraction(22, 7)
[230] Fix | Delete
>>> Fraction('3.141592653589793').limit_denominator(100)
[231] Fix | Delete
Fraction(311, 99)
[232] Fix | Delete
>>> Fraction(4321, 8765).limit_denominator(10000)
[233] Fix | Delete
Fraction(4321, 8765)
[234] Fix | Delete
[235] Fix | Delete
"""
[236] Fix | Delete
# Algorithm notes: For any real number x, define a *best upper
[237] Fix | Delete
# approximation* to x to be a rational number p/q such that:
[238] Fix | Delete
#
[239] Fix | Delete
# (1) p/q >= x, and
[240] Fix | Delete
# (2) if p/q > r/s >= x then s > q, for any rational r/s.
[241] Fix | Delete
#
[242] Fix | Delete
# Define *best lower approximation* similarly. Then it can be
[243] Fix | Delete
# proved that a rational number is a best upper or lower
[244] Fix | Delete
# approximation to x if, and only if, it is a convergent or
[245] Fix | Delete
# semiconvergent of the (unique shortest) continued fraction
[246] Fix | Delete
# associated to x.
[247] Fix | Delete
#
[248] Fix | Delete
# To find a best rational approximation with denominator <= M,
[249] Fix | Delete
# we find the best upper and lower approximations with
[250] Fix | Delete
# denominator <= M and take whichever of these is closer to x.
[251] Fix | Delete
# In the event of a tie, the bound with smaller denominator is
[252] Fix | Delete
# chosen. If both denominators are equal (which can happen
[253] Fix | Delete
# only when max_denominator == 1 and self is midway between
[254] Fix | Delete
# two integers) the lower bound---i.e., the floor of self, is
[255] Fix | Delete
# taken.
[256] Fix | Delete
[257] Fix | Delete
if max_denominator < 1:
[258] Fix | Delete
raise ValueError("max_denominator should be at least 1")
[259] Fix | Delete
if self._denominator <= max_denominator:
[260] Fix | Delete
return Fraction(self)
[261] Fix | Delete
[262] Fix | Delete
p0, q0, p1, q1 = 0, 1, 1, 0
[263] Fix | Delete
n, d = self._numerator, self._denominator
[264] Fix | Delete
while True:
[265] Fix | Delete
a = n//d
[266] Fix | Delete
q2 = q0+a*q1
[267] Fix | Delete
if q2 > max_denominator:
[268] Fix | Delete
break
[269] Fix | Delete
p0, q0, p1, q1 = p1, q1, p0+a*p1, q2
[270] Fix | Delete
n, d = d, n-a*d
[271] Fix | Delete
[272] Fix | Delete
k = (max_denominator-q0)//q1
[273] Fix | Delete
bound1 = Fraction(p0+k*p1, q0+k*q1)
[274] Fix | Delete
bound2 = Fraction(p1, q1)
[275] Fix | Delete
if abs(bound2 - self) <= abs(bound1-self):
[276] Fix | Delete
return bound2
[277] Fix | Delete
else:
[278] Fix | Delete
return bound1
[279] Fix | Delete
[280] Fix | Delete
@property
[281] Fix | Delete
def numerator(a):
[282] Fix | Delete
return a._numerator
[283] Fix | Delete
[284] Fix | Delete
@property
[285] Fix | Delete
def denominator(a):
[286] Fix | Delete
return a._denominator
[287] Fix | Delete
[288] Fix | Delete
def __repr__(self):
[289] Fix | Delete
"""repr(self)"""
[290] Fix | Delete
return '%s(%s, %s)' % (self.__class__.__name__,
[291] Fix | Delete
self._numerator, self._denominator)
[292] Fix | Delete
[293] Fix | Delete
def __str__(self):
[294] Fix | Delete
"""str(self)"""
[295] Fix | Delete
if self._denominator == 1:
[296] Fix | Delete
return str(self._numerator)
[297] Fix | Delete
else:
[298] Fix | Delete
return '%s/%s' % (self._numerator, self._denominator)
[299] Fix | Delete
[300] Fix | Delete
def _operator_fallbacks(monomorphic_operator, fallback_operator):
[301] Fix | Delete
"""Generates forward and reverse operators given a purely-rational
[302] Fix | Delete
operator and a function from the operator module.
[303] Fix | Delete
[304] Fix | Delete
Use this like:
[305] Fix | Delete
__op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op)
[306] Fix | Delete
[307] Fix | Delete
In general, we want to implement the arithmetic operations so
[308] Fix | Delete
that mixed-mode operations either call an implementation whose
[309] Fix | Delete
author knew about the types of both arguments, or convert both
[310] Fix | Delete
to the nearest built in type and do the operation there. In
[311] Fix | Delete
Fraction, that means that we define __add__ and __radd__ as:
[312] Fix | Delete
[313] Fix | Delete
def __add__(self, other):
[314] Fix | Delete
# Both types have numerators/denominator attributes,
[315] Fix | Delete
# so do the operation directly
[316] Fix | Delete
if isinstance(other, (int, Fraction)):
[317] Fix | Delete
return Fraction(self.numerator * other.denominator +
[318] Fix | Delete
other.numerator * self.denominator,
[319] Fix | Delete
self.denominator * other.denominator)
[320] Fix | Delete
# float and complex don't have those operations, but we
[321] Fix | Delete
# know about those types, so special case them.
[322] Fix | Delete
elif isinstance(other, float):
[323] Fix | Delete
return float(self) + other
[324] Fix | Delete
elif isinstance(other, complex):
[325] Fix | Delete
return complex(self) + other
[326] Fix | Delete
# Let the other type take over.
[327] Fix | Delete
return NotImplemented
[328] Fix | Delete
[329] Fix | Delete
def __radd__(self, other):
[330] Fix | Delete
# radd handles more types than add because there's
[331] Fix | Delete
# nothing left to fall back to.
[332] Fix | Delete
if isinstance(other, numbers.Rational):
[333] Fix | Delete
return Fraction(self.numerator * other.denominator +
[334] Fix | Delete
other.numerator * self.denominator,
[335] Fix | Delete
self.denominator * other.denominator)
[336] Fix | Delete
elif isinstance(other, Real):
[337] Fix | Delete
return float(other) + float(self)
[338] Fix | Delete
elif isinstance(other, Complex):
[339] Fix | Delete
return complex(other) + complex(self)
[340] Fix | Delete
return NotImplemented
[341] Fix | Delete
[342] Fix | Delete
[343] Fix | Delete
There are 5 different cases for a mixed-type addition on
[344] Fix | Delete
Fraction. I'll refer to all of the above code that doesn't
[345] Fix | Delete
refer to Fraction, float, or complex as "boilerplate". 'r'
[346] Fix | Delete
will be an instance of Fraction, which is a subtype of
[347] Fix | Delete
Rational (r : Fraction <: Rational), and b : B <:
[348] Fix | Delete
Complex. The first three involve 'r + b':
[349] Fix | Delete
[350] Fix | Delete
1. If B <: Fraction, int, float, or complex, we handle
[351] Fix | Delete
that specially, and all is well.
[352] Fix | Delete
2. If Fraction falls back to the boilerplate code, and it
[353] Fix | Delete
were to return a value from __add__, we'd miss the
[354] Fix | Delete
possibility that B defines a more intelligent __radd__,
[355] Fix | Delete
so the boilerplate should return NotImplemented from
[356] Fix | Delete
__add__. In particular, we don't handle Rational
[357] Fix | Delete
here, even though we could get an exact answer, in case
[358] Fix | Delete
the other type wants to do something special.
[359] Fix | Delete
3. If B <: Fraction, Python tries B.__radd__ before
[360] Fix | Delete
Fraction.__add__. This is ok, because it was
[361] Fix | Delete
implemented with knowledge of Fraction, so it can
[362] Fix | Delete
handle those instances before delegating to Real or
[363] Fix | Delete
Complex.
[364] Fix | Delete
[365] Fix | Delete
The next two situations describe 'b + r'. We assume that b
[366] Fix | Delete
didn't know about Fraction in its implementation, and that it
[367] Fix | Delete
uses similar boilerplate code:
[368] Fix | Delete
[369] Fix | Delete
4. If B <: Rational, then __radd_ converts both to the
[370] Fix | Delete
builtin rational type (hey look, that's us) and
[371] Fix | Delete
proceeds.
[372] Fix | Delete
5. Otherwise, __radd__ tries to find the nearest common
[373] Fix | Delete
base ABC, and fall back to its builtin type. Since this
[374] Fix | Delete
class doesn't subclass a concrete type, there's no
[375] Fix | Delete
implementation to fall back to, so we need to try as
[376] Fix | Delete
hard as possible to return an actual value, or the user
[377] Fix | Delete
will get a TypeError.
[378] Fix | Delete
[379] Fix | Delete
"""
[380] Fix | Delete
def forward(a, b):
[381] Fix | Delete
if isinstance(b, (int, Fraction)):
[382] Fix | Delete
return monomorphic_operator(a, b)
[383] Fix | Delete
elif isinstance(b, float):
[384] Fix | Delete
return fallback_operator(float(a), b)
[385] Fix | Delete
elif isinstance(b, complex):
[386] Fix | Delete
return fallback_operator(complex(a), b)
[387] Fix | Delete
else:
[388] Fix | Delete
return NotImplemented
[389] Fix | Delete
forward.__name__ = '__' + fallback_operator.__name__ + '__'
[390] Fix | Delete
forward.__doc__ = monomorphic_operator.__doc__
[391] Fix | Delete
[392] Fix | Delete
def reverse(b, a):
[393] Fix | Delete
if isinstance(a, numbers.Rational):
[394] Fix | Delete
# Includes ints.
[395] Fix | Delete
return monomorphic_operator(a, b)
[396] Fix | Delete
elif isinstance(a, numbers.Real):
[397] Fix | Delete
return fallback_operator(float(a), float(b))
[398] Fix | Delete
elif isinstance(a, numbers.Complex):
[399] Fix | Delete
return fallback_operator(complex(a), complex(b))
[400] Fix | Delete
else:
[401] Fix | Delete
return NotImplemented
[402] Fix | Delete
reverse.__name__ = '__r' + fallback_operator.__name__ + '__'
[403] Fix | Delete
reverse.__doc__ = monomorphic_operator.__doc__
[404] Fix | Delete
[405] Fix | Delete
return forward, reverse
[406] Fix | Delete
[407] Fix | Delete
def _add(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
__add__, __radd__ = _operator_fallbacks(_add, operator.add)
[414] Fix | Delete
[415] Fix | Delete
def _sub(a, b):
[416] Fix | Delete
"""a - b"""
[417] Fix | Delete
da, db = a.denominator, b.denominator
[418] Fix | Delete
return Fraction(a.numerator * db - b.numerator * da,
[419] Fix | Delete
da * db)
[420] Fix | Delete
[421] Fix | Delete
__sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub)
[422] Fix | Delete
[423] Fix | Delete
def _mul(a, b):
[424] Fix | Delete
"""a * b"""
[425] Fix | Delete
return Fraction(a.numerator * b.numerator, a.denominator * b.denominator)
[426] Fix | Delete
[427] Fix | Delete
__mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul)
[428] Fix | Delete
[429] Fix | Delete
def _div(a, b):
[430] Fix | Delete
"""a / b"""
[431] Fix | Delete
return Fraction(a.numerator * b.denominator,
[432] Fix | Delete
a.denominator * b.numerator)
[433] Fix | Delete
[434] Fix | Delete
__truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv)
[435] Fix | Delete
[436] Fix | Delete
def _floordiv(a, b):
[437] Fix | Delete
"""a // b"""
[438] Fix | Delete
return (a.numerator * b.denominator) // (a.denominator * b.numerator)
[439] Fix | Delete
[440] Fix | Delete
__floordiv__, __rfloordiv__ = _operator_fallbacks(_floordiv, operator.floordiv)
[441] Fix | Delete
[442] Fix | Delete
def _divmod(a, b):
[443] Fix | Delete
"""(a // b, a % b)"""
[444] Fix | Delete
da, db = a.denominator, b.denominator
[445] Fix | Delete
div, n_mod = divmod(a.numerator * db, da * b.numerator)
[446] Fix | Delete
return div, Fraction(n_mod, da * db)
[447] Fix | Delete
[448] Fix | Delete
__divmod__, __rdivmod__ = _operator_fallbacks(_divmod, divmod)
[449] Fix | Delete
[450] Fix | Delete
def _mod(a, b):
[451] Fix | Delete
"""a % b"""
[452] Fix | Delete
da, db = a.denominator, b.denominator
[453] Fix | Delete
return Fraction((a.numerator * db) % (b.numerator * da), da * db)
[454] Fix | Delete
[455] Fix | Delete
__mod__, __rmod__ = _operator_fallbacks(_mod, operator.mod)
[456] Fix | Delete
[457] Fix | Delete
def __pow__(a, b):
[458] Fix | Delete
"""a ** b
[459] Fix | Delete
[460] Fix | Delete
If b is not an integer, the result will be a float or complex
[461] Fix | Delete
since roots are generally irrational. If b is an integer, the
[462] Fix | Delete
result will be rational.
[463] Fix | Delete
[464] Fix | Delete
"""
[465] Fix | Delete
if isinstance(b, numbers.Rational):
[466] Fix | Delete
if b.denominator == 1:
[467] Fix | Delete
power = b.numerator
[468] Fix | Delete
if power >= 0:
[469] Fix | Delete
return Fraction(a._numerator ** power,
[470] Fix | Delete
a._denominator ** power,
[471] Fix | Delete
_normalize=False)
[472] Fix | Delete
elif a._numerator >= 0:
[473] Fix | Delete
return Fraction(a._denominator ** -power,
[474] Fix | Delete
a._numerator ** -power,
[475] Fix | Delete
_normalize=False)
[476] Fix | Delete
else:
[477] Fix | Delete
return Fraction((-a._denominator) ** -power,
[478] Fix | Delete
(-a._numerator) ** -power,
[479] Fix | Delete
_normalize=False)
[480] Fix | Delete
else:
[481] Fix | Delete
# A fractional power will generally produce an
[482] Fix | Delete
# irrational number.
[483] Fix | Delete
return float(a) ** float(b)
[484] Fix | Delete
else:
[485] Fix | Delete
return float(a) ** b
[486] Fix | Delete
[487] Fix | Delete
def __rpow__(b, a):
[488] Fix | Delete
"""a ** b"""
[489] Fix | Delete
if b._denominator == 1 and b._numerator >= 0:
[490] Fix | Delete
# If a is an int, keep it that way if possible.
[491] Fix | Delete
return a ** b._numerator
[492] Fix | Delete
[493] Fix | Delete
if isinstance(a, numbers.Rational):
[494] Fix | Delete
return Fraction(a.numerator, a.denominator) ** b
[495] Fix | Delete
[496] Fix | Delete
if b._denominator == 1:
[497] Fix | Delete
return a ** b._numerator
[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