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