def make_error_block(ec_info, data_block):
"""\
Creates the error code words for the provided data block.
:param ec_info: ECC information (number of blocks, number of code words etc.)
:param data_block: Iterable of (integer) code words.
"""
num_error_words = ec_info.num_total - ec_info.num_data
error_block = bytearray(data_block)
error_block.extend([0] * num_error_words)
gen = consts.GEN_POLY[num_error_words]
gen_log = consts.GALIOS_LOG
gen_exp = consts.GALIOS_EXP
len_data = len(data_block)
# Extended synthetic division, see http://research.swtch.com/field
for i in range(len_data):
coef = error_block[i]
if coef != 0: # log(0) is undefined
lcoef = gen_log[coef]
for j in range(num_error_words):
error_block[i + j + 1] ^= gen_exp[lcoef + gen[j]]
return error_block[len_data:]
python类division()的实例源码
def check_truediv(Poly):
# true division is valid only if the denominator is a Number and
# not a python bool.
p1 = Poly([1,2,3])
p2 = p1 * 5
for stype in np.ScalarType:
if not issubclass(stype, Number) or issubclass(stype, bool):
continue
s = stype(5)
assert_poly_almost_equal(op.truediv(p2, s), p1)
assert_raises(TypeError, op.truediv, s, p2)
for stype in (int, long, float):
s = stype(5)
assert_poly_almost_equal(op.truediv(p2, s), p1)
assert_raises(TypeError, op.truediv, s, p2)
for stype in [complex]:
s = stype(5, 0)
assert_poly_almost_equal(op.truediv(p2, s), p1)
assert_raises(TypeError, op.truediv, s, p2)
for s in [tuple(), list(), dict(), bool(), np.array([1])]:
assert_raises(TypeError, op.truediv, p2, s)
assert_raises(TypeError, op.truediv, s, p2)
for ptype in classes:
assert_raises(TypeError, op.truediv, p2, ptype(1))
def execute(self, repeat=1, unbind=True):
kernel = kernel_specs.get_kernel(self.kernel_name, self.kernel_opts)
for r in range(repeat):
if self.zero:
drv.memset_d32_async(*self.zero_args)
kernel.prepared_async_call(*self.kernel_args)
self.output_trans.execute()
if unbind:
self.output_trans.unbind()
self.zero_args = None
self.kernel_args[2:6] = (None,) * 4
# Magic numbers and shift amounts for integer division
# Suitable for when nmax*magic fits in 32 bits
# Shamelessly pulled directly from:
# http://www.hackersdelight.org/hdcodetxt/magicgu.py.txt
def make_error_block(ec_info, data_block):
"""\
Creates the error code words for the provided data block.
:param ec_info: ECC information (number of blocks, number of code words etc.)
:param data_block: Iterable of (integer) code words.
"""
num_error_words = ec_info.num_total - ec_info.num_data
error_block = bytearray(data_block)
error_block.extend([0] * num_error_words)
gen = consts.GEN_POLY[num_error_words]
gen_log = consts.GALIOS_LOG
gen_exp = consts.GALIOS_EXP
len_data = len(data_block)
# Extended synthetic division, see http://research.swtch.com/field
for i in range(len_data):
coef = error_block[i]
if coef != 0: # log(0) is undefined
lcoef = gen_log[coef]
for j in range(num_error_words):
error_block[i + j + 1] ^= gen_exp[lcoef + gen[j]]
return error_block[len_data:]
def __div__(self, den, slashed=False):
"""Make a pretty division; stacked or slashed.
"""
if slashed:
raise NotImplementedError("Can't do slashed fraction yet")
num = self
if num.binding == prettyForm.DIV:
num = stringPict(*num.parens())
if den.binding == prettyForm.DIV:
den = stringPict(*den.parens())
if num.binding==prettyForm.NEG:
num = num.right(" ")[0]
return prettyForm(binding=prettyForm.DIV, *stringPict.stack(
num,
stringPict.LINE,
den))
def gcdex_diophantine(a, b, c):
"""
Extended Euclidean Algorithm, Diophantine version.
Given a, b in K[x] and c in (a, b), the ideal generated by a and b,
return (s, t) such that s*a + t*b == c and either s == 0 or s.degree()
< b.degree().
"""
# Extended Euclidean Algorithm (Diophantine Version) pg. 13
# TODO: This should go in densetools.py.
# XXX: Bettter name?
s, g = a.half_gcdex(b)
q = c.exquo(g) # Inexact division means c is not in (a, b)
s = q*s
if not s.is_zero and b.degree() >= b.degree():
q, s = s.div(b)
t = (c - s*a).exquo(b)
return (s, t)
def quotient_ring(self, e):
"""
Form a quotient ring of ``self``.
Here ``e`` can be an ideal or an iterable.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> QQ.old_poly_ring(x).quotient_ring(QQ.old_poly_ring(x).ideal(x**2))
QQ[x]/<x**2>
>>> QQ.old_poly_ring(x).quotient_ring([x**2])
QQ[x]/<x**2>
The division operator has been overloaded for this:
>>> QQ.old_poly_ring(x)/[x**2]
QQ[x]/<x**2>
"""
from sympy.polys.agca.ideals import Ideal
from sympy.polys.domains.quotientring import QuotientRing
if not isinstance(e, Ideal):
e = self.ideal(*e)
return QuotientRing(self, e)
def dup_exquo_ground(f, c, K):
"""
Exact quotient by a constant in ``K[x]``.
Examples
========
>>> from sympy.polys import ring, QQ
>>> R, x = ring("x", QQ)
>>> R.dup_exquo_ground(x**2 + 2, QQ(2))
1/2*x**2 + 1
"""
if not c:
raise ZeroDivisionError('polynomial division')
if not f:
return f
return [ K.exquo(cf, c) for cf in f ]
def dmp_div(f, g, u, K):
"""
Polynomial division with remainder in ``K[X]``.
Examples
========
>>> from sympy.polys import ring, ZZ, QQ
>>> R, x,y = ring("x,y", ZZ)
>>> R.dmp_div(x**2 + x*y, 2*x + 2)
(0, x**2 + x*y)
>>> R, x,y = ring("x,y", QQ)
>>> R.dmp_div(x**2 + x*y, 2*x + 2)
(1/2*x + 1/2*y - 1/2, -y + 1)
"""
if K.has_Field:
return dmp_ff_div(f, g, u, K)
else:
return dmp_rr_div(f, g, u, K)
def __str__(self):
if self.domain.is_EX:
msg = "You may want to use a different simplification algorithm. Note " \
"that in general it's not possible to guarantee to detect zero " \
"in this domain."
elif not self.domain.is_Exact:
msg = "Your working precision or tolerance of computations may be set " \
"improperly. Adjust those parameters of the coefficient domain " \
"and try again."
else:
msg = "Zero detection is guaranteed in this coefficient domain. This " \
"may indicate a bug in SymPy or the domain is user defined and " \
"doesn't implement zero detection properly."
return "couldn't reduce degree in a polynomial division algorithm when " \
"dividing %s by %s. This can happen when it's not possible to " \
"detect zero in the coefficient domain. The domain of computation " \
"is %s. %s" % (self.f, self.g, self.domain, msg)
def quotient_module(self, submodule):
"""
Return a quotient module.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> M = QQ.old_poly_ring(x).free_module(2)
>>> M.quotient_module(M.submodule([1, x], [x, 2]))
QQ[x]**2/<[1, x], [x, 2]>
Or more conicisely, using the overloaded division operator:
>>> QQ.old_poly_ring(x).free_module(2) / [[1, x], [x, 2]]
QQ[x]**2/<[1, x], [x, 2]>
"""
return QuotientModule(self.ring, self, submodule)
def quotient_module(self, other, **opts):
"""
Return a quotient module.
This is the same as taking a submodule of a quotient of the containing
module.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> S1 = F.submodule([x, 1])
>>> S2 = F.submodule([x**2, x])
>>> S1.quotient_module(S2)
<[x, 1] + <[x**2, x]>>
Or more coincisely, using the overloaded division operator:
>>> F.submodule([x, 1]) / [(x**2, x)]
<[x, 1] + <[x**2, x]>>
"""
if not self.is_submodule(other):
raise ValueError('%s not a submodule of %s' % (other, self))
return SubQuotientModule(self.gens,
self.container.quotient_module(other), **opts)
def pdiv(f, g):
"""
Polynomial pseudo-division of ``f`` by ``g``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 1, x).pdiv(Poly(2*x - 4, x))
(Poly(2*x + 4, x, domain='ZZ'), Poly(20, x, domain='ZZ'))
"""
_, per, F, G = f._unify(g)
if hasattr(f.rep, 'pdiv'):
q, r = F.pdiv(G)
else: # pragma: no cover
raise OperationNotSupported(f, 'pdiv')
return per(q), per(r)
def __mod__(p1, p2):
ring = p1.ring
p = ring.zero
if not p2:
raise ZeroDivisionError("polynomial division")
elif isinstance(p2, ring.dtype):
return p1.rem(p2)
elif isinstance(p2, PolyElement):
if isinstance(ring.domain, PolynomialRing) and ring.domain.ring == p2.ring:
pass
elif isinstance(p2.ring.domain, PolynomialRing) and p2.ring.domain.ring == ring:
return p2.__rmod__(p1)
else:
return NotImplemented
try:
p2 = ring.domain_new(p2)
except CoercionFailed:
return NotImplemented
else:
return p1.rem_ground(p2)
def __truediv__(p1, p2):
ring = p1.ring
p = ring.zero
if not p2:
raise ZeroDivisionError("polynomial division")
elif isinstance(p2, ring.dtype):
return p1.quo(p2)
elif isinstance(p2, PolyElement):
if isinstance(ring.domain, PolynomialRing) and ring.domain.ring == p2.ring:
pass
elif isinstance(p2.ring.domain, PolynomialRing) and p2.ring.domain.ring == ring:
return p2.__rtruediv__(p1)
else:
return NotImplemented
try:
p2 = ring.domain_new(p2)
except CoercionFailed:
return NotImplemented
else:
return p1.quo_ground(p2)
def dmp_trial_division(f, factors, u, K):
"""Determine multiplicities of factors using trial division. """
result = []
for factor in factors:
k = 0
while True:
q, r = dmp_div(f, factor, u, K)
if dmp_zero_p(r, u):
f, k = q, k + 1
else:
break
result.append((factor, k))
return _sort_factors(result)
def check_truediv(Poly):
# true division is valid only if the denominator is a Number and
# not a python bool.
p1 = Poly([1,2,3])
p2 = p1 * 5
for stype in np.ScalarType:
if not issubclass(stype, Number) or issubclass(stype, bool):
continue
s = stype(5)
assert_poly_almost_equal(op.truediv(p2, s), p1)
assert_raises(TypeError, op.truediv, s, p2)
for stype in (int, long, float):
s = stype(5)
assert_poly_almost_equal(op.truediv(p2, s), p1)
assert_raises(TypeError, op.truediv, s, p2)
for stype in [complex]:
s = stype(5, 0)
assert_poly_almost_equal(op.truediv(p2, s), p1)
assert_raises(TypeError, op.truediv, s, p2)
for s in [tuple(), list(), dict(), bool(), np.array([1])]:
assert_raises(TypeError, op.truediv, p2, s)
assert_raises(TypeError, op.truediv, s, p2)
for ptype in classes:
assert_raises(TypeError, op.truediv, p2, ptype(1))
def test_shebang_blank_with_future_division_import(self):
"""
Issue #43: Is shebang line preserved as the first
line by futurize when followed by a blank line?
"""
before = """
#!/usr/bin/env python
import math
1 / 5
"""
after = """
#!/usr/bin/env python
from __future__ import division
from past.utils import old_div
import math
old_div(1, 5)
"""
self.convert_check(before, after)
def test_safe_division(self):
"""
Tests whether Py2 scripts using old-style division still work
after futurization.
"""
before = """
x = 3 / 2
y = 3. / 2
assert x == 1 and isinstance(x, int)
assert y == 1.5 and isinstance(y, float)
"""
after = """
from __future__ import division
from past.utils import old_div
x = old_div(3, 2)
y = old_div(3., 2)
assert x == 1 and isinstance(x, int)
assert y == 1.5 and isinstance(y, float)
"""
self.convert_check(before, after)
def download_speed(self):
# Avoid zero division errors...
if self.avg == 0.0:
return "..."
return format_size(1 / self.avg) + "/s"
def download_speed(self):
# Avoid zero division errors...
if self.avg == 0.0:
return "..."
return format_size(1 / self.avg) + "/s"
def __div__(self, other):
"""self / other without __future__ division
May promote to float.
"""
raise NotImplementedError
def __rdiv__(self, other):
"""other / self without __future__ division"""
raise NotImplementedError
def __truediv__(self, other):
"""self / other with __future__ division.
Should promote to float when necessary.
"""
raise NotImplementedError
def __rtruediv__(self, other):
"""other / self with __future__ division"""
raise NotImplementedError
def __float__(self):
"""float(self) = self.numerator / self.denominator
It's important that this conversion use the integer's "true"
division rather than casting one side to float before dividing
so that ratios of huge integers convert without overflowing.
"""
return self.numerator / self.denominator
def __truediv__(self, other, *args):
'''
Float division (/)
'''
return self._apply_operator(other, "__truediv__", *args)
def __div__(self, other, *args):
'''
Integer division (//)
'''
return self._apply_operator(other, "__div__", *args)
def __truediv__(self, other, *args):
'''
Float division (/)
'''
return self._apply_operator(other, "__truediv__", *args)
def __truediv__(self, other, *args):
'''
Float division (/)
'''
return self._apply_operator(other, "__truediv__", *args)