Search is not available for this dataset
repo
stringlengths 2
152
⌀ | file
stringlengths 15
239
| code
stringlengths 0
58.4M
| file_length
int64 0
58.4M
| avg_line_length
float64 0
1.81M
| max_line_length
int64 0
12.7M
| extension_type
stringclasses 364
values |
---|---|---|---|---|---|---|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/tests/test_constructor.py
|
"""Tests for tools for constructing domains for expressions. """
from sympy.polys.constructor import construct_domain
from sympy.polys.domains import ZZ, QQ, RR, EX
from sympy.polys.domains.realfield import RealField
from sympy import S, sqrt, sin, Float, E, GoldenRatio, pi, Catalan
from sympy.abc import x, y
def test_construct_domain():
assert construct_domain([1, 2, 3]) == (ZZ, [ZZ(1), ZZ(2), ZZ(3)])
assert construct_domain([1, 2, 3], field=True) == (QQ, [QQ(1), QQ(2), QQ(3)])
assert construct_domain([S(1), S(2), S(3)]) == (ZZ, [ZZ(1), ZZ(2), ZZ(3)])
assert construct_domain([S(1), S(2), S(3)], field=True) == (QQ, [QQ(1), QQ(2), QQ(3)])
assert construct_domain([S(1)/2, S(2)]) == (QQ, [QQ(1, 2), QQ(2)])
result = construct_domain([3.14, 1, S(1)/2])
assert isinstance(result[0], RealField)
assert result[1] == [RR(3.14), RR(1.0), RR(0.5)]
assert construct_domain([3.14, sqrt(2)], extension=None) == (EX, [EX(3.14), EX(sqrt(2))])
assert construct_domain([3.14, sqrt(2)], extension=True) == (EX, [EX(3.14), EX(sqrt(2))])
assert construct_domain([1, sqrt(2)], extension=None) == (EX, [EX(1), EX(sqrt(2))])
assert construct_domain([x, sqrt(x)]) == (EX, [EX(x), EX(sqrt(x))])
assert construct_domain([x, sqrt(x), sqrt(y)]) == (EX, [EX(x), EX(sqrt(x)), EX(sqrt(y))])
alg = QQ.algebraic_field(sqrt(2))
assert construct_domain([7, S(1)/2, sqrt(2)], extension=True) == \
(alg, [alg.convert(7), alg.convert(S(1)/2), alg.convert(sqrt(2))])
alg = QQ.algebraic_field(sqrt(2) + sqrt(3))
assert construct_domain([7, sqrt(2), sqrt(3)], extension=True) == \
(alg, [alg.convert(7), alg.convert(sqrt(2)), alg.convert(sqrt(3))])
dom = ZZ[x]
assert construct_domain([2*x, 3]) == \
(dom, [dom.convert(2*x), dom.convert(3)])
dom = ZZ[x, y]
assert construct_domain([2*x, 3*y]) == \
(dom, [dom.convert(2*x), dom.convert(3*y)])
dom = QQ[x]
assert construct_domain([x/2, 3]) == \
(dom, [dom.convert(x/2), dom.convert(3)])
dom = QQ[x, y]
assert construct_domain([x/2, 3*y]) == \
(dom, [dom.convert(x/2), dom.convert(3*y)])
dom = RR[x]
assert construct_domain([x/2, 3.5]) == \
(dom, [dom.convert(x/2), dom.convert(3.5)])
dom = RR[x, y]
assert construct_domain([x/2, 3.5*y]) == \
(dom, [dom.convert(x/2), dom.convert(3.5*y)])
dom = ZZ.frac_field(x)
assert construct_domain([2/x, 3]) == \
(dom, [dom.convert(2/x), dom.convert(3)])
dom = ZZ.frac_field(x, y)
assert construct_domain([2/x, 3*y]) == \
(dom, [dom.convert(2/x), dom.convert(3*y)])
dom = RR.frac_field(x)
assert construct_domain([2/x, 3.5]) == \
(dom, [dom.convert(2/x), dom.convert(3.5)])
dom = RR.frac_field(x, y)
assert construct_domain([2/x, 3.5*y]) == \
(dom, [dom.convert(2/x), dom.convert(3.5*y)])
dom = RealField(prec=336)[x]
assert construct_domain([pi.evalf(100)*x]) == \
(dom, [dom.convert(pi.evalf(100)*x)])
assert construct_domain(2) == (ZZ, ZZ(2))
assert construct_domain(S(2)/3) == (QQ, QQ(2, 3))
assert construct_domain({}) == (ZZ, {})
def test_composite_option():
assert construct_domain({(1,): sin(y)}, composite=False) == \
(EX, {(1,): EX(sin(y))})
assert construct_domain({(1,): y}, composite=False) == \
(EX, {(1,): EX(y)})
assert construct_domain({(1, 1): 1}, composite=False) == \
(ZZ, {(1, 1): 1})
assert construct_domain({(1, 0): y}, composite=False) == \
(EX, {(1, 0): EX(y)})
def test_precision():
f1 = Float("1.01")
f2 = Float("1.0000000000000000000001")
for x in [1, 1e-2, 1e-6, 1e-13, 1e-14, 1e-16, 1e-20, 1e-100, 1e-300,
f1, f2]:
result = construct_domain([x])
y = float(result[1][0])
assert abs(x - y) / x < 1e-14 # Test relative accuracy
result = construct_domain([f1])
y = result[1][0]
assert y-1 > 1e-50
result = construct_domain([f2])
y = result[1][0]
assert y-1 > 1e-50
def test_issue_11538():
for n in [E, pi, Catalan]:
assert construct_domain(n)[0] == ZZ[n]
assert construct_domain(x + n)[0] == ZZ[x, n]
assert construct_domain(GoldenRatio)[0] == EX
assert construct_domain(x + GoldenRatio)[0] == EX
| 4,345 | 30.042857 | 93 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/tests/test_factortools.py
|
"""Tools for polynomial factorization routines in characteristic zero. """
from sympy.polys.rings import ring, xring
from sympy.polys.domains import FF, ZZ, QQ, RR, EX
from sympy.polys import polyconfig as config
from sympy.polys.polyerrors import DomainError
from sympy.polys.polyclasses import ANP
from sympy.polys.specialpolys import f_polys, w_polys
from sympy import nextprime, sin, sqrt, I
from sympy.utilities.pytest import raises
from sympy.core.compatibility import range
f_0, f_1, f_2, f_3, f_4, f_5, f_6 = f_polys()
w_1, w_2 = w_polys()
def test_dup_trial_division():
R, x = ring("x", ZZ)
assert R.dup_trial_division(x**5 + 8*x**4 + 25*x**3 + 38*x**2 + 28*x + 8, (x + 1, x + 2)) == [(x + 1, 2), (x + 2, 3)]
def test_dmp_trial_division():
R, x, y = ring("x,y", ZZ)
assert R.dmp_trial_division(x**5 + 8*x**4 + 25*x**3 + 38*x**2 + 28*x + 8, (x + 1, x + 2)) == [(x + 1, 2), (x + 2, 3)]
def test_dup_zz_mignotte_bound():
R, x = ring("x", ZZ)
assert R.dup_zz_mignotte_bound(2*x**2 + 3*x + 4) == 32
def test_dmp_zz_mignotte_bound():
R, x, y = ring("x,y", ZZ)
assert R.dmp_zz_mignotte_bound(2*x**2 + 3*x + 4) == 32
def test_dup_zz_hensel_step():
R, x = ring("x", ZZ)
f = x**4 - 1
g = x**3 + 2*x**2 - x - 2
h = x - 2
s = -2
t = 2*x**2 - 2*x - 1
G, H, S, T = R.dup_zz_hensel_step(5, f, g, h, s, t)
assert G == x**3 + 7*x**2 - x - 7
assert H == x - 7
assert S == 8
assert T == -8*x**2 - 12*x - 1
def test_dup_zz_hensel_lift():
R, x = ring("x", ZZ)
f = x**4 - 1
F = [x - 1, x - 2, x + 2, x + 1]
assert R.dup_zz_hensel_lift(ZZ(5), f, F, 4) == \
[x - 1, x - 182, x + 182, x + 1]
def test_dup_zz_irreducible_p():
R, x = ring("x", ZZ)
assert R.dup_zz_irreducible_p(3*x**4 + 2*x**3 + 6*x**2 + 8*x + 7) is None
assert R.dup_zz_irreducible_p(3*x**4 + 2*x**3 + 6*x**2 + 8*x + 4) is None
assert R.dup_zz_irreducible_p(3*x**4 + 2*x**3 + 6*x**2 + 8*x + 10) is True
assert R.dup_zz_irreducible_p(3*x**4 + 2*x**3 + 6*x**2 + 8*x + 14) is True
def test_dup_cyclotomic_p():
R, x = ring("x", ZZ)
assert R.dup_cyclotomic_p(x - 1) is True
assert R.dup_cyclotomic_p(x + 1) is True
assert R.dup_cyclotomic_p(x**2 + x + 1) is True
assert R.dup_cyclotomic_p(x**2 + 1) is True
assert R.dup_cyclotomic_p(x**4 + x**3 + x**2 + x + 1) is True
assert R.dup_cyclotomic_p(x**2 - x + 1) is True
assert R.dup_cyclotomic_p(x**6 + x**5 + x**4 + x**3 + x**2 + x + 1) is True
assert R.dup_cyclotomic_p(x**4 + 1) is True
assert R.dup_cyclotomic_p(x**6 + x**3 + 1) is True
assert R.dup_cyclotomic_p(0) is False
assert R.dup_cyclotomic_p(1) is False
assert R.dup_cyclotomic_p(x) is False
assert R.dup_cyclotomic_p(x + 2) is False
assert R.dup_cyclotomic_p(3*x + 1) is False
assert R.dup_cyclotomic_p(x**2 - 1) is False
f = x**16 + x**14 - x**10 + x**8 - x**6 + x**2 + 1
assert R.dup_cyclotomic_p(f) is False
g = x**16 + x**14 - x**10 - x**8 - x**6 + x**2 + 1
assert R.dup_cyclotomic_p(g) is True
R, x = ring("x", QQ)
assert R.dup_cyclotomic_p(x**2 + x + 1) is True
assert R.dup_cyclotomic_p(QQ(1,2)*x**2 + x + 1) is False
R, x = ring("x", ZZ["y"])
assert R.dup_cyclotomic_p(x**2 + x + 1) is False
def test_dup_zz_cyclotomic_poly():
R, x = ring("x", ZZ)
assert R.dup_zz_cyclotomic_poly(1) == x - 1
assert R.dup_zz_cyclotomic_poly(2) == x + 1
assert R.dup_zz_cyclotomic_poly(3) == x**2 + x + 1
assert R.dup_zz_cyclotomic_poly(4) == x**2 + 1
assert R.dup_zz_cyclotomic_poly(5) == x**4 + x**3 + x**2 + x + 1
assert R.dup_zz_cyclotomic_poly(6) == x**2 - x + 1
assert R.dup_zz_cyclotomic_poly(7) == x**6 + x**5 + x**4 + x**3 + x**2 + x + 1
assert R.dup_zz_cyclotomic_poly(8) == x**4 + 1
assert R.dup_zz_cyclotomic_poly(9) == x**6 + x**3 + 1
def test_dup_zz_cyclotomic_factor():
R, x = ring("x", ZZ)
assert R.dup_zz_cyclotomic_factor(0) is None
assert R.dup_zz_cyclotomic_factor(1) is None
assert R.dup_zz_cyclotomic_factor(2*x**10 - 1) is None
assert R.dup_zz_cyclotomic_factor(x**10 - 3) is None
assert R.dup_zz_cyclotomic_factor(x**10 + x**5 - 1) is None
assert R.dup_zz_cyclotomic_factor(x + 1) == [x + 1]
assert R.dup_zz_cyclotomic_factor(x - 1) == [x - 1]
assert R.dup_zz_cyclotomic_factor(x**2 + 1) == [x**2 + 1]
assert R.dup_zz_cyclotomic_factor(x**2 - 1) == [x - 1, x + 1]
assert R.dup_zz_cyclotomic_factor(x**27 + 1) == \
[x + 1, x**2 - x + 1, x**6 - x**3 + 1, x**18 - x**9 + 1]
assert R.dup_zz_cyclotomic_factor(x**27 - 1) == \
[x - 1, x**2 + x + 1, x**6 + x**3 + 1, x**18 + x**9 + 1]
def test_dup_zz_factor():
R, x = ring("x", ZZ)
assert R.dup_zz_factor(0) == (0, [])
assert R.dup_zz_factor(7) == (7, [])
assert R.dup_zz_factor(-7) == (-7, [])
assert R.dup_zz_factor_sqf(0) == (0, [])
assert R.dup_zz_factor_sqf(7) == (7, [])
assert R.dup_zz_factor_sqf(-7) == (-7, [])
assert R.dup_zz_factor(2*x + 4) == (2, [(x + 2, 1)])
assert R.dup_zz_factor_sqf(2*x + 4) == (2, [x + 2])
f = x**4 + x + 1
for i in range(0, 20):
assert R.dup_zz_factor(f) == (1, [(f, 1)])
assert R.dup_zz_factor(x**2 + 2*x + 2) == \
(1, [(x**2 + 2*x + 2, 1)])
assert R.dup_zz_factor(18*x**2 + 12*x + 2) == \
(2, [(3*x + 1, 2)])
assert R.dup_zz_factor(-9*x**2 + 1) == \
(-1, [(3*x - 1, 1),
(3*x + 1, 1)])
assert R.dup_zz_factor_sqf(-9*x**2 + 1) == \
(-1, [3*x - 1,
3*x + 1])
assert R.dup_zz_factor(x**3 - 6*x**2 + 11*x - 6) == \
(1, [(x - 3, 1),
(x - 2, 1),
(x - 1, 1)])
assert R.dup_zz_factor_sqf(x**3 - 6*x**2 + 11*x - 6) == \
(1, [x - 3,
x - 2,
x - 1])
assert R.dup_zz_factor(3*x**3 + 10*x**2 + 13*x + 10) == \
(1, [(x + 2, 1),
(3*x**2 + 4*x + 5, 1)])
assert R.dup_zz_factor_sqf(3*x**3 + 10*x**2 + 13*x + 10) == \
(1, [x + 2,
3*x**2 + 4*x + 5])
assert R.dup_zz_factor(-x**6 + x**2) == \
(-1, [(x - 1, 1),
(x + 1, 1),
(x, 2),
(x**2 + 1, 1)])
f = 1080*x**8 + 5184*x**7 + 2099*x**6 + 744*x**5 + 2736*x**4 - 648*x**3 + 129*x**2 - 324
assert R.dup_zz_factor(f) == \
(1, [(5*x**4 + 24*x**3 + 9*x**2 + 12, 1),
(216*x**4 + 31*x**2 - 27, 1)])
f = -29802322387695312500000000000000000000*x**25 \
+ 2980232238769531250000000000000000*x**20 \
+ 1743435859680175781250000000000*x**15 \
+ 114142894744873046875000000*x**10 \
- 210106372833251953125*x**5 \
+ 95367431640625
assert R.dup_zz_factor(f) == \
(-95367431640625, [(5*x - 1, 1),
(100*x**2 + 10*x - 1, 2),
(625*x**4 + 125*x**3 + 25*x**2 + 5*x + 1, 1),
(10000*x**4 - 3000*x**3 + 400*x**2 - 20*x + 1, 2),
(10000*x**4 + 2000*x**3 + 400*x**2 + 30*x + 1, 2)])
f = x**10 - 1
config.setup('USE_CYCLOTOMIC_FACTOR', True)
F_0 = R.dup_zz_factor(f)
config.setup('USE_CYCLOTOMIC_FACTOR', False)
F_1 = R.dup_zz_factor(f)
assert F_0 == F_1 == \
(1, [(x - 1, 1),
(x + 1, 1),
(x**4 - x**3 + x**2 - x + 1, 1),
(x**4 + x**3 + x**2 + x + 1, 1)])
config.setup('USE_CYCLOTOMIC_FACTOR')
f = x**10 + 1
config.setup('USE_CYCLOTOMIC_FACTOR', True)
F_0 = R.dup_zz_factor(f)
config.setup('USE_CYCLOTOMIC_FACTOR', False)
F_1 = R.dup_zz_factor(f)
assert F_0 == F_1 == \
(1, [(x**2 + 1, 1),
(x**8 - x**6 + x**4 - x**2 + 1, 1)])
config.setup('USE_CYCLOTOMIC_FACTOR')
def test_dmp_zz_wang():
R, x,y,z = ring("x,y,z", ZZ)
UV, _x = ring("x", ZZ)
p = ZZ(nextprime(R.dmp_zz_mignotte_bound(w_1)))
assert p == 6291469
t_1, k_1, e_1 = y, 1, ZZ(-14)
t_2, k_2, e_2 = z, 2, ZZ(3)
t_3, k_3, e_3 = y + z, 2, ZZ(-11)
t_4, k_4, e_4 = y - z, 1, ZZ(-17)
T = [t_1, t_2, t_3, t_4]
K = [k_1, k_2, k_3, k_4]
E = [e_1, e_2, e_3, e_4]
T = zip([ t.drop(x) for t in T ], K)
A = [ZZ(-14), ZZ(3)]
S = R.dmp_eval_tail(w_1, A)
cs, s = UV.dup_primitive(S)
assert cs == 1 and s == S == \
1036728*_x**6 + 915552*_x**5 + 55748*_x**4 + 105621*_x**3 - 17304*_x**2 - 26841*_x - 644
assert R.dmp_zz_wang_non_divisors(E, cs, ZZ(4)) == [7, 3, 11, 17]
assert UV.dup_sqf_p(s) and UV.dup_degree(s) == R.dmp_degree(w_1)
_, H = UV.dup_zz_factor_sqf(s)
h_1 = 44*_x**2 + 42*_x + 1
h_2 = 126*_x**2 - 9*_x + 28
h_3 = 187*_x**2 - 23
assert H == [h_1, h_2, h_3]
LC = [ lc.drop(x) for lc in [-4*y - 4*z, -y*z**2, y**2 - z**2] ]
assert R.dmp_zz_wang_lead_coeffs(w_1, T, cs, E, H, A) == (w_1, H, LC)
H_1 = [44*x**2 + 42*x + 1, 126*x**2 - 9*x + 28, 187*x**2 - 23]
H_2 = [-4*x**2*y - 12*x**2 - 3*x*y + 1, -9*x**2*y - 9*x - 2*y, x**2*y**2 - 9*x**2 + y - 9]
H_3 = [-4*x**2*y - 12*x**2 - 3*x*y + 1, -9*x**2*y - 9*x - 2*y, x**2*y**2 - 9*x**2 + y - 9]
c_1 = -70686*x**5 - 5863*x**4 - 17826*x**3 + 2009*x**2 + 5031*x + 74
c_2 = 9*x**5*y**4 + 12*x**5*y**3 - 45*x**5*y**2 - 108*x**5*y - 324*x**5 + 18*x**4*y**3 - 216*x**4*y**2 - 810*x**4*y + 2*x**3*y**4 + 9*x**3*y**3 - 252*x**3*y**2 - 288*x**3*y - 945*x**3 - 30*x**2*y**2 - 414*x**2*y + 2*x*y**3 - 54*x*y**2 - 3*x*y + 81*x + 12*y
c_3 = -36*x**4*y**2 - 108*x**4*y - 27*x**3*y**2 - 36*x**3*y - 108*x**3 - 8*x**2*y**2 - 42*x**2*y - 6*x*y**2 + 9*x + 2*y
# TODO
#assert R.dmp_zz_diophantine(H_1, c_1, [], 5, p) == [-3*x, -2, 1]
#assert R.dmp_zz_diophantine(H_2, c_2, [ZZ(-14)], 5, p) == [-x*y, -3*x, -6]
#assert R.dmp_zz_diophantine(H_3, c_3, [ZZ(-14)], 5, p) == [0, 0, -1]
factors = R.dmp_zz_wang_hensel_lifting(w_1, H, LC, A, p)
assert R.dmp_expand(factors) == w_1
def test_issue_6355():
# This tests a bug in the Wang algorithm that occured only with a very
# specific set of random numbers.
random_sequence = [-1, -1, 0, 0, 0, 0, -1, -1, 0, -1, 3, -1, 3, 3, 3, 3, -1, 3]
R, x, y, z = ring("x,y,z", ZZ)
f = 2*x**2 + y*z - y - z**2 + z
assert R.dmp_zz_wang(f, seed=random_sequence) == [f]
def test_dmp_zz_factor():
R, x = ring("x", ZZ)
assert R.dmp_zz_factor(0) == (0, [])
assert R.dmp_zz_factor(7) == (7, [])
assert R.dmp_zz_factor(-7) == (-7, [])
assert R.dmp_zz_factor(x**2 - 9) == (1, [(x - 3, 1), (x + 3, 1)])
R, x, y = ring("x,y", ZZ)
assert R.dmp_zz_factor(0) == (0, [])
assert R.dmp_zz_factor(7) == (7, [])
assert R.dmp_zz_factor(-7) == (-7, [])
assert R.dmp_zz_factor(x) == (1, [(x, 1)])
assert R.dmp_zz_factor(4*x) == (4, [(x, 1)])
assert R.dmp_zz_factor(4*x + 2) == (2, [(2*x + 1, 1)])
assert R.dmp_zz_factor(x*y + 1) == (1, [(x*y + 1, 1)])
assert R.dmp_zz_factor(y**2 + 1) == (1, [(y**2 + 1, 1)])
assert R.dmp_zz_factor(y**2 - 1) == (1, [(y - 1, 1), (y + 1, 1)])
assert R.dmp_zz_factor(x**2*y**2 + 6*x**2*y + 9*x**2 - 1) == (1, [(x*y + 3*x - 1, 1), (x*y + 3*x + 1, 1)])
assert R.dmp_zz_factor(x**2*y**2 - 9) == (1, [(x*y - 3, 1), (x*y + 3, 1)])
R, x, y, z = ring("x,y,z", ZZ)
assert R.dmp_zz_factor(x**2*y**2*z**2 - 9) == \
(1, [(x*y*z - 3, 1),
(x*y*z + 3, 1)])
R, x, y, z, u = ring("x,y,z,u", ZZ)
assert R.dmp_zz_factor(x**2*y**2*z**2*u**2 - 9) == \
(1, [(x*y*z*u - 3, 1),
(x*y*z*u + 3, 1)])
R, x, y, z = ring("x,y,z", ZZ)
assert R.dmp_zz_factor(f_1) == \
(1, [(x + y*z + 20, 1),
(x*y + z + 10, 1),
(x*z + y + 30, 1)])
assert R.dmp_zz_factor(f_2) == \
(1, [(x**2*y**2 + x**2*z**2 + y + 90, 1),
(x**3*y + x**3*z + z - 11, 1)])
assert R.dmp_zz_factor(f_3) == \
(1, [(x**2*y**2 + x*z**4 + x + z, 1),
(x**3 + x*y*z + y**2 + y*z**3, 1)])
assert R.dmp_zz_factor(f_4) == \
(-1, [(x*y**3 + z**2, 1),
(x**2*z + y**4*z**2 + 5, 1),
(x**3*y - z**2 - 3, 1),
(x**3*y**4 + z**2, 1)])
assert R.dmp_zz_factor(f_5) == \
(-1, [(x + y - z, 3)])
R, x, y, z, t = ring("x,y,z,t", ZZ)
assert R.dmp_zz_factor(f_6) == \
(1, [(47*x*y + z**3*t**2 - t**2, 1),
(45*x**3 - 9*y**3 - y**2 + 3*z**3 + 2*z*t, 1)])
R, x, y, z = ring("x,y,z", ZZ)
assert R.dmp_zz_factor(w_1) == \
(1, [(x**2*y**2 - x**2*z**2 + y - z**2, 1),
(x**2*y*z**2 + 3*x*z + 2*y, 1),
(4*x**2*y + 4*x**2*z + x*y*z - 1, 1)])
R, x, y = ring("x,y", ZZ)
f = -12*x**16*y + 240*x**12*y**3 - 768*x**10*y**4 + 1080*x**8*y**5 - 768*x**6*y**6 + 240*x**4*y**7 - 12*y**9
assert R.dmp_zz_factor(f) == \
(-12, [(y, 1),
(x**2 - y, 6),
(x**4 + 6*x**2*y + y**2, 1)])
def test_dup_ext_factor():
R, x = ring("x", QQ.algebraic_field(I))
def anp(element):
return ANP(element, [QQ(1), QQ(0), QQ(1)], QQ)
assert R.dup_ext_factor(0) == (anp([]), [])
f = anp([QQ(1)])*x + anp([QQ(1)])
assert R.dup_ext_factor(f) == (anp([QQ(1)]), [(f, 1)])
g = anp([QQ(2)])*x + anp([QQ(2)])
assert R.dup_ext_factor(g) == (anp([QQ(2)]), [(f, 1)])
f = anp([QQ(7)])*x**4 + anp([QQ(1, 1)])
g = anp([QQ(1)])*x**4 + anp([QQ(1, 7)])
assert R.dup_ext_factor(f) == (anp([QQ(7)]), [(g, 1)])
f = anp([QQ(1)])*x**4 + anp([QQ(1)])
assert R.dup_ext_factor(f) == \
(anp([QQ(1, 1)]), [(anp([QQ(1)])*x**2 + anp([QQ(-1), QQ(0)]), 1),
(anp([QQ(1)])*x**2 + anp([QQ( 1), QQ(0)]), 1)])
f = anp([QQ(4, 1)])*x**2 + anp([QQ(9, 1)])
assert R.dup_ext_factor(f) == \
(anp([QQ(4, 1)]), [(anp([QQ(1, 1)])*x + anp([-QQ(3, 2), QQ(0, 1)]), 1),
(anp([QQ(1, 1)])*x + anp([ QQ(3, 2), QQ(0, 1)]), 1)])
f = anp([QQ(4, 1)])*x**4 + anp([QQ(8, 1)])*x**3 + anp([QQ(77, 1)])*x**2 + anp([QQ(18, 1)])*x + anp([QQ(153, 1)])
assert R.dup_ext_factor(f) == \
(anp([QQ(4, 1)]), [(anp([QQ(1, 1)])*x + anp([-QQ(4, 1), QQ(1, 1)]), 1),
(anp([QQ(1, 1)])*x + anp([-QQ(3, 2), QQ(0, 1)]), 1),
(anp([QQ(1, 1)])*x + anp([ QQ(3, 2), QQ(0, 1)]), 1),
(anp([QQ(1, 1)])*x + anp([ QQ(4, 1), QQ(1, 1)]), 1)])
R, x = ring("x", QQ.algebraic_field(sqrt(2)))
def anp(element):
return ANP(element, [QQ(1), QQ(0), QQ(-2)], QQ)
f = anp([QQ(1)])*x**4 + anp([QQ(1, 1)])
assert R.dup_ext_factor(f) == \
(anp([QQ(1)]), [(anp([QQ(1)])*x**2 + anp([QQ(-1), QQ(0)])*x + anp([QQ(1)]), 1),
(anp([QQ(1)])*x**2 + anp([QQ( 1), QQ(0)])*x + anp([QQ(1)]), 1)])
f = anp([QQ(1, 1)])*x**2 + anp([QQ(2), QQ(0)])*x + anp([QQ(2, 1)])
assert R.dup_ext_factor(f) == \
(anp([QQ(1, 1)]), [(anp([1])*x + anp([1, 0]), 2)])
assert R.dup_ext_factor(f**3) == \
(anp([QQ(1, 1)]), [(anp([1])*x + anp([1, 0]), 6)])
f *= anp([QQ(2, 1)])
assert R.dup_ext_factor(f) == \
(anp([QQ(2, 1)]), [(anp([1])*x + anp([1, 0]), 2)])
assert R.dup_ext_factor(f**3) == \
(anp([QQ(8, 1)]), [(anp([1])*x + anp([1, 0]), 6)])
def test_dmp_ext_factor():
R, x,y = ring("x,y", QQ.algebraic_field(sqrt(2)))
def anp(x):
return ANP(x, [QQ(1), QQ(0), QQ(-2)], QQ)
assert R.dmp_ext_factor(0) == (anp([]), [])
f = anp([QQ(1)])*x + anp([QQ(1)])
assert R.dmp_ext_factor(f) == (anp([QQ(1)]), [(f, 1)])
g = anp([QQ(2)])*x + anp([QQ(2)])
assert R.dmp_ext_factor(g) == (anp([QQ(2)]), [(f, 1)])
f = anp([QQ(1)])*x**2 + anp([QQ(-2)])*y**2
assert R.dmp_ext_factor(f) == \
(anp([QQ(1)]), [(anp([QQ(1)])*x + anp([QQ(-1), QQ(0)])*y, 1),
(anp([QQ(1)])*x + anp([QQ( 1), QQ(0)])*y, 1)])
f = anp([QQ(2)])*x**2 + anp([QQ(-4)])*y**2
assert R.dmp_ext_factor(f) == \
(anp([QQ(2)]), [(anp([QQ(1)])*x + anp([QQ(-1), QQ(0)])*y, 1),
(anp([QQ(1)])*x + anp([QQ( 1), QQ(0)])*y, 1)])
def test_dup_factor_list():
R, x = ring("x", ZZ)
assert R.dup_factor_list(0) == (0, [])
assert R.dup_factor_list(7) == (7, [])
R, x = ring("x", QQ)
assert R.dup_factor_list(0) == (0, [])
assert R.dup_factor_list(QQ(1, 7)) == (QQ(1, 7), [])
R, x = ring("x", ZZ['t'])
assert R.dup_factor_list(0) == (0, [])
assert R.dup_factor_list(7) == (7, [])
R, x = ring("x", QQ['t'])
assert R.dup_factor_list(0) == (0, [])
assert R.dup_factor_list(QQ(1, 7)) == (QQ(1, 7), [])
R, x = ring("x", ZZ)
assert R.dup_factor_list_include(0) == [(0, 1)]
assert R.dup_factor_list_include(7) == [(7, 1)]
assert R.dup_factor_list(x**2 + 2*x + 1) == (1, [(x + 1, 2)])
assert R.dup_factor_list_include(x**2 + 2*x + 1) == [(x + 1, 2)]
# issue 8037
assert R.dup_factor_list(6*x**2 - 5*x - 6) == (1, [(2*x - 3, 1), (3*x + 2, 1)])
R, x = ring("x", QQ)
assert R.dup_factor_list(QQ(1,2)*x**2 + x + QQ(1,2)) == (QQ(1, 2), [(x + 1, 2)])
R, x = ring("x", FF(2))
assert R.dup_factor_list(x**2 + 1) == (1, [(x + 1, 2)])
R, x = ring("x", RR)
assert R.dup_factor_list(1.0*x**2 + 2.0*x + 1.0) == (1.0, [(1.0*x + 1.0, 2)])
assert R.dup_factor_list(2.0*x**2 + 4.0*x + 2.0) == (2.0, [(1.0*x + 1.0, 2)])
f = 6.7225336055071*x**2 - 10.6463972754741*x - 0.33469524022264
coeff, factors = R.dup_factor_list(f)
assert coeff == RR(1.0) and len(factors) == 1 and factors[0][0].almosteq(f, 1e-10) and factors[0][1] == 1
Rt, t = ring("t", ZZ)
R, x = ring("x", Rt)
f = 4*t*x**2 + 4*t**2*x
assert R.dup_factor_list(f) == \
(4*t, [(x, 1),
(x + t, 1)])
Rt, t = ring("t", QQ)
R, x = ring("x", Rt)
f = QQ(1, 2)*t*x**2 + QQ(1, 2)*t**2*x
assert R.dup_factor_list(f) == \
(QQ(1, 2)*t, [(x, 1),
(x + t, 1)])
R, x = ring("x", QQ.algebraic_field(I))
def anp(element):
return ANP(element, [QQ(1), QQ(0), QQ(1)], QQ)
f = anp([QQ(1, 1)])*x**4 + anp([QQ(2, 1)])*x**2
assert R.dup_factor_list(f) == \
(anp([QQ(1, 1)]), [(anp([QQ(1, 1)])*x, 2),
(anp([QQ(1, 1)])*x**2 + anp([])*x + anp([QQ(2, 1)]), 1)])
R, x = ring("x", EX)
raises(DomainError, lambda: R.dup_factor_list(EX(sin(1))))
def test_dmp_factor_list():
R, x, y = ring("x,y", ZZ)
assert R.dmp_factor_list(0) == (ZZ(0), [])
assert R.dmp_factor_list(7) == (7, [])
R, x, y = ring("x,y", QQ)
assert R.dmp_factor_list(0) == (QQ(0), [])
assert R.dmp_factor_list(QQ(1, 7)) == (QQ(1, 7), [])
Rt, t = ring("t", ZZ)
R, x, y = ring("x,y", Rt)
assert R.dmp_factor_list(0) == (0, [])
assert R.dmp_factor_list(7) == (ZZ(7), [])
Rt, t = ring("t", QQ)
R, x, y = ring("x,y", Rt)
assert R.dmp_factor_list(0) == (0, [])
assert R.dmp_factor_list(QQ(1, 7)) == (QQ(1, 7), [])
R, x, y = ring("x,y", ZZ)
assert R.dmp_factor_list_include(0) == [(0, 1)]
assert R.dmp_factor_list_include(7) == [(7, 1)]
R, X = xring("x:200", ZZ)
f, g = X[0]**2 + 2*X[0] + 1, X[0] + 1
assert R.dmp_factor_list(f) == (1, [(g, 2)])
f, g = X[-1]**2 + 2*X[-1] + 1, X[-1] + 1
assert R.dmp_factor_list(f) == (1, [(g, 2)])
R, x = ring("x", ZZ)
assert R.dmp_factor_list(x**2 + 2*x + 1) == (1, [(x + 1, 2)])
R, x = ring("x", QQ)
assert R.dmp_factor_list(QQ(1,2)*x**2 + x + QQ(1,2)) == (QQ(1,2), [(x + 1, 2)])
R, x, y = ring("x,y", ZZ)
assert R.dmp_factor_list(x**2 + 2*x + 1) == (1, [(x + 1, 2)])
R, x, y = ring("x,y", QQ)
assert R.dmp_factor_list(QQ(1,2)*x**2 + x + QQ(1,2)) == (QQ(1,2), [(x + 1, 2)])
R, x, y = ring("x,y", ZZ)
f = 4*x**2*y + 4*x*y**2
assert R.dmp_factor_list(f) == \
(4, [(y, 1),
(x, 1),
(x + y, 1)])
assert R.dmp_factor_list_include(f) == \
[(4*y, 1),
(x, 1),
(x + y, 1)]
R, x, y = ring("x,y", QQ)
f = QQ(1,2)*x**2*y + QQ(1,2)*x*y**2
assert R.dmp_factor_list(f) == \
(QQ(1,2), [(y, 1),
(x, 1),
(x + y, 1)])
R, x, y = ring("x,y", RR)
f = 2.0*x**2 - 8.0*y**2
assert R.dmp_factor_list(f) == \
(RR(2.0), [(1.0*x - 2.0*y, 1),
(1.0*x + 2.0*y, 1)])
f = 6.7225336055071*x**2*y**2 - 10.6463972754741*x*y - 0.33469524022264
coeff, factors = R.dmp_factor_list(f)
assert coeff == RR(1.0) and len(factors) == 1 and factors[0][0].almosteq(f, 1e-10) and factors[0][1] == 1
Rt, t = ring("t", ZZ)
R, x, y = ring("x,y", Rt)
f = 4*t*x**2 + 4*t**2*x
assert R.dmp_factor_list(f) == \
(4*t, [(x, 1),
(x + t, 1)])
Rt, t = ring("t", QQ)
R, x, y = ring("x,y", Rt)
f = QQ(1, 2)*t*x**2 + QQ(1, 2)*t**2*x
assert R.dmp_factor_list(f) == \
(QQ(1, 2)*t, [(x, 1),
(x + t, 1)])
R, x, y = ring("x,y", FF(2))
raises(NotImplementedError, lambda: R.dmp_factor_list(x**2 + y**2))
R, x, y = ring("x,y", EX)
raises(DomainError, lambda: R.dmp_factor_list(EX(sin(1))))
def test_dup_irreducible_p():
R, x = ring("x", ZZ)
assert R.dup_irreducible_p(x**2 + x + 1) is True
assert R.dup_irreducible_p(x**2 + 2*x + 1) is False
def test_dmp_irreducible_p():
R, x, y = ring("x,y", ZZ)
assert R.dmp_irreducible_p(x**2 + x + 1) is True
assert R.dmp_irreducible_p(x**2 + 2*x + 1) is False
| 21,611 | 31.208644 | 260 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/tests/test_densebasic.py
|
"""Tests for dense recursive polynomials' basic tools. """
from sympy.polys.densebasic import (
dup_LC, dmp_LC,
dup_TC, dmp_TC,
dmp_ground_LC, dmp_ground_TC,
dmp_true_LT,
dup_degree, dmp_degree,
dmp_degree_in, dmp_degree_list,
dup_strip, dmp_strip,
dmp_validate,
dup_reverse,
dup_copy, dmp_copy,
dup_normal, dmp_normal,
dup_convert, dmp_convert,
dup_from_sympy, dmp_from_sympy,
dup_nth, dmp_nth, dmp_ground_nth,
dmp_zero_p, dmp_zero,
dmp_one_p, dmp_one,
dmp_ground_p, dmp_ground,
dmp_negative_p, dmp_positive_p,
dmp_zeros, dmp_grounds,
dup_from_dict, dup_from_raw_dict,
dup_to_dict, dup_to_raw_dict,
dmp_from_dict, dmp_to_dict,
dmp_swap, dmp_permute,
dmp_nest, dmp_raise,
dup_deflate, dmp_deflate,
dup_multi_deflate, dmp_multi_deflate,
dup_inflate, dmp_inflate,
dmp_exclude, dmp_include,
dmp_inject, dmp_eject,
dup_terms_gcd, dmp_terms_gcd,
dmp_list_terms, dmp_apply_pairs,
dup_slice,
dup_random,
)
from sympy.polys.specialpolys import f_polys
from sympy.polys.domains import ZZ, QQ
from sympy.polys.rings import ring
from sympy.core.singleton import S
from sympy.utilities.pytest import raises
from sympy import oo
f_0, f_1, f_2, f_3, f_4, f_5, f_6 = [ f.to_dense() for f in f_polys() ]
def test_dup_LC():
assert dup_LC([], ZZ) == 0
assert dup_LC([2, 3, 4, 5], ZZ) == 2
def test_dup_TC():
assert dup_TC([], ZZ) == 0
assert dup_TC([2, 3, 4, 5], ZZ) == 5
def test_dmp_LC():
assert dmp_LC([[]], ZZ) == []
assert dmp_LC([[2, 3, 4], [5]], ZZ) == [2, 3, 4]
assert dmp_LC([[[]]], ZZ) == [[]]
assert dmp_LC([[[2], [3, 4]], [[5]]], ZZ) == [[2], [3, 4]]
def test_dmp_TC():
assert dmp_TC([[]], ZZ) == []
assert dmp_TC([[2, 3, 4], [5]], ZZ) == [5]
assert dmp_TC([[[]]], ZZ) == [[]]
assert dmp_TC([[[2], [3, 4]], [[5]]], ZZ) == [[5]]
def test_dmp_ground_LC():
assert dmp_ground_LC([[]], 1, ZZ) == 0
assert dmp_ground_LC([[2, 3, 4], [5]], 1, ZZ) == 2
assert dmp_ground_LC([[[]]], 2, ZZ) == 0
assert dmp_ground_LC([[[2], [3, 4]], [[5]]], 2, ZZ) == 2
def test_dmp_ground_TC():
assert dmp_ground_TC([[]], 1, ZZ) == 0
assert dmp_ground_TC([[2, 3, 4], [5]], 1, ZZ) == 5
assert dmp_ground_TC([[[]]], 2, ZZ) == 0
assert dmp_ground_TC([[[2], [3, 4]], [[5]]], 2, ZZ) == 5
def test_dmp_true_LT():
assert dmp_true_LT([[]], 1, ZZ) == ((0, 0), 0)
assert dmp_true_LT([[7]], 1, ZZ) == ((0, 0), 7)
assert dmp_true_LT([[1, 0]], 1, ZZ) == ((0, 1), 1)
assert dmp_true_LT([[1], []], 1, ZZ) == ((1, 0), 1)
assert dmp_true_LT([[1, 0], []], 1, ZZ) == ((1, 1), 1)
def test_dup_degree():
assert dup_degree([]) == -oo
assert dup_degree([1]) == 0
assert dup_degree([1, 0]) == 1
assert dup_degree([1, 0, 0, 0, 1]) == 4
def test_dmp_degree():
assert dmp_degree([[]], 1) == -oo
assert dmp_degree([[[]]], 2) == -oo
assert dmp_degree([[1]], 1) == 0
assert dmp_degree([[2], [1]], 1) == 1
def test_dmp_degree_in():
assert dmp_degree_in([[[]]], 0, 2) == -oo
assert dmp_degree_in([[[]]], 1, 2) == -oo
assert dmp_degree_in([[[]]], 2, 2) == -oo
assert dmp_degree_in([[[1]]], 0, 2) == 0
assert dmp_degree_in([[[1]]], 1, 2) == 0
assert dmp_degree_in([[[1]]], 2, 2) == 0
assert dmp_degree_in(f_4, 0, 2) == 9
assert dmp_degree_in(f_4, 1, 2) == 12
assert dmp_degree_in(f_4, 2, 2) == 8
assert dmp_degree_in(f_6, 0, 2) == 4
assert dmp_degree_in(f_6, 1, 2) == 4
assert dmp_degree_in(f_6, 2, 2) == 6
assert dmp_degree_in(f_6, 3, 3) == 3
raises(IndexError, lambda: dmp_degree_in([[1]], -5, 1))
def test_dmp_degree_list():
assert dmp_degree_list([[[[ ]]]], 3) == (-oo, -oo, -oo, -oo)
assert dmp_degree_list([[[[1]]]], 3) == ( 0, 0, 0, 0)
assert dmp_degree_list(f_0, 2) == (2, 2, 2)
assert dmp_degree_list(f_1, 2) == (3, 3, 3)
assert dmp_degree_list(f_2, 2) == (5, 3, 3)
assert dmp_degree_list(f_3, 2) == (5, 4, 7)
assert dmp_degree_list(f_4, 2) == (9, 12, 8)
assert dmp_degree_list(f_5, 2) == (3, 3, 3)
assert dmp_degree_list(f_6, 3) == (4, 4, 6, 3)
def test_dup_strip():
assert dup_strip([]) == []
assert dup_strip([0]) == []
assert dup_strip([0, 0, 0]) == []
assert dup_strip([1]) == [1]
assert dup_strip([0, 1]) == [1]
assert dup_strip([0, 0, 0, 1]) == [1]
assert dup_strip([1, 2, 0]) == [1, 2, 0]
assert dup_strip([0, 1, 2, 0]) == [1, 2, 0]
assert dup_strip([0, 0, 0, 1, 2, 0]) == [1, 2, 0]
def test_dmp_strip():
assert dmp_strip([0, 1, 0], 0) == [1, 0]
assert dmp_strip([[]], 1) == [[]]
assert dmp_strip([[], []], 1) == [[]]
assert dmp_strip([[], [], []], 1) == [[]]
assert dmp_strip([[[]]], 2) == [[[]]]
assert dmp_strip([[[]], [[]]], 2) == [[[]]]
assert dmp_strip([[[]], [[]], [[]]], 2) == [[[]]]
assert dmp_strip([[[1]]], 2) == [[[1]]]
assert dmp_strip([[[]], [[1]]], 2) == [[[1]]]
assert dmp_strip([[[]], [[1]], [[]]], 2) == [[[1]], [[]]]
def test_dmp_validate():
assert dmp_validate([]) == ([], 0)
assert dmp_validate([0, 0, 0, 1, 0]) == ([1, 0], 0)
assert dmp_validate([[[]]]) == ([[[]]], 2)
assert dmp_validate([[0], [], [0], [1], [0]]) == ([[1], []], 1)
raises(ValueError, lambda: dmp_validate([[0], 0, [0], [1], [0]]))
def test_dup_reverse():
assert dup_reverse([1, 2, 0, 3]) == [3, 0, 2, 1]
assert dup_reverse([1, 2, 3, 0]) == [3, 2, 1]
def test_dup_copy():
f = [ZZ(1), ZZ(0), ZZ(2)]
g = dup_copy(f)
g[0], g[2] = ZZ(7), ZZ(0)
assert f != g
def test_dmp_copy():
f = [[ZZ(1)], [ZZ(2), ZZ(0)]]
g = dmp_copy(f, 1)
g[0][0], g[1][1] = ZZ(7), ZZ(1)
assert f != g
def test_dup_normal():
assert dup_normal([0, 0, 2, 1, 0, 11, 0], ZZ) == \
[ZZ(2), ZZ(1), ZZ(0), ZZ(11), ZZ(0)]
def test_dmp_normal():
assert dmp_normal([[0], [], [0, 2, 1], [0], [11], []], 1, ZZ) == \
[[ZZ(2), ZZ(1)], [], [ZZ(11)], []]
def test_dup_convert():
K0, K1 = ZZ['x'], ZZ
f = [K0(1), K0(2), K0(0), K0(3)]
assert dup_convert(f, K0, K1) == \
[ZZ(1), ZZ(2), ZZ(0), ZZ(3)]
def test_dmp_convert():
K0, K1 = ZZ['x'], ZZ
f = [[K0(1)], [K0(2)], [], [K0(3)]]
assert dmp_convert(f, 1, K0, K1) == \
[[ZZ(1)], [ZZ(2)], [], [ZZ(3)]]
def test_dup_from_sympy():
assert dup_from_sympy([S(1), S(2)], ZZ) == \
[ZZ(1), ZZ(2)]
assert dup_from_sympy([S(1)/2, S(3)], QQ) == \
[QQ(1, 2), QQ(3, 1)]
def test_dmp_from_sympy():
assert dmp_from_sympy([[S(1), S(2)], [S(0)]], 1, ZZ) == \
[[ZZ(1), ZZ(2)], []]
assert dmp_from_sympy([[S(1)/2, S(2)]], 1, QQ) == \
[[QQ(1, 2), QQ(2, 1)]]
def test_dup_nth():
assert dup_nth([1, 2, 3], 0, ZZ) == 3
assert dup_nth([1, 2, 3], 1, ZZ) == 2
assert dup_nth([1, 2, 3], 2, ZZ) == 1
assert dup_nth([1, 2, 3], 9, ZZ) == 0
raises(IndexError, lambda: dup_nth([3, 4, 5], -1, ZZ))
def test_dmp_nth():
assert dmp_nth([[1], [2], [3]], 0, 1, ZZ) == [3]
assert dmp_nth([[1], [2], [3]], 1, 1, ZZ) == [2]
assert dmp_nth([[1], [2], [3]], 2, 1, ZZ) == [1]
assert dmp_nth([[1], [2], [3]], 9, 1, ZZ) == []
raises(IndexError, lambda: dmp_nth([[3], [4], [5]], -1, 1, ZZ))
def test_dmp_ground_nth():
assert dmp_ground_nth([[]], (0, 0), 1, ZZ) == 0
assert dmp_ground_nth([[1], [2], [3]], (0, 0), 1, ZZ) == 3
assert dmp_ground_nth([[1], [2], [3]], (1, 0), 1, ZZ) == 2
assert dmp_ground_nth([[1], [2], [3]], (2, 0), 1, ZZ) == 1
assert dmp_ground_nth([[1], [2], [3]], (2, 1), 1, ZZ) == 0
assert dmp_ground_nth([[1], [2], [3]], (3, 0), 1, ZZ) == 0
raises(IndexError, lambda: dmp_ground_nth([[3], [4], [5]], (2, -1), 1, ZZ))
def test_dmp_zero_p():
assert dmp_zero_p([], 0) is True
assert dmp_zero_p([[]], 1) is True
assert dmp_zero_p([[[]]], 2) is True
assert dmp_zero_p([[[1]]], 2) is False
def test_dmp_zero():
assert dmp_zero(0) == []
assert dmp_zero(2) == [[[]]]
def test_dmp_one_p():
assert dmp_one_p([1], 0, ZZ) is True
assert dmp_one_p([[1]], 1, ZZ) is True
assert dmp_one_p([[[1]]], 2, ZZ) is True
assert dmp_one_p([[[12]]], 2, ZZ) is False
def test_dmp_one():
assert dmp_one(0, ZZ) == [ZZ(1)]
assert dmp_one(2, ZZ) == [[[ZZ(1)]]]
def test_dmp_ground_p():
assert dmp_ground_p([], 0, 0) is True
assert dmp_ground_p([[]], 0, 1) is True
assert dmp_ground_p([[]], 1, 1) is False
assert dmp_ground_p([[ZZ(1)]], 1, 1) is True
assert dmp_ground_p([[[ZZ(2)]]], 2, 2) is True
assert dmp_ground_p([[[ZZ(2)]]], 3, 2) is False
assert dmp_ground_p([[[ZZ(3)], []]], 3, 2) is False
assert dmp_ground_p([], None, 0) is True
assert dmp_ground_p([[]], None, 1) is True
assert dmp_ground_p([ZZ(1)], None, 0) is True
assert dmp_ground_p([[[ZZ(1)]]], None, 2) is True
assert dmp_ground_p([[[ZZ(3)], []]], None, 2) is False
def test_dmp_ground():
assert dmp_ground(ZZ(0), 2) == [[[]]]
assert dmp_ground(ZZ(7), -1) == ZZ(7)
assert dmp_ground(ZZ(7), 0) == [ZZ(7)]
assert dmp_ground(ZZ(7), 2) == [[[ZZ(7)]]]
def test_dmp_zeros():
assert dmp_zeros(4, 0, ZZ) == [[], [], [], []]
assert dmp_zeros(0, 2, ZZ) == []
assert dmp_zeros(1, 2, ZZ) == [[[[]]]]
assert dmp_zeros(2, 2, ZZ) == [[[[]]], [[[]]]]
assert dmp_zeros(3, 2, ZZ) == [[[[]]], [[[]]], [[[]]]]
assert dmp_zeros(3, -1, ZZ) == [0, 0, 0]
def test_dmp_grounds():
assert dmp_grounds(ZZ(7), 0, 2) == []
assert dmp_grounds(ZZ(7), 1, 2) == [[[[7]]]]
assert dmp_grounds(ZZ(7), 2, 2) == [[[[7]]], [[[7]]]]
assert dmp_grounds(ZZ(7), 3, 2) == [[[[7]]], [[[7]]], [[[7]]]]
assert dmp_grounds(ZZ(7), 3, -1) == [7, 7, 7]
def test_dmp_negative_p():
assert dmp_negative_p([[[]]], 2, ZZ) is False
assert dmp_negative_p([[[1], [2]]], 2, ZZ) is False
assert dmp_negative_p([[[-1], [2]]], 2, ZZ) is True
def test_dmp_positive_p():
assert dmp_positive_p([[[]]], 2, ZZ) is False
assert dmp_positive_p([[[1], [2]]], 2, ZZ) is True
assert dmp_positive_p([[[-1], [2]]], 2, ZZ) is False
def test_dup_from_to_dict():
assert dup_from_raw_dict({}, ZZ) == []
assert dup_from_dict({}, ZZ) == []
assert dup_to_raw_dict([]) == {}
assert dup_to_dict([]) == {}
assert dup_to_raw_dict([], ZZ, zero=True) == {0: ZZ(0)}
assert dup_to_dict([], ZZ, zero=True) == {(0,): ZZ(0)}
f = [3, 0, 0, 2, 0, 0, 0, 0, 8]
g = {8: 3, 5: 2, 0: 8}
h = {(8,): 3, (5,): 2, (0,): 8}
assert dup_from_raw_dict(g, ZZ) == f
assert dup_from_dict(h, ZZ) == f
assert dup_to_raw_dict(f) == g
assert dup_to_dict(f) == h
R, x,y = ring("x,y", ZZ)
K = R.to_domain()
f = [R(3), R(0), R(2), R(0), R(0), R(8)]
g = {5: R(3), 3: R(2), 0: R(8)}
h = {(5,): R(3), (3,): R(2), (0,): R(8)}
assert dup_from_raw_dict(g, K) == f
assert dup_from_dict(h, K) == f
assert dup_to_raw_dict(f) == g
assert dup_to_dict(f) == h
def test_dmp_from_to_dict():
assert dmp_from_dict({}, 1, ZZ) == [[]]
assert dmp_to_dict([[]], 1) == {}
assert dmp_to_dict([], 0, ZZ, zero=True) == {(0,): ZZ(0)}
assert dmp_to_dict([[]], 1, ZZ, zero=True) == {(0, 0): ZZ(0)}
f = [[3], [], [], [2], [], [], [], [], [8]]
g = {(8, 0): 3, (5, 0): 2, (0, 0): 8}
assert dmp_from_dict(g, 1, ZZ) == f
assert dmp_to_dict(f, 1) == g
def test_dmp_swap():
f = dmp_normal([[1, 0, 0], [], [1, 0], [], [1]], 1, ZZ)
g = dmp_normal([[1, 0, 0, 0, 0], [1, 0, 0], [1]], 1, ZZ)
assert dmp_swap(f, 1, 1, 1, ZZ) == f
assert dmp_swap(f, 0, 1, 1, ZZ) == g
assert dmp_swap(g, 0, 1, 1, ZZ) == f
raises(IndexError, lambda: dmp_swap(f, -1, -7, 1, ZZ))
def test_dmp_permute():
f = dmp_normal([[1, 0, 0], [], [1, 0], [], [1]], 1, ZZ)
g = dmp_normal([[1, 0, 0, 0, 0], [1, 0, 0], [1]], 1, ZZ)
assert dmp_permute(f, [0, 1], 1, ZZ) == f
assert dmp_permute(g, [0, 1], 1, ZZ) == g
assert dmp_permute(f, [1, 0], 1, ZZ) == g
assert dmp_permute(g, [1, 0], 1, ZZ) == f
def test_dmp_nest():
assert dmp_nest(ZZ(1), 2, ZZ) == [[[1]]]
assert dmp_nest([[1]], 0, ZZ) == [[1]]
assert dmp_nest([[1]], 1, ZZ) == [[[1]]]
assert dmp_nest([[1]], 2, ZZ) == [[[[1]]]]
def test_dmp_raise():
assert dmp_raise([], 2, 0, ZZ) == [[[]]]
assert dmp_raise([[1]], 0, 1, ZZ) == [[1]]
assert dmp_raise([[1, 2, 3], [], [2, 3]], 2, 1, ZZ) == \
[[[[1]], [[2]], [[3]]], [[[]]], [[[2]], [[3]]]]
def test_dup_deflate():
assert dup_deflate([], ZZ) == (1, [])
assert dup_deflate([2], ZZ) == (1, [2])
assert dup_deflate([1, 2, 3], ZZ) == (1, [1, 2, 3])
assert dup_deflate([1, 0, 2, 0, 3], ZZ) == (2, [1, 2, 3])
assert dup_deflate(dup_from_raw_dict({7: 1, 1: 1}, ZZ), ZZ) == \
(1, [1, 0, 0, 0, 0, 0, 1, 0])
assert dup_deflate(dup_from_raw_dict({7: 1, 0: 1}, ZZ), ZZ) == \
(7, [1, 1])
assert dup_deflate(dup_from_raw_dict({7: 1, 3: 1}, ZZ), ZZ) == \
(1, [1, 0, 0, 0, 1, 0, 0, 0])
assert dup_deflate(dup_from_raw_dict({7: 1, 4: 1}, ZZ), ZZ) == \
(1, [1, 0, 0, 1, 0, 0, 0, 0])
assert dup_deflate(dup_from_raw_dict({8: 1, 4: 1}, ZZ), ZZ) == \
(4, [1, 1, 0])
assert dup_deflate(dup_from_raw_dict({8: 1}, ZZ), ZZ) == \
(8, [1, 0])
assert dup_deflate(dup_from_raw_dict({7: 1}, ZZ), ZZ) == \
(7, [1, 0])
assert dup_deflate(dup_from_raw_dict({1: 1}, ZZ), ZZ) == \
(1, [1, 0])
def test_dmp_deflate():
assert dmp_deflate([[]], 1, ZZ) == ((1, 1), [[]])
assert dmp_deflate([[2]], 1, ZZ) == ((1, 1), [[2]])
f = [[1, 0, 0], [], [1, 0], [], [1]]
assert dmp_deflate(f, 1, ZZ) == ((2, 1), [[1, 0, 0], [1, 0], [1]])
def test_dup_multi_deflate():
assert dup_multi_deflate(([2],), ZZ) == (1, ([2],))
assert dup_multi_deflate(([], []), ZZ) == (1, ([], []))
assert dup_multi_deflate(([1, 2, 3],), ZZ) == (1, ([1, 2, 3],))
assert dup_multi_deflate(([1, 0, 2, 0, 3],), ZZ) == (2, ([1, 2, 3],))
assert dup_multi_deflate(([1, 0, 2, 0, 3], [2, 0, 0]), ZZ) == \
(2, ([1, 2, 3], [2, 0]))
assert dup_multi_deflate(([1, 0, 2, 0, 3], [2, 1, 0]), ZZ) == \
(1, ([1, 0, 2, 0, 3], [2, 1, 0]))
def test_dmp_multi_deflate():
assert dmp_multi_deflate(([[]],), 1, ZZ) == \
((1, 1), ([[]],))
assert dmp_multi_deflate(([[]], [[]]), 1, ZZ) == \
((1, 1), ([[]], [[]]))
assert dmp_multi_deflate(([[1]], [[]]), 1, ZZ) == \
((1, 1), ([[1]], [[]]))
assert dmp_multi_deflate(([[1]], [[2]]), 1, ZZ) == \
((1, 1), ([[1]], [[2]]))
assert dmp_multi_deflate(([[1]], [[2, 0]]), 1, ZZ) == \
((1, 1), ([[1]], [[2, 0]]))
assert dmp_multi_deflate(([[2, 0]], [[2, 0]]), 1, ZZ) == \
((1, 1), ([[2, 0]], [[2, 0]]))
assert dmp_multi_deflate(
([[2]], [[2, 0, 0]]), 1, ZZ) == ((1, 2), ([[2]], [[2, 0]]))
assert dmp_multi_deflate(
([[2, 0, 0]], [[2, 0, 0]]), 1, ZZ) == ((1, 2), ([[2, 0]], [[2, 0]]))
assert dmp_multi_deflate(([2, 0, 0], [1, 0, 4, 0, 1]), 0, ZZ) == \
((2,), ([2, 0], [1, 4, 1]))
f = [[1, 0, 0], [], [1, 0], [], [1]]
g = [[1, 0, 1, 0], [], [1]]
assert dmp_multi_deflate((f,), 1, ZZ) == \
((2, 1), ([[1, 0, 0], [1, 0], [1]],))
assert dmp_multi_deflate((f, g), 1, ZZ) == \
((2, 1), ([[1, 0, 0], [1, 0], [1]],
[[1, 0, 1, 0], [1]]))
def test_dup_inflate():
assert dup_inflate([], 17, ZZ) == []
assert dup_inflate([1, 2, 3], 1, ZZ) == [1, 2, 3]
assert dup_inflate([1, 2, 3], 2, ZZ) == [1, 0, 2, 0, 3]
assert dup_inflate([1, 2, 3], 3, ZZ) == [1, 0, 0, 2, 0, 0, 3]
assert dup_inflate([1, 2, 3], 4, ZZ) == [1, 0, 0, 0, 2, 0, 0, 0, 3]
raises(IndexError, lambda: dup_inflate([1, 2, 3], 0, ZZ))
def test_dmp_inflate():
assert dmp_inflate([1], (3,), 0, ZZ) == [1]
assert dmp_inflate([[]], (3, 7), 1, ZZ) == [[]]
assert dmp_inflate([[2]], (1, 2), 1, ZZ) == [[2]]
assert dmp_inflate([[2, 0]], (1, 1), 1, ZZ) == [[2, 0]]
assert dmp_inflate([[2, 0]], (1, 2), 1, ZZ) == [[2, 0, 0]]
assert dmp_inflate([[2, 0]], (1, 3), 1, ZZ) == [[2, 0, 0, 0]]
assert dmp_inflate([[1, 0, 0], [1], [1, 0]], (2, 1), 1, ZZ) == \
[[1, 0, 0], [], [1], [], [1, 0]]
raises(IndexError, lambda: dmp_inflate([[]], (-3, 7), 1, ZZ))
def test_dmp_exclude():
assert dmp_exclude([[[]]], 2, ZZ) == ([], [[[]]], 2)
assert dmp_exclude([[[7]]], 2, ZZ) == ([], [[[7]]], 2)
assert dmp_exclude([1, 2, 3], 0, ZZ) == ([], [1, 2, 3], 0)
assert dmp_exclude([[1], [2, 3]], 1, ZZ) == ([], [[1], [2, 3]], 1)
assert dmp_exclude([[1, 2, 3]], 1, ZZ) == ([0], [1, 2, 3], 0)
assert dmp_exclude([[1], [2], [3]], 1, ZZ) == ([1], [1, 2, 3], 0)
assert dmp_exclude([[[1, 2, 3]]], 2, ZZ) == ([0, 1], [1, 2, 3], 0)
assert dmp_exclude([[[1]], [[2]], [[3]]], 2, ZZ) == ([1, 2], [1, 2, 3], 0)
def test_dmp_include():
assert dmp_include([1, 2, 3], [], 0, ZZ) == [1, 2, 3]
assert dmp_include([1, 2, 3], [0], 0, ZZ) == [[1, 2, 3]]
assert dmp_include([1, 2, 3], [1], 0, ZZ) == [[1], [2], [3]]
assert dmp_include([1, 2, 3], [0, 1], 0, ZZ) == [[[1, 2, 3]]]
assert dmp_include([1, 2, 3], [1, 2], 0, ZZ) == [[[1]], [[2]], [[3]]]
def test_dmp_inject():
R, x,y = ring("x,y", ZZ)
K = R.to_domain()
assert dmp_inject([], 0, K) == ([[[]]], 2)
assert dmp_inject([[]], 1, K) == ([[[[]]]], 3)
assert dmp_inject([R(1)], 0, K) == ([[[1]]], 2)
assert dmp_inject([[R(1)]], 1, K) == ([[[[1]]]], 3)
assert dmp_inject([R(1), 2*x + 3*y + 4], 0, K) == ([[[1]], [[2], [3, 4]]], 2)
f = [3*x**2 + 7*x*y + 5*y**2, 2*x, R(0), x*y**2 + 11]
g = [[[3], [7, 0], [5, 0, 0]], [[2], []], [[]], [[1, 0, 0], [11]]]
assert dmp_inject(f, 0, K) == (g, 2)
def test_dmp_eject():
R, x,y = ring("x,y", ZZ)
K = R.to_domain()
assert dmp_eject([[[]]], 2, K) == []
assert dmp_eject([[[[]]]], 3, K) == [[]]
assert dmp_eject([[[1]]], 2, K) == [R(1)]
assert dmp_eject([[[[1]]]], 3, K) == [[R(1)]]
assert dmp_eject([[[1]], [[2], [3, 4]]], 2, K) == [R(1), 2*x + 3*y + 4]
f = [3*x**2 + 7*x*y + 5*y**2, 2*x, R(0), x*y**2 + 11]
g = [[[3], [7, 0], [5, 0, 0]], [[2], []], [[]], [[1, 0, 0], [11]]]
assert dmp_eject(g, 2, K) == f
def test_dup_terms_gcd():
assert dup_terms_gcd([], ZZ) == (0, [])
assert dup_terms_gcd([1, 0, 1], ZZ) == (0, [1, 0, 1])
assert dup_terms_gcd([1, 0, 1, 0], ZZ) == (1, [1, 0, 1])
def test_dmp_terms_gcd():
assert dmp_terms_gcd([[]], 1, ZZ) == ((0, 0), [[]])
assert dmp_terms_gcd([1, 0, 1, 0], 0, ZZ) == ((1,), [1, 0, 1])
assert dmp_terms_gcd([[1], [], [1], []], 1, ZZ) == ((1, 0), [[1], [], [1]])
assert dmp_terms_gcd(
[[1, 0], [], [1]], 1, ZZ) == ((0, 0), [[1, 0], [], [1]])
assert dmp_terms_gcd(
[[1, 0], [1, 0, 0], [], []], 1, ZZ) == ((2, 1), [[1], [1, 0]])
def test_dmp_list_terms():
assert dmp_list_terms([[[]]], 2, ZZ) == [((0, 0, 0), 0)]
assert dmp_list_terms([[[1]]], 2, ZZ) == [((0, 0, 0), 1)]
assert dmp_list_terms([1, 2, 4, 3, 5], 0, ZZ) == \
[((4,), 1), ((3,), 2), ((2,), 4), ((1,), 3), ((0,), 5)]
assert dmp_list_terms([[1], [2, 4], [3, 5, 0]], 1, ZZ) == \
[((2, 0), 1), ((1, 1), 2), ((1, 0), 4), ((0, 2), 3), ((0, 1), 5)]
f = [[2, 0, 0, 0], [1, 0, 0], []]
assert dmp_list_terms(f, 1, ZZ, order='lex') == [((2, 3), 2), ((1, 2), 1)]
assert dmp_list_terms(
f, 1, ZZ, order='grlex') == [((2, 3), 2), ((1, 2), 1)]
f = [[2, 0, 0, 0], [1, 0, 0, 0, 0, 0], []]
assert dmp_list_terms(f, 1, ZZ, order='lex') == [((2, 3), 2), ((1, 5), 1)]
assert dmp_list_terms(
f, 1, ZZ, order='grlex') == [((1, 5), 1), ((2, 3), 2)]
def test_dmp_apply_pairs():
h = lambda a, b: a*b
assert dmp_apply_pairs([1, 2, 3], [4, 5, 6], h, [], 0, ZZ) == [4, 10, 18]
assert dmp_apply_pairs([2, 3], [4, 5, 6], h, [], 0, ZZ) == [10, 18]
assert dmp_apply_pairs([1, 2, 3], [5, 6], h, [], 0, ZZ) == [10, 18]
assert dmp_apply_pairs(
[[1, 2], [3]], [[4, 5], [6]], h, [], 1, ZZ) == [[4, 10], [18]]
assert dmp_apply_pairs(
[[1, 2], [3]], [[4], [5, 6]], h, [], 1, ZZ) == [[8], [18]]
assert dmp_apply_pairs(
[[1], [2, 3]], [[4, 5], [6]], h, [], 1, ZZ) == [[5], [18]]
def test_dup_slice():
f = [1, 2, 3, 4]
assert dup_slice(f, 0, 0, ZZ) == []
assert dup_slice(f, 0, 1, ZZ) == [4]
assert dup_slice(f, 0, 2, ZZ) == [3, 4]
assert dup_slice(f, 0, 3, ZZ) == [2, 3, 4]
assert dup_slice(f, 0, 4, ZZ) == [1, 2, 3, 4]
assert dup_slice(f, 0, 4, ZZ) == f
assert dup_slice(f, 0, 9, ZZ) == f
assert dup_slice(f, 1, 0, ZZ) == []
assert dup_slice(f, 1, 1, ZZ) == []
assert dup_slice(f, 1, 2, ZZ) == [3, 0]
assert dup_slice(f, 1, 3, ZZ) == [2, 3, 0]
assert dup_slice(f, 1, 4, ZZ) == [1, 2, 3, 0]
assert dup_slice([1, 2], 0, 3, ZZ) == [1, 2]
def test_dup_random():
f = dup_random(0, -10, 10, ZZ)
assert dup_degree(f) == 0
assert all(-10 <= c <= 10 for c in f)
f = dup_random(1, -20, 20, ZZ)
assert dup_degree(f) == 1
assert all(-20 <= c <= 20 for c in f)
f = dup_random(2, -30, 30, ZZ)
assert dup_degree(f) == 2
assert all(-30 <= c <= 30 for c in f)
f = dup_random(3, -40, 40, ZZ)
assert dup_degree(f) == 3
assert all(-40 <= c <= 40 for c in f)
| 21,462 | 28.604138 | 81 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/tests/test_orthopolys.py
|
"""Tests for efficient functions for generating orthogonal polynomials. """
from sympy import Poly, S, Rational as Q
from sympy.utilities.pytest import raises
from sympy.polys.orthopolys import (
jacobi_poly,
gegenbauer_poly,
chebyshevt_poly,
chebyshevu_poly,
hermite_poly,
legendre_poly,
laguerre_poly,
)
from sympy.abc import x, a, b
def test_jacobi_poly():
raises(ValueError, lambda: jacobi_poly(-1, a, b, x))
assert jacobi_poly(1, a, b, x, polys=True) == Poly(
(a/2 + b/2 + 1)*x + a/2 - b/2, x, domain='ZZ(a,b)')
assert jacobi_poly(0, a, b, x) == 1
assert jacobi_poly(1, a, b, x) == a/2 - b/2 + x*(a/2 + b/2 + 1)
assert jacobi_poly(2, a, b, x) == (a**2/8 - a*b/4 - a/8 + b**2/8 - b/8 + x**2*(a**2/8 + a*b/4 + 7*a/8 +
b**2/8 + 7*b/8 + S(3)/2) + x*(a**2/4 + 3*a/4 - b**2/4 - 3*b/4) - S(1)/2)
assert jacobi_poly(1, a, b, polys=True) == Poly(
(a/2 + b/2 + 1)*x + a/2 - b/2, x, domain='ZZ(a,b)')
def test_gegenbauer_poly():
raises(ValueError, lambda: gegenbauer_poly(-1, a, x))
assert gegenbauer_poly(
1, a, x, polys=True) == Poly(2*a*x, x, domain='ZZ(a)')
assert gegenbauer_poly(0, a, x) == 1
assert gegenbauer_poly(1, a, x) == 2*a*x
assert gegenbauer_poly(2, a, x) == -a + x**2*(2*a**2 + 2*a)
assert gegenbauer_poly(
3, a, x) == x**3*(4*a**3/3 + 4*a**2 + 8*a/3) + x*(-2*a**2 - 2*a)
assert gegenbauer_poly(1, S.Half).dummy_eq(x)
assert gegenbauer_poly(1, a, polys=True) == Poly(2*a*x, x, domain='ZZ(a)')
def test_chebyshevt_poly():
raises(ValueError, lambda: chebyshevt_poly(-1, x))
assert chebyshevt_poly(1, x, polys=True) == Poly(x)
assert chebyshevt_poly(0, x) == 1
assert chebyshevt_poly(1, x) == x
assert chebyshevt_poly(2, x) == 2*x**2 - 1
assert chebyshevt_poly(3, x) == 4*x**3 - 3*x
assert chebyshevt_poly(4, x) == 8*x**4 - 8*x**2 + 1
assert chebyshevt_poly(5, x) == 16*x**5 - 20*x**3 + 5*x
assert chebyshevt_poly(6, x) == 32*x**6 - 48*x**4 + 18*x**2 - 1
assert chebyshevt_poly(1).dummy_eq(x)
assert chebyshevt_poly(1, polys=True) == Poly(x)
def test_chebyshevu_poly():
raises(ValueError, lambda: chebyshevu_poly(-1, x))
assert chebyshevu_poly(1, x, polys=True) == Poly(2*x)
assert chebyshevu_poly(0, x) == 1
assert chebyshevu_poly(1, x) == 2*x
assert chebyshevu_poly(2, x) == 4*x**2 - 1
assert chebyshevu_poly(3, x) == 8*x**3 - 4*x
assert chebyshevu_poly(4, x) == 16*x**4 - 12*x**2 + 1
assert chebyshevu_poly(5, x) == 32*x**5 - 32*x**3 + 6*x
assert chebyshevu_poly(6, x) == 64*x**6 - 80*x**4 + 24*x**2 - 1
assert chebyshevu_poly(1).dummy_eq(2*x)
assert chebyshevu_poly(1, polys=True) == Poly(2*x)
def test_hermite_poly():
raises(ValueError, lambda: hermite_poly(-1, x))
assert hermite_poly(1, x, polys=True) == Poly(2*x)
assert hermite_poly(0, x) == 1
assert hermite_poly(1, x) == 2*x
assert hermite_poly(2, x) == 4*x**2 - 2
assert hermite_poly(3, x) == 8*x**3 - 12*x
assert hermite_poly(4, x) == 16*x**4 - 48*x**2 + 12
assert hermite_poly(5, x) == 32*x**5 - 160*x**3 + 120*x
assert hermite_poly(6, x) == 64*x**6 - 480*x**4 + 720*x**2 - 120
assert hermite_poly(1).dummy_eq(2*x)
assert hermite_poly(1, polys=True) == Poly(2*x)
def test_legendre_poly():
raises(ValueError, lambda: legendre_poly(-1, x))
assert legendre_poly(1, x, polys=True) == Poly(x)
assert legendre_poly(0, x) == 1
assert legendre_poly(1, x) == x
assert legendre_poly(2, x) == Q(3, 2)*x**2 - Q(1, 2)
assert legendre_poly(3, x) == Q(5, 2)*x**3 - Q(3, 2)*x
assert legendre_poly(4, x) == Q(35, 8)*x**4 - Q(30, 8)*x**2 + Q(3, 8)
assert legendre_poly(5, x) == Q(63, 8)*x**5 - Q(70, 8)*x**3 + Q(15, 8)*x
assert legendre_poly(6, x) == Q(
231, 16)*x**6 - Q(315, 16)*x**4 + Q(105, 16)*x**2 - Q(5, 16)
assert legendre_poly(1).dummy_eq(x)
assert legendre_poly(1, polys=True) == Poly(x)
def test_laguerre_poly():
raises(ValueError, lambda: laguerre_poly(-1, x))
assert laguerre_poly(1, x, polys=True) == Poly(-x + 1)
assert laguerre_poly(0, x) == 1
assert laguerre_poly(1, x) == -x + 1
assert laguerre_poly(2, x) == Q(1, 2)*x**2 - Q(4, 2)*x + 1
assert laguerre_poly(3, x) == -Q(1, 6)*x**3 + Q(9, 6)*x**2 - Q(18, 6)*x + 1
assert laguerre_poly(4, x) == Q(
1, 24)*x**4 - Q(16, 24)*x**3 + Q(72, 24)*x**2 - Q(96, 24)*x + 1
assert laguerre_poly(5, x) == -Q(1, 120)*x**5 + Q(25, 120)*x**4 - Q(
200, 120)*x**3 + Q(600, 120)*x**2 - Q(600, 120)*x + 1
assert laguerre_poly(6, x) == Q(1, 720)*x**6 - Q(36, 720)*x**5 + Q(450, 720)*x**4 - Q(2400, 720)*x**3 + Q(5400, 720)*x**2 - Q(4320, 720)*x + 1
assert laguerre_poly(0, x, a) == 1
assert laguerre_poly(1, x, a) == -x + a + 1
assert laguerre_poly(2, x, a) == x**2/2 + (-a - 2)*x + a**2/2 + 3*a/2 + 1
assert laguerre_poly(3, x, a) == -x**3/6 + (a/2 + Q(
3)/2)*x**2 + (-a**2/2 - 5*a/2 - 3)*x + a**3/6 + a**2 + 11*a/6 + 1
assert laguerre_poly(1).dummy_eq(-x + 1)
assert laguerre_poly(1, polys=True) == Poly(-x + 1)
| 5,176 | 35.457746 | 146 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/tests/test_monomials.py
|
"""Tests for tools and arithmetics for monomials of distributed polynomials. """
from sympy.polys.monomials import (
itermonomials, monomial_count,
monomial_mul, monomial_div,
monomial_gcd, monomial_lcm,
monomial_max, monomial_min,
monomial_divides,
Monomial,
)
from sympy.polys.polyerrors import ExactQuotientFailed
from sympy.abc import a, b, c, x, y, z
from sympy.core import S
from sympy.utilities.pytest import raises
def test_monomials():
assert itermonomials([], 0) == {S(1)}
assert itermonomials([], 1) == {S(1)}
assert itermonomials([], 2) == {S(1)}
assert itermonomials([], 3) == {S(1)}
assert itermonomials([x], 0) == {S(1)}
assert itermonomials([x], 1) == {S(1), x}
assert itermonomials([x], 2) == {S(1), x, x**2}
assert itermonomials([x], 3) == {S(1), x, x**2, x**3}
assert itermonomials([x, y], 0) == {S(1)}
assert itermonomials([x, y], 1) == {S(1), x, y}
assert itermonomials([x, y], 2) == {S(1), x, y, x**2, y**2, x*y}
assert itermonomials([x, y], 3) == \
{S(1), x, y, x**2, x**3, y**2, y**3, x*y, x*y**2, y*x**2}
def test_monomial_count():
assert monomial_count(2, 2) == 6
assert monomial_count(2, 3) == 10
def test_monomial_mul():
assert monomial_mul((3, 4, 1), (1, 2, 0)) == (4, 6, 1)
def test_monomial_div():
assert monomial_div((3, 4, 1), (1, 2, 0)) == (2, 2, 1)
def test_monomial_gcd():
assert monomial_gcd((3, 4, 1), (1, 2, 0)) == (1, 2, 0)
def test_monomial_lcm():
assert monomial_lcm((3, 4, 1), (1, 2, 0)) == (3, 4, 1)
def test_monomial_max():
assert monomial_max((3, 4, 5), (0, 5, 1), (6, 3, 9)) == (6, 5, 9)
def test_monomial_min():
assert monomial_min((3, 4, 5), (0, 5, 1), (6, 3, 9)) == (0, 3, 1)
def test_monomial_divides():
assert monomial_divides((1, 2, 3), (4, 5, 6)) is True
assert monomial_divides((1, 2, 3), (0, 5, 6)) is False
def test_Monomial():
m = Monomial((3, 4, 1), (x, y, z))
n = Monomial((1, 2, 0), (x, y, z))
assert m.as_expr() == x**3*y**4*z
assert n.as_expr() == x**1*y**2
assert m.as_expr(a, b, c) == a**3*b**4*c
assert n.as_expr(a, b, c) == a**1*b**2
assert m.exponents == (3, 4, 1)
assert m.gens == (x, y, z)
assert n.exponents == (1, 2, 0)
assert n.gens == (x, y, z)
assert m == (3, 4, 1)
assert n != (3, 4, 1)
assert m != (1, 2, 0)
assert n == (1, 2, 0)
assert m[0] == m[-3] == 3
assert m[1] == m[-2] == 4
assert m[2] == m[-1] == 1
assert n[0] == n[-3] == 1
assert n[1] == n[-2] == 2
assert n[2] == n[-1] == 0
assert m[:2] == (3, 4)
assert n[:2] == (1, 2)
assert m*n == Monomial((4, 6, 1))
assert m/n == Monomial((2, 2, 1))
assert m*(1, 2, 0) == Monomial((4, 6, 1))
assert m/(1, 2, 0) == Monomial((2, 2, 1))
assert m.gcd(n) == Monomial((1, 2, 0))
assert m.lcm(n) == Monomial((3, 4, 1))
assert m.gcd((1, 2, 0)) == Monomial((1, 2, 0))
assert m.lcm((1, 2, 0)) == Monomial((3, 4, 1))
assert m**0 == Monomial((0, 0, 0))
assert m**1 == m
assert m**2 == Monomial((6, 8, 2))
assert m**3 == Monomial((9, 12, 3))
raises(ExactQuotientFailed, lambda: m/Monomial((5, 2, 0)))
| 3,206 | 27.380531 | 80 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/tests/test_rings.py
|
"""Test sparse polynomials. """
from operator import add, mul
from sympy.polys.rings import ring, xring, sring, PolyRing, PolyElement
from sympy.polys.fields import field, FracField
from sympy.polys.domains import ZZ, QQ, RR, FF, EX
from sympy.polys.orderings import lex, grlex
from sympy.polys.polyerrors import GeneratorsError, GeneratorsNeeded, \
ExactQuotientFailed, MultivariatePolynomialError, CoercionFailed
from sympy.utilities.pytest import raises
from sympy.core import Symbol, symbols
from sympy.core.compatibility import reduce, range
from sympy import sqrt, pi, oo
def test_PolyRing___init__():
x, y, z, t = map(Symbol, "xyzt")
assert len(PolyRing("x,y,z", ZZ, lex).gens) == 3
assert len(PolyRing(x, ZZ, lex).gens) == 1
assert len(PolyRing(("x", "y", "z"), ZZ, lex).gens) == 3
assert len(PolyRing((x, y, z), ZZ, lex).gens) == 3
assert len(PolyRing("", ZZ, lex).gens) == 0
assert len(PolyRing([], ZZ, lex).gens) == 0
raises(GeneratorsError, lambda: PolyRing(0, ZZ, lex))
assert PolyRing("x", ZZ[t], lex).domain == ZZ[t]
assert PolyRing("x", 'ZZ[t]', lex).domain == ZZ[t]
assert PolyRing("x", PolyRing("t", ZZ, lex), lex).domain == ZZ[t]
raises(GeneratorsError, lambda: PolyRing("x", PolyRing("x", ZZ, lex), lex))
_lex = Symbol("lex")
assert PolyRing("x", ZZ, lex).order == lex
assert PolyRing("x", ZZ, _lex).order == lex
assert PolyRing("x", ZZ, 'lex').order == lex
R1 = PolyRing("x,y", ZZ, lex)
R2 = PolyRing("x,y", ZZ, lex)
R3 = PolyRing("x,y,z", ZZ, lex)
assert R1.x == R1.gens[0]
assert R1.y == R1.gens[1]
assert R1.x == R2.x
assert R1.y == R2.y
assert R1.x != R3.x
assert R1.y != R3.y
def test_PolyRing___hash__():
R, x, y, z = ring("x,y,z", QQ)
assert hash(R)
def test_PolyRing___eq__():
assert ring("x,y,z", QQ)[0] == ring("x,y,z", QQ)[0]
assert ring("x,y,z", QQ)[0] is ring("x,y,z", QQ)[0]
assert ring("x,y,z", QQ)[0] != ring("x,y,z", ZZ)[0]
assert ring("x,y,z", QQ)[0] is not ring("x,y,z", ZZ)[0]
assert ring("x,y,z", ZZ)[0] != ring("x,y,z", QQ)[0]
assert ring("x,y,z", ZZ)[0] is not ring("x,y,z", QQ)[0]
assert ring("x,y,z", QQ)[0] != ring("x,y", QQ)[0]
assert ring("x,y,z", QQ)[0] is not ring("x,y", QQ)[0]
assert ring("x,y", QQ)[0] != ring("x,y,z", QQ)[0]
assert ring("x,y", QQ)[0] is not ring("x,y,z", QQ)[0]
def test_PolyRing_ring_new():
R, x, y, z = ring("x,y,z", QQ)
assert R.ring_new(7) == R(7)
assert R.ring_new(7*x*y*z) == 7*x*y*z
f = x**2 + 2*x*y + 3*x + 4*z**2 + 5*z + 6
assert R.ring_new([[[1]], [[2], [3]], [[4, 5, 6]]]) == f
assert R.ring_new({(2, 0, 0): 1, (1, 1, 0): 2, (1, 0, 0): 3, (0, 0, 2): 4, (0, 0, 1): 5, (0, 0, 0): 6}) == f
assert R.ring_new([((2, 0, 0), 1), ((1, 1, 0), 2), ((1, 0, 0), 3), ((0, 0, 2), 4), ((0, 0, 1), 5), ((0, 0, 0), 6)]) == f
R, = ring("", QQ)
assert R.ring_new([((), 7)]) == R(7)
def test_PolyRing_drop():
R, x,y,z = ring("x,y,z", ZZ)
assert R.drop(x) == PolyRing("y,z", ZZ, lex)
assert R.drop(y) == PolyRing("x,z", ZZ, lex)
assert R.drop(z) == PolyRing("x,y", ZZ, lex)
assert R.drop(0) == PolyRing("y,z", ZZ, lex)
assert R.drop(0).drop(0) == PolyRing("z", ZZ, lex)
assert R.drop(0).drop(0).drop(0) == ZZ
assert R.drop(1) == PolyRing("x,z", ZZ, lex)
assert R.drop(2) == PolyRing("x,y", ZZ, lex)
assert R.drop(2).drop(1) == PolyRing("x", ZZ, lex)
assert R.drop(2).drop(1).drop(0) == ZZ
raises(ValueError, lambda: R.drop(3))
raises(ValueError, lambda: R.drop(x).drop(y))
def test_PolyRing___getitem__():
R, x,y,z = ring("x,y,z", ZZ)
assert R[0:] == PolyRing("x,y,z", ZZ, lex)
assert R[1:] == PolyRing("y,z", ZZ, lex)
assert R[2:] == PolyRing("z", ZZ, lex)
assert R[3:] == ZZ
def test_PolyRing_is_():
R = PolyRing("x", QQ, lex)
assert R.is_univariate is True
assert R.is_multivariate is False
R = PolyRing("x,y,z", QQ, lex)
assert R.is_univariate is False
assert R.is_multivariate is True
R = PolyRing("", QQ, lex)
assert R.is_univariate is False
assert R.is_multivariate is False
def test_PolyRing_add():
R, x = ring("x", ZZ)
F = [ x**2 + 2*i + 3 for i in range(4) ]
assert R.add(F) == reduce(add, F) == 4*x**2 + 24
R, = ring("", ZZ)
assert R.add([2, 5, 7]) == 14
def test_PolyRing_mul():
R, x = ring("x", ZZ)
F = [ x**2 + 2*i + 3 for i in range(4) ]
assert R.mul(F) == reduce(mul, F) == x**8 + 24*x**6 + 206*x**4 + 744*x**2 + 945
R, = ring("", ZZ)
assert R.mul([2, 3, 5]) == 30
def test_sring():
x, y, z, t = symbols("x,y,z,t")
R = PolyRing("x,y,z", ZZ, lex)
assert sring(x + 2*y + 3*z) == (R, R.x + 2*R.y + 3*R.z)
R = PolyRing("x,y,z", QQ, lex)
assert sring(x + 2*y + z/3) == (R, R.x + 2*R.y + R.z/3)
assert sring([x, 2*y, z/3]) == (R, [R.x, 2*R.y, R.z/3])
Rt = PolyRing("t", ZZ, lex)
R = PolyRing("x,y,z", Rt, lex)
assert sring(x + 2*t*y + 3*t**2*z, x, y, z) == (R, R.x + 2*Rt.t*R.y + 3*Rt.t**2*R.z)
Rt = PolyRing("t", QQ, lex)
R = PolyRing("x,y,z", Rt, lex)
assert sring(x + t*y/2 + t**2*z/3, x, y, z) == (R, R.x + Rt.t*R.y/2 + Rt.t**2*R.z/3)
Rt = FracField("t", ZZ, lex)
R = PolyRing("x,y,z", Rt, lex)
assert sring(x + 2*y/t + t**2*z/3, x, y, z) == (R, R.x + 2*R.y/Rt.t + Rt.t**2*R.z/3)
r = sqrt(2) - sqrt(3)
R, a = sring(r, extension=True)
assert R.domain == QQ.algebraic_field(r)
assert R.gens == ()
assert a == R.domain.from_sympy(r)
def test_PolyElement___hash__():
R, x, y, z = ring("x,y,z", QQ)
assert hash(x*y*z)
def test_PolyElement___eq__():
R, x, y = ring("x,y", ZZ, lex)
assert ((x*y + 5*x*y) == 6) == False
assert ((x*y + 5*x*y) == 6*x*y) == True
assert (6 == (x*y + 5*x*y)) == False
assert (6*x*y == (x*y + 5*x*y)) == True
assert ((x*y - x*y) == 0) == True
assert (0 == (x*y - x*y)) == True
assert ((x*y - x*y) == 1) == False
assert (1 == (x*y - x*y)) == False
assert ((x*y - x*y) == 1) == False
assert (1 == (x*y - x*y)) == False
assert ((x*y + 5*x*y) != 6) == True
assert ((x*y + 5*x*y) != 6*x*y) == False
assert (6 != (x*y + 5*x*y)) == True
assert (6*x*y != (x*y + 5*x*y)) == False
assert ((x*y - x*y) != 0) == False
assert (0 != (x*y - x*y)) == False
assert ((x*y - x*y) != 1) == True
assert (1 != (x*y - x*y)) == True
Rt, t = ring("t", ZZ)
R, x, y = ring("x,y", Rt)
assert (t**3*x/x == t**3) == True
assert (t**3*x/x == t**4) == False
def test_PolyElement__lt_le_gt_ge__():
R, x, y = ring("x,y", ZZ)
assert R(1) < x < x**2 < x**3
assert R(1) <= x <= x**2 <= x**3
assert x**3 > x**2 > x > R(1)
assert x**3 >= x**2 >= x >= R(1)
def test_PolyElement_copy():
R, x, y, z = ring("x,y,z", ZZ)
f = x*y + 3*z
g = f.copy()
assert f == g
g[(1, 1, 1)] = 7
assert f != g
def test_PolyElement_as_expr():
R, x, y, z = ring("x,y,z", ZZ)
f = 3*x**2*y - x*y*z + 7*z**3 + 1
X, Y, Z = R.symbols
g = 3*X**2*Y - X*Y*Z + 7*Z**3 + 1
assert f != g
assert f.as_expr() == g
X, Y, Z = symbols("x,y,z")
g = 3*X**2*Y - X*Y*Z + 7*Z**3 + 1
assert f != g
assert f.as_expr(X, Y, Z) == g
raises(ValueError, lambda: f.as_expr(X))
R, = ring("", ZZ)
R(3).as_expr() == 3
def test_PolyElement_from_expr():
x, y, z = symbols("x,y,z")
R, X, Y, Z = ring((x, y, z), ZZ)
f = R.from_expr(1)
assert f == 1 and isinstance(f, R.dtype)
f = R.from_expr(x)
assert f == X and isinstance(f, R.dtype)
f = R.from_expr(x*y*z)
assert f == X*Y*Z and isinstance(f, R.dtype)
f = R.from_expr(x*y*z + x*y + x)
assert f == X*Y*Z + X*Y + X and isinstance(f, R.dtype)
f = R.from_expr(x**3*y*z + x**2*y**7 + 1)
assert f == X**3*Y*Z + X**2*Y**7 + 1 and isinstance(f, R.dtype)
raises(ValueError, lambda: R.from_expr(1/x))
raises(ValueError, lambda: R.from_expr(2**x))
raises(ValueError, lambda: R.from_expr(7*x + sqrt(2)))
R, = ring("", ZZ)
f = R.from_expr(1)
assert f == 1 and isinstance(f, R.dtype)
def test_PolyElement_degree():
R, x,y,z = ring("x,y,z", ZZ)
assert R(0).degree() == -oo
assert R(1).degree() == 0
assert (x + 1).degree() == 1
assert (2*y**3 + z).degree() == 0
assert (x*y**3 + z).degree() == 1
assert (x**5*y**3 + z).degree() == 5
assert R(0).degree(x) == -oo
assert R(1).degree(x) == 0
assert (x + 1).degree(x) == 1
assert (2*y**3 + z).degree(x) == 0
assert (x*y**3 + z).degree(x) == 1
assert (7*x**5*y**3 + z).degree(x) == 5
assert R(0).degree(y) == -oo
assert R(1).degree(y) == 0
assert (x + 1).degree(y) == 0
assert (2*y**3 + z).degree(y) == 3
assert (x*y**3 + z).degree(y) == 3
assert (7*x**5*y**3 + z).degree(y) == 3
assert R(0).degree(z) == -oo
assert R(1).degree(z) == 0
assert (x + 1).degree(z) == 0
assert (2*y**3 + z).degree(z) == 1
assert (x*y**3 + z).degree(z) == 1
assert (7*x**5*y**3 + z).degree(z) == 1
R, = ring("", ZZ)
assert R(0).degree() == -oo
assert R(1).degree() == 0
def test_PolyElement_tail_degree():
R, x,y,z = ring("x,y,z", ZZ)
assert R(0).tail_degree() == -oo
assert R(1).tail_degree() == 0
assert (x + 1).tail_degree() == 0
assert (2*y**3 + x**3*z).tail_degree() == 0
assert (x*y**3 + x**3*z).tail_degree() == 1
assert (x**5*y**3 + x**3*z).tail_degree() == 3
assert R(0).tail_degree(x) == -oo
assert R(1).tail_degree(x) == 0
assert (x + 1).tail_degree(x) == 0
assert (2*y**3 + x**3*z).tail_degree(x) == 0
assert (x*y**3 + x**3*z).tail_degree(x) == 1
assert (7*x**5*y**3 + x**3*z).tail_degree(x) == 3
assert R(0).tail_degree(y) == -oo
assert R(1).tail_degree(y) == 0
assert (x + 1).tail_degree(y) == 0
assert (2*y**3 + x**3*z).tail_degree(y) == 0
assert (x*y**3 + x**3*z).tail_degree(y) == 0
assert (7*x**5*y**3 + x**3*z).tail_degree(y) == 0
assert R(0).tail_degree(z) == -oo
assert R(1).tail_degree(z) == 0
assert (x + 1).tail_degree(z) == 0
assert (2*y**3 + x**3*z).tail_degree(z) == 0
assert (x*y**3 + x**3*z).tail_degree(z) == 0
assert (7*x**5*y**3 + x**3*z).tail_degree(z) == 0
R, = ring("", ZZ)
assert R(0).tail_degree() == -oo
assert R(1).tail_degree() == 0
def test_PolyElement_degrees():
R, x,y,z = ring("x,y,z", ZZ)
assert R(0).degrees() == (-oo, -oo, -oo)
assert R(1).degrees() == (0, 0, 0)
assert (x**2*y + x**3*z**2).degrees() == (3, 1, 2)
def test_PolyElement_tail_degrees():
R, x,y,z = ring("x,y,z", ZZ)
assert R(0).tail_degrees() == (-oo, -oo, -oo)
assert R(1).tail_degrees() == (0, 0, 0)
assert (x**2*y + x**3*z**2).tail_degrees() == (2, 0, 0)
def test_PolyElement_coeff():
R, x, y, z = ring("x,y,z", ZZ, lex)
f = 3*x**2*y - x*y*z + 7*z**3 + 23
assert f.coeff(1) == 23
raises(ValueError, lambda: f.coeff(3))
assert f.coeff(x) == 0
assert f.coeff(y) == 0
assert f.coeff(z) == 0
assert f.coeff(x**2*y) == 3
assert f.coeff(x*y*z) == -1
assert f.coeff(z**3) == 7
raises(ValueError, lambda: f.coeff(3*x**2*y))
raises(ValueError, lambda: f.coeff(-x*y*z))
raises(ValueError, lambda: f.coeff(7*z**3))
R, = ring("", ZZ)
R(3).coeff(1) == 3
def test_PolyElement_LC():
R, x, y = ring("x,y", QQ, lex)
assert R(0).LC == QQ(0)
assert (QQ(1,2)*x).LC == QQ(1, 2)
assert (QQ(1,4)*x*y + QQ(1,2)*x).LC == QQ(1, 4)
def test_PolyElement_LM():
R, x, y = ring("x,y", QQ, lex)
assert R(0).LM == (0, 0)
assert (QQ(1,2)*x).LM == (1, 0)
assert (QQ(1,4)*x*y + QQ(1,2)*x).LM == (1, 1)
def test_PolyElement_LT():
R, x, y = ring("x,y", QQ, lex)
assert R(0).LT == ((0, 0), QQ(0))
assert (QQ(1,2)*x).LT == ((1, 0), QQ(1, 2))
assert (QQ(1,4)*x*y + QQ(1,2)*x).LT == ((1, 1), QQ(1, 4))
R, = ring("", ZZ)
assert R(0).LT == ((), 0)
assert R(1).LT == ((), 1)
def test_PolyElement_leading_monom():
R, x, y = ring("x,y", QQ, lex)
assert R(0).leading_monom() == 0
assert (QQ(1,2)*x).leading_monom() == x
assert (QQ(1,4)*x*y + QQ(1,2)*x).leading_monom() == x*y
def test_PolyElement_leading_term():
R, x, y = ring("x,y", QQ, lex)
assert R(0).leading_term() == 0
assert (QQ(1,2)*x).leading_term() == QQ(1,2)*x
assert (QQ(1,4)*x*y + QQ(1,2)*x).leading_term() == QQ(1,4)*x*y
def test_PolyElement_terms():
R, x,y,z = ring("x,y,z", QQ)
terms = (x**2/3 + y**3/4 + z**4/5).terms()
assert terms == [((2,0,0), QQ(1,3)), ((0,3,0), QQ(1,4)), ((0,0,4), QQ(1,5))]
R, x,y = ring("x,y", ZZ, lex)
f = x*y**7 + 2*x**2*y**3
assert f.terms() == f.terms(lex) == f.terms('lex') == [((2, 3), 2), ((1, 7), 1)]
assert f.terms(grlex) == f.terms('grlex') == [((1, 7), 1), ((2, 3), 2)]
R, x,y = ring("x,y", ZZ, grlex)
f = x*y**7 + 2*x**2*y**3
assert f.terms() == f.terms(grlex) == f.terms('grlex') == [((1, 7), 1), ((2, 3), 2)]
assert f.terms(lex) == f.terms('lex') == [((2, 3), 2), ((1, 7), 1)]
R, = ring("", ZZ)
assert R(3).terms() == [((), 3)]
def test_PolyElement_monoms():
R, x,y,z = ring("x,y,z", QQ)
monoms = (x**2/3 + y**3/4 + z**4/5).monoms()
assert monoms == [(2,0,0), (0,3,0), (0,0,4)]
R, x,y = ring("x,y", ZZ, lex)
f = x*y**7 + 2*x**2*y**3
assert f.monoms() == f.monoms(lex) == f.monoms('lex') == [(2, 3), (1, 7)]
assert f.monoms(grlex) == f.monoms('grlex') == [(1, 7), (2, 3)]
R, x,y = ring("x,y", ZZ, grlex)
f = x*y**7 + 2*x**2*y**3
assert f.monoms() == f.monoms(grlex) == f.monoms('grlex') == [(1, 7), (2, 3)]
assert f.monoms(lex) == f.monoms('lex') == [(2, 3), (1, 7)]
def test_PolyElement_coeffs():
R, x,y,z = ring("x,y,z", QQ)
coeffs = (x**2/3 + y**3/4 + z**4/5).coeffs()
assert coeffs == [QQ(1,3), QQ(1,4), QQ(1,5)]
R, x,y = ring("x,y", ZZ, lex)
f = x*y**7 + 2*x**2*y**3
assert f.coeffs() == f.coeffs(lex) == f.coeffs('lex') == [2, 1]
assert f.coeffs(grlex) == f.coeffs('grlex') == [1, 2]
R, x,y = ring("x,y", ZZ, grlex)
f = x*y**7 + 2*x**2*y**3
assert f.coeffs() == f.coeffs(grlex) == f.coeffs('grlex') == [1, 2]
assert f.coeffs(lex) == f.coeffs('lex') == [2, 1]
def test_PolyElement___add__():
Rt, t = ring("t", ZZ)
Ruv, u,v = ring("u,v", ZZ)
Rxyz, x,y,z = ring("x,y,z", Ruv)
assert dict(x + 3*y) == {(1, 0, 0): 1, (0, 1, 0): 3}
assert dict(u + x) == dict(x + u) == {(1, 0, 0): 1, (0, 0, 0): u}
assert dict(u + x*y) == dict(x*y + u) == {(1, 1, 0): 1, (0, 0, 0): u}
assert dict(u + x*y + z) == dict(x*y + z + u) == {(1, 1, 0): 1, (0, 0, 1): 1, (0, 0, 0): u}
assert dict(u*x + x) == dict(x + u*x) == {(1, 0, 0): u + 1}
assert dict(u*x + x*y) == dict(x*y + u*x) == {(1, 1, 0): 1, (1, 0, 0): u}
assert dict(u*x + x*y + z) == dict(x*y + z + u*x) == {(1, 1, 0): 1, (0, 0, 1): 1, (1, 0, 0): u}
raises(TypeError, lambda: t + x)
raises(TypeError, lambda: x + t)
raises(TypeError, lambda: t + u)
raises(TypeError, lambda: u + t)
Fuv, u,v = field("u,v", ZZ)
Rxyz, x,y,z = ring("x,y,z", Fuv)
assert dict(u + x) == dict(x + u) == {(1, 0, 0): 1, (0, 0, 0): u}
Rxyz, x,y,z = ring("x,y,z", EX)
assert dict(EX(pi) + x*y*z) == dict(x*y*z + EX(pi)) == {(1, 1, 1): EX(1), (0, 0, 0): EX(pi)}
def test_PolyElement___sub__():
Rt, t = ring("t", ZZ)
Ruv, u,v = ring("u,v", ZZ)
Rxyz, x,y,z = ring("x,y,z", Ruv)
assert dict(x - 3*y) == {(1, 0, 0): 1, (0, 1, 0): -3}
assert dict(-u + x) == dict(x - u) == {(1, 0, 0): 1, (0, 0, 0): -u}
assert dict(-u + x*y) == dict(x*y - u) == {(1, 1, 0): 1, (0, 0, 0): -u}
assert dict(-u + x*y + z) == dict(x*y + z - u) == {(1, 1, 0): 1, (0, 0, 1): 1, (0, 0, 0): -u}
assert dict(-u*x + x) == dict(x - u*x) == {(1, 0, 0): -u + 1}
assert dict(-u*x + x*y) == dict(x*y - u*x) == {(1, 1, 0): 1, (1, 0, 0): -u}
assert dict(-u*x + x*y + z) == dict(x*y + z - u*x) == {(1, 1, 0): 1, (0, 0, 1): 1, (1, 0, 0): -u}
raises(TypeError, lambda: t - x)
raises(TypeError, lambda: x - t)
raises(TypeError, lambda: t - u)
raises(TypeError, lambda: u - t)
Fuv, u,v = field("u,v", ZZ)
Rxyz, x,y,z = ring("x,y,z", Fuv)
assert dict(-u + x) == dict(x - u) == {(1, 0, 0): 1, (0, 0, 0): -u}
Rxyz, x,y,z = ring("x,y,z", EX)
assert dict(-EX(pi) + x*y*z) == dict(x*y*z - EX(pi)) == {(1, 1, 1): EX(1), (0, 0, 0): -EX(pi)}
def test_PolyElement___mul__():
Rt, t = ring("t", ZZ)
Ruv, u,v = ring("u,v", ZZ)
Rxyz, x,y,z = ring("x,y,z", Ruv)
assert dict(u*x) == dict(x*u) == {(1, 0, 0): u}
assert dict(2*u*x + z) == dict(x*2*u + z) == {(1, 0, 0): 2*u, (0, 0, 1): 1}
assert dict(u*2*x + z) == dict(2*x*u + z) == {(1, 0, 0): 2*u, (0, 0, 1): 1}
assert dict(2*u*x + z) == dict(x*2*u + z) == {(1, 0, 0): 2*u, (0, 0, 1): 1}
assert dict(u*x*2 + z) == dict(x*u*2 + z) == {(1, 0, 0): 2*u, (0, 0, 1): 1}
assert dict(2*u*x*y + z) == dict(x*y*2*u + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1}
assert dict(u*2*x*y + z) == dict(2*x*y*u + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1}
assert dict(2*u*x*y + z) == dict(x*y*2*u + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1}
assert dict(u*x*y*2 + z) == dict(x*y*u*2 + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1}
assert dict(2*u*y*x + z) == dict(y*x*2*u + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1}
assert dict(u*2*y*x + z) == dict(2*y*x*u + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1}
assert dict(2*u*y*x + z) == dict(y*x*2*u + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1}
assert dict(u*y*x*2 + z) == dict(y*x*u*2 + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1}
assert dict(3*u*(x + y) + z) == dict((x + y)*3*u + z) == {(1, 0, 0): 3*u, (0, 1, 0): 3*u, (0, 0, 1): 1}
raises(TypeError, lambda: t*x + z)
raises(TypeError, lambda: x*t + z)
raises(TypeError, lambda: t*u + z)
raises(TypeError, lambda: u*t + z)
Fuv, u,v = field("u,v", ZZ)
Rxyz, x,y,z = ring("x,y,z", Fuv)
assert dict(u*x) == dict(x*u) == {(1, 0, 0): u}
Rxyz, x,y,z = ring("x,y,z", EX)
assert dict(EX(pi)*x*y*z) == dict(x*y*z*EX(pi)) == {(1, 1, 1): EX(pi)}
def test_PolyElement___div__():
R, x,y,z = ring("x,y,z", ZZ)
assert (2*x**2 - 4)/2 == x**2 - 2
assert (2*x**2 - 3)/2 == x**2
assert (x**2 - 1).quo(x) == x
assert (x**2 - x).quo(x) == x - 1
assert (x**2 - 1)/x == x - x**(-1)
assert (x**2 - x)/x == x - 1
assert (x**2 - 1)/(2*x) == x/2 - x**(-1)/2
assert (x**2 - 1).quo(2*x) == 0
assert (x**2 - x)/(x - 1) == (x**2 - x).quo(x - 1) == x
R, x,y,z = ring("x,y,z", ZZ)
assert len((x**2/3 + y**3/4 + z**4/5).terms()) == 0
R, x,y,z = ring("x,y,z", QQ)
assert len((x**2/3 + y**3/4 + z**4/5).terms()) == 3
Rt, t = ring("t", ZZ)
Ruv, u,v = ring("u,v", ZZ)
Rxyz, x,y,z = ring("x,y,z", Ruv)
assert dict((u**2*x + u)/u) == {(1, 0, 0): u, (0, 0, 0): 1}
raises(TypeError, lambda: u/(u**2*x + u))
raises(TypeError, lambda: t/x)
raises(TypeError, lambda: x/t)
raises(TypeError, lambda: t/u)
raises(TypeError, lambda: u/t)
R, x = ring("x", ZZ)
f, g = x**2 + 2*x + 3, R(0)
raises(ZeroDivisionError, lambda: f.div(g))
raises(ZeroDivisionError, lambda: divmod(f, g))
raises(ZeroDivisionError, lambda: f.rem(g))
raises(ZeroDivisionError, lambda: f % g)
raises(ZeroDivisionError, lambda: f.quo(g))
raises(ZeroDivisionError, lambda: f / g)
raises(ZeroDivisionError, lambda: f.exquo(g))
R, x, y = ring("x,y", ZZ)
f, g = x*y + 2*x + 3, R(0)
raises(ZeroDivisionError, lambda: f.div(g))
raises(ZeroDivisionError, lambda: divmod(f, g))
raises(ZeroDivisionError, lambda: f.rem(g))
raises(ZeroDivisionError, lambda: f % g)
raises(ZeroDivisionError, lambda: f.quo(g))
raises(ZeroDivisionError, lambda: f / g)
raises(ZeroDivisionError, lambda: f.exquo(g))
R, x = ring("x", ZZ)
f, g = x**2 + 1, 2*x - 4
q, r = R(0), x**2 + 1
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
raises(ExactQuotientFailed, lambda: f.exquo(g))
f, g = 3*x**3 + x**2 + x + 5, 5*x**2 - 3*x + 1
q, r = R(0), f
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
raises(ExactQuotientFailed, lambda: f.exquo(g))
f, g = 5*x**4 + 4*x**3 + 3*x**2 + 2*x + 1, x**2 + 2*x + 3
q, r = 5*x**2 - 6*x, 20*x + 1
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
raises(ExactQuotientFailed, lambda: f.exquo(g))
f, g = 5*x**5 + 4*x**4 + 3*x**3 + 2*x**2 + x, x**4 + 2*x**3 + 9
q, r = 5*x - 6, 15*x**3 + 2*x**2 - 44*x + 54
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
raises(ExactQuotientFailed, lambda: f.exquo(g))
R, x = ring("x", QQ)
f, g = x**2 + 1, 2*x - 4
q, r = x/2 + 1, R(5)
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
raises(ExactQuotientFailed, lambda: f.exquo(g))
f, g = 3*x**3 + x**2 + x + 5, 5*x**2 - 3*x + 1
q, r = QQ(3, 5)*x + QQ(14, 25), QQ(52, 25)*x + QQ(111, 25)
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
raises(ExactQuotientFailed, lambda: f.exquo(g))
R, x,y = ring("x,y", ZZ)
f, g = x**2 - y**2, x - y
q, r = x + y, R(0)
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
assert f.exquo(g) == q
f, g = x**2 + y**2, x - y
q, r = x + y, 2*y**2
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
raises(ExactQuotientFailed, lambda: f.exquo(g))
f, g = x**2 + y**2, -x + y
q, r = -x - y, 2*y**2
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
raises(ExactQuotientFailed, lambda: f.exquo(g))
f, g = x**2 + y**2, 2*x - 2*y
q, r = R(0), f
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
raises(ExactQuotientFailed, lambda: f.exquo(g))
R, x,y = ring("x,y", QQ)
f, g = x**2 - y**2, x - y
q, r = x + y, R(0)
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
assert f.exquo(g) == q
f, g = x**2 + y**2, x - y
q, r = x + y, 2*y**2
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
raises(ExactQuotientFailed, lambda: f.exquo(g))
f, g = x**2 + y**2, -x + y
q, r = -x - y, 2*y**2
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
raises(ExactQuotientFailed, lambda: f.exquo(g))
f, g = x**2 + y**2, 2*x - 2*y
q, r = x/2 + y/2, 2*y**2
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
raises(ExactQuotientFailed, lambda: f.exquo(g))
def test_PolyElement___pow__():
R, x = ring("x", ZZ, grlex)
f = 2*x + 3
assert f**0 == 1
assert f**1 == f
raises(ValueError, lambda: f**(-1))
assert x**(-1) == x**(-1)
assert f**2 == f._pow_generic(2) == f._pow_multinomial(2) == 4*x**2 + 12*x + 9
assert f**3 == f._pow_generic(3) == f._pow_multinomial(3) == 8*x**3 + 36*x**2 + 54*x + 27
assert f**4 == f._pow_generic(4) == f._pow_multinomial(4) == 16*x**4 + 96*x**3 + 216*x**2 + 216*x + 81
assert f**5 == f._pow_generic(5) == f._pow_multinomial(5) == 32*x**5 + 240*x**4 + 720*x**3 + 1080*x**2 + 810*x + 243
R, x,y,z = ring("x,y,z", ZZ, grlex)
f = x**3*y - 2*x*y**2 - 3*z + 1
g = x**6*y**2 - 4*x**4*y**3 - 6*x**3*y*z + 2*x**3*y + 4*x**2*y**4 + 12*x*y**2*z - 4*x*y**2 + 9*z**2 - 6*z + 1
assert f**2 == f._pow_generic(2) == f._pow_multinomial(2) == g
R, t = ring("t", ZZ)
f = -11200*t**4 - 2604*t**2 + 49
g = 15735193600000000*t**16 + 14633730048000000*t**14 + 4828147466240000*t**12 \
+ 598976863027200*t**10 + 3130812416256*t**8 - 2620523775744*t**6 \
+ 92413760096*t**4 - 1225431984*t**2 + 5764801
assert f**4 == f._pow_generic(4) == f._pow_multinomial(4) == g
def test_PolyElement_div():
R, x = ring("x", ZZ, grlex)
f = x**3 - 12*x**2 - 42
g = x - 3
q = x**2 - 9*x - 27
r = -123
assert f.div([g]) == ([q], r)
R, x = ring("x", ZZ, grlex)
f = x**2 + 2*x + 2
assert f.div([R(1)]) == ([f], 0)
R, x = ring("x", QQ, grlex)
f = x**2 + 2*x + 2
assert f.div([R(2)]) == ([QQ(1,2)*x**2 + x + 1], 0)
R, x,y = ring("x,y", ZZ, grlex)
f = 4*x**2*y - 2*x*y + 4*x - 2*y + 8
assert f.div([R(2)]) == ([2*x**2*y - x*y + 2*x - y + 4], 0)
assert f.div([2*y]) == ([2*x**2 - x - 1], 4*x + 8)
f = x - 1
g = y - 1
assert f.div([g]) == ([0], f)
f = x*y**2 + 1
G = [x*y + 1, y + 1]
Q = [y, -1]
r = 2
assert f.div(G) == (Q, r)
f = x**2*y + x*y**2 + y**2
G = [x*y - 1, y**2 - 1]
Q = [x + y, 1]
r = x + y + 1
assert f.div(G) == (Q, r)
G = [y**2 - 1, x*y - 1]
Q = [x + 1, x]
r = 2*x + 1
assert f.div(G) == (Q, r)
R, = ring("", ZZ)
assert R(3).div(R(2)) == (0, 3)
R, = ring("", QQ)
assert R(3).div(R(2)) == (QQ(3, 2), 0)
def test_PolyElement_rem():
R, x = ring("x", ZZ, grlex)
f = x**3 - 12*x**2 - 42
g = x - 3
r = -123
assert f.rem([g]) == f.div([g])[1] == r
R, x,y = ring("x,y", ZZ, grlex)
f = 4*x**2*y - 2*x*y + 4*x - 2*y + 8
assert f.rem([R(2)]) == f.div([R(2)])[1] == 0
assert f.rem([2*y]) == f.div([2*y])[1] == 4*x + 8
f = x - 1
g = y - 1
assert f.rem([g]) == f.div([g])[1] == f
f = x*y**2 + 1
G = [x*y + 1, y + 1]
r = 2
assert f.rem(G) == f.div(G)[1] == r
f = x**2*y + x*y**2 + y**2
G = [x*y - 1, y**2 - 1]
r = x + y + 1
assert f.rem(G) == f.div(G)[1] == r
G = [y**2 - 1, x*y - 1]
r = 2*x + 1
assert f.rem(G) == f.div(G)[1] == r
def test_PolyElement_deflate():
R, x = ring("x", ZZ)
assert (2*x**2).deflate(x**4 + 4*x**2 + 1) == ((2,), [2*x, x**2 + 4*x + 1])
R, x,y = ring("x,y", ZZ)
assert R(0).deflate(R(0)) == ((1, 1), [0, 0])
assert R(1).deflate(R(0)) == ((1, 1), [1, 0])
assert R(1).deflate(R(2)) == ((1, 1), [1, 2])
assert R(1).deflate(2*y) == ((1, 1), [1, 2*y])
assert (2*y).deflate(2*y) == ((1, 1), [2*y, 2*y])
assert R(2).deflate(2*y**2) == ((1, 2), [2, 2*y])
assert (2*y**2).deflate(2*y**2) == ((1, 2), [2*y, 2*y])
f = x**4*y**2 + x**2*y + 1
g = x**2*y**3 + x**2*y + 1
assert f.deflate(g) == ((2, 1), [x**2*y**2 + x*y + 1, x*y**3 + x*y + 1])
def test_PolyElement_clear_denoms():
R, x,y = ring("x,y", QQ)
assert R(1).clear_denoms() == (ZZ(1), 1)
assert R(7).clear_denoms() == (ZZ(1), 7)
assert R(QQ(7,3)).clear_denoms() == (3, 7)
assert R(QQ(7,3)).clear_denoms() == (3, 7)
assert (3*x**2 + x).clear_denoms() == (1, 3*x**2 + x)
assert (x**2 + QQ(1,2)*x).clear_denoms() == (2, 2*x**2 + x)
rQQ, x,t = ring("x,t", QQ, lex)
rZZ, X,T = ring("x,t", ZZ, lex)
F = [x - QQ(17824537287975195925064602467992950991718052713078834557692023531499318507213727406844943097,413954288007559433755329699713866804710749652268151059918115348815925474842910720000)*t**7
- QQ(4882321164854282623427463828745855894130208215961904469205260756604820743234704900167747753,12936071500236232304854053116058337647210926633379720622441104650497671088840960000)*t**6
- QQ(36398103304520066098365558157422127347455927422509913596393052633155821154626830576085097433,25872143000472464609708106232116675294421853266759441244882209300995342177681920000)*t**5
- QQ(168108082231614049052707339295479262031324376786405372698857619250210703675982492356828810819,58212321751063045371843239022262519412449169850208742800984970927239519899784320000)*t**4
- QQ(5694176899498574510667890423110567593477487855183144378347226247962949388653159751849449037,1617008937529529038106756639507292205901365829172465077805138081312208886105120000)*t**3
- QQ(154482622347268833757819824809033388503591365487934245386958884099214649755244381307907779,60637835157357338929003373981523457721301218593967440417692678049207833228942000)*t**2
- QQ(2452813096069528207645703151222478123259511586701148682951852876484544822947007791153163,2425513406294293557160134959260938308852048743758697616707707121968313329157680)*t
- QQ(34305265428126440542854669008203683099323146152358231964773310260498715579162112959703,202126117191191129763344579938411525737670728646558134725642260164026110763140),
t**8 + QQ(693749860237914515552,67859264524169150569)*t**7
+ QQ(27761407182086143225024,610733380717522355121)*t**6
+ QQ(7785127652157884044288,67859264524169150569)*t**5
+ QQ(36567075214771261409792,203577793572507451707)*t**4
+ QQ(36336335165196147384320,203577793572507451707)*t**3
+ QQ(7452455676042754048000,67859264524169150569)*t**2
+ QQ(2593331082514399232000,67859264524169150569)*t
+ QQ(390399197427343360000,67859264524169150569)]
G = [3725588592068034903797967297424801242396746870413359539263038139343329273586196480000*X -
160420835591776763325581422211936558925462474417709511019228211783493866564923546661604487873*T**7 -
1406108495478033395547109582678806497509499966197028487131115097902188374051595011248311352864*T**6 -
5241326875850889518164640374668786338033653548841427557880599579174438246266263602956254030352*T**5 -
10758917262823299139373269714910672770004760114329943852726887632013485035262879510837043892416*T**4 -
13119383576444715672578819534846747735372132018341964647712009275306635391456880068261130581248*T**3 -
9491412317016197146080450036267011389660653495578680036574753839055748080962214787557853941760*T**2 -
3767520915562795326943800040277726397326609797172964377014046018280260848046603967211258368000*T -
632314652371226552085897259159210286886724229880266931574701654721512325555116066073245696000,
610733380717522355121*T**8 +
6243748742141230639968*T**7 +
27761407182086143225024*T**6 +
70066148869420956398592*T**5 +
109701225644313784229376*T**4 +
109009005495588442152960*T**3 +
67072101084384786432000*T**2 +
23339979742629593088000*T +
3513592776846090240000]
assert [ f.clear_denoms()[1].set_ring(rZZ) for f in F ] == G
def test_PolyElement_cofactors():
R, x, y = ring("x,y", ZZ)
f, g = R(0), R(0)
assert f.cofactors(g) == (0, 0, 0)
f, g = R(2), R(0)
assert f.cofactors(g) == (2, 1, 0)
f, g = R(-2), R(0)
assert f.cofactors(g) == (2, -1, 0)
f, g = R(0), R(-2)
assert f.cofactors(g) == (2, 0, -1)
f, g = R(0), 2*x + 4
assert f.cofactors(g) == (2*x + 4, 0, 1)
f, g = 2*x + 4, R(0)
assert f.cofactors(g) == (2*x + 4, 1, 0)
f, g = R(2), R(2)
assert f.cofactors(g) == (2, 1, 1)
f, g = R(-2), R(2)
assert f.cofactors(g) == (2, -1, 1)
f, g = R(2), R(-2)
assert f.cofactors(g) == (2, 1, -1)
f, g = R(-2), R(-2)
assert f.cofactors(g) == (2, -1, -1)
f, g = x**2 + 2*x + 1, R(1)
assert f.cofactors(g) == (1, x**2 + 2*x + 1, 1)
f, g = x**2 + 2*x + 1, R(2)
assert f.cofactors(g) == (1, x**2 + 2*x + 1, 2)
f, g = 2*x**2 + 4*x + 2, R(2)
assert f.cofactors(g) == (2, x**2 + 2*x + 1, 1)
f, g = R(2), 2*x**2 + 4*x + 2
assert f.cofactors(g) == (2, 1, x**2 + 2*x + 1)
f, g = 2*x**2 + 4*x + 2, x + 1
assert f.cofactors(g) == (x + 1, 2*x + 2, 1)
f, g = x + 1, 2*x**2 + 4*x + 2
assert f.cofactors(g) == (x + 1, 1, 2*x + 2)
R, x, y, z, t = ring("x,y,z,t", ZZ)
f, g = t**2 + 2*t + 1, 2*t + 2
assert f.cofactors(g) == (t + 1, t + 1, 2)
f, g = z**2*t**2 + 2*z**2*t + z**2 + z*t + z, t**2 + 2*t + 1
h, cff, cfg = t + 1, z**2*t + z**2 + z, t + 1
assert f.cofactors(g) == (h, cff, cfg)
assert g.cofactors(f) == (h, cfg, cff)
R, x, y = ring("x,y", QQ)
f = QQ(1,2)*x**2 + x + QQ(1,2)
g = QQ(1,2)*x + QQ(1,2)
h = x + 1
assert f.cofactors(g) == (h, g, QQ(1,2))
assert g.cofactors(f) == (h, QQ(1,2), g)
R, x, y = ring("x,y", RR)
f = 2.1*x*y**2 - 2.1*x*y + 2.1*x
g = 2.1*x**3
h = 1.0*x
assert f.cofactors(g) == (h, f/h, g/h)
assert g.cofactors(f) == (h, g/h, f/h)
def test_PolyElement_gcd():
R, x, y = ring("x,y", QQ)
f = QQ(1,2)*x**2 + x + QQ(1,2)
g = QQ(1,2)*x + QQ(1,2)
assert f.gcd(g) == x + 1
def test_PolyElement_cancel():
R, x, y = ring("x,y", ZZ)
f = 2*x**3 + 4*x**2 + 2*x
g = 3*x**2 + 3*x
F = 2*x + 2
G = 3
assert f.cancel(g) == (F, G)
assert (-f).cancel(g) == (-F, G)
assert f.cancel(-g) == (-F, G)
R, x, y = ring("x,y", QQ)
f = QQ(1,2)*x**3 + x**2 + QQ(1,2)*x
g = QQ(1,3)*x**2 + QQ(1,3)*x
F = 3*x + 3
G = 2
assert f.cancel(g) == (F, G)
assert (-f).cancel(g) == (-F, G)
assert f.cancel(-g) == (-F, G)
Fx, x = field("x", ZZ)
Rt, t = ring("t", Fx)
f = (-x**2 - 4)/4*t
g = t**2 + (x**2 + 2)/2
assert f.cancel(g) == ((-x**2 - 4)*t, 4*t**2 + 2*x**2 + 4)
def test_PolyElement_max_norm():
R, x, y = ring("x,y", ZZ)
assert R(0).max_norm() == 0
assert R(1).max_norm() == 1
assert (x**3 + 4*x**2 + 2*x + 3).max_norm() == 4
def test_PolyElement_l1_norm():
R, x, y = ring("x,y", ZZ)
assert R(0).l1_norm() == 0
assert R(1).l1_norm() == 1
assert (x**3 + 4*x**2 + 2*x + 3).l1_norm() == 10
def test_PolyElement_diff():
R, X = xring("x:11", QQ)
f = QQ(288,5)*X[0]**8*X[1]**6*X[4]**3*X[10]**2 + 8*X[0]**2*X[2]**3*X[4]**3 +2*X[0]**2 - 2*X[1]**2
assert f.diff(X[0]) == QQ(2304,5)*X[0]**7*X[1]**6*X[4]**3*X[10]**2 + 16*X[0]*X[2]**3*X[4]**3 + 4*X[0]
assert f.diff(X[4]) == QQ(864,5)*X[0]**8*X[1]**6*X[4]**2*X[10]**2 + 24*X[0]**2*X[2]**3*X[4]**2
assert f.diff(X[10]) == QQ(576,5)*X[0]**8*X[1]**6*X[4]**3*X[10]
def test_PolyElement___call__():
R, x = ring("x", ZZ)
f = 3*x + 1
assert f(0) == 1
assert f(1) == 4
raises(ValueError, lambda: f())
raises(ValueError, lambda: f(0, 1))
raises(CoercionFailed, lambda: f(QQ(1,7)))
R, x,y = ring("x,y", ZZ)
f = 3*x + y**2 + 1
assert f(0, 0) == 1
assert f(1, 7) == 53
Ry = R.drop(x)
assert f(0) == Ry.y**2 + 1
assert f(1) == Ry.y**2 + 4
raises(ValueError, lambda: f())
raises(ValueError, lambda: f(0, 1, 2))
raises(CoercionFailed, lambda: f(1, QQ(1,7)))
raises(CoercionFailed, lambda: f(QQ(1,7), 1))
raises(CoercionFailed, lambda: f(QQ(1,7), QQ(1,7)))
def test_PolyElement_evaluate():
R, x = ring("x", ZZ)
f = x**3 + 4*x**2 + 2*x + 3
r = f.evaluate(x, 0)
assert r == 3 and not isinstance(r, PolyElement)
raises(CoercionFailed, lambda: f.evaluate(x, QQ(1,7)))
R, x, y, z = ring("x,y,z", ZZ)
f = (x*y)**3 + 4*(x*y)**2 + 2*x*y + 3
r = f.evaluate(x, 0)
assert r == 3 and isinstance(r, R.drop(x).dtype)
r = f.evaluate([(x, 0), (y, 0)])
assert r == 3 and isinstance(r, R.drop(x, y).dtype)
r = f.evaluate(y, 0)
assert r == 3 and isinstance(r, R.drop(y).dtype)
r = f.evaluate([(y, 0), (x, 0)])
assert r == 3 and isinstance(r, R.drop(y, x).dtype)
r = f.evaluate([(x, 0), (y, 0), (z, 0)])
assert r == 3 and not isinstance(r, PolyElement)
raises(CoercionFailed, lambda: f.evaluate([(x, 1), (y, QQ(1,7))]))
raises(CoercionFailed, lambda: f.evaluate([(x, QQ(1,7)), (y, 1)]))
raises(CoercionFailed, lambda: f.evaluate([(x, QQ(1,7)), (y, QQ(1,7))]))
def test_PolyElement_subs():
R, x = ring("x", ZZ)
f = x**3 + 4*x**2 + 2*x + 3
r = f.subs(x, 0)
assert r == 3 and isinstance(r, R.dtype)
raises(CoercionFailed, lambda: f.subs(x, QQ(1,7)))
R, x, y, z = ring("x,y,z", ZZ)
f = x**3 + 4*x**2 + 2*x + 3
r = f.subs(x, 0)
assert r == 3 and isinstance(r, R.dtype)
r = f.subs([(x, 0), (y, 0)])
assert r == 3 and isinstance(r, R.dtype)
raises(CoercionFailed, lambda: f.subs([(x, 1), (y, QQ(1,7))]))
raises(CoercionFailed, lambda: f.subs([(x, QQ(1,7)), (y, 1)]))
raises(CoercionFailed, lambda: f.subs([(x, QQ(1,7)), (y, QQ(1,7))]))
def test_PolyElement_compose():
R, x = ring("x", ZZ)
f = x**3 + 4*x**2 + 2*x + 3
r = f.compose(x, 0)
assert r == 3 and isinstance(r, R.dtype)
assert f.compose(x, x) == f
assert f.compose(x, x**2) == x**6 + 4*x**4 + 2*x**2 + 3
raises(CoercionFailed, lambda: f.compose(x, QQ(1,7)))
R, x, y, z = ring("x,y,z", ZZ)
f = x**3 + 4*x**2 + 2*x + 3
r = f.compose(x, 0)
assert r == 3 and isinstance(r, R.dtype)
r = f.compose([(x, 0), (y, 0)])
assert r == 3 and isinstance(r, R.dtype)
r = (x**3 + 4*x**2 + 2*x*y*z + 3).compose(x, y*z**2 - 1)
q = (y*z**2 - 1)**3 + 4*(y*z**2 - 1)**2 + 2*(y*z**2 - 1)*y*z + 3
assert r == q and isinstance(r, R.dtype)
def test_PolyElement_is_():
R, x,y,z = ring("x,y,z", QQ)
assert (x - x).is_generator == False
assert (x - x).is_ground == True
assert (x - x).is_monomial == True
assert (x - x).is_term == True
assert (x - x + 1).is_generator == False
assert (x - x + 1).is_ground == True
assert (x - x + 1).is_monomial == True
assert (x - x + 1).is_term == True
assert x.is_generator == True
assert x.is_ground == False
assert x.is_monomial == True
assert x.is_term == True
assert (x*y).is_generator == False
assert (x*y).is_ground == False
assert (x*y).is_monomial == True
assert (x*y).is_term == True
assert (3*x).is_generator == False
assert (3*x).is_ground == False
assert (3*x).is_monomial == False
assert (3*x).is_term == True
assert (3*x + 1).is_generator == False
assert (3*x + 1).is_ground == False
assert (3*x + 1).is_monomial == False
assert (3*x + 1).is_term == False
assert R(0).is_zero is True
assert R(1).is_zero is False
assert R(0).is_one is False
assert R(1).is_one is True
assert (x - 1).is_monic is True
assert (2*x - 1).is_monic is False
assert (3*x + 2).is_primitive is True
assert (4*x + 2).is_primitive is False
assert (x + y + z + 1).is_linear is True
assert (x*y*z + 1).is_linear is False
assert (x*y + z + 1).is_quadratic is True
assert (x*y*z + 1).is_quadratic is False
assert (x - 1).is_squarefree is True
assert ((x - 1)**2).is_squarefree is False
assert (x**2 + x + 1).is_irreducible is True
assert (x**2 + 2*x + 1).is_irreducible is False
_, t = ring("t", FF(11))
assert (7*t + 3).is_irreducible is True
assert (7*t**2 + 3*t + 1).is_irreducible is False
_, u = ring("u", ZZ)
f = u**16 + u**14 - u**10 - u**8 - u**6 + u**2
assert f.is_cyclotomic is False
assert (f + 1).is_cyclotomic is True
raises(MultivariatePolynomialError, lambda: x.is_cyclotomic)
R, = ring("", ZZ)
assert R(4).is_squarefree is True
assert R(6).is_irreducible is True
def test_PolyElement_drop():
R, x,y,z = ring("x,y,z", ZZ)
assert R(1).drop(0).ring == PolyRing("y,z", ZZ, lex)
assert R(1).drop(0).drop(0).ring == PolyRing("z", ZZ, lex)
assert isinstance(R(1).drop(0).drop(0).drop(0), R.dtype) is False
raises(ValueError, lambda: z.drop(0).drop(0).drop(0))
raises(ValueError, lambda: x.drop(0))
def test_PolyElement_pdiv():
_, x, y = ring("x,y", ZZ)
f, g = x**2 - y**2, x - y
q, r = x + y, 0
assert f.pdiv(g) == (q, r)
assert f.prem(g) == r
assert f.pquo(g) == q
assert f.pexquo(g) == q
def test_PolyElement_gcdex():
_, x = ring("x", QQ)
f, g = 2*x, x**2 - 16
s, t, h = x/32, -QQ(1, 16), 1
assert f.half_gcdex(g) == (s, h)
assert f.gcdex(g) == (s, t, h)
def test_PolyElement_subresultants():
_, x = ring("x", ZZ)
f, g, h = x**2 - 2*x + 1, x**2 - 1, 2*x - 2
assert f.subresultants(g) == [f, g, h]
def test_PolyElement_resultant():
_, x = ring("x", ZZ)
f, g, h = x**2 - 2*x + 1, x**2 - 1, 0
assert f.resultant(g) == h
def test_PolyElement_discriminant():
_, x = ring("x", ZZ)
f, g = x**3 + 3*x**2 + 9*x - 13, -11664
assert f.discriminant() == g
F, a, b, c = ring("a,b,c", ZZ)
_, x = ring("x", F)
f, g = a*x**2 + b*x + c, b**2 - 4*a*c
assert f.discriminant() == g
def test_PolyElement_decompose():
_, x = ring("x", ZZ)
f = x**12 + 20*x**10 + 150*x**8 + 500*x**6 + 625*x**4 - 2*x**3 - 10*x + 9
g = x**4 - 2*x + 9
h = x**3 + 5*x
assert g.compose(x, h) == f
assert f.decompose() == [g, h]
def test_PolyElement_shift():
_, x = ring("x", ZZ)
assert (x**2 - 2*x + 1).shift(2) == x**2 + 2*x + 1
def test_PolyElement_sturm():
F, t = field("t", ZZ)
_, x = ring("x", F)
f = 1024/(15625*t**8)*x**5 - 4096/(625*t**8)*x**4 + 32/(15625*t**4)*x**3 - 128/(625*t**4)*x**2 + F(1)/62500*x - F(1)/625
assert f.sturm() == [
x**3 - 100*x**2 + t**4/64*x - 25*t**4/16,
3*x**2 - 200*x + t**4/64,
(-t**4/96 + F(20000)/9)*x + 25*t**4/18,
(-9*t**12 - 11520000*t**8 - 3686400000000*t**4)/(576*t**8 - 245760000*t**4 + 26214400000000),
]
def test_PolyElement_gff_list():
_, x = ring("x", ZZ)
f = x**5 + 2*x**4 - x**3 - 2*x**2
assert f.gff_list() == [(x, 1), (x + 2, 4)]
f = x*(x - 1)**3*(x - 2)**2*(x - 4)**2*(x - 5)
assert f.gff_list() == [(x**2 - 5*x + 4, 1), (x**2 - 5*x + 4, 2), (x, 3)]
def test_PolyElement_sqf_norm():
R, x = ring("x", QQ.algebraic_field(sqrt(3)))
X = R.to_ground().x
assert (x**2 - 2).sqf_norm() == (1, x**2 - 2*sqrt(3)*x + 1, X**4 - 10*X**2 + 1)
R, x = ring("x", QQ.algebraic_field(sqrt(2)))
X = R.to_ground().x
assert (x**2 - 3).sqf_norm() == (1, x**2 - 2*sqrt(2)*x - 1, X**4 - 10*X**2 + 1)
def test_PolyElement_sqf_list():
_, x = ring("x", ZZ)
f = x**5 - x**3 - x**2 + 1
g = x**3 + 2*x**2 + 2*x + 1
h = x - 1
p = x**4 + x**3 - x - 1
assert f.sqf_part() == p
assert f.sqf_list() == (1, [(g, 1), (h, 2)])
def test_PolyElement_factor_list():
_, x = ring("x", ZZ)
f = x**5 - x**3 - x**2 + 1
u = x + 1
v = x - 1
w = x**2 + x + 1
assert f.factor_list() == (1, [(u, 1), (v, 2), (w, 1)])
| 42,862 | 29.704155 | 199 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/tests/test_densearith.py
|
"""Tests for dense recursive polynomials' arithmetics. """
from sympy.polys.densebasic import (
dup_normal, dmp_normal,
)
from sympy.polys.densearith import (
dup_add_term, dmp_add_term,
dup_sub_term, dmp_sub_term,
dup_mul_term, dmp_mul_term,
dup_add_ground, dmp_add_ground,
dup_sub_ground, dmp_sub_ground,
dup_mul_ground, dmp_mul_ground,
dup_quo_ground, dmp_quo_ground,
dup_exquo_ground, dmp_exquo_ground,
dup_lshift, dup_rshift,
dup_abs, dmp_abs,
dup_neg, dmp_neg,
dup_add, dmp_add,
dup_sub, dmp_sub,
dup_mul, dmp_mul,
dup_sqr, dmp_sqr,
dup_pow, dmp_pow,
dup_add_mul, dmp_add_mul,
dup_sub_mul, dmp_sub_mul,
dup_pdiv, dup_prem, dup_pquo, dup_pexquo,
dmp_pdiv, dmp_prem, dmp_pquo, dmp_pexquo,
dup_rr_div, dmp_rr_div,
dup_ff_div, dmp_ff_div,
dup_div, dup_rem, dup_quo, dup_exquo,
dmp_div, dmp_rem, dmp_quo, dmp_exquo,
dup_max_norm, dmp_max_norm,
dup_l1_norm, dmp_l1_norm,
dup_expand, dmp_expand,
)
from sympy.polys.polyerrors import (
ExactQuotientFailed,
)
from sympy.polys.specialpolys import f_polys
from sympy.polys.domains import FF, ZZ, QQ
from sympy.utilities.pytest import raises
f_0, f_1, f_2, f_3, f_4, f_5, f_6 = [ f.to_dense() for f in f_polys() ]
F_0 = dmp_mul_ground(dmp_normal(f_0, 2, QQ), QQ(1, 7), 2, QQ)
def test_dup_add_term():
f = dup_normal([], ZZ)
assert dup_add_term(f, ZZ(0), 0, ZZ) == dup_normal([], ZZ)
assert dup_add_term(f, ZZ(1), 0, ZZ) == dup_normal([1], ZZ)
assert dup_add_term(f, ZZ(1), 1, ZZ) == dup_normal([1, 0], ZZ)
assert dup_add_term(f, ZZ(1), 2, ZZ) == dup_normal([1, 0, 0], ZZ)
f = dup_normal([1, 1, 1], ZZ)
assert dup_add_term(f, ZZ(1), 0, ZZ) == dup_normal([1, 1, 2], ZZ)
assert dup_add_term(f, ZZ(1), 1, ZZ) == dup_normal([1, 2, 1], ZZ)
assert dup_add_term(f, ZZ(1), 2, ZZ) == dup_normal([2, 1, 1], ZZ)
assert dup_add_term(f, ZZ(1), 3, ZZ) == dup_normal([1, 1, 1, 1], ZZ)
assert dup_add_term(f, ZZ(1), 4, ZZ) == dup_normal([1, 0, 1, 1, 1], ZZ)
assert dup_add_term(f, ZZ(1), 5, ZZ) == dup_normal([1, 0, 0, 1, 1, 1], ZZ)
assert dup_add_term(
f, ZZ(1), 6, ZZ) == dup_normal([1, 0, 0, 0, 1, 1, 1], ZZ)
assert dup_add_term(f, ZZ(-1), 2, ZZ) == dup_normal([1, 1], ZZ)
def test_dmp_add_term():
assert dmp_add_term([ZZ(1), ZZ(1), ZZ(1)], ZZ(1), 2, 0, ZZ) == \
dup_add_term([ZZ(1), ZZ(1), ZZ(1)], ZZ(1), 2, ZZ)
assert dmp_add_term(f_0, [[]], 3, 2, ZZ) == f_0
assert dmp_add_term(F_0, [[]], 3, 2, QQ) == F_0
def test_dup_sub_term():
f = dup_normal([], ZZ)
assert dup_sub_term(f, ZZ(0), 0, ZZ) == dup_normal([], ZZ)
assert dup_sub_term(f, ZZ(1), 0, ZZ) == dup_normal([-1], ZZ)
assert dup_sub_term(f, ZZ(1), 1, ZZ) == dup_normal([-1, 0], ZZ)
assert dup_sub_term(f, ZZ(1), 2, ZZ) == dup_normal([-1, 0, 0], ZZ)
f = dup_normal([1, 1, 1], ZZ)
assert dup_sub_term(f, ZZ(2), 0, ZZ) == dup_normal([ 1, 1, -1], ZZ)
assert dup_sub_term(f, ZZ(2), 1, ZZ) == dup_normal([ 1, -1, 1], ZZ)
assert dup_sub_term(f, ZZ(2), 2, ZZ) == dup_normal([-1, 1, 1], ZZ)
assert dup_sub_term(f, ZZ(1), 3, ZZ) == dup_normal([-1, 1, 1, 1], ZZ)
assert dup_sub_term(f, ZZ(1), 4, ZZ) == dup_normal([-1, 0, 1, 1, 1], ZZ)
assert dup_sub_term(f, ZZ(1), 5, ZZ) == dup_normal([-1, 0, 0, 1, 1, 1], ZZ)
assert dup_sub_term(
f, ZZ(1), 6, ZZ) == dup_normal([-1, 0, 0, 0, 1, 1, 1], ZZ)
assert dup_sub_term(f, ZZ(1), 2, ZZ) == dup_normal([1, 1], ZZ)
def test_dmp_sub_term():
assert dmp_sub_term([ZZ(1), ZZ(1), ZZ(1)], ZZ(1), 2, 0, ZZ) == \
dup_sub_term([ZZ(1), ZZ(1), ZZ(1)], ZZ(1), 2, ZZ)
assert dmp_sub_term(f_0, [[]], 3, 2, ZZ) == f_0
assert dmp_sub_term(F_0, [[]], 3, 2, QQ) == F_0
def test_dup_mul_term():
f = dup_normal([], ZZ)
assert dup_mul_term(f, ZZ(2), 3, ZZ) == dup_normal([], ZZ)
f = dup_normal([1, 1], ZZ)
assert dup_mul_term(f, ZZ(0), 3, ZZ) == dup_normal([], ZZ)
f = dup_normal([1, 2, 3], ZZ)
assert dup_mul_term(f, ZZ(2), 0, ZZ) == dup_normal([2, 4, 6], ZZ)
assert dup_mul_term(f, ZZ(2), 1, ZZ) == dup_normal([2, 4, 6, 0], ZZ)
assert dup_mul_term(f, ZZ(2), 2, ZZ) == dup_normal([2, 4, 6, 0, 0], ZZ)
assert dup_mul_term(f, ZZ(2), 3, ZZ) == dup_normal([2, 4, 6, 0, 0, 0], ZZ)
def test_dmp_mul_term():
assert dmp_mul_term([ZZ(1), ZZ(2), ZZ(3)], ZZ(2), 1, 0, ZZ) == \
dup_mul_term([ZZ(1), ZZ(2), ZZ(3)], ZZ(2), 1, ZZ)
assert dmp_mul_term([[]], [ZZ(2)], 3, 1, ZZ) == [[]]
assert dmp_mul_term([[ZZ(1)]], [], 3, 1, ZZ) == [[]]
assert dmp_mul_term([[ZZ(1), ZZ(2)], [ZZ(3)]], [ZZ(2)], 2, 1, ZZ) == \
[[ZZ(2), ZZ(4)], [ZZ(6)], [], []]
assert dmp_mul_term([[]], [QQ(2, 3)], 3, 1, QQ) == [[]]
assert dmp_mul_term([[QQ(1, 2)]], [], 3, 1, QQ) == [[]]
assert dmp_mul_term([[QQ(1, 5), QQ(2, 5)], [QQ(3, 5)]], [QQ(2, 3)], 2, 1, QQ) == \
[[QQ(2, 15), QQ(4, 15)], [QQ(6, 15)], [], []]
def test_dup_add_ground():
f = ZZ.map([1, 2, 3, 4])
g = ZZ.map([1, 2, 3, 8])
assert dup_add_ground(f, ZZ(4), ZZ) == g
def test_dmp_add_ground():
f = ZZ.map([[1], [2], [3], [4]])
g = ZZ.map([[1], [2], [3], [8]])
assert dmp_add_ground(f, ZZ(4), 1, ZZ) == g
def test_dup_sub_ground():
f = ZZ.map([1, 2, 3, 4])
g = ZZ.map([1, 2, 3, 0])
assert dup_sub_ground(f, ZZ(4), ZZ) == g
def test_dmp_sub_ground():
f = ZZ.map([[1], [2], [3], [4]])
g = ZZ.map([[1], [2], [3], []])
assert dmp_sub_ground(f, ZZ(4), 1, ZZ) == g
def test_dup_mul_ground():
f = dup_normal([], ZZ)
assert dup_mul_ground(f, ZZ(2), ZZ) == dup_normal([], ZZ)
f = dup_normal([1, 2, 3], ZZ)
assert dup_mul_ground(f, ZZ(0), ZZ) == dup_normal([], ZZ)
assert dup_mul_ground(f, ZZ(2), ZZ) == dup_normal([2, 4, 6], ZZ)
def test_dmp_mul_ground():
assert dmp_mul_ground(f_0, ZZ(2), 2, ZZ) == [
[[ZZ(2), ZZ(4), ZZ(6)], [ZZ(4)]],
[[ZZ(6)]],
[[ZZ(8), ZZ(10), ZZ(12)], [ZZ(2), ZZ(4), ZZ(2)], [ZZ(2)]]
]
assert dmp_mul_ground(F_0, QQ(1, 2), 2, QQ) == [
[[QQ(1, 14), QQ(2, 14), QQ(3, 14)], [QQ(2, 14)]],
[[QQ(3, 14)]],
[[QQ(4, 14), QQ(5, 14), QQ(6, 14)], [QQ(1, 14), QQ(2, 14),
QQ(1, 14)], [QQ(1, 14)]]
]
def test_dup_quo_ground():
raises(ZeroDivisionError, lambda: dup_quo_ground(dup_normal([1, 2,
3], ZZ), ZZ(0), ZZ))
f = dup_normal([], ZZ)
assert dup_quo_ground(f, ZZ(3), ZZ) == dup_normal([], ZZ)
f = dup_normal([6, 2, 8], ZZ)
assert dup_quo_ground(f, ZZ(1), ZZ) == f
assert dup_quo_ground(f, ZZ(2), ZZ) == dup_normal([3, 1, 4], ZZ)
assert dup_quo_ground(f, ZZ(3), ZZ) == dup_normal([2, 0, 2], ZZ)
f = dup_normal([6, 2, 8], QQ)
assert dup_quo_ground(f, QQ(1), QQ) == f
assert dup_quo_ground(f, QQ(2), QQ) == [QQ(3), QQ(1), QQ(4)]
assert dup_quo_ground(f, QQ(7), QQ) == [QQ(6, 7), QQ(2, 7), QQ(8, 7)]
def test_dup_exquo_ground():
raises(ZeroDivisionError, lambda: dup_exquo_ground(dup_normal([1,
2, 3], ZZ), ZZ(0), ZZ))
raises(ExactQuotientFailed, lambda: dup_exquo_ground(dup_normal([1,
2, 3], ZZ), ZZ(3), ZZ))
f = dup_normal([], ZZ)
assert dup_exquo_ground(f, ZZ(3), ZZ) == dup_normal([], ZZ)
f = dup_normal([6, 2, 8], ZZ)
assert dup_exquo_ground(f, ZZ(1), ZZ) == f
assert dup_exquo_ground(f, ZZ(2), ZZ) == dup_normal([3, 1, 4], ZZ)
f = dup_normal([6, 2, 8], QQ)
assert dup_exquo_ground(f, QQ(1), QQ) == f
assert dup_exquo_ground(f, QQ(2), QQ) == [QQ(3), QQ(1), QQ(4)]
assert dup_exquo_ground(f, QQ(7), QQ) == [QQ(6, 7), QQ(2, 7), QQ(8, 7)]
def test_dmp_quo_ground():
f = dmp_normal([[6], [2], [8]], 1, ZZ)
assert dmp_quo_ground(f, ZZ(1), 1, ZZ) == f
assert dmp_quo_ground(
f, ZZ(2), 1, ZZ) == dmp_normal([[3], [1], [4]], 1, ZZ)
assert dmp_normal(dmp_quo_ground(
f, ZZ(3), 1, ZZ), 1, ZZ) == dmp_normal([[2], [], [2]], 1, ZZ)
def test_dmp_exquo_ground():
f = dmp_normal([[6], [2], [8]], 1, ZZ)
assert dmp_exquo_ground(f, ZZ(1), 1, ZZ) == f
assert dmp_exquo_ground(
f, ZZ(2), 1, ZZ) == dmp_normal([[3], [1], [4]], 1, ZZ)
def test_dup_lshift():
assert dup_lshift([], 3, ZZ) == []
assert dup_lshift([1], 3, ZZ) == [1, 0, 0, 0]
def test_dup_rshift():
assert dup_rshift([], 3, ZZ) == []
assert dup_rshift([1, 0, 0, 0], 3, ZZ) == [1]
def test_dup_abs():
assert dup_abs([], ZZ) == []
assert dup_abs([ZZ( 1)], ZZ) == [ZZ(1)]
assert dup_abs([ZZ(-7)], ZZ) == [ZZ(7)]
assert dup_abs([ZZ(-1), ZZ(2), ZZ(3)], ZZ) == [ZZ(1), ZZ(2), ZZ(3)]
assert dup_abs([], QQ) == []
assert dup_abs([QQ( 1, 2)], QQ) == [QQ(1, 2)]
assert dup_abs([QQ(-7, 3)], QQ) == [QQ(7, 3)]
assert dup_abs(
[QQ(-1, 7), QQ(2, 7), QQ(3, 7)], QQ) == [QQ(1, 7), QQ(2, 7), QQ(3, 7)]
def test_dmp_abs():
assert dmp_abs([ZZ(-1)], 0, ZZ) == [ZZ(1)]
assert dmp_abs([QQ(-1, 2)], 0, QQ) == [QQ(1, 2)]
assert dmp_abs([[[]]], 2, ZZ) == [[[]]]
assert dmp_abs([[[ZZ(1)]]], 2, ZZ) == [[[ZZ(1)]]]
assert dmp_abs([[[ZZ(-7)]]], 2, ZZ) == [[[ZZ(7)]]]
assert dmp_abs([[[]]], 2, QQ) == [[[]]]
assert dmp_abs([[[QQ(1, 2)]]], 2, QQ) == [[[QQ(1, 2)]]]
assert dmp_abs([[[QQ(-7, 9)]]], 2, QQ) == [[[QQ(7, 9)]]]
def test_dup_neg():
assert dup_neg([], ZZ) == []
assert dup_neg([ZZ(1)], ZZ) == [ZZ(-1)]
assert dup_neg([ZZ(-7)], ZZ) == [ZZ(7)]
assert dup_neg([ZZ(-1), ZZ(2), ZZ(3)], ZZ) == [ZZ(1), ZZ(-2), ZZ(-3)]
assert dup_neg([], QQ) == []
assert dup_neg([QQ(1, 2)], QQ) == [QQ(-1, 2)]
assert dup_neg([QQ(-7, 9)], QQ) == [QQ(7, 9)]
assert dup_neg([QQ(
-1, 7), QQ(2, 7), QQ(3, 7)], QQ) == [QQ(1, 7), QQ(-2, 7), QQ(-3, 7)]
def test_dmp_neg():
assert dmp_neg([ZZ(-1)], 0, ZZ) == [ZZ(1)]
assert dmp_neg([QQ(-1, 2)], 0, QQ) == [QQ(1, 2)]
assert dmp_neg([[[]]], 2, ZZ) == [[[]]]
assert dmp_neg([[[ZZ(1)]]], 2, ZZ) == [[[ZZ(-1)]]]
assert dmp_neg([[[ZZ(-7)]]], 2, ZZ) == [[[ZZ(7)]]]
assert dmp_neg([[[]]], 2, QQ) == [[[]]]
assert dmp_neg([[[QQ(1, 9)]]], 2, QQ) == [[[QQ(-1, 9)]]]
assert dmp_neg([[[QQ(-7, 9)]]], 2, QQ) == [[[QQ(7, 9)]]]
def test_dup_add():
assert dup_add([], [], ZZ) == []
assert dup_add([ZZ(1)], [], ZZ) == [ZZ(1)]
assert dup_add([], [ZZ(1)], ZZ) == [ZZ(1)]
assert dup_add([ZZ(1)], [ZZ(1)], ZZ) == [ZZ(2)]
assert dup_add([ZZ(1)], [ZZ(2)], ZZ) == [ZZ(3)]
assert dup_add([ZZ(1), ZZ(2)], [ZZ(1)], ZZ) == [ZZ(1), ZZ(3)]
assert dup_add([ZZ(1)], [ZZ(1), ZZ(2)], ZZ) == [ZZ(1), ZZ(3)]
assert dup_add([ZZ(1), ZZ(
2), ZZ(3)], [ZZ(8), ZZ(9), ZZ(10)], ZZ) == [ZZ(9), ZZ(11), ZZ(13)]
assert dup_add([], [], QQ) == []
assert dup_add([QQ(1, 2)], [], QQ) == [QQ(1, 2)]
assert dup_add([], [QQ(1, 2)], QQ) == [QQ(1, 2)]
assert dup_add([QQ(1, 4)], [QQ(1, 4)], QQ) == [QQ(1, 2)]
assert dup_add([QQ(1, 4)], [QQ(1, 2)], QQ) == [QQ(3, 4)]
assert dup_add([QQ(1, 2), QQ(2, 3)], [QQ(1)], QQ) == [QQ(1, 2), QQ(5, 3)]
assert dup_add([QQ(1)], [QQ(1, 2), QQ(2, 3)], QQ) == [QQ(1, 2), QQ(5, 3)]
assert dup_add([QQ(1, 7), QQ(2, 7), QQ(3, 7)], [QQ(
8, 7), QQ(9, 7), QQ(10, 7)], QQ) == [QQ(9, 7), QQ(11, 7), QQ(13, 7)]
def test_dmp_add():
assert dmp_add([ZZ(1), ZZ(2)], [ZZ(1)], 0, ZZ) == \
dup_add([ZZ(1), ZZ(2)], [ZZ(1)], ZZ)
assert dmp_add([QQ(1, 2), QQ(2, 3)], [QQ(1)], 0, QQ) == \
dup_add([QQ(1, 2), QQ(2, 3)], [QQ(1)], QQ)
assert dmp_add([[[]]], [[[]]], 2, ZZ) == [[[]]]
assert dmp_add([[[ZZ(1)]]], [[[]]], 2, ZZ) == [[[ZZ(1)]]]
assert dmp_add([[[]]], [[[ZZ(1)]]], 2, ZZ) == [[[ZZ(1)]]]
assert dmp_add([[[ZZ(2)]]], [[[ZZ(1)]]], 2, ZZ) == [[[ZZ(3)]]]
assert dmp_add([[[ZZ(1)]]], [[[ZZ(2)]]], 2, ZZ) == [[[ZZ(3)]]]
assert dmp_add([[[]]], [[[]]], 2, QQ) == [[[]]]
assert dmp_add([[[QQ(1, 2)]]], [[[]]], 2, QQ) == [[[QQ(1, 2)]]]
assert dmp_add([[[]]], [[[QQ(1, 2)]]], 2, QQ) == [[[QQ(1, 2)]]]
assert dmp_add([[[QQ(2, 7)]]], [[[QQ(1, 7)]]], 2, QQ) == [[[QQ(3, 7)]]]
assert dmp_add([[[QQ(1, 7)]]], [[[QQ(2, 7)]]], 2, QQ) == [[[QQ(3, 7)]]]
def test_dup_sub():
assert dup_sub([], [], ZZ) == []
assert dup_sub([ZZ(1)], [], ZZ) == [ZZ(1)]
assert dup_sub([], [ZZ(1)], ZZ) == [ZZ(-1)]
assert dup_sub([ZZ(1)], [ZZ(1)], ZZ) == []
assert dup_sub([ZZ(1)], [ZZ(2)], ZZ) == [ZZ(-1)]
assert dup_sub([ZZ(1), ZZ(2)], [ZZ(1)], ZZ) == [ZZ(1), ZZ(1)]
assert dup_sub([ZZ(1)], [ZZ(1), ZZ(2)], ZZ) == [ZZ(-1), ZZ(-1)]
assert dup_sub([ZZ(3), ZZ(
2), ZZ(1)], [ZZ(8), ZZ(9), ZZ(10)], ZZ) == [ZZ(-5), ZZ(-7), ZZ(-9)]
assert dup_sub([], [], QQ) == []
assert dup_sub([QQ(1, 2)], [], QQ) == [QQ(1, 2)]
assert dup_sub([], [QQ(1, 2)], QQ) == [QQ(-1, 2)]
assert dup_sub([QQ(1, 3)], [QQ(1, 3)], QQ) == []
assert dup_sub([QQ(1, 3)], [QQ(2, 3)], QQ) == [QQ(-1, 3)]
assert dup_sub([QQ(1, 7), QQ(2, 7)], [QQ(1)], QQ) == [QQ(1, 7), QQ(-5, 7)]
assert dup_sub([QQ(1)], [QQ(1, 7), QQ(2, 7)], QQ) == [QQ(-1, 7), QQ(5, 7)]
assert dup_sub([QQ(3, 7), QQ(2, 7), QQ(1, 7)], [QQ(
8, 7), QQ(9, 7), QQ(10, 7)], QQ) == [QQ(-5, 7), QQ(-7, 7), QQ(-9, 7)]
def test_dmp_sub():
assert dmp_sub([ZZ(1), ZZ(2)], [ZZ(1)], 0, ZZ) == \
dup_sub([ZZ(1), ZZ(2)], [ZZ(1)], ZZ)
assert dmp_sub([QQ(1, 2), QQ(2, 3)], [QQ(1)], 0, QQ) == \
dup_sub([QQ(1, 2), QQ(2, 3)], [QQ(1)], QQ)
assert dmp_sub([[[]]], [[[]]], 2, ZZ) == [[[]]]
assert dmp_sub([[[ZZ(1)]]], [[[]]], 2, ZZ) == [[[ZZ(1)]]]
assert dmp_sub([[[]]], [[[ZZ(1)]]], 2, ZZ) == [[[ZZ(-1)]]]
assert dmp_sub([[[ZZ(2)]]], [[[ZZ(1)]]], 2, ZZ) == [[[ZZ(1)]]]
assert dmp_sub([[[ZZ(1)]]], [[[ZZ(2)]]], 2, ZZ) == [[[ZZ(-1)]]]
assert dmp_sub([[[]]], [[[]]], 2, QQ) == [[[]]]
assert dmp_sub([[[QQ(1, 2)]]], [[[]]], 2, QQ) == [[[QQ(1, 2)]]]
assert dmp_sub([[[]]], [[[QQ(1, 2)]]], 2, QQ) == [[[QQ(-1, 2)]]]
assert dmp_sub([[[QQ(2, 7)]]], [[[QQ(1, 7)]]], 2, QQ) == [[[QQ(1, 7)]]]
assert dmp_sub([[[QQ(1, 7)]]], [[[QQ(2, 7)]]], 2, QQ) == [[[QQ(-1, 7)]]]
def test_dup_add_mul():
assert dup_add_mul([ZZ(1), ZZ(2), ZZ(3)], [ZZ(3), ZZ(2), ZZ(1)],
[ZZ(1), ZZ(2)], ZZ) == [ZZ(3), ZZ(9), ZZ(7), ZZ(5)]
assert dmp_add_mul([[ZZ(1), ZZ(2)], [ZZ(3)]], [[ZZ(3)], [ZZ(2), ZZ(1)]],
[[ZZ(1)], [ZZ(2)]], 1, ZZ) == [[ZZ(3)], [ZZ(3), ZZ(9)], [ZZ(4), ZZ(5)]]
def test_dup_sub_mul():
assert dup_sub_mul([ZZ(1), ZZ(2), ZZ(3)], [ZZ(3), ZZ(2), ZZ(1)],
[ZZ(1), ZZ(2)], ZZ) == [ZZ(-3), ZZ(-7), ZZ(-3), ZZ(1)]
assert dmp_sub_mul([[ZZ(1), ZZ(2)], [ZZ(3)]], [[ZZ(3)], [ZZ(2), ZZ(1)]],
[[ZZ(1)], [ZZ(2)]], 1, ZZ) == [[ZZ(-3)], [ZZ(-1), ZZ(-5)], [ZZ(-4), ZZ(1)]]
def test_dup_mul():
assert dup_mul([], [], ZZ) == []
assert dup_mul([], [ZZ(1)], ZZ) == []
assert dup_mul([ZZ(1)], [], ZZ) == []
assert dup_mul([ZZ(1)], [ZZ(1)], ZZ) == [ZZ(1)]
assert dup_mul([ZZ(5)], [ZZ(7)], ZZ) == [ZZ(35)]
assert dup_mul([], [], QQ) == []
assert dup_mul([], [QQ(1, 2)], QQ) == []
assert dup_mul([QQ(1, 2)], [], QQ) == []
assert dup_mul([QQ(1, 2)], [QQ(4, 7)], QQ) == [QQ(2, 7)]
assert dup_mul([QQ(5, 7)], [QQ(3, 7)], QQ) == [QQ(15, 49)]
f = dup_normal([3, 0, 0, 6, 1, 2], ZZ)
g = dup_normal([4, 0, 1, 0], ZZ)
h = dup_normal([12, 0, 3, 24, 4, 14, 1, 2, 0], ZZ)
assert dup_mul(f, g, ZZ) == h
assert dup_mul(g, f, ZZ) == h
f = dup_normal([2, 0, 0, 1, 7], ZZ)
h = dup_normal([4, 0, 0, 4, 28, 0, 1, 14, 49], ZZ)
assert dup_mul(f, f, ZZ) == h
K = FF(6)
assert dup_mul([K(2), K(1)], [K(3), K(4)], K) == [K(5), K(4)]
p1 = dup_normal([79, -1, 78, -94, -10, 11, 32, -19, 78, 2, -89, 30, 73, 42,
85, 77, 83, -30, -34, -2, 95, -81, 37, -49, -46, -58, -16, 37, 35, -11,
-57, -15, -31, 67, -20, 27, 76, 2, 70, 67, -65, 65, -26, -93, -44, -12,
-92, 57, -90, -57, -11, -67, -98, -69, 97, -41, 89, 33, 89, -50, 81,
-31, 60, -27, 43, 29, -77, 44, 21, -91, 32, -57, 33, 3, 53, -51, -38,
-99, -84, 23, -50, 66, -100, 1, -75, -25, 27, -60, 98, -51, -87, 6, 8,
78, -28, -95, -88, 12, -35, 26, -9, 16, -92, 55, -7, -86, 68, -39, -46,
84, 94, 45, 60, 92, 68, -75, -74, -19, 8, 75, 78, 91, 57, 34, 14, -3,
-49, 65, 78, -18, 6, -29, -80, -98, 17, 13, 58, 21, 20, 9, 37, 7, -30,
-53, -20, 34, 67, -42, 89, -22, 73, 43, -6, 5, 51, -8, -15, -52, -22,
-58, -72, -3, 43, -92, 82, 83, -2, -13, -23, -60, 16, -94, -8, -28,
-95, -72, 63, -90, 76, 6, -43, -100, -59, 76, 3, 3, 46, -85, 75, 62,
-71, -76, 88, 97, -72, -1, 30, -64, 72, -48, 14, -78, 58, 63, -91, 24,
-87, -27, -80, -100, -44, 98, 70, 100, -29, -38, 11, 77, 100, 52, 86,
65, -5, -42, -81, -38, -42, 43, -2, -70, -63, -52], ZZ)
p2 = dup_normal([65, -19, -47, 1, 90, 81, -15, -34, 25, -75, 9, -83, 50, -5,
-44, 31, 1, 70, -7, 78, 74, 80, 85, 65, 21, 41, 66, 19, -40, 63, -21,
-27, 32, 69, 83, 34, -35, 14, 81, 57, -75, 32, -67, -89, -100, -61, 46,
84, -78, -29, -50, -94, -24, -32, -68, -16, 100, -7, -72, -89, 35, 82,
58, 81, -92, 62, 5, -47, -39, -58, -72, -13, 84, 44, 55, -25, 48, -54,
-31, -56, -11, -50, -84, 10, 67, 17, 13, -14, 61, 76, -64, -44, -40,
-96, 11, -11, -94, 2, 6, 27, -6, 68, -54, 66, -74, -14, -1, -24, -73,
96, 89, -11, -89, 56, -53, 72, -43, 96, 25, 63, -31, 29, 68, 83, 91,
-93, -19, -38, -40, 40, -12, -19, -79, 44, 100, -66, -29, -77, 62, 39,
-8, 11, -97, 14, 87, 64, 21, -18, 13, 15, -59, -75, -99, -88, 57, 54,
56, -67, 6, -63, -59, -14, 28, 87, -20, -39, 84, -91, -2, 49, -75, 11,
-24, -95, 36, 66, 5, 25, -72, -40, 86, 90, 37, -33, 57, -35, 29, -18,
4, -79, 64, -17, -27, 21, 29, -5, -44, -87, -24, 52, 78, 11, -23, -53,
36, 42, 21, -68, 94, -91, -51, -21, 51, -76, 72, 31, 24, -48, -80, -9,
37, -47, -6, -8, -63, -91, 79, -79, -100, 38, -20, 38, 100, 83, -90,
87, 63, -36, 82, -19, 18, -98, -38, 26, 98, -70, 79, 92, 12, 12, 70,
74, 36, 48, -13, 31, 31, -47, -71, -12, -64, 36, -42, 32, -86, 60, 83,
70, 55, 0, 1, 29, -35, 8, -82, 8, -73, -46, -50, 43, 48, -5, -86, -72,
44, -90, 19, 19, 5, -20, 97, -13, -66, -5, 5, -69, 64, -30, 41, 51, 36,
13, -99, -61, 94, -12, 74, 98, 68, 24, 46, -97, -87, -6, -27, 82, 62,
-11, -77, 86, 66, -47, -49, -50, 13, 18, 89, -89, 46, -80, 13, 98, -35,
-36, -25, 12, 20, 26, -52, 79, 27, 79, 100, 8, 62, -58, -28, 37], ZZ)
res = dup_normal([5135, -1566, 1376, -7466, 4579, 11710, 8001, -7183,
-3737, -7439, 345, -10084, 24522, -1201, 1070, -10245, 9582, 9264,
1903, 23312, 18953, 10037, -15268, -5450, 6442, -6243, -3777, 5110,
10936, -16649, -6022, 16255, 31300, 24818, 31922, 32760, 7854, 27080,
15766, 29596, 7139, 31945, -19810, 465, -38026, -3971, 9641, 465,
-19375, 5524, -30112, -11960, -12813, 13535, 30670, 5925, -43725,
-14089, 11503, -22782, 6371, 43881, 37465, -33529, -33590, -39798,
-37854, -18466, -7908, -35825, -26020, -36923, -11332, -5699, 25166,
-3147, 19885, 12962, -20659, -1642, 27723, -56331, -24580, -11010,
-20206, 20087, -23772, -16038, 38580, 20901, -50731, 32037, -4299,
26508, 18038, -28357, 31846, -7405, -20172, -15894, 2096, 25110,
-45786, 45918, -55333, -31928, -49428, -29824, -58796, -24609, -15408,
69, -35415, -18439, 10123, -20360, -65949, 33356, -20333, 26476,
-32073, 33621, 930, 28803, -42791, 44716, 38164, 12302, -1739, 11421,
73385, -7613, 14297, 38155, -414, 77587, 24338, -21415, 29367, 42639,
13901, -288, 51027, -11827, 91260, 43407, 88521, -15186, 70572, -12049,
5090, -12208, -56374, 15520, -623, -7742, 50825, 11199, -14894, 40892,
59591, -31356, -28696, -57842, -87751, -33744, -28436, -28945, -40287,
37957, -35638, 33401, -61534, 14870, 40292, 70366, -10803, 102290,
-71719, -85251, 7902, -22409, 75009, 99927, 35298, -1175, -762, -34744,
-10587, -47574, -62629, -19581, -43659, -54369, -32250, -39545, 15225,
-24454, 11241, -67308, -30148, 39929, 37639, 14383, -73475, -77636,
-81048, -35992, 41601, -90143, 76937, -8112, 56588, 9124, -40094,
-32340, 13253, 10898, -51639, 36390, 12086, -1885, 100714, -28561,
-23784, -18735, 18916, 16286, 10742, -87360, -13697, 10689, -19477,
-29770, 5060, 20189, -8297, 112407, 47071, 47743, 45519, -4109, 17468,
-68831, 78325, -6481, -21641, -19459, 30919, 96115, 8607, 53341, 32105,
-16211, 23538, 57259, -76272, -40583, 62093, 38511, -34255, -40665,
-40604, -37606, -15274, 33156, -13885, 103636, 118678, -14101, -92682,
-100791, 2634, 63791, 98266, 19286, -34590, -21067, -71130, 25380,
-40839, -27614, -26060, 52358, -15537, 27138, -6749, 36269, -33306,
13207, -91084, -5540, -57116, 69548, 44169, -57742, -41234, -103327,
-62904, -8566, 41149, -12866, 71188, 23980, 1838, 58230, 73950, 5594,
43113, -8159, -15925, 6911, 85598, -75016, -16214, -62726, -39016,
8618, -63882, -4299, 23182, 49959, 49342, -3238, -24913, -37138, 78361,
32451, 6337, -11438, -36241, -37737, 8169, -3077, -24829, 57953, 53016,
-31511, -91168, 12599, -41849, 41576, 55275, -62539, 47814, -62319,
12300, -32076, -55137, -84881, -27546, 4312, -3433, -54382, 113288,
-30157, 74469, 18219, 79880, -2124, 98911, 17655, -33499, -32861,
47242, -37393, 99765, 14831, -44483, 10800, -31617, -52710, 37406,
22105, 29704, -20050, 13778, 43683, 36628, 8494, 60964, -22644, 31550,
-17693, 33805, -124879, -12302, 19343, 20400, -30937, -21574, -34037,
-33380, 56539, -24993, -75513, -1527, 53563, 65407, -101, 53577, 37991,
18717, -23795, -8090, -47987, -94717, 41967, 5170, -14815, -94311,
17896, -17734, -57718, -774, -38410, 24830, 29682, 76480, 58802,
-46416, -20348, -61353, -68225, -68306, 23822, -31598, 42972, 36327,
28968, -65638, -21638, 24354, -8356, 26777, 52982, -11783, -44051,
-26467, -44721, -28435, -53265, -25574, -2669, 44155, 22946, -18454,
-30718, -11252, 58420, 8711, 67447, 4425, 41749, 67543, 43162, 11793,
-41907, 20477, -13080, 6559, -6104, -13244, 42853, 42935, 29793, 36730,
-28087, 28657, 17946, 7503, 7204, 21491, -27450, -24241, -98156,
-18082, -42613, -24928, 10775, -14842, -44127, 55910, 14777, 31151, -2194,
39206, -2100, -4211, 11827, -8918, -19471, 72567, 36447, -65590, -34861,
-17147, -45303, 9025, -7333, -35473, 11101, 11638, 3441, 6626, -41800,
9416, 13679, 33508, 40502, -60542, 16358, 8392, -43242, -35864, -34127,
-48721, 35878, 30598, 28630, 20279, -19983, -14638, -24455, -1851, -11344,
45150, 42051, 26034, -28889, -32382, -3527, -14532, 22564, -22346, 477,
11706, 28338, -25972, -9185, -22867, -12522, 32120, -4424, 11339, -33913,
-7184, 5101, -23552, -17115, -31401, -6104, 21906, 25708, 8406, 6317,
-7525, 5014, 20750, 20179, 22724, 11692, 13297, 2493, -253, -16841, -17339,
-6753, -4808, 2976, -10881, -10228, -13816, -12686, 1385, 2316, 2190, -875,
-1924], ZZ)
assert dup_mul(p1, p2, ZZ) == res
p1 = dup_normal([83, -61, -86, -24, 12, 43, -88, -9, 42, 55, -66, 74, 95,
-25, -12, 68, -99, 4, 45, 6, -15, -19, 78, 65, -55, 47, -13, 17, 86,
81, -58, -27, 50, -40, -24, 39, -41, -92, 75, 90, -1, 40, -15, -27,
-35, 68, 70, -64, -40, 78, -88, -58, -39, 69, 46, 12, 28, -94, -37,
-50, -80, -96, -61, 25, 1, 71, 4, 12, 48, 4, 34, -47, -75, 5, 48, 82,
88, 23, 98, 35, 17, -10, 48, -61, -95, 47, 65, -19, -66, -57, -6, -51,
-42, -89, 66, -13, 18, 37, 90, -23, 72, 96, -53, 0, 40, -73, -52, -68,
32, -25, -53, 79, -52, 18, 44, 73, -81, 31, -90, 70, 3, 36, 48, 76,
-24, -44, 23, 98, -4, 73, 69, 88, -70, 14, -68, 94, -78, -15, -64, -97,
-70, -35, 65, 88, 49, -53, -7, 12, -45, -7, 59, -94, 99, -2, 67, -60,
-71, 29, -62, -77, 1, 51, 17, 80, -20, -47, -19, 24, -9, 39, -23, 21,
-84, 10, 84, 56, -17, -21, -66, 85, 70, 46, -51, -22, -95, 78, -60,
-96, -97, -45, 72, 35, 30, -61, -92, -93, -60, -61, 4, -4, -81, -73,
46, 53, -11, 26, 94, 45, 14, -78, 55, 84, -68, 98, 60, 23, 100, -63,
68, 96, -16, 3, 56, 21, -58, 62, -67, 66, 85, 41, -79, -22, 97, -67,
82, 82, -96, -20, -7, 48, -67, 48, -9, -39, 78], ZZ)
p2 = dup_normal([52, 88, 76, 66, 9, -64, 46, -20, -28, 69, 60, 96, -36,
-92, -30, -11, -35, 35, 55, 63, -92, -7, 25, -58, 74, 55, -6, 4, 47,
-92, -65, 67, -45, 74, -76, 59, -6, 69, 39, 24, -71, -7, 39, -45, 60,
-68, 98, 97, -79, 17, 4, 94, -64, 68, -100, -96, -2, 3, 22, 96, 54,
-77, -86, 67, 6, 57, 37, 40, 89, -78, 64, -94, -45, -92, 57, 87, -26,
36, 19, 97, 25, 77, -87, 24, 43, -5, 35, 57, 83, 71, 35, 63, 61, 96,
-22, 8, -1, 96, 43, 45, 94, -93, 36, 71, -41, -99, 85, -48, 59, 52,
-17, 5, 87, -16, -68, -54, 76, -18, 100, 91, -42, -70, -66, -88, -12,
1, 95, -82, 52, 43, -29, 3, 12, 72, -99, -43, -32, -93, -51, 16, -20,
-12, -11, 5, 33, -38, 93, -5, -74, 25, 74, -58, 93, 59, -63, -86, 63,
-20, -4, -74, -73, -95, 29, -28, 93, -91, -2, -38, -62, 77, -58, -85,
-28, 95, 38, 19, -69, 86, 94, 25, -2, -4, 47, 34, -59, 35, -48, 29,
-63, -53, 34, 29, 66, 73, 6, 92, -84, 89, 15, 81, 93, 97, 51, -72, -78,
25, 60, 90, -45, 39, 67, -84, -62, 57, 26, -32, -56, -14, -83, 76, 5,
-2, 99, -100, 28, 46, 94, -7, 53, -25, 16, -23, -36, 89, -78, -63, 31,
1, 84, -99, -52, 76, 48, 90, -76, 44, -19, 54, -36, -9, -73, -100, -69,
31, 42, 25, -39, 76, -26, -8, -14, 51, 3, 37, 45, 2, -54, 13, -34, -92,
17, -25, -65, 53, -63, 30, 4, -70, -67, 90, 52, 51, 18, -3, 31, -45,
-9, 59, 63, -87, 22, -32, 29, -38, 21, 36, -82, 27, -11], ZZ)
res = dup_normal([4316, 4132, -3532, -7974, -11303, -10069, 5484, -3330,
-5874, 7734, 4673, 11327, -9884, -8031, 17343, 21035, -10570, -9285,
15893, 3780, -14083, 8819, 17592, 10159, 7174, -11587, 8598, -16479,
3602, 25596, 9781, 12163, 150, 18749, -21782, -12307, 27578, -2757,
-12573, 12565, 6345, -18956, 19503, -15617, 1443, -16778, 36851, 23588,
-28474, 5749, 40695, -7521, -53669, -2497, -18530, 6770, 57038, 3926,
-6927, -15399, 1848, -64649, -27728, 3644, 49608, 15187, -8902, -9480,
-7398, -40425, 4824, 23767, -7594, -6905, 33089, 18786, 12192, 24670,
31114, 35334, -4501, -14676, 7107, -59018, -21352, 20777, 19661, 20653,
33754, -885, -43758, 6269, 51897, -28719, -97488, -9527, 13746, 11644,
17644, -21720, 23782, -10481, 47867, 20752, 33810, -1875, 39918, -7710,
-40840, 19808, -47075, 23066, 46616, 25201, 9287, 35436, -1602, 9645,
-11978, 13273, 15544, 33465, 20063, 44539, 11687, 27314, -6538, -37467,
14031, 32970, -27086, 41323, 29551, 65910, -39027, -37800, -22232,
8212, 46316, -28981, -55282, 50417, -44929, -44062, 73879, 37573,
-2596, -10877, -21893, -133218, -33707, -25753, -9531, 17530, 61126,
2748, -56235, 43874, -10872, -90459, -30387, 115267, -7264, -44452,
122626, 14839, -599, 10337, 57166, -67467, -54957, 63669, 1202, 18488,
52594, 7205, -97822, 612, 78069, -5403, -63562, 47236, 36873, -154827,
-26188, 82427, -39521, 5628, 7416, 5276, -53095, 47050, 26121, -42207,
79021, -13035, 2499, -66943, 29040, -72355, -23480, 23416, -12885,
-44225, -42688, -4224, 19858, 55299, 15735, 11465, 101876, -39169,
51786, 14723, 43280, -68697, 16410, 92295, 56767, 7183, 111850, 4550,
115451, -38443, -19642, -35058, 10230, 93829, 8925, 63047, 3146, 29250,
8530, 5255, -98117, -115517, -76817, -8724, 41044, 1312, -35974, 79333,
-28567, 7547, -10580, -24559, -16238, 10794, -3867, 24848, 57770,
-51536, -35040, 71033, 29853, 62029, -7125, -125585, -32169, -47907,
156811, -65176, -58006, -15757, -57861, 11963, 30225, -41901, -41681,
31310, 27982, 18613, 61760, 60746, -59096, 33499, 30097, -17997, 24032,
56442, -83042, 23747, -20931, -21978, -158752, -9883, -73598, -7987,
-7333, -125403, -116329, 30585, 53281, 51018, -29193, 88575, 8264,
-40147, -16289, 113088, 12810, -6508, 101552, -13037, 34440, -41840,
101643, 24263, 80532, 61748, 65574, 6423, -20672, 6591, -10834, -71716,
86919, -92626, 39161, 28490, 81319, 46676, 106720, 43530, 26998, 57456,
-8862, 60989, 13982, 3119, -2224, 14743, 55415, -49093, -29303, 28999,
1789, 55953, -84043, -7780, -65013, 57129, -47251, 61484, 61994,
-78361, -82778, 22487, -26894, 9756, -74637, -15519, -4360, 30115,
42433, 35475, 15286, 69768, 21509, -20214, 78675, -21163, 13596, 11443,
-10698, -53621, -53867, -24155, 64500, -42784, -33077, -16500, 873,
-52788, 14546, -38011, 36974, -39849, -34029, -94311, 83068, -50437,
-26169, -46746, 59185, 42259, -101379, -12943, 30089, -59086, 36271,
22723, -30253, -52472, -70826, -23289, 3331, -31687, 14183, -857,
-28627, 35246, -51284, 5636, -6933, 66539, 36654, 50927, 24783, 3457,
33276, 45281, 45650, -4938, -9968, -22590, 47995, 69229, 5214, -58365,
-17907, -14651, 18668, 18009, 12649, -11851, -13387, 20339, 52472,
-1087, -21458, -68647, 52295, 15849, 40608, 15323, 25164, -29368,
10352, -7055, 7159, 21695, -5373, -54849, 101103, -24963, -10511,
33227, 7659, 41042, -69588, 26718, -20515, 6441, 38135, -63, 24088,
-35364, -12785, -18709, 47843, 48533, -48575, 17251, -19394, 32878,
-9010, -9050, 504, -12407, 28076, -3429, 25324, -4210, -26119, 752,
-29203, 28251, -11324, -32140, -3366, -25135, 18702, -31588, -7047,
-24267, 49987, -14975, -33169, 37744, -7720, -9035, 16964, -2807, -421,
14114, -17097, -13662, 40628, -12139, -9427, 5369, 17551, -13232, -16211,
9804, -7422, 2677, 28635, -8280, -4906, 2908, -22558, 5604, 12459, 8756,
-3980, -4745, -18525, 7913, 5970, -16457, 20230, -6247, -13812, 2505,
11899, 1409, -15094, 22540, -18863, 137, 11123, -4516, 2290, -8594, 12150,
-10380, 3005, 5235, -7350, 2535, -858], ZZ)
assert dup_mul(p1, p2, ZZ) == res
def test_dmp_mul():
assert dmp_mul([ZZ(5)], [ZZ(7)], 0, ZZ) == \
dup_mul([ZZ(5)], [ZZ(7)], ZZ)
assert dmp_mul([QQ(5, 7)], [QQ(3, 7)], 0, QQ) == \
dup_mul([QQ(5, 7)], [QQ(3, 7)], QQ)
assert dmp_mul([[[]]], [[[]]], 2, ZZ) == [[[]]]
assert dmp_mul([[[ZZ(1)]]], [[[]]], 2, ZZ) == [[[]]]
assert dmp_mul([[[]]], [[[ZZ(1)]]], 2, ZZ) == [[[]]]
assert dmp_mul([[[ZZ(2)]]], [[[ZZ(1)]]], 2, ZZ) == [[[ZZ(2)]]]
assert dmp_mul([[[ZZ(1)]]], [[[ZZ(2)]]], 2, ZZ) == [[[ZZ(2)]]]
assert dmp_mul([[[]]], [[[]]], 2, QQ) == [[[]]]
assert dmp_mul([[[QQ(1, 2)]]], [[[]]], 2, QQ) == [[[]]]
assert dmp_mul([[[]]], [[[QQ(1, 2)]]], 2, QQ) == [[[]]]
assert dmp_mul([[[QQ(2, 7)]]], [[[QQ(1, 3)]]], 2, QQ) == [[[QQ(2, 21)]]]
assert dmp_mul([[[QQ(1, 7)]]], [[[QQ(2, 3)]]], 2, QQ) == [[[QQ(2, 21)]]]
K = FF(6)
assert dmp_mul(
[[K(2)], [K(1)]], [[K(3)], [K(4)]], 1, K) == [[K(5)], [K(4)]]
def test_dup_sqr():
assert dup_sqr([], ZZ) == []
assert dup_sqr([ZZ(2)], ZZ) == [ZZ(4)]
assert dup_sqr([ZZ(1), ZZ(2)], ZZ) == [ZZ(1), ZZ(4), ZZ(4)]
assert dup_sqr([], QQ) == []
assert dup_sqr([QQ(2, 3)], QQ) == [QQ(4, 9)]
assert dup_sqr([QQ(1, 3), QQ(2, 3)], QQ) == [QQ(1, 9), QQ(4, 9), QQ(4, 9)]
f = dup_normal([2, 0, 0, 1, 7], ZZ)
assert dup_sqr(f, ZZ) == dup_normal([4, 0, 0, 4, 28, 0, 1, 14, 49], ZZ)
K = FF(9)
assert dup_sqr([K(3), K(4)], K) == [K(6), K(7)]
def test_dmp_sqr():
assert dmp_sqr([ZZ(1), ZZ(2)], 0, ZZ) == \
dup_sqr([ZZ(1), ZZ(2)], ZZ)
assert dmp_sqr([[[]]], 2, ZZ) == [[[]]]
assert dmp_sqr([[[ZZ(2)]]], 2, ZZ) == [[[ZZ(4)]]]
assert dmp_sqr([[[]]], 2, QQ) == [[[]]]
assert dmp_sqr([[[QQ(2, 3)]]], 2, QQ) == [[[QQ(4, 9)]]]
K = FF(9)
assert dmp_sqr([[K(3)], [K(4)]], 1, K) == [[K(6)], [K(7)]]
def test_dup_pow():
assert dup_pow([], 0, ZZ) == [ZZ(1)]
assert dup_pow([], 0, QQ) == [QQ(1)]
assert dup_pow([], 1, ZZ) == []
assert dup_pow([], 7, ZZ) == []
assert dup_pow([ZZ(1)], 0, ZZ) == [ZZ(1)]
assert dup_pow([ZZ(1)], 1, ZZ) == [ZZ(1)]
assert dup_pow([ZZ(1)], 7, ZZ) == [ZZ(1)]
assert dup_pow([ZZ(3)], 0, ZZ) == [ZZ(1)]
assert dup_pow([ZZ(3)], 1, ZZ) == [ZZ(3)]
assert dup_pow([ZZ(3)], 7, ZZ) == [ZZ(2187)]
assert dup_pow([QQ(1, 1)], 0, QQ) == [QQ(1, 1)]
assert dup_pow([QQ(1, 1)], 1, QQ) == [QQ(1, 1)]
assert dup_pow([QQ(1, 1)], 7, QQ) == [QQ(1, 1)]
assert dup_pow([QQ(3, 7)], 0, QQ) == [QQ(1, 1)]
assert dup_pow([QQ(3, 7)], 1, QQ) == [QQ(3, 7)]
assert dup_pow([QQ(3, 7)], 7, QQ) == [QQ(2187, 823543)]
f = dup_normal([2, 0, 0, 1, 7], ZZ)
assert dup_pow(f, 0, ZZ) == dup_normal([1], ZZ)
assert dup_pow(f, 1, ZZ) == dup_normal([2, 0, 0, 1, 7], ZZ)
assert dup_pow(f, 2, ZZ) == dup_normal([4, 0, 0, 4, 28, 0, 1, 14, 49], ZZ)
assert dup_pow(f, 3, ZZ) == dup_normal(
[8, 0, 0, 12, 84, 0, 6, 84, 294, 1, 21, 147, 343], ZZ)
def test_dmp_pow():
assert dmp_pow([[]], 0, 1, ZZ) == [[ZZ(1)]]
assert dmp_pow([[]], 0, 1, QQ) == [[QQ(1)]]
assert dmp_pow([[]], 1, 1, ZZ) == [[]]
assert dmp_pow([[]], 7, 1, ZZ) == [[]]
assert dmp_pow([[ZZ(1)]], 0, 1, ZZ) == [[ZZ(1)]]
assert dmp_pow([[ZZ(1)]], 1, 1, ZZ) == [[ZZ(1)]]
assert dmp_pow([[ZZ(1)]], 7, 1, ZZ) == [[ZZ(1)]]
assert dmp_pow([[QQ(3, 7)]], 0, 1, QQ) == [[QQ(1, 1)]]
assert dmp_pow([[QQ(3, 7)]], 1, 1, QQ) == [[QQ(3, 7)]]
assert dmp_pow([[QQ(3, 7)]], 7, 1, QQ) == [[QQ(2187, 823543)]]
f = dup_normal([2, 0, 0, 1, 7], ZZ)
assert dmp_pow(f, 2, 0, ZZ) == dup_pow(f, 2, ZZ)
def test_dup_pdiv():
f = dup_normal([3, 1, 1, 5], ZZ)
g = dup_normal([5, -3, 1], ZZ)
q = dup_normal([15, 14], ZZ)
r = dup_normal([52, 111], ZZ)
assert dup_pdiv(f, g, ZZ) == (q, r)
assert dup_pquo(f, g, ZZ) == q
assert dup_prem(f, g, ZZ) == r
raises(ExactQuotientFailed, lambda: dup_pexquo(f, g, ZZ))
f = dup_normal([3, 1, 1, 5], QQ)
g = dup_normal([5, -3, 1], QQ)
q = dup_normal([15, 14], QQ)
r = dup_normal([52, 111], QQ)
assert dup_pdiv(f, g, QQ) == (q, r)
assert dup_pquo(f, g, QQ) == q
assert dup_prem(f, g, QQ) == r
raises(ExactQuotientFailed, lambda: dup_pexquo(f, g, QQ))
def test_dmp_pdiv():
f = dmp_normal([[1], [], [1, 0, 0]], 1, ZZ)
g = dmp_normal([[1], [-1, 0]], 1, ZZ)
q = dmp_normal([[1], [1, 0]], 1, ZZ)
r = dmp_normal([[2, 0, 0]], 1, ZZ)
assert dmp_pdiv(f, g, 1, ZZ) == (q, r)
assert dmp_pquo(f, g, 1, ZZ) == q
assert dmp_prem(f, g, 1, ZZ) == r
raises(ExactQuotientFailed, lambda: dmp_pexquo(f, g, 1, ZZ))
f = dmp_normal([[1], [], [1, 0, 0]], 1, ZZ)
g = dmp_normal([[2], [-2, 0]], 1, ZZ)
q = dmp_normal([[2], [2, 0]], 1, ZZ)
r = dmp_normal([[8, 0, 0]], 1, ZZ)
assert dmp_pdiv(f, g, 1, ZZ) == (q, r)
assert dmp_pquo(f, g, 1, ZZ) == q
assert dmp_prem(f, g, 1, ZZ) == r
raises(ExactQuotientFailed, lambda: dmp_pexquo(f, g, 1, ZZ))
def test_dup_rr_div():
raises(ZeroDivisionError, lambda: dup_rr_div([1, 2, 3], [], ZZ))
f = dup_normal([3, 1, 1, 5], ZZ)
g = dup_normal([5, -3, 1], ZZ)
q, r = [], f
assert dup_rr_div(f, g, ZZ) == (q, r)
def test_dmp_rr_div():
raises(ZeroDivisionError, lambda: dmp_rr_div([[1, 2], [3]], [[]], 1, ZZ))
f = dmp_normal([[1], [], [1, 0, 0]], 1, ZZ)
g = dmp_normal([[1], [-1, 0]], 1, ZZ)
q = dmp_normal([[1], [1, 0]], 1, ZZ)
r = dmp_normal([[2, 0, 0]], 1, ZZ)
assert dmp_rr_div(f, g, 1, ZZ) == (q, r)
f = dmp_normal([[1], [], [1, 0, 0]], 1, ZZ)
g = dmp_normal([[-1], [1, 0]], 1, ZZ)
q = dmp_normal([[-1], [-1, 0]], 1, ZZ)
r = dmp_normal([[2, 0, 0]], 1, ZZ)
assert dmp_rr_div(f, g, 1, ZZ) == (q, r)
f = dmp_normal([[1], [], [1, 0, 0]], 1, ZZ)
g = dmp_normal([[2], [-2, 0]], 1, ZZ)
q, r = [[]], f
assert dmp_rr_div(f, g, 1, ZZ) == (q, r)
def test_dup_ff_div():
raises(ZeroDivisionError, lambda: dup_ff_div([1, 2, 3], [], QQ))
f = dup_normal([3, 1, 1, 5], QQ)
g = dup_normal([5, -3, 1], QQ)
q = [QQ(3, 5), QQ(14, 25)]
r = [QQ(52, 25), QQ(111, 25)]
assert dup_ff_div(f, g, QQ) == (q, r)
def test_dup_ff_div_gmpy2():
try:
from gmpy2 import mpq
except ImportError:
return
from sympy.polys.domains import GMPYRationalField
K = GMPYRationalField()
f = [mpq(1,3), mpq(3,2)]
g = [mpq(2,1)]
assert dmp_ff_div(f, g, 0, K) == ([mpq(1,6), mpq(3,4)], [])
f = [mpq(1,2), mpq(1,3), mpq(1,4), mpq(1,5)]
g = [mpq(-1,1), mpq(1,1), mpq(-1,1)]
assert dmp_ff_div(f, g, 0, K) == ([mpq(-1,2), mpq(-5,6)], [mpq(7,12), mpq(-19,30)])
def test_dmp_ff_div():
raises(ZeroDivisionError, lambda: dmp_ff_div([[1, 2], [3]], [[]], 1, QQ))
f = dmp_normal([[1], [], [1, 0, 0]], 1, QQ)
g = dmp_normal([[1], [-1, 0]], 1, QQ)
q = [[QQ(1, 1)], [QQ(1, 1), QQ(0, 1)]]
r = [[QQ(2, 1), QQ(0, 1), QQ(0, 1)]]
assert dmp_ff_div(f, g, 1, QQ) == (q, r)
f = dmp_normal([[1], [], [1, 0, 0]], 1, QQ)
g = dmp_normal([[-1], [1, 0]], 1, QQ)
q = [[QQ(-1, 1)], [QQ(-1, 1), QQ(0, 1)]]
r = [[QQ(2, 1), QQ(0, 1), QQ(0, 1)]]
assert dmp_ff_div(f, g, 1, QQ) == (q, r)
f = dmp_normal([[1], [], [1, 0, 0]], 1, QQ)
g = dmp_normal([[2], [-2, 0]], 1, QQ)
q = [[QQ(1, 2)], [QQ(1, 2), QQ(0, 1)]]
r = [[QQ(2, 1), QQ(0, 1), QQ(0, 1)]]
assert dmp_ff_div(f, g, 1, QQ) == (q, r)
def test_dup_div():
f, g, q, r = [5, 4, 3, 2, 1], [1, 2, 3], [5, -6, 0], [20, 1]
assert dup_div(f, g, ZZ) == (q, r)
assert dup_quo(f, g, ZZ) == q
assert dup_rem(f, g, ZZ) == r
raises(ExactQuotientFailed, lambda: dup_exquo(f, g, ZZ))
f, g, q, r = [5, 4, 3, 2, 1, 0], [1, 2, 0, 0, 9], [5, -6], [15, 2, -44, 54]
assert dup_div(f, g, ZZ) == (q, r)
assert dup_quo(f, g, ZZ) == q
assert dup_rem(f, g, ZZ) == r
raises(ExactQuotientFailed, lambda: dup_exquo(f, g, ZZ))
def test_dmp_div():
f, g, q, r = [5, 4, 3, 2, 1], [1, 2, 3], [5, -6, 0], [20, 1]
assert dmp_div(f, g, 0, ZZ) == (q, r)
assert dmp_quo(f, g, 0, ZZ) == q
assert dmp_rem(f, g, 0, ZZ) == r
raises(ExactQuotientFailed, lambda: dmp_exquo(f, g, 0, ZZ))
f, g, q, r = [[[1]]], [[[2]], [1]], [[[]]], [[[1]]]
assert dmp_div(f, g, 2, ZZ) == (q, r)
assert dmp_quo(f, g, 2, ZZ) == q
assert dmp_rem(f, g, 2, ZZ) == r
raises(ExactQuotientFailed, lambda: dmp_exquo(f, g, 2, ZZ))
def test_dup_max_norm():
assert dup_max_norm([], ZZ) == 0
assert dup_max_norm([1], ZZ) == 1
assert dup_max_norm([1, 4, 2, 3], ZZ) == 4
def test_dmp_max_norm():
assert dmp_max_norm([[[]]], 2, ZZ) == 0
assert dmp_max_norm([[[1]]], 2, ZZ) == 1
assert dmp_max_norm(f_0, 2, ZZ) == 6
def test_dup_l1_norm():
assert dup_l1_norm([], ZZ) == 0
assert dup_l1_norm([1], ZZ) == 1
assert dup_l1_norm([1, 4, 2, 3], ZZ) == 10
def test_dmp_l1_norm():
assert dmp_l1_norm([[[]]], 2, ZZ) == 0
assert dmp_l1_norm([[[1]]], 2, ZZ) == 1
assert dmp_l1_norm(f_0, 2, ZZ) == 31
def test_dup_expand():
assert dup_expand((), ZZ) == [1]
assert dup_expand(([1, 2, 3], [1, 2], [7, 5, 4, 3]), ZZ) == \
dup_mul([1, 2, 3], dup_mul([1, 2], [7, 5, 4, 3], ZZ), ZZ)
def test_dmp_expand():
assert dmp_expand((), 1, ZZ) == [[1]]
assert dmp_expand(([[1], [2], [3]], [[1], [2]], [[7], [5], [4], [3]]), 1, ZZ) == \
dmp_mul([[1], [2], [3]], dmp_mul([[1], [2]], [[7], [5], [
4], [3]], 1, ZZ), 1, ZZ)
| 40,019 | 39.670732 | 90 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/tests/test_rationaltools.py
|
"""Tests for tools for manipulation of rational expressions. """
from sympy.polys.rationaltools import together
from sympy import S, symbols, Rational, sin, exp, Eq, Integral, Mul
from sympy.abc import x, y, z
A, B = symbols('A,B', commutative=False)
def test_together():
assert together(0) == 0
assert together(1) == 1
assert together(x*y*z) == x*y*z
assert together(x + y) == x + y
assert together(1/x) == 1/x
assert together(1/x + 1) == (x + 1)/x
assert together(1/x + 3) == (3*x + 1)/x
assert together(1/x + x) == (x**2 + 1)/x
assert together(1/x + Rational(1, 2)) == (x + 2)/(2*x)
assert together(Rational(1, 2) + x/2) == Mul(S.Half, x + 1, evaluate=False)
assert together(1/x + 2/y) == (2*x + y)/(y*x)
assert together(1/(1 + 1/x)) == x/(1 + x)
assert together(x/(1 + 1/x)) == x**2/(1 + x)
assert together(1/x + 1/y + 1/z) == (x*y + x*z + y*z)/(x*y*z)
assert together(1/(1 + x + 1/y + 1/z)) == y*z/(y + z + y*z + x*y*z)
assert together(1/(x*y) + 1/(x*y)**2) == y**(-2)*x**(-2)*(1 + x*y)
assert together(1/(x*y) + 1/(x*y)**4) == y**(-4)*x**(-4)*(1 + x**3*y**3)
assert together(1/(x**7*y) + 1/(x*y)**4) == y**(-4)*x**(-7)*(x**3 + y**3)
assert together(5/(2 + 6/(3 + 7/(4 + 8/(5 + 9/x))))) == \
(S(5)/2)*((171 + 119*x)/(279 + 203*x))
assert together(1 + 1/(x + 1)**2) == (1 + (x + 1)**2)/(x + 1)**2
assert together(1 + 1/(x*(1 + x))) == (1 + x*(1 + x))/(x*(1 + x))
assert together(
1/(x*(x + 1)) + 1/(x*(x + 2))) == (3 + 2*x)/(x*(1 + x)*(2 + x))
assert together(1 + 1/(2*x + 2)**2) == (4*(x + 1)**2 + 1)/(4*(x + 1)**2)
assert together(sin(1/x + 1/y)) == sin(1/x + 1/y)
assert together(sin(1/x + 1/y), deep=True) == sin((x + y)/(x*y))
assert together(1/exp(x) + 1/(x*exp(x))) == (1 + x)/(x*exp(x))
assert together(1/exp(2*x) + 1/(x*exp(3*x))) == (1 + exp(x)*x)/(x*exp(3*x))
assert together(Integral(1/x + 1/y, x)) == Integral((x + y)/(x*y), x)
assert together(Eq(1/x + 1/y, 1 + 1/z)) == Eq((x + y)/(x*y), (z + 1)/z)
assert together((A*B)**-1 + (B*A)**-1) == (A*B)**-1 + (B*A)**-1
| 2,135 | 36.473684 | 79 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/tests/test_rootisolation.py
|
"""Tests for real and complex root isolation and refinement algorithms. """
from sympy.polys.rings import ring
from sympy.polys.domains import ZZ, QQ, EX
from sympy.polys.polyerrors import DomainError, RefinementFailed
from sympy.utilities.pytest import raises
def test_dup_sturm():
R, x = ring("x", QQ)
assert R.dup_sturm(5) == [1]
assert R.dup_sturm(x) == [x, 1]
f = x**3 - 2*x**2 + 3*x - 5
assert R.dup_sturm(f) == [f, 3*x**2 - 4*x + 3, -QQ(10,9)*x + QQ(13,3), -QQ(3303,100)]
def test_dup_refine_real_root():
R, x = ring("x", ZZ)
f = x**2 - 2
assert R.dup_refine_real_root(f, QQ(1), QQ(1), steps=1) == (QQ(1), QQ(1))
assert R.dup_refine_real_root(f, QQ(1), QQ(1), steps=9) == (QQ(1), QQ(1))
raises(ValueError, lambda: R.dup_refine_real_root(f, QQ(-2), QQ(2)))
s, t = QQ(1, 1), QQ(2, 1)
assert R.dup_refine_real_root(f, s, t, steps=0) == (QQ(1, 1), QQ(2, 1))
assert R.dup_refine_real_root(f, s, t, steps=1) == (QQ(1, 1), QQ(3, 2))
assert R.dup_refine_real_root(f, s, t, steps=2) == (QQ(4, 3), QQ(3, 2))
assert R.dup_refine_real_root(f, s, t, steps=3) == (QQ(7, 5), QQ(3, 2))
assert R.dup_refine_real_root(f, s, t, steps=4) == (QQ(7, 5), QQ(10, 7))
s, t = QQ(1, 1), QQ(3, 2)
assert R.dup_refine_real_root(f, s, t, steps=0) == (QQ(1, 1), QQ(3, 2))
assert R.dup_refine_real_root(f, s, t, steps=1) == (QQ(4, 3), QQ(3, 2))
assert R.dup_refine_real_root(f, s, t, steps=2) == (QQ(7, 5), QQ(3, 2))
assert R.dup_refine_real_root(f, s, t, steps=3) == (QQ(7, 5), QQ(10, 7))
assert R.dup_refine_real_root(f, s, t, steps=4) == (QQ(7, 5), QQ(17, 12))
s, t = QQ(1, 1), QQ(5, 3)
assert R.dup_refine_real_root(f, s, t, steps=0) == (QQ(1, 1), QQ(5, 3))
assert R.dup_refine_real_root(f, s, t, steps=1) == (QQ(1, 1), QQ(3, 2))
assert R.dup_refine_real_root(f, s, t, steps=2) == (QQ(7, 5), QQ(3, 2))
assert R.dup_refine_real_root(f, s, t, steps=3) == (QQ(7, 5), QQ(13, 9))
assert R.dup_refine_real_root(f, s, t, steps=4) == (QQ(7, 5), QQ(27, 19))
s, t = QQ(-1, 1), QQ(-2, 1)
assert R.dup_refine_real_root(f, s, t, steps=0) == (-QQ(2, 1), -QQ(1, 1))
assert R.dup_refine_real_root(f, s, t, steps=1) == (-QQ(3, 2), -QQ(1, 1))
assert R.dup_refine_real_root(f, s, t, steps=2) == (-QQ(3, 2), -QQ(4, 3))
assert R.dup_refine_real_root(f, s, t, steps=3) == (-QQ(3, 2), -QQ(7, 5))
assert R.dup_refine_real_root(f, s, t, steps=4) == (-QQ(10, 7), -QQ(7, 5))
raises(RefinementFailed, lambda: R.dup_refine_real_root(f, QQ(0), QQ(1)))
s, t, u, v, w = QQ(1), QQ(2), QQ(24, 17), QQ(17, 12), QQ(7, 5)
assert R.dup_refine_real_root(f, s, t, eps=QQ(1, 100)) == (u, v)
assert R.dup_refine_real_root(f, s, t, steps=6) == (u, v)
assert R.dup_refine_real_root(f, s, t, eps=QQ(1, 100), steps=5) == (w, v)
assert R.dup_refine_real_root(f, s, t, eps=QQ(1, 100), steps=6) == (u, v)
assert R.dup_refine_real_root(f, s, t, eps=QQ(1, 100), steps=7) == (u, v)
s, t, u, v = QQ(-2), QQ(-1), QQ(-3, 2), QQ(-4, 3)
assert R.dup_refine_real_root(f, s, t, disjoint=QQ(-5)) == (s, t)
assert R.dup_refine_real_root(f, s, t, disjoint=-v) == (s, t)
assert R.dup_refine_real_root(f, s, t, disjoint=v) == (u, v)
s, t, u, v = QQ(1), QQ(2), QQ(4, 3), QQ(3, 2)
assert R.dup_refine_real_root(f, s, t, disjoint=QQ(5)) == (s, t)
assert R.dup_refine_real_root(f, s, t, disjoint=-u) == (s, t)
assert R.dup_refine_real_root(f, s, t, disjoint=u) == (u, v)
def test_dup_isolate_real_roots_sqf():
R, x = ring("x", ZZ)
assert R.dup_isolate_real_roots_sqf(0) == []
assert R.dup_isolate_real_roots_sqf(5) == []
assert R.dup_isolate_real_roots_sqf(x**2 + x) == [(-1, -1), (0, 0)]
assert R.dup_isolate_real_roots_sqf(x**2 - x) == [( 0, 0), (1, 1)]
assert R.dup_isolate_real_roots_sqf(x**4 + x + 1) == []
I = [(-2, -1), (1, 2)]
assert R.dup_isolate_real_roots_sqf(x**2 - 2) == I
assert R.dup_isolate_real_roots_sqf(-x**2 + 2) == I
assert R.dup_isolate_real_roots_sqf(x - 1) == \
[(1, 1)]
assert R.dup_isolate_real_roots_sqf(x**2 - 3*x + 2) == \
[(1, 1), (2, 2)]
assert R.dup_isolate_real_roots_sqf(x**3 - 6*x**2 + 11*x - 6) == \
[(1, 1), (2, 2), (3, 3)]
assert R.dup_isolate_real_roots_sqf(x**4 - 10*x**3 + 35*x**2 - 50*x + 24) == \
[(1, 1), (2, 2), (3, 3), (4, 4)]
assert R.dup_isolate_real_roots_sqf(x**5 - 15*x**4 + 85*x**3 - 225*x**2 + 274*x - 120) == \
[(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)]
assert R.dup_isolate_real_roots_sqf(x - 10) == \
[(10, 10)]
assert R.dup_isolate_real_roots_sqf(x**2 - 30*x + 200) == \
[(10, 10), (20, 20)]
assert R.dup_isolate_real_roots_sqf(x**3 - 60*x**2 + 1100*x - 6000) == \
[(10, 10), (20, 20), (30, 30)]
assert R.dup_isolate_real_roots_sqf(x**4 - 100*x**3 + 3500*x**2 - 50000*x + 240000) == \
[(10, 10), (20, 20), (30, 30), (40, 40)]
assert R.dup_isolate_real_roots_sqf(x**5 - 150*x**4 + 8500*x**3 - 225000*x**2 + 2740000*x - 12000000) == \
[(10, 10), (20, 20), (30, 30), (40, 40), (50, 50)]
assert R.dup_isolate_real_roots_sqf(x + 1) == \
[(-1, -1)]
assert R.dup_isolate_real_roots_sqf(x**2 + 3*x + 2) == \
[(-2, -2), (-1, -1)]
assert R.dup_isolate_real_roots_sqf(x**3 + 6*x**2 + 11*x + 6) == \
[(-3, -3), (-2, -2), (-1, -1)]
assert R.dup_isolate_real_roots_sqf(x**4 + 10*x**3 + 35*x**2 + 50*x + 24) == \
[(-4, -4), (-3, -3), (-2, -2), (-1, -1)]
assert R.dup_isolate_real_roots_sqf(x**5 + 15*x**4 + 85*x**3 + 225*x**2 + 274*x + 120) == \
[(-5, -5), (-4, -4), (-3, -3), (-2, -2), (-1, -1)]
assert R.dup_isolate_real_roots_sqf(x + 10) == \
[(-10, -10)]
assert R.dup_isolate_real_roots_sqf(x**2 + 30*x + 200) == \
[(-20, -20), (-10, -10)]
assert R.dup_isolate_real_roots_sqf(x**3 + 60*x**2 + 1100*x + 6000) == \
[(-30, -30), (-20, -20), (-10, -10)]
assert R.dup_isolate_real_roots_sqf(x**4 + 100*x**3 + 3500*x**2 + 50000*x + 240000) == \
[(-40, -40), (-30, -30), (-20, -20), (-10, -10)]
assert R.dup_isolate_real_roots_sqf(x**5 + 150*x**4 + 8500*x**3 + 225000*x**2 + 2740000*x + 12000000) == \
[(-50, -50), (-40, -40), (-30, -30), (-20, -20), (-10, -10)]
assert R.dup_isolate_real_roots_sqf(x**2 - 5) == [(-3, -2), (2, 3)]
assert R.dup_isolate_real_roots_sqf(x**3 - 5) == [(1, 2)]
assert R.dup_isolate_real_roots_sqf(x**4 - 5) == [(-2, -1), (1, 2)]
assert R.dup_isolate_real_roots_sqf(x**5 - 5) == [(1, 2)]
assert R.dup_isolate_real_roots_sqf(x**6 - 5) == [(-2, -1), (1, 2)]
assert R.dup_isolate_real_roots_sqf(x**7 - 5) == [(1, 2)]
assert R.dup_isolate_real_roots_sqf(x**8 - 5) == [(-2, -1), (1, 2)]
assert R.dup_isolate_real_roots_sqf(x**9 - 5) == [(1, 2)]
assert R.dup_isolate_real_roots_sqf(x**2 - 1) == \
[(-1, -1), (1, 1)]
assert R.dup_isolate_real_roots_sqf(x**3 + 2*x**2 - x - 2) == \
[(-2, -2), (-1, -1), (1, 1)]
assert R.dup_isolate_real_roots_sqf(x**4 - 5*x**2 + 4) == \
[(-2, -2), (-1, -1), (1, 1), (2, 2)]
assert R.dup_isolate_real_roots_sqf(x**5 + 3*x**4 - 5*x**3 - 15*x**2 + 4*x + 12) == \
[(-3, -3), (-2, -2), (-1, -1), (1, 1), (2, 2)]
assert R.dup_isolate_real_roots_sqf(x**6 - 14*x**4 + 49*x**2 - 36) == \
[(-3, -3), (-2, -2), (-1, -1), (1, 1), (2, 2), (3, 3)]
assert R.dup_isolate_real_roots_sqf(2*x**7 + x**6 - 28*x**5 - 14*x**4 + 98*x**3 + 49*x**2 - 72*x - 36) == \
[(-3, -3), (-2, -2), (-1, -1), (-1, 0), (1, 1), (2, 2), (3, 3)]
assert R.dup_isolate_real_roots_sqf(4*x**8 - 57*x**6 + 210*x**4 - 193*x**2 + 36) == \
[(-3, -3), (-2, -2), (-1, -1), (-1, 0), (0, 1), (1, 1), (2, 2), (3, 3)]
f = 9*x**2 - 2
assert R.dup_isolate_real_roots_sqf(f) == \
[(-1, 0), (0, 1)]
assert R.dup_isolate_real_roots_sqf(f, eps=QQ(1, 10)) == \
[(QQ(-1, 2), QQ(-3, 7)), (QQ(3, 7), QQ(1, 2))]
assert R.dup_isolate_real_roots_sqf(f, eps=QQ(1, 100)) == \
[(QQ(-9, 19), QQ(-8, 17)), (QQ(8, 17), QQ(9, 19))]
assert R.dup_isolate_real_roots_sqf(f, eps=QQ(1, 1000)) == \
[(QQ(-33, 70), QQ(-8, 17)), (QQ(8, 17), QQ(33, 70))]
assert R.dup_isolate_real_roots_sqf(f, eps=QQ(1, 10000)) == \
[(QQ(-33, 70), QQ(-107, 227)), (QQ(107, 227), QQ(33, 70))]
assert R.dup_isolate_real_roots_sqf(f, eps=QQ(1, 100000)) == \
[(QQ(-305, 647), QQ(-272, 577)), (QQ(272, 577), QQ(305, 647))]
assert R.dup_isolate_real_roots_sqf(f, eps=QQ(1, 1000000)) == \
[(QQ(-1121, 2378), QQ(-272, 577)), (QQ(272, 577), QQ(1121, 2378))]
f = 200100012*x**5 - 700390052*x**4 + 700490079*x**3 - 200240054*x**2 + 40017*x - 2
assert R.dup_isolate_real_roots_sqf(f) == \
[(QQ(0), QQ(1, 10002)), (QQ(1, 10002), QQ(1, 10002)),
(QQ(1, 2), QQ(1, 2)), (QQ(1), QQ(1)), (QQ(2), QQ(2))]
assert R.dup_isolate_real_roots_sqf(f, eps=QQ(1, 100000)) == \
[(QQ(1, 10003), QQ(1, 10003)), (QQ(1, 10002), QQ(1, 10002)),
(QQ(1, 2), QQ(1, 2)), (QQ(1), QQ(1)), (QQ(2), QQ(2))]
a, b, c, d = 10000090000001, 2000100003, 10000300007, 10000005000008
f = 20001600074001600021*x**4 \
+ 1700135866278935491773999857*x**3 \
- 2000179008931031182161141026995283662899200197*x**2 \
- 800027600594323913802305066986600025*x \
+ 100000950000540000725000008
assert R.dup_isolate_real_roots_sqf(f) == \
[(-a, -a), (-1, 0), (0, 1), (d, d)]
assert R.dup_isolate_real_roots_sqf(f, eps=QQ(1, 100000000000)) == \
[(-QQ(a), -QQ(a)), (-QQ(1, b), -QQ(1, b)), (QQ(1, c), QQ(1, c)), (QQ(d), QQ(d))]
(u, v), B, C, (s, t) = R.dup_isolate_real_roots_sqf(f, fast=True)
assert u < -a < v and B == (-QQ(1), QQ(0)) and C == (QQ(0), QQ(1)) and s < d < t
assert R.dup_isolate_real_roots_sqf(f, fast=True, eps=QQ(1, 100000000000000000000000000000)) == \
[(-QQ(a), -QQ(a)), (-QQ(1, b), -QQ(1, b)), (QQ(1, c), QQ(1, c)), (QQ(d), QQ(d))]
f = -10*x**4 + 8*x**3 + 80*x**2 - 32*x - 160
assert R.dup_isolate_real_roots_sqf(f) == \
[(-2, -2), (-2, -1), (2, 2), (2, 3)]
assert R.dup_isolate_real_roots_sqf(f, eps=QQ(1, 100)) == \
[(-QQ(2), -QQ(2)), (-QQ(23, 14), -QQ(18, 11)), (QQ(2), QQ(2)), (QQ(39, 16), QQ(22, 9))]
f = x - 1
assert R.dup_isolate_real_roots_sqf(f, inf=2) == []
assert R.dup_isolate_real_roots_sqf(f, sup=0) == []
assert R.dup_isolate_real_roots_sqf(f) == [(1, 1)]
assert R.dup_isolate_real_roots_sqf(f, inf=1) == [(1, 1)]
assert R.dup_isolate_real_roots_sqf(f, sup=1) == [(1, 1)]
assert R.dup_isolate_real_roots_sqf(f, inf=1, sup=1) == [(1, 1)]
f = x**2 - 2
assert R.dup_isolate_real_roots_sqf(f, inf=QQ(7, 4)) == []
assert R.dup_isolate_real_roots_sqf(f, inf=QQ(7, 5)) == [(QQ(7, 5), QQ(3, 2))]
assert R.dup_isolate_real_roots_sqf(f, sup=QQ(7, 5)) == [(-2, -1)]
assert R.dup_isolate_real_roots_sqf(f, sup=QQ(7, 4)) == [(-2, -1), (1, QQ(3, 2))]
assert R.dup_isolate_real_roots_sqf(f, sup=-QQ(7, 4)) == []
assert R.dup_isolate_real_roots_sqf(f, sup=-QQ(7, 5)) == [(-QQ(3, 2), -QQ(7, 5))]
assert R.dup_isolate_real_roots_sqf(f, inf=-QQ(7, 5)) == [(1, 2)]
assert R.dup_isolate_real_roots_sqf(f, inf=-QQ(7, 4)) == [(-QQ(3, 2), -1), (1, 2)]
I = [(-2, -1), (1, 2)]
assert R.dup_isolate_real_roots_sqf(f, inf=-2) == I
assert R.dup_isolate_real_roots_sqf(f, sup=+2) == I
assert R.dup_isolate_real_roots_sqf(f, inf=-2, sup=2) == I
R, x = ring("x", QQ)
f = QQ(8, 5)*x**2 - QQ(87374, 3855)*x - QQ(17, 771)
assert R.dup_isolate_real_roots_sqf(f) == [(-1, 0), (14, 15)]
R, x = ring("x", EX)
raises(DomainError, lambda: R.dup_isolate_real_roots_sqf(x + 3))
def test_dup_isolate_real_roots():
R, x = ring("x", ZZ)
assert R.dup_isolate_real_roots(0) == []
assert R.dup_isolate_real_roots(3) == []
assert R.dup_isolate_real_roots(5*x) == [((0, 0), 1)]
assert R.dup_isolate_real_roots(7*x**4) == [((0, 0), 4)]
assert R.dup_isolate_real_roots(x**2 + x) == [((-1, -1), 1), ((0, 0), 1)]
assert R.dup_isolate_real_roots(x**2 - x) == [((0, 0), 1), ((1, 1), 1)]
assert R.dup_isolate_real_roots(x**4 + x + 1) == []
I = [((-2, -1), 1), ((1, 2), 1)]
assert R.dup_isolate_real_roots(x**2 - 2) == I
assert R.dup_isolate_real_roots(-x**2 + 2) == I
f = 16*x**14 - 96*x**13 + 24*x**12 + 936*x**11 - 1599*x**10 - 2880*x**9 + 9196*x**8 \
+ 552*x**7 - 21831*x**6 + 13968*x**5 + 21690*x**4 - 26784*x**3 - 2916*x**2 + 15552*x - 5832
g = R.dup_sqf_part(f)
assert R.dup_isolate_real_roots(f) == \
[((-QQ(2), -QQ(3, 2)), 2), ((-QQ(3, 2), -QQ(1, 1)), 3), ((QQ(1), QQ(3, 2)), 3),
((QQ(3, 2), QQ(3, 2)), 4), ((QQ(5, 3), QQ(2)), 2)]
assert R.dup_isolate_real_roots_sqf(g) == \
[(-QQ(2), -QQ(3, 2)), (-QQ(3, 2), -QQ(1, 1)), (QQ(1), QQ(3, 2)),
(QQ(3, 2), QQ(3, 2)), (QQ(3, 2), QQ(2))]
assert R.dup_isolate_real_roots(g) == \
[((-QQ(2), -QQ(3, 2)), 1), ((-QQ(3, 2), -QQ(1, 1)), 1), ((QQ(1), QQ(3, 2)), 1),
((QQ(3, 2), QQ(3, 2)), 1), ((QQ(3, 2), QQ(2)), 1)]
f = x - 1
assert R.dup_isolate_real_roots(f, inf=2) == []
assert R.dup_isolate_real_roots(f, sup=0) == []
assert R.dup_isolate_real_roots(f) == [((1, 1), 1)]
assert R.dup_isolate_real_roots(f, inf=1) == [((1, 1), 1)]
assert R.dup_isolate_real_roots(f, sup=1) == [((1, 1), 1)]
assert R.dup_isolate_real_roots(f, inf=1, sup=1) == [((1, 1), 1)]
f = x**4 - 4*x**2 + 4
assert R.dup_isolate_real_roots(f, inf=QQ(7, 4)) == []
assert R.dup_isolate_real_roots(f, inf=QQ(7, 5)) == [((QQ(7, 5), QQ(3, 2)), 2)]
assert R.dup_isolate_real_roots(f, sup=QQ(7, 5)) == [((-2, -1), 2)]
assert R.dup_isolate_real_roots(f, sup=QQ(7, 4)) == [((-2, -1), 2), ((1, QQ(3, 2)), 2)]
assert R.dup_isolate_real_roots(f, sup=-QQ(7, 4)) == []
assert R.dup_isolate_real_roots(f, sup=-QQ(7, 5)) == [((-QQ(3, 2), -QQ(7, 5)), 2)]
assert R.dup_isolate_real_roots(f, inf=-QQ(7, 5)) == [((1, 2), 2)]
assert R.dup_isolate_real_roots(f, inf=-QQ(7, 4)) == [((-QQ(3, 2), -1), 2), ((1, 2), 2)]
I = [((-2, -1), 2), ((1, 2), 2)]
assert R.dup_isolate_real_roots(f, inf=-2) == I
assert R.dup_isolate_real_roots(f, sup=+2) == I
assert R.dup_isolate_real_roots(f, inf=-2, sup=2) == I
f = x**11 - 3*x**10 - x**9 + 11*x**8 - 8*x**7 - 8*x**6 + 12*x**5 - 4*x**4
assert R.dup_isolate_real_roots(f, basis=False) == \
[((-2, -1), 2), ((0, 0), 4), ((1, 1), 3), ((1, 2), 2)]
assert R.dup_isolate_real_roots(f, basis=True) == \
[((-2, -1), 2, [1, 0, -2]), ((0, 0), 4, [1, 0]), ((1, 1), 3, [1, -1]), ((1, 2), 2, [1, 0, -2])]
f = (x**45 - 45*x**44 + 990*x**43 - 1)
g = (x**46 - 15180*x**43 + 9366819*x**40 - 53524680*x**39 + 260932815*x**38 - 1101716330*x**37 + 4076350421*x**36 - 13340783196*x**35 + 38910617655*x**34 - 101766230790*x**33 + 239877544005*x**32 - 511738760544*x**31 + 991493848554*x**30 - 1749695026860*x**29 + 2818953098830*x**28 - 4154246671960*x**27 + 5608233007146*x**26 - 6943526580276*x**25 + 7890371113950*x**24 - 8233430727600*x**23 + 7890371113950*x**22 - 6943526580276*x**21 + 5608233007146*x**20 - 4154246671960*x**19 + 2818953098830*x**18 - 1749695026860*x**17 + 991493848554*x**16 - 511738760544*x**15 + 239877544005*x**14 - 101766230790*x**13 + 38910617655*x**12 - 13340783196*x**11 + 4076350421*x**10 - 1101716330*x**9 + 260932815*x**8 - 53524680*x**7 + 9366819*x**6 - 1370754*x**5 + 163185*x**4 - 15180*x**3 + 1035*x**2 - 47*x + 1)
assert R.dup_isolate_real_roots(f*g) == \
[((0, QQ(1, 2)), 1), ((QQ(2, 3), QQ(3, 4)), 1), ((QQ(3, 4), 1), 1), ((6, 7), 1), ((24, 25), 1)]
R, x = ring("x", EX)
raises(DomainError, lambda: R.dup_isolate_real_roots(x + 3))
def test_dup_isolate_real_roots_list():
R, x = ring("x", ZZ)
assert R.dup_isolate_real_roots_list([x**2 + x, x]) == \
[((-1, -1), {0: 1}), ((0, 0), {0: 1, 1: 1})]
assert R.dup_isolate_real_roots_list([x**2 - x, x]) == \
[((0, 0), {0: 1, 1: 1}), ((1, 1), {0: 1})]
assert R.dup_isolate_real_roots_list([x + 1, x + 2, x - 1, x + 1, x - 1, x - 1]) == \
[((-QQ(2), -QQ(2)), {1: 1}), ((-QQ(1), -QQ(1)), {0: 1, 3: 1}), ((QQ(1), QQ(1)), {2: 1, 4: 1, 5: 1})]
assert R.dup_isolate_real_roots_list([x + 1, x + 2, x - 1, x + 1, x - 1, x + 2]) == \
[((-QQ(2), -QQ(2)), {1: 1, 5: 1}), ((-QQ(1), -QQ(1)), {0: 1, 3: 1}), ((QQ(1), QQ(1)), {2: 1, 4: 1})]
f, g = x**4 - 4*x**2 + 4, x - 1
assert R.dup_isolate_real_roots_list([f, g], inf=QQ(7, 4)) == []
assert R.dup_isolate_real_roots_list([f, g], inf=QQ(7, 5)) == \
[((QQ(7, 5), QQ(3, 2)), {0: 2})]
assert R.dup_isolate_real_roots_list([f, g], sup=QQ(7, 5)) == \
[((-2, -1), {0: 2}), ((1, 1), {1: 1})]
assert R.dup_isolate_real_roots_list([f, g], sup=QQ(7, 4)) == \
[((-2, -1), {0: 2}), ((1, 1), {1: 1}), ((1, QQ(3, 2)), {0: 2})]
assert R.dup_isolate_real_roots_list([f, g], sup=-QQ(7, 4)) == []
assert R.dup_isolate_real_roots_list([f, g], sup=-QQ(7, 5)) == \
[((-QQ(3, 2), -QQ(7, 5)), {0: 2})]
assert R.dup_isolate_real_roots_list([f, g], inf=-QQ(7, 5)) == \
[((1, 1), {1: 1}), ((1, 2), {0: 2})]
assert R.dup_isolate_real_roots_list([f, g], inf=-QQ(7, 4)) == \
[((-QQ(3, 2), -1), {0: 2}), ((1, 1), {1: 1}), ((1, 2), {0: 2})]
f, g = 2*x**2 - 1, x**2 - 2
assert R.dup_isolate_real_roots_list([f, g]) == \
[((-QQ(2), -QQ(1)), {1: 1}), ((-QQ(1), QQ(0)), {0: 1}),
((QQ(0), QQ(1)), {0: 1}), ((QQ(1), QQ(2)), {1: 1})]
assert R.dup_isolate_real_roots_list([f, g], strict=True) == \
[((-QQ(3, 2), -QQ(4, 3)), {1: 1}), ((-QQ(1), -QQ(2, 3)), {0: 1}),
((QQ(2, 3), QQ(1)), {0: 1}), ((QQ(4, 3), QQ(3, 2)), {1: 1})]
f, g = x**2 - 2, x**3 - x**2 - 2*x + 2
assert R.dup_isolate_real_roots_list([f, g]) == \
[((-QQ(2), -QQ(1)), {1: 1, 0: 1}), ((QQ(1), QQ(1)), {1: 1}), ((QQ(1), QQ(2)), {1: 1, 0: 1})]
f, g = x**3 - 2*x, x**5 - x**4 - 2*x**3 + 2*x**2
assert R.dup_isolate_real_roots_list([f, g]) == \
[((-QQ(2), -QQ(1)), {1: 1, 0: 1}), ((QQ(0), QQ(0)), {0: 1, 1: 2}),
((QQ(1), QQ(1)), {1: 1}), ((QQ(1), QQ(2)), {1: 1, 0: 1})]
f, g = x**9 - 3*x**8 - x**7 + 11*x**6 - 8*x**5 - 8*x**4 + 12*x**3 - 4*x**2, x**5 - 2*x**4 + 3*x**3 - 4*x**2 + 2*x
assert R.dup_isolate_real_roots_list([f, g], basis=False) == \
[((-2, -1), {0: 2}), ((0, 0), {0: 2, 1: 1}), ((1, 1), {0: 3, 1: 2}), ((1, 2), {0: 2})]
assert R.dup_isolate_real_roots_list([f, g], basis=True) == \
[((-2, -1), {0: 2}, [1, 0, -2]), ((0, 0), {0: 2, 1: 1}, [1, 0]),
((1, 1), {0: 3, 1: 2}, [1, -1]), ((1, 2), {0: 2}, [1, 0, -2])]
R, x = ring("x", EX)
raises(DomainError, lambda: R.dup_isolate_real_roots_list([x + 3]))
def test_dup_isolate_real_roots_list_QQ():
R, x = ring("x", ZZ)
f = x**5 - 200
g = x**5 - 201
assert R.dup_isolate_real_roots_list([f, g]) == \
[((QQ(75, 26), QQ(101, 35)), {0: 1}), ((QQ(309, 107), QQ(26, 9)), {1: 1})]
R, x = ring("x", QQ)
f = -QQ(1, 200)*x**5 + 1
g = -QQ(1, 201)*x**5 + 1
assert R.dup_isolate_real_roots_list([f, g]) == \
[((QQ(75, 26), QQ(101, 35)), {0: 1}), ((QQ(309, 107), QQ(26, 9)), {1: 1})]
def test_dup_count_real_roots():
R, x = ring("x", ZZ)
assert R.dup_count_real_roots(0) == 0
assert R.dup_count_real_roots(7) == 0
f = x - 1
assert R.dup_count_real_roots(f) == 1
assert R.dup_count_real_roots(f, inf=1) == 1
assert R.dup_count_real_roots(f, sup=0) == 0
assert R.dup_count_real_roots(f, sup=1) == 1
assert R.dup_count_real_roots(f, inf=0, sup=1) == 1
assert R.dup_count_real_roots(f, inf=0, sup=2) == 1
assert R.dup_count_real_roots(f, inf=1, sup=2) == 1
f = x**2 - 2
assert R.dup_count_real_roots(f) == 2
assert R.dup_count_real_roots(f, sup=0) == 1
assert R.dup_count_real_roots(f, inf=-1, sup=1) == 0
# parameters for test_dup_count_complex_roots_n(): n = 1..8
a, b = (-QQ(1), -QQ(1)), (QQ(1), QQ(1))
c, d = ( QQ(0), QQ(0)), (QQ(1), QQ(1))
def test_dup_count_complex_roots_1():
R, x = ring("x", ZZ)
# z-1
f = x - 1
assert R.dup_count_complex_roots(f, a, b) == 1
assert R.dup_count_complex_roots(f, c, d) == 1
# z+1
f = x + 1
assert R.dup_count_complex_roots(f, a, b) == 1
assert R.dup_count_complex_roots(f, c, d) == 0
def test_dup_count_complex_roots_2():
R, x = ring("x", ZZ)
# (z-1)*(z)
f = x**2 - x
assert R.dup_count_complex_roots(f, a, b) == 2
assert R.dup_count_complex_roots(f, c, d) == 2
# (z-1)*(-z)
f = -x**2 + x
assert R.dup_count_complex_roots(f, a, b) == 2
assert R.dup_count_complex_roots(f, c, d) == 2
# (z+1)*(z)
f = x**2 + x
assert R.dup_count_complex_roots(f, a, b) == 2
assert R.dup_count_complex_roots(f, c, d) == 1
# (z+1)*(-z)
f = -x**2 - x
assert R.dup_count_complex_roots(f, a, b) == 2
assert R.dup_count_complex_roots(f, c, d) == 1
def test_dup_count_complex_roots_3():
R, x = ring("x", ZZ)
# (z-1)*(z+1)
f = x**2 - 1
assert R.dup_count_complex_roots(f, a, b) == 2
assert R.dup_count_complex_roots(f, c, d) == 1
# (z-1)*(z+1)*(z)
f = x**3 - x
assert R.dup_count_complex_roots(f, a, b) == 3
assert R.dup_count_complex_roots(f, c, d) == 2
# (z-1)*(z+1)*(-z)
f = -x**3 + x
assert R.dup_count_complex_roots(f, a, b) == 3
assert R.dup_count_complex_roots(f, c, d) == 2
def test_dup_count_complex_roots_4():
R, x = ring("x", ZZ)
# (z-I)*(z+I)
f = x**2 + 1
assert R.dup_count_complex_roots(f, a, b) == 2
assert R.dup_count_complex_roots(f, c, d) == 1
# (z-I)*(z+I)*(z)
f = x**3 + x
assert R.dup_count_complex_roots(f, a, b) == 3
assert R.dup_count_complex_roots(f, c, d) == 2
# (z-I)*(z+I)*(-z)
f = -x**3 - x
assert R.dup_count_complex_roots(f, a, b) == 3
assert R.dup_count_complex_roots(f, c, d) == 2
# (z-I)*(z+I)*(z-1)
f = x**3 - x**2 + x - 1
assert R.dup_count_complex_roots(f, a, b) == 3
assert R.dup_count_complex_roots(f, c, d) == 2
# (z-I)*(z+I)*(z-1)*(z)
f = x**4 - x**3 + x**2 - x
assert R.dup_count_complex_roots(f, a, b) == 4
assert R.dup_count_complex_roots(f, c, d) == 3
# (z-I)*(z+I)*(z-1)*(-z)
f = -x**4 + x**3 - x**2 + x
assert R.dup_count_complex_roots(f, a, b) == 4
assert R.dup_count_complex_roots(f, c, d) == 3
# (z-I)*(z+I)*(z-1)*(z+1)
f = x**4 - 1
assert R.dup_count_complex_roots(f, a, b) == 4
assert R.dup_count_complex_roots(f, c, d) == 2
# (z-I)*(z+I)*(z-1)*(z+1)*(z)
f = x**5 - x
assert R.dup_count_complex_roots(f, a, b) == 5
assert R.dup_count_complex_roots(f, c, d) == 3
# (z-I)*(z+I)*(z-1)*(z+1)*(-z)
f = -x**5 + x
assert R.dup_count_complex_roots(f, a, b) == 5
assert R.dup_count_complex_roots(f, c, d) == 3
def test_dup_count_complex_roots_5():
R, x = ring("x", ZZ)
# (z-I+1)*(z+I+1)
f = x**2 + 2*x + 2
assert R.dup_count_complex_roots(f, a, b) == 2
assert R.dup_count_complex_roots(f, c, d) == 0
# (z-I+1)*(z+I+1)*(z-1)
f = x**3 + x**2 - 2
assert R.dup_count_complex_roots(f, a, b) == 3
assert R.dup_count_complex_roots(f, c, d) == 1
# (z-I+1)*(z+I+1)*(z-1)*z
f = x**4 + x**3 - 2*x
assert R.dup_count_complex_roots(f, a, b) == 4
assert R.dup_count_complex_roots(f, c, d) == 2
# (z-I+1)*(z+I+1)*(z+1)
f = x**3 + 3*x**2 + 4*x + 2
assert R.dup_count_complex_roots(f, a, b) == 3
assert R.dup_count_complex_roots(f, c, d) == 0
# (z-I+1)*(z+I+1)*(z+1)*z
f = x**4 + 3*x**3 + 4*x**2 + 2*x
assert R.dup_count_complex_roots(f, a, b) == 4
assert R.dup_count_complex_roots(f, c, d) == 1
# (z-I+1)*(z+I+1)*(z-1)*(z+1)
f = x**4 + 2*x**3 + x**2 - 2*x - 2
assert R.dup_count_complex_roots(f, a, b) == 4
assert R.dup_count_complex_roots(f, c, d) == 1
# (z-I+1)*(z+I+1)*(z-1)*(z+1)*z
f = x**5 + 2*x**4 + x**3 - 2*x**2 - 2*x
assert R.dup_count_complex_roots(f, a, b) == 5
assert R.dup_count_complex_roots(f, c, d) == 2
def test_dup_count_complex_roots_6():
R, x = ring("x", ZZ)
# (z-I-1)*(z+I-1)
f = x**2 - 2*x + 2
assert R.dup_count_complex_roots(f, a, b) == 2
assert R.dup_count_complex_roots(f, c, d) == 1
# (z-I-1)*(z+I-1)*(z-1)
f = x**3 - 3*x**2 + 4*x - 2
assert R.dup_count_complex_roots(f, a, b) == 3
assert R.dup_count_complex_roots(f, c, d) == 2
# (z-I-1)*(z+I-1)*(z-1)*z
f = x**4 - 3*x**3 + 4*x**2 - 2*x
assert R.dup_count_complex_roots(f, a, b) == 4
assert R.dup_count_complex_roots(f, c, d) == 3
# (z-I-1)*(z+I-1)*(z+1)
f = x**3 - x**2 + 2
assert R.dup_count_complex_roots(f, a, b) == 3
assert R.dup_count_complex_roots(f, c, d) == 1
# (z-I-1)*(z+I-1)*(z+1)*z
f = x**4 - x**3 + 2*x
assert R.dup_count_complex_roots(f, a, b) == 4
assert R.dup_count_complex_roots(f, c, d) == 2
# (z-I-1)*(z+I-1)*(z-1)*(z+1)
f = x**4 - 2*x**3 + x**2 + 2*x - 2
assert R.dup_count_complex_roots(f, a, b) == 4
assert R.dup_count_complex_roots(f, c, d) == 2
# (z-I-1)*(z+I-1)*(z-1)*(z+1)*z
f = x**5 - 2*x**4 + x**3 + 2*x**2 - 2*x
assert R.dup_count_complex_roots(f, a, b) == 5
assert R.dup_count_complex_roots(f, c, d) == 3
def test_dup_count_complex_roots_7():
R, x = ring("x", ZZ)
# (z-I-1)*(z+I-1)*(z-I+1)*(z+I+1)
f = x**4 + 4
assert R.dup_count_complex_roots(f, a, b) == 4
assert R.dup_count_complex_roots(f, c, d) == 1
# (z-I-1)*(z+I-1)*(z-I+1)*(z+I+1)*(z-2)
f = x**5 - 2*x**4 + 4*x - 8
assert R.dup_count_complex_roots(f, a, b) == 4
assert R.dup_count_complex_roots(f, c, d) == 1
# (z-I-1)*(z+I-1)*(z-I+1)*(z+I+1)*(z**2-2)
f = x**6 - 2*x**4 + 4*x**2 - 8
assert R.dup_count_complex_roots(f, a, b) == 4
assert R.dup_count_complex_roots(f, c, d) == 1
# (z-I-1)*(z+I-1)*(z-I+1)*(z+I+1)*(z-1)
f = x**5 - x**4 + 4*x - 4
assert R.dup_count_complex_roots(f, a, b) == 5
assert R.dup_count_complex_roots(f, c, d) == 2
# (z-I-1)*(z+I-1)*(z-I+1)*(z+I+1)*(z-1)*z
f = x**6 - x**5 + 4*x**2 - 4*x
assert R.dup_count_complex_roots(f, a, b) == 6
assert R.dup_count_complex_roots(f, c, d) == 3
# (z-I-1)*(z+I-1)*(z-I+1)*(z+I+1)*(z+1)
f = x**5 + x**4 + 4*x + 4
assert R.dup_count_complex_roots(f, a, b) == 5
assert R.dup_count_complex_roots(f, c, d) == 1
# (z-I-1)*(z+I-1)*(z-I+1)*(z+I+1)*(z+1)*z
f = x**6 + x**5 + 4*x**2 + 4*x
assert R.dup_count_complex_roots(f, a, b) == 6
assert R.dup_count_complex_roots(f, c, d) == 2
# (z-I-1)*(z+I-1)*(z-I+1)*(z+I+1)*(z-1)*(z+1)
f = x**6 - x**4 + 4*x**2 - 4
assert R.dup_count_complex_roots(f, a, b) == 6
assert R.dup_count_complex_roots(f, c, d) == 2
# (z-I-1)*(z+I-1)*(z-I+1)*(z+I+1)*(z-1)*(z+1)*z
f = x**7 - x**5 + 4*x**3 - 4*x
assert R.dup_count_complex_roots(f, a, b) == 7
assert R.dup_count_complex_roots(f, c, d) == 3
# (z-I-1)*(z+I-1)*(z-I+1)*(z+I+1)*(z-1)*(z+1)*(z-I)*(z+I)
f = x**8 + 3*x**4 - 4
assert R.dup_count_complex_roots(f, a, b) == 8
assert R.dup_count_complex_roots(f, c, d) == 3
def test_dup_count_complex_roots_8():
R, x = ring("x", ZZ)
# (z-I-1)*(z+I-1)*(z-I+1)*(z+I+1)*(z-1)*(z+1)*(z-I)*(z+I)*z
f = x**9 + 3*x**5 - 4*x
assert R.dup_count_complex_roots(f, a, b) == 9
assert R.dup_count_complex_roots(f, c, d) == 4
# (z-I-1)*(z+I-1)*(z-I+1)*(z+I+1)*(z-1)*(z+1)*(z-I)*(z+I)*(z**2-2)*z
f = x**11 - 2*x**9 + 3*x**7 - 6*x**5 - 4*x**3 + 8*x
assert R.dup_count_complex_roots(f, a, b) == 9
assert R.dup_count_complex_roots(f, c, d) == 4
def test_dup_count_complex_roots_implicit():
R, x = ring("x", ZZ)
# z*(z-1)*(z+1)*(z-I)*(z+I)
f = x**5 - x
assert R.dup_count_complex_roots(f) == 5
assert R.dup_count_complex_roots(f, sup=(0, 0)) == 3
assert R.dup_count_complex_roots(f, inf=(0, 0)) == 3
def test_dup_count_complex_roots_exclude():
R, x = ring("x", ZZ)
# z*(z-1)*(z+1)*(z-I)*(z+I)
f = x**5 - x
a, b = (-QQ(1), QQ(0)), (QQ(1), QQ(1))
assert R.dup_count_complex_roots(f, a, b) == 4
assert R.dup_count_complex_roots(f, a, b, exclude=['S']) == 3
assert R.dup_count_complex_roots(f, a, b, exclude=['N']) == 3
assert R.dup_count_complex_roots(f, a, b, exclude=['S', 'N']) == 2
assert R.dup_count_complex_roots(f, a, b, exclude=['E']) == 4
assert R.dup_count_complex_roots(f, a, b, exclude=['W']) == 4
assert R.dup_count_complex_roots(f, a, b, exclude=['E', 'W']) == 4
assert R.dup_count_complex_roots(f, a, b, exclude=['N', 'S', 'E', 'W']) == 2
assert R.dup_count_complex_roots(f, a, b, exclude=['SW']) == 3
assert R.dup_count_complex_roots(f, a, b, exclude=['SE']) == 3
assert R.dup_count_complex_roots(f, a, b, exclude=['SW', 'SE']) == 2
assert R.dup_count_complex_roots(f, a, b, exclude=['SW', 'SE', 'S']) == 1
assert R.dup_count_complex_roots(f, a, b, exclude=['SW', 'SE', 'S', 'N']) == 0
a, b = (QQ(0), QQ(0)), (QQ(1), QQ(1))
assert R.dup_count_complex_roots(f, a, b, exclude=True) == 1
def test_dup_isolate_complex_roots_sqf():
R, x = ring("x", ZZ)
f = x**2 - 2*x + 3
assert R.dup_isolate_complex_roots_sqf(f) == \
[((0, -6), (6, 0)), ((0, 0), (6, 6))]
assert [ r.as_tuple() for r in R.dup_isolate_complex_roots_sqf(f, blackbox=True) ] == \
[((0, -6), (6, 0)), ((0, 0), (6, 6))]
assert R.dup_isolate_complex_roots_sqf(f, eps=QQ(1, 10)) == \
[((QQ(15, 16), -QQ(3, 2)), (QQ(33, 32), -QQ(45, 32))),
((QQ(15, 16), QQ(45, 32)), (QQ(33, 32), QQ(3, 2)))]
assert R.dup_isolate_complex_roots_sqf(f, eps=QQ(1, 100)) == \
[((QQ(255, 256), -QQ(363, 256)), (QQ(513, 512), -QQ(723, 512))),
((QQ(255, 256), QQ(723, 512)), (QQ(513, 512), QQ(363, 256)))]
f = 7*x**4 - 19*x**3 + 20*x**2 + 17*x + 20
assert R.dup_isolate_complex_roots_sqf(f) == \
[((-QQ(40, 7), -QQ(40, 7)), (0, 0)), ((-QQ(40, 7), 0), (0, QQ(40, 7))),
((0, -QQ(40, 7)), (QQ(40, 7), 0)), ((0, 0), (QQ(40, 7), QQ(40, 7)))]
def test_dup_isolate_all_roots_sqf():
R, x = ring("x", ZZ)
f = 4*x**4 - x**3 + 2*x**2 + 5*x
assert R.dup_isolate_all_roots_sqf(f) == \
([(-1, 0), (0, 0)],
[((0, -QQ(5, 2)), (QQ(5, 2), 0)), ((0, 0), (QQ(5, 2), QQ(5, 2)))])
assert R.dup_isolate_all_roots_sqf(f, eps=QQ(1, 10)) == \
([(QQ(-7, 8), QQ(-6, 7)), (0, 0)],
[((QQ(35, 64), -QQ(35, 32)), (QQ(5, 8), -QQ(65, 64))), ((QQ(35, 64), QQ(65, 64)), (QQ(5, 8), QQ(35, 32)))])
def test_dup_isolate_all_roots():
R, x = ring("x", ZZ)
f = 4*x**4 - x**3 + 2*x**2 + 5*x
assert R.dup_isolate_all_roots(f) == \
([((-1, 0), 1), ((0, 0), 1)],
[(((0, -QQ(5, 2)), (QQ(5, 2), 0)), 1),
(((0, 0), (QQ(5, 2), QQ(5, 2))), 1)])
assert R.dup_isolate_all_roots(f, eps=QQ(1, 10)) == \
([((QQ(-7, 8), QQ(-6, 7)), 1), ((0, 0), 1)],
[(((QQ(35, 64), -QQ(35, 32)), (QQ(5, 8), -QQ(65, 64))), 1),
(((QQ(35, 64), QQ(65, 64)), (QQ(5, 8), QQ(35, 32))), 1)])
f = x**5 + x**4 - 2*x**3 - 2*x**2 + x + 1
raises(NotImplementedError, lambda: R.dup_isolate_all_roots(f))
| 31,462 | 38.576101 | 802 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/tests/test_numberfields.py
|
"""Tests for computational algebraic number field theory. """
from sympy import (S, Rational, Symbol, Poly, sqrt, I, oo, Tuple, expand,
pi, cos, sin, exp)
from sympy.utilities.pytest import raises, slow
from sympy.core.compatibility import range
from sympy.polys.numberfields import (
minimal_polynomial,
primitive_element,
is_isomorphism_possible,
field_isomorphism_pslq,
field_isomorphism,
to_number_field,
AlgebraicNumber,
isolate, IntervalPrinter,
)
from sympy.polys.polyerrors import (
IsomorphismFailed,
NotAlgebraic,
GeneratorsError,
)
from sympy.polys.polyclasses import DMP
from sympy.polys.domains import QQ
from sympy.polys.rootoftools import rootof
from sympy.polys.polytools import degree
from sympy.abc import x, y, z
Q = Rational
def test_minimal_polynomial():
assert minimal_polynomial(-7, x) == x + 7
assert minimal_polynomial(-1, x) == x + 1
assert minimal_polynomial( 0, x) == x
assert minimal_polynomial( 1, x) == x - 1
assert minimal_polynomial( 7, x) == x - 7
assert minimal_polynomial(sqrt(2), x) == x**2 - 2
assert minimal_polynomial(sqrt(5), x) == x**2 - 5
assert minimal_polynomial(sqrt(6), x) == x**2 - 6
assert minimal_polynomial(2*sqrt(2), x) == x**2 - 8
assert minimal_polynomial(3*sqrt(5), x) == x**2 - 45
assert minimal_polynomial(4*sqrt(6), x) == x**2 - 96
assert minimal_polynomial(2*sqrt(2) + 3, x) == x**2 - 6*x + 1
assert minimal_polynomial(3*sqrt(5) + 6, x) == x**2 - 12*x - 9
assert minimal_polynomial(4*sqrt(6) + 7, x) == x**2 - 14*x - 47
assert minimal_polynomial(2*sqrt(2) - 3, x) == x**2 + 6*x + 1
assert minimal_polynomial(3*sqrt(5) - 6, x) == x**2 + 12*x - 9
assert minimal_polynomial(4*sqrt(6) - 7, x) == x**2 + 14*x - 47
assert minimal_polynomial(sqrt(1 + sqrt(6)), x) == x**4 - 2*x**2 - 5
assert minimal_polynomial(sqrt(I + sqrt(6)), x) == x**8 - 10*x**4 + 49
assert minimal_polynomial(2*I + sqrt(2 + I), x) == x**4 + 4*x**2 + 8*x + 37
assert minimal_polynomial(sqrt(2) + sqrt(3), x) == x**4 - 10*x**2 + 1
assert minimal_polynomial(
sqrt(2) + sqrt(3) + sqrt(6), x) == x**4 - 22*x**2 - 48*x - 23
a = 1 - 9*sqrt(2) + 7*sqrt(3)
assert minimal_polynomial(
1/a, x) == 392*x**4 - 1232*x**3 + 612*x**2 + 4*x - 1
assert minimal_polynomial(
1/sqrt(a), x) == 392*x**8 - 1232*x**6 + 612*x**4 + 4*x**2 - 1
raises(NotAlgebraic, lambda: minimal_polynomial(oo, x))
raises(NotAlgebraic, lambda: minimal_polynomial(2**y, x))
raises(NotAlgebraic, lambda: minimal_polynomial(sin(1), x))
assert minimal_polynomial(sqrt(2)).dummy_eq(x**2 - 2)
assert minimal_polynomial(sqrt(2), x) == x**2 - 2
assert minimal_polynomial(sqrt(2), polys=True) == Poly(x**2 - 2)
assert minimal_polynomial(sqrt(2), x, polys=True) == Poly(x**2 - 2)
assert minimal_polynomial(sqrt(2), x, polys=True, compose=False) == Poly(x**2 - 2)
a = AlgebraicNumber(sqrt(2))
b = AlgebraicNumber(sqrt(3))
assert minimal_polynomial(a, x) == x**2 - 2
assert minimal_polynomial(b, x) == x**2 - 3
assert minimal_polynomial(a, x, polys=True) == Poly(x**2 - 2)
assert minimal_polynomial(b, x, polys=True) == Poly(x**2 - 3)
assert minimal_polynomial(sqrt(a/2 + 17), x) == 2*x**4 - 68*x**2 + 577
assert minimal_polynomial(sqrt(b/2 + 17), x) == 4*x**4 - 136*x**2 + 1153
a, b = sqrt(2)/3 + 7, AlgebraicNumber(sqrt(2)/3 + 7)
f = 81*x**8 - 2268*x**6 - 4536*x**5 + 22644*x**4 + 63216*x**3 - \
31608*x**2 - 189648*x + 141358
assert minimal_polynomial(sqrt(a) + sqrt(sqrt(a)), x) == f
assert minimal_polynomial(sqrt(b) + sqrt(sqrt(b)), x) == f
assert minimal_polynomial(
a**Q(3, 2), x) == 729*x**4 - 506898*x**2 + 84604519
# issue 5994
eq = S('''
-1/(800*sqrt(-1/240 + 1/(18000*(-1/17280000 +
sqrt(15)*I/28800000)**(1/3)) + 2*(-1/17280000 +
sqrt(15)*I/28800000)**(1/3)))''')
assert minimal_polynomial(eq, x) == 8000*x**2 - 1
ex = 1 + sqrt(2) + sqrt(3)
mp = minimal_polynomial(ex, x)
assert mp == x**4 - 4*x**3 - 4*x**2 + 16*x - 8
ex = 1/(1 + sqrt(2) + sqrt(3))
mp = minimal_polynomial(ex, x)
assert mp == 8*x**4 - 16*x**3 + 4*x**2 + 4*x - 1
p = (expand((1 + sqrt(2) - 2*sqrt(3) + sqrt(7))**3))**Rational(1, 3)
mp = minimal_polynomial(p, x)
assert mp == x**8 - 8*x**7 - 56*x**6 + 448*x**5 + 480*x**4 - 5056*x**3 + 1984*x**2 + 7424*x - 3008
p = expand((1 + sqrt(2) - 2*sqrt(3) + sqrt(7))**3)
mp = minimal_polynomial(p, x)
assert mp == x**8 - 512*x**7 - 118208*x**6 + 31131136*x**5 + 647362560*x**4 - 56026611712*x**3 + 116994310144*x**2 + 404854931456*x - 27216576512
assert minimal_polynomial(S("-sqrt(5)/2 - 1/2 + (-sqrt(5)/2 - 1/2)**2"), x) == x - 1
a = 1 + sqrt(2)
assert minimal_polynomial((a*sqrt(2) + a)**3, x) == x**2 - 198*x + 1
p = 1/(1 + sqrt(2) + sqrt(3))
assert minimal_polynomial(p, x, compose=False) == 8*x**4 - 16*x**3 + 4*x**2 + 4*x - 1
p = 2/(1 + sqrt(2) + sqrt(3))
assert minimal_polynomial(p, x, compose=False) == x**4 - 4*x**3 + 2*x**2 + 4*x - 2
assert minimal_polynomial(1 + sqrt(2)*I, x, compose=False) == x**2 - 2*x + 3
assert minimal_polynomial(1/(1 + sqrt(2)) + 1, x, compose=False) == x**2 - 2
assert minimal_polynomial(sqrt(2)*I + I*(1 + sqrt(2)), x,
compose=False) == x**4 + 18*x**2 + 49
def test_minimal_polynomial_hi_prec():
p = 1/sqrt(1 - 9*sqrt(2) + 7*sqrt(3) + S(1)/10**30)
mp = minimal_polynomial(p, x)
# checked with Wolfram Alpha
assert mp.coeff(x**6) == -1232000000000000000000000000001223999999999999999999999999999987999999999999999999999999999996000000000000000000000000000000
def test_minimal_polynomial_sq():
from sympy import Add, expand_multinomial
p = expand_multinomial((1 + 5*sqrt(2) + 2*sqrt(3))**3)
mp = minimal_polynomial(p**Rational(1, 3), x)
assert mp == x**4 - 4*x**3 - 118*x**2 + 244*x + 1321
p = expand_multinomial((1 + sqrt(2) - 2*sqrt(3) + sqrt(7))**3)
mp = minimal_polynomial(p**Rational(1, 3), x)
assert mp == x**8 - 8*x**7 - 56*x**6 + 448*x**5 + 480*x**4 - 5056*x**3 + 1984*x**2 + 7424*x - 3008
p = Add(*[sqrt(i) for i in range(1, 12)])
mp = minimal_polynomial(p, x)
assert mp.subs({x: 0}) == -71965773323122507776
def test_minpoly_compose():
# issue 6868
eq = S('''
-1/(800*sqrt(-1/240 + 1/(18000*(-1/17280000 +
sqrt(15)*I/28800000)**(1/3)) + 2*(-1/17280000 +
sqrt(15)*I/28800000)**(1/3)))''')
mp = minimal_polynomial(eq + 3, x)
assert mp == 8000*x**2 - 48000*x + 71999
# issue 5888
assert minimal_polynomial(exp(I*pi/8), x) == x**8 + 1
mp = minimal_polynomial(sin(pi/7) + sqrt(2), x)
assert mp == 4096*x**12 - 63488*x**10 + 351488*x**8 - 826496*x**6 + \
770912*x**4 - 268432*x**2 + 28561
mp = minimal_polynomial(cos(pi/7) + sqrt(2), x)
assert mp == 64*x**6 - 64*x**5 - 432*x**4 + 304*x**3 + 712*x**2 - \
232*x - 239
mp = minimal_polynomial(exp(I*pi/7) + sqrt(2), x)
assert mp == x**12 - 2*x**11 - 9*x**10 + 16*x**9 + 43*x**8 - 70*x**7 - 97*x**6 + 126*x**5 + 211*x**4 - 212*x**3 - 37*x**2 + 142*x + 127
mp = minimal_polynomial(sin(pi/7) + sqrt(2), x)
assert mp == 4096*x**12 - 63488*x**10 + 351488*x**8 - 826496*x**6 + \
770912*x**4 - 268432*x**2 + 28561
mp = minimal_polynomial(cos(pi/7) + sqrt(2), x)
assert mp == 64*x**6 - 64*x**5 - 432*x**4 + 304*x**3 + 712*x**2 - \
232*x - 239
mp = minimal_polynomial(exp(I*pi/7) + sqrt(2), x)
assert mp == x**12 - 2*x**11 - 9*x**10 + 16*x**9 + 43*x**8 - 70*x**7 - 97*x**6 + 126*x**5 + 211*x**4 - 212*x**3 - 37*x**2 + 142*x + 127
mp = minimal_polynomial(exp(2*I*pi/7), x)
assert mp == x**6 + x**5 + x**4 + x**3 + x**2 + x + 1
mp = minimal_polynomial(exp(2*I*pi/15), x)
assert mp == x**8 - x**7 + x**5 - x**4 + x**3 - x + 1
mp = minimal_polynomial(cos(2*pi/7), x)
assert mp == 8*x**3 + 4*x**2 - 4*x - 1
mp = minimal_polynomial(sin(2*pi/7), x)
ex = (5*cos(2*pi/7) - 7)/(9*cos(pi/7) - 5*cos(3*pi/7))
mp = minimal_polynomial(ex, x)
assert mp == x**3 + 2*x**2 - x - 1
assert minimal_polynomial(-1/(2*cos(pi/7)), x) == x**3 + 2*x**2 - x - 1
assert minimal_polynomial(sin(2*pi/15), x) == \
256*x**8 - 448*x**6 + 224*x**4 - 32*x**2 + 1
assert minimal_polynomial(sin(5*pi/14), x) == 8*x**3 - 4*x**2 - 4*x + 1
assert minimal_polynomial(cos(pi/15), x) == 16*x**4 + 8*x**3 - 16*x**2 - 8*x + 1
ex = rootof(x**3 +x*4 + 1, 0)
mp = minimal_polynomial(ex, x)
assert mp == x**3 + 4*x + 1
mp = minimal_polynomial(ex + 1, x)
assert mp == x**3 - 3*x**2 + 7*x - 4
assert minimal_polynomial(exp(I*pi/3), x) == x**2 - x + 1
assert minimal_polynomial(exp(I*pi/4), x) == x**4 + 1
assert minimal_polynomial(exp(I*pi/6), x) == x**4 - x**2 + 1
assert minimal_polynomial(exp(I*pi/9), x) == x**6 - x**3 + 1
assert minimal_polynomial(exp(I*pi/10), x) == x**8 - x**6 + x**4 - x**2 + 1
assert minimal_polynomial(sin(pi/9), x) == 64*x**6 - 96*x**4 + 36*x**2 - 3
assert minimal_polynomial(sin(pi/11), x) == 1024*x**10 - 2816*x**8 + \
2816*x**6 - 1232*x**4 + 220*x**2 - 11
ex = 2**Rational(1, 3)*exp(Rational(2, 3)*I*pi)
assert minimal_polynomial(ex, x) == x**3 - 2
raises(NotAlgebraic, lambda: minimal_polynomial(cos(pi*sqrt(2)), x))
raises(NotAlgebraic, lambda: minimal_polynomial(sin(pi*sqrt(2)), x))
raises(NotAlgebraic, lambda: minimal_polynomial(exp(I*pi*sqrt(2)), x))
# issue 5934
ex = 1/(-36000 - 7200*sqrt(5) + (12*sqrt(10)*sqrt(sqrt(5) + 5) +
24*sqrt(10)*sqrt(-sqrt(5) + 5))**2) + 1
raises(ZeroDivisionError, lambda: minimal_polynomial(ex, x))
ex = sqrt(1 + 2**Rational(1,3)) + sqrt(1 + 2**Rational(1,4)) + sqrt(2)
mp = minimal_polynomial(ex, x)
assert degree(mp) == 48 and mp.subs({x:0}) == -16630256576
def test_minpoly_issue_7113():
# see discussion in https://github.com/sympy/sympy/pull/2234
from sympy.simplify.simplify import nsimplify
r = nsimplify(pi, tolerance=0.000000001)
mp = minimal_polynomial(r, x)
assert mp == 1768292677839237920489538677417507171630859375*x**109 - \
2734577732179183863586489182929671773182898498218854181690460140337930774573792597743853652058046464
def test_minpoly_issue_7574():
ex = -(-1)**Rational(1, 3) + (-1)**Rational(2,3)
assert minimal_polynomial(ex, x) == x + 1
def test_primitive_element():
assert primitive_element([sqrt(2)], x) == (x**2 - 2, [1])
assert primitive_element(
[sqrt(2), sqrt(3)], x) == (x**4 - 10*x**2 + 1, [1, 1])
assert primitive_element([sqrt(2)], x, polys=True) == (Poly(x**2 - 2), [1])
assert primitive_element([sqrt(
2), sqrt(3)], x, polys=True) == (Poly(x**4 - 10*x**2 + 1), [1, 1])
assert primitive_element(
[sqrt(2)], x, ex=True) == (x**2 - 2, [1], [[1, 0]])
assert primitive_element([sqrt(2), sqrt(3)], x, ex=True) == \
(x**4 - 10*x**2 + 1, [1, 1], [[Q(1, 2), 0, -Q(9, 2), 0], [-
Q(1, 2), 0, Q(11, 2), 0]])
assert primitive_element(
[sqrt(2)], x, ex=True, polys=True) == (Poly(x**2 - 2), [1], [[1, 0]])
assert primitive_element([sqrt(2), sqrt(3)], x, ex=True, polys=True) == \
(Poly(x**4 - 10*x**2 + 1), [1, 1], [[Q(1, 2), 0, -Q(9, 2),
0], [-Q(1, 2), 0, Q(11, 2), 0]])
assert primitive_element([sqrt(2)], polys=True) == (Poly(x**2 - 2), [1])
raises(ValueError, lambda: primitive_element([], x, ex=False))
raises(ValueError, lambda: primitive_element([], x, ex=True))
def test_field_isomorphism_pslq():
a = AlgebraicNumber(I)
b = AlgebraicNumber(I*sqrt(3))
raises(NotImplementedError, lambda: field_isomorphism_pslq(a, b))
a = AlgebraicNumber(sqrt(2))
b = AlgebraicNumber(sqrt(3))
c = AlgebraicNumber(sqrt(7))
d = AlgebraicNumber(sqrt(2) + sqrt(3))
e = AlgebraicNumber(sqrt(2) + sqrt(3) + sqrt(7))
assert field_isomorphism_pslq(a, a) == [1, 0]
assert field_isomorphism_pslq(a, b) is None
assert field_isomorphism_pslq(a, c) is None
assert field_isomorphism_pslq(a, d) == [Q(1, 2), 0, -Q(9, 2), 0]
assert field_isomorphism_pslq(
a, e) == [Q(1, 80), 0, -Q(1, 2), 0, Q(59, 20), 0]
assert field_isomorphism_pslq(b, a) is None
assert field_isomorphism_pslq(b, b) == [1, 0]
assert field_isomorphism_pslq(b, c) is None
assert field_isomorphism_pslq(b, d) == [-Q(1, 2), 0, Q(11, 2), 0]
assert field_isomorphism_pslq(b, e) == [-Q(
3, 640), 0, Q(67, 320), 0, -Q(297, 160), 0, Q(313, 80), 0]
assert field_isomorphism_pslq(c, a) is None
assert field_isomorphism_pslq(c, b) is None
assert field_isomorphism_pslq(c, c) == [1, 0]
assert field_isomorphism_pslq(c, d) is None
assert field_isomorphism_pslq(c, e) == [Q(
3, 640), 0, -Q(71, 320), 0, Q(377, 160), 0, -Q(469, 80), 0]
assert field_isomorphism_pslq(d, a) is None
assert field_isomorphism_pslq(d, b) is None
assert field_isomorphism_pslq(d, c) is None
assert field_isomorphism_pslq(d, d) == [1, 0]
assert field_isomorphism_pslq(d, e) == [-Q(
3, 640), 0, Q(71, 320), 0, -Q(377, 160), 0, Q(549, 80), 0]
assert field_isomorphism_pslq(e, a) is None
assert field_isomorphism_pslq(e, b) is None
assert field_isomorphism_pslq(e, c) is None
assert field_isomorphism_pslq(e, d) is None
assert field_isomorphism_pslq(e, e) == [1, 0]
f = AlgebraicNumber(3*sqrt(2) + 8*sqrt(7) - 5)
assert field_isomorphism_pslq(
f, e) == [Q(3, 80), 0, -Q(139, 80), 0, Q(347, 20), 0, -Q(761, 20), -5]
def test_field_isomorphism():
assert field_isomorphism(3, sqrt(2)) == [3]
assert field_isomorphism( I*sqrt(3), I*sqrt(3)/2) == [ 2, 0]
assert field_isomorphism(-I*sqrt(3), I*sqrt(3)/2) == [-2, 0]
assert field_isomorphism( I*sqrt(3), -I*sqrt(3)/2) == [-2, 0]
assert field_isomorphism(-I*sqrt(3), -I*sqrt(3)/2) == [ 2, 0]
assert field_isomorphism( 2*I*sqrt(3)/7, 5*I*sqrt(3)/3) == [ S(6)/35, 0]
assert field_isomorphism(-2*I*sqrt(3)/7, 5*I*sqrt(3)/3) == [-S(6)/35, 0]
assert field_isomorphism( 2*I*sqrt(3)/7, -5*I*sqrt(3)/3) == [-S(6)/35, 0]
assert field_isomorphism(-2*I*sqrt(3)/7, -5*I*sqrt(3)/3) == [ S(6)/35, 0]
assert field_isomorphism(
2*I*sqrt(3)/7 + 27, 5*I*sqrt(3)/3) == [ S(6)/35, 27]
assert field_isomorphism(
-2*I*sqrt(3)/7 + 27, 5*I*sqrt(3)/3) == [-S(6)/35, 27]
assert field_isomorphism(
2*I*sqrt(3)/7 + 27, -5*I*sqrt(3)/3) == [-S(6)/35, 27]
assert field_isomorphism(
-2*I*sqrt(3)/7 + 27, -5*I*sqrt(3)/3) == [ S(6)/35, 27]
p = AlgebraicNumber( sqrt(2) + sqrt(3))
q = AlgebraicNumber(-sqrt(2) + sqrt(3))
r = AlgebraicNumber( sqrt(2) - sqrt(3))
s = AlgebraicNumber(-sqrt(2) - sqrt(3))
pos_coeffs = [ S(1)/2, S(0), -S(9)/2, S(0)]
neg_coeffs = [-S(1)/2, S(0), S(9)/2, S(0)]
a = AlgebraicNumber(sqrt(2))
assert is_isomorphism_possible(a, p) is True
assert is_isomorphism_possible(a, q) is True
assert is_isomorphism_possible(a, r) is True
assert is_isomorphism_possible(a, s) is True
assert field_isomorphism(a, p, fast=True) == pos_coeffs
assert field_isomorphism(a, q, fast=True) == neg_coeffs
assert field_isomorphism(a, r, fast=True) == pos_coeffs
assert field_isomorphism(a, s, fast=True) == neg_coeffs
assert field_isomorphism(a, p, fast=False) == pos_coeffs
assert field_isomorphism(a, q, fast=False) == neg_coeffs
assert field_isomorphism(a, r, fast=False) == pos_coeffs
assert field_isomorphism(a, s, fast=False) == neg_coeffs
a = AlgebraicNumber(-sqrt(2))
assert is_isomorphism_possible(a, p) is True
assert is_isomorphism_possible(a, q) is True
assert is_isomorphism_possible(a, r) is True
assert is_isomorphism_possible(a, s) is True
assert field_isomorphism(a, p, fast=True) == neg_coeffs
assert field_isomorphism(a, q, fast=True) == pos_coeffs
assert field_isomorphism(a, r, fast=True) == neg_coeffs
assert field_isomorphism(a, s, fast=True) == pos_coeffs
assert field_isomorphism(a, p, fast=False) == neg_coeffs
assert field_isomorphism(a, q, fast=False) == pos_coeffs
assert field_isomorphism(a, r, fast=False) == neg_coeffs
assert field_isomorphism(a, s, fast=False) == pos_coeffs
pos_coeffs = [ S(1)/2, S(0), -S(11)/2, S(0)]
neg_coeffs = [-S(1)/2, S(0), S(11)/2, S(0)]
a = AlgebraicNumber(sqrt(3))
assert is_isomorphism_possible(a, p) is True
assert is_isomorphism_possible(a, q) is True
assert is_isomorphism_possible(a, r) is True
assert is_isomorphism_possible(a, s) is True
assert field_isomorphism(a, p, fast=True) == neg_coeffs
assert field_isomorphism(a, q, fast=True) == neg_coeffs
assert field_isomorphism(a, r, fast=True) == pos_coeffs
assert field_isomorphism(a, s, fast=True) == pos_coeffs
assert field_isomorphism(a, p, fast=False) == neg_coeffs
assert field_isomorphism(a, q, fast=False) == neg_coeffs
assert field_isomorphism(a, r, fast=False) == pos_coeffs
assert field_isomorphism(a, s, fast=False) == pos_coeffs
a = AlgebraicNumber(-sqrt(3))
assert is_isomorphism_possible(a, p) is True
assert is_isomorphism_possible(a, q) is True
assert is_isomorphism_possible(a, r) is True
assert is_isomorphism_possible(a, s) is True
assert field_isomorphism(a, p, fast=True) == pos_coeffs
assert field_isomorphism(a, q, fast=True) == pos_coeffs
assert field_isomorphism(a, r, fast=True) == neg_coeffs
assert field_isomorphism(a, s, fast=True) == neg_coeffs
assert field_isomorphism(a, p, fast=False) == pos_coeffs
assert field_isomorphism(a, q, fast=False) == pos_coeffs
assert field_isomorphism(a, r, fast=False) == neg_coeffs
assert field_isomorphism(a, s, fast=False) == neg_coeffs
pos_coeffs = [ S(3)/2, S(0), -S(33)/2, -S(8)]
neg_coeffs = [-S(3)/2, S(0), S(33)/2, -S(8)]
a = AlgebraicNumber(3*sqrt(3) - 8)
assert is_isomorphism_possible(a, p) is True
assert is_isomorphism_possible(a, q) is True
assert is_isomorphism_possible(a, r) is True
assert is_isomorphism_possible(a, s) is True
assert field_isomorphism(a, p, fast=True) == neg_coeffs
assert field_isomorphism(a, q, fast=True) == neg_coeffs
assert field_isomorphism(a, r, fast=True) == pos_coeffs
assert field_isomorphism(a, s, fast=True) == pos_coeffs
assert field_isomorphism(a, p, fast=False) == neg_coeffs
assert field_isomorphism(a, q, fast=False) == neg_coeffs
assert field_isomorphism(a, r, fast=False) == pos_coeffs
assert field_isomorphism(a, s, fast=False) == pos_coeffs
a = AlgebraicNumber(3*sqrt(2) + 2*sqrt(3) + 1)
pos_1_coeffs = [ S(1)/2, S(0), -S(5)/2, S(1)]
neg_5_coeffs = [-S(5)/2, S(0), S(49)/2, S(1)]
pos_5_coeffs = [ S(5)/2, S(0), -S(49)/2, S(1)]
neg_1_coeffs = [-S(1)/2, S(0), S(5)/2, S(1)]
assert is_isomorphism_possible(a, p) is True
assert is_isomorphism_possible(a, q) is True
assert is_isomorphism_possible(a, r) is True
assert is_isomorphism_possible(a, s) is True
assert field_isomorphism(a, p, fast=True) == pos_1_coeffs
assert field_isomorphism(a, q, fast=True) == neg_5_coeffs
assert field_isomorphism(a, r, fast=True) == pos_5_coeffs
assert field_isomorphism(a, s, fast=True) == neg_1_coeffs
assert field_isomorphism(a, p, fast=False) == pos_1_coeffs
assert field_isomorphism(a, q, fast=False) == neg_5_coeffs
assert field_isomorphism(a, r, fast=False) == pos_5_coeffs
assert field_isomorphism(a, s, fast=False) == neg_1_coeffs
a = AlgebraicNumber(sqrt(2))
b = AlgebraicNumber(sqrt(3))
c = AlgebraicNumber(sqrt(7))
assert is_isomorphism_possible(a, b) is True
assert is_isomorphism_possible(b, a) is True
assert is_isomorphism_possible(c, p) is False
assert field_isomorphism(sqrt(2), sqrt(3), fast=True) is None
assert field_isomorphism(sqrt(3), sqrt(2), fast=True) is None
assert field_isomorphism(sqrt(2), sqrt(3), fast=False) is None
assert field_isomorphism(sqrt(3), sqrt(2), fast=False) is None
def test_to_number_field():
assert to_number_field(sqrt(2)) == AlgebraicNumber(sqrt(2))
assert to_number_field(
[sqrt(2), sqrt(3)]) == AlgebraicNumber(sqrt(2) + sqrt(3))
a = AlgebraicNumber(sqrt(2) + sqrt(3), [S(1)/2, S(0), -S(9)/2, S(0)])
assert to_number_field(sqrt(2), sqrt(2) + sqrt(3)) == a
assert to_number_field(sqrt(2), AlgebraicNumber(sqrt(2) + sqrt(3))) == a
raises(IsomorphismFailed, lambda: to_number_field(sqrt(2), sqrt(3)))
def test_AlgebraicNumber():
minpoly, root = x**2 - 2, sqrt(2)
a = AlgebraicNumber(root, gen=x)
assert a.rep == DMP([QQ(1), QQ(0)], QQ)
assert a.root == root
assert a.alias is None
assert a.minpoly == minpoly
assert a.is_number
assert a.is_aliased is False
assert a.coeffs() == [S(1), S(0)]
assert a.native_coeffs() == [QQ(1), QQ(0)]
a = AlgebraicNumber(root, gen=x, alias='y')
assert a.rep == DMP([QQ(1), QQ(0)], QQ)
assert a.root == root
assert a.alias == Symbol('y')
assert a.minpoly == minpoly
assert a.is_number
assert a.is_aliased is True
a = AlgebraicNumber(root, gen=x, alias=Symbol('y'))
assert a.rep == DMP([QQ(1), QQ(0)], QQ)
assert a.root == root
assert a.alias == Symbol('y')
assert a.minpoly == minpoly
assert a.is_number
assert a.is_aliased is True
assert AlgebraicNumber(sqrt(2), []).rep == DMP([], QQ)
assert AlgebraicNumber(sqrt(2), ()).rep == DMP([], QQ)
assert AlgebraicNumber(sqrt(2), (0, 0)).rep == DMP([], QQ)
assert AlgebraicNumber(sqrt(2), [8]).rep == DMP([QQ(8)], QQ)
assert AlgebraicNumber(sqrt(2), [S(8)/3]).rep == DMP([QQ(8, 3)], QQ)
assert AlgebraicNumber(sqrt(2), [7, 3]).rep == DMP([QQ(7), QQ(3)], QQ)
assert AlgebraicNumber(
sqrt(2), [S(7)/9, S(3)/2]).rep == DMP([QQ(7, 9), QQ(3, 2)], QQ)
assert AlgebraicNumber(sqrt(2), [1, 2, 3]).rep == DMP([QQ(2), QQ(5)], QQ)
a = AlgebraicNumber(AlgebraicNumber(root, gen=x), [1, 2])
assert a.rep == DMP([QQ(1), QQ(2)], QQ)
assert a.root == root
assert a.alias is None
assert a.minpoly == minpoly
assert a.is_number
assert a.is_aliased is False
assert a.coeffs() == [S(1), S(2)]
assert a.native_coeffs() == [QQ(1), QQ(2)]
a = AlgebraicNumber((minpoly, root), [1, 2])
assert a.rep == DMP([QQ(1), QQ(2)], QQ)
assert a.root == root
assert a.alias is None
assert a.minpoly == minpoly
assert a.is_number
assert a.is_aliased is False
a = AlgebraicNumber((Poly(minpoly), root), [1, 2])
assert a.rep == DMP([QQ(1), QQ(2)], QQ)
assert a.root == root
assert a.alias is None
assert a.minpoly == minpoly
assert a.is_number
assert a.is_aliased is False
assert AlgebraicNumber( sqrt(3)).rep == DMP([ QQ(1), QQ(0)], QQ)
assert AlgebraicNumber(-sqrt(3)).rep == DMP([-QQ(1), QQ(0)], QQ)
a = AlgebraicNumber(sqrt(2))
b = AlgebraicNumber(sqrt(2))
assert a == b
c = AlgebraicNumber(sqrt(2), gen=x)
d = AlgebraicNumber(sqrt(2), gen=x)
assert a == b
assert a == c
a = AlgebraicNumber(sqrt(2), [1, 2])
b = AlgebraicNumber(sqrt(2), [1, 3])
assert a != b and a != sqrt(2) + 3
assert (a == x) is False and (a != x) is True
a = AlgebraicNumber(sqrt(2), [1, 0])
b = AlgebraicNumber(sqrt(2), [1, 0], alias=y)
assert a.as_poly(x) == Poly(x)
assert b.as_poly() == Poly(y)
assert a.as_expr() == sqrt(2)
assert a.as_expr(x) == x
assert b.as_expr() == sqrt(2)
assert b.as_expr(x) == x
a = AlgebraicNumber(sqrt(2), [2, 3])
b = AlgebraicNumber(sqrt(2), [2, 3], alias=y)
p = a.as_poly()
assert p == Poly(2*p.gen + 3)
assert a.as_poly(x) == Poly(2*x + 3)
assert b.as_poly() == Poly(2*y + 3)
assert a.as_expr() == 2*sqrt(2) + 3
assert a.as_expr(x) == 2*x + 3
assert b.as_expr() == 2*sqrt(2) + 3
assert b.as_expr(x) == 2*x + 3
a = AlgebraicNumber(sqrt(2))
b = to_number_field(sqrt(2))
assert a.args == b.args == (sqrt(2), Tuple(1, 0))
b = AlgebraicNumber(sqrt(2), alias='alpha')
assert b.args == (sqrt(2), Tuple(1, 0), Symbol('alpha'))
a = AlgebraicNumber(sqrt(2), [1, 2, 3])
assert a.args == (sqrt(2), Tuple(1, 2, 3))
def test_to_algebraic_integer():
a = AlgebraicNumber(sqrt(3), gen=x).to_algebraic_integer()
assert a.minpoly == x**2 - 3
assert a.root == sqrt(3)
assert a.rep == DMP([QQ(1), QQ(0)], QQ)
a = AlgebraicNumber(2*sqrt(3), gen=x).to_algebraic_integer()
assert a.minpoly == x**2 - 12
assert a.root == 2*sqrt(3)
assert a.rep == DMP([QQ(1), QQ(0)], QQ)
a = AlgebraicNumber(sqrt(3)/2, gen=x).to_algebraic_integer()
assert a.minpoly == x**2 - 12
assert a.root == 2*sqrt(3)
assert a.rep == DMP([QQ(1), QQ(0)], QQ)
a = AlgebraicNumber(sqrt(3)/2, [S(7)/19, 3], gen=x).to_algebraic_integer()
assert a.minpoly == x**2 - 12
assert a.root == 2*sqrt(3)
assert a.rep == DMP([QQ(7, 19), QQ(3)], QQ)
def test_IntervalPrinter():
ip = IntervalPrinter()
assert ip.doprint(x**Q(1, 3)) == "x**(mpi('1/3'))"
assert ip.doprint(sqrt(x)) == "x**(mpi('1/2'))"
def test_isolate():
assert isolate(1) == (1, 1)
assert isolate(S(1)/2) == (S(1)/2, S(1)/2)
assert isolate(sqrt(2)) == (1, 2)
assert isolate(-sqrt(2)) == (-2, -1)
assert isolate(sqrt(2), eps=S(1)/100) == (S(24)/17, S(17)/12)
assert isolate(-sqrt(2), eps=S(1)/100) == (-S(17)/12, -S(24)/17)
raises(NotImplementedError, lambda: isolate(I))
def test_minpoly_fraction_field():
assert minimal_polynomial(1/x, y) == -x*y + 1
assert minimal_polynomial(1 / (x + 1), y) == (x + 1)*y - 1
assert minimal_polynomial(sqrt(x), y) == y**2 - x
assert minimal_polynomial(sqrt(x + 1), y) == y**2 - x - 1
assert minimal_polynomial(sqrt(x) / x, y) == x*y**2 - 1
assert minimal_polynomial(sqrt(2) * sqrt(x), y) == y**2 - 2 * x
assert minimal_polynomial(sqrt(2) + sqrt(x), y) == \
y**4 + (-2*x - 4)*y**2 + x**2 - 4*x + 4
assert minimal_polynomial(x**Rational(1,3), y) == y**3 - x
assert minimal_polynomial(x**Rational(1,3) + sqrt(x), y) == \
y**6 - 3*x*y**4 - 2*x*y**3 + 3*x**2*y**2 - 6*x**2*y - x**3 + x**2
assert minimal_polynomial(sqrt(x) / z, y) == z**2*y**2 - x
assert minimal_polynomial(sqrt(x) / (z + 1), y) == (z**2 + 2*z + 1)*y**2 - x
assert minimal_polynomial(1/x, y, polys=True) == Poly(-x*y + 1, y)
assert minimal_polynomial(1 / (x + 1), y, polys=True) == \
Poly((x + 1)*y - 1, y)
assert minimal_polynomial(sqrt(x), y, polys=True) == Poly(y**2 - x, y)
assert minimal_polynomial(sqrt(x) / z, y, polys=True) == \
Poly(z**2*y**2 - x, y)
# this is (sqrt(1 + x**3)/x).integrate(x).diff(x) - sqrt(1 + x**3)/x
a = sqrt(x)/sqrt(1 + x**(-3)) - sqrt(x**3 + 1)/x + 1/(x**(S(5)/2)* \
(1 + x**(-3))**(S(3)/2)) + 1/(x**(S(11)/2)*(1 + x**(-3))**(S(3)/2))
assert minimal_polynomial(a, y) == y
raises(NotAlgebraic, lambda: minimal_polynomial(exp(x), y))
raises(GeneratorsError, lambda: minimal_polynomial(sqrt(x), x))
raises(GeneratorsError, lambda: minimal_polynomial(sqrt(x) - y, x))
raises(NotImplementedError, lambda: minimal_polynomial(sqrt(x), y, compose=False))
@slow
def test_minpoly_fraction_field_slow():
assert minimal_polynomial(minimal_polynomial(sqrt(x**Rational(1,5) - 1),
y).subs(y, sqrt(x**Rational(1,5) - 1)), z) == z
def test_minpoly_domain():
assert minimal_polynomial(sqrt(2), x, domain=QQ.algebraic_field(sqrt(2))) == \
x - sqrt(2)
assert minimal_polynomial(sqrt(8), x, domain=QQ.algebraic_field(sqrt(2))) == \
x - 2*sqrt(2)
assert minimal_polynomial(sqrt(Rational(3,2)), x,
domain=QQ.algebraic_field(sqrt(2))) == 2*x**2 - 3
raises(NotAlgebraic, lambda: minimal_polynomial(y, x, domain=QQ))
| 28,137 | 36.870794 | 154 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/tests/test_modulargcd.py
|
from sympy.polys.rings import ring
from sympy.polys.domains import ZZ, QQ, AlgebraicField
from sympy.polys.modulargcd import (
modgcd_univariate,
modgcd_bivariate,
_chinese_remainder_reconstruction_multivariate,
modgcd_multivariate,
_to_ZZ_poly,
_to_ANP_poly,
func_field_modgcd,
_func_field_modgcd_m)
from sympy import sqrt
def test_modgcd_univariate_integers():
R, x = ring("x", ZZ)
f, g = R.zero, R.zero
assert modgcd_univariate(f, g) == (0, 0, 0)
f, g = R.zero, x
assert modgcd_univariate(f, g) == (x, 0, 1)
assert modgcd_univariate(g, f) == (x, 1, 0)
f, g = R.zero, -x
assert modgcd_univariate(f, g) == (x, 0, -1)
assert modgcd_univariate(g, f) == (x, -1, 0)
f, g = 2*x, R(2)
assert modgcd_univariate(f, g) == (2, x, 1)
f, g = 2*x + 2, 6*x**2 - 6
assert modgcd_univariate(f, g) == (2*x + 2, 1, 3*x - 3)
f = x**4 + 8*x**3 + 21*x**2 + 22*x + 8
g = x**3 + 6*x**2 + 11*x + 6
h = x**2 + 3*x + 2
cff = x**2 + 5*x + 4
cfg = x + 3
assert modgcd_univariate(f, g) == (h, cff, cfg)
f = x**4 - 4
g = x**4 + 4*x**2 + 4
h = x**2 + 2
cff = x**2 - 2
cfg = x**2 + 2
assert modgcd_univariate(f, g) == (h, cff, cfg)
f = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5
g = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21
h = 1
cff = f
cfg = g
assert modgcd_univariate(f, g) == (h, cff, cfg)
f = - 352518131239247345597970242177235495263669787845475025293906825864749649589178600387510272*x**49 \
+ 46818041807522713962450042363465092040687472354933295397472942006618953623327997952*x**42 \
+ 378182690892293941192071663536490788434899030680411695933646320291525827756032*x**35 \
+ 112806468807371824947796775491032386836656074179286744191026149539708928*x**28 \
- 12278371209708240950316872681744825481125965781519138077173235712*x**21 \
+ 289127344604779611146960547954288113529690984687482920704*x**14 \
+ 19007977035740498977629742919480623972236450681*x**7 \
+ 311973482284542371301330321821976049
g = 365431878023781158602430064717380211405897160759702125019136*x**21 \
+ 197599133478719444145775798221171663643171734081650688*x**14 \
- 9504116979659010018253915765478924103928886144*x**7 \
- 311973482284542371301330321821976049
assert modgcd_univariate(f, f.diff(x))[0] == g
f = 1317378933230047068160*x + 2945748836994210856960
g = 120352542776360960*x + 269116466014453760
h = 120352542776360960*x + 269116466014453760
cff = 10946
cfg = 1
assert modgcd_univariate(f, g) == (h, cff, cfg)
def test_modgcd_bivariate_integers():
R, x, y = ring("x,y", ZZ)
f, g = R.zero, R.zero
assert modgcd_bivariate(f, g) == (0, 0, 0)
f, g = 2*x, R(2)
assert modgcd_bivariate(f, g) == (2, x, 1)
f, g = x + 2*y, x + y
assert modgcd_bivariate(f, g) == (1, f, g)
f, g = x**2 + 2*x*y + y**2, x**3 + y**3
assert modgcd_bivariate(f, g) == (x + y, x + y, x**2 - x*y + y**2)
f, g = x*y**2 + 2*x*y + x, x*y**3 + x
assert modgcd_bivariate(f, g) == (x*y + x, y + 1, y**2 - y + 1)
f, g = x**2*y**2 + x**2*y + 1, x*y**2 + x*y + 1
assert modgcd_bivariate(f, g) == (1, f, g)
f = 2*x*y**2 + 4*x*y + 2*x + y**2 + 2*y + 1
g = 2*x*y**3 + 2*x + y**3 + 1
assert modgcd_bivariate(f, g) == (2*x*y + 2*x + y + 1, y + 1, y**2 - y + 1)
f, g = 2*x**2 + 4*x + 2, x + 1
assert modgcd_bivariate(f, g) == (x + 1, 2*x + 2, 1)
f, g = x + 1, 2*x**2 + 4*x + 2
assert modgcd_bivariate(f, g) == (x + 1, 1, 2*x + 2)
f = 2*x**2 + 4*x*y - 2*x - 4*y
g = x**2 + x - 2
assert modgcd_bivariate(f, g) == (x - 1, 2*x + 4*y, x + 2)
f = 2*x**2 + 2*x*y - 3*x - 3*y
g = 4*x*y - 2*x + 4*y**2 - 2*y
assert modgcd_bivariate(f, g) == (x + y, 2*x - 3, 4*y - 2)
def test_chinese_remainder():
R, x, y = ring("x, y", ZZ)
p, q = 3, 5
hp = x**3*y - x**2 - 1
hq = -x**3*y - 2*x*y**2 + 2
hpq = _chinese_remainder_reconstruction_multivariate(hp, hq, p, q)
assert hpq.trunc_ground(p) == hp
assert hpq.trunc_ground(q) == hq
T, z = ring("z", R)
p, q = 3, 7
hp = (x*y + 1)*z**2 + x
hq = (x**2 - 3*y)*z + 2
hpq = _chinese_remainder_reconstruction_multivariate(hp, hq, p, q)
assert hpq.trunc_ground(p) == hp
assert hpq.trunc_ground(q) == hq
def test_modgcd_multivariate_integers():
R, x, y = ring("x,y", ZZ)
f, g = R.zero, R.zero
assert modgcd_multivariate(f, g) == (0, 0, 0)
f, g = 2*x**2 + 4*x + 2, x + 1
assert modgcd_multivariate(f, g) == (x + 1, 2*x + 2, 1)
f, g = x + 1, 2*x**2 + 4*x + 2
assert modgcd_multivariate(f, g) == (x + 1, 1, 2*x + 2)
f = 2*x**2 + 2*x*y - 3*x - 3*y
g = 4*x*y - 2*x + 4*y**2 - 2*y
assert modgcd_multivariate(f, g) == (x + y, 2*x - 3, 4*y - 2)
f, g = x*y**2 + 2*x*y + x, x*y**3 + x
assert modgcd_multivariate(f, g) == (x*y + x, y + 1, y**2 - y + 1)
f, g = x**2*y**2 + x**2*y + 1, x*y**2 + x*y + 1
assert modgcd_multivariate(f, g) == (1, f, g)
f = x**4 + 8*x**3 + 21*x**2 + 22*x + 8
g = x**3 + 6*x**2 + 11*x + 6
h = x**2 + 3*x + 2
cff = x**2 + 5*x + 4
cfg = x + 3
assert modgcd_multivariate(f, g) == (h, cff, cfg)
R, x, y, z, u = ring("x,y,z,u", ZZ)
f, g = x + y + z, -x - y - z - u
assert modgcd_multivariate(f, g) == (1, f, g)
f, g = u**2 + 2*u + 1, 2*u + 2
assert modgcd_multivariate(f, g) == (u + 1, u + 1, 2)
f, g = z**2*u**2 + 2*z**2*u + z**2 + z*u + z, u**2 + 2*u + 1
h, cff, cfg = u + 1, z**2*u + z**2 + z, u + 1
assert modgcd_multivariate(f, g) == (h, cff, cfg)
assert modgcd_multivariate(g, f) == (h, cfg, cff)
R, x, y, z = ring("x,y,z", ZZ)
f, g = x - y*z, x - y*z
assert modgcd_multivariate(f, g) == (x - y*z, 1, 1)
f, g, h = R.fateman_poly_F_1()
H, cff, cfg = modgcd_multivariate(f, g)
assert H == h and H*cff == f and H*cfg == g
R, x, y, z, u, v = ring("x,y,z,u,v", ZZ)
f, g, h = R.fateman_poly_F_1()
H, cff, cfg = modgcd_multivariate(f, g)
assert H == h and H*cff == f and H*cfg == g
R, x, y, z, u, v, a, b = ring("x,y,z,u,v,a,b", ZZ)
f, g, h = R.fateman_poly_F_1()
H, cff, cfg = modgcd_multivariate(f, g)
assert H == h and H*cff == f and H*cfg == g
R, x, y, z, u, v, a, b, c, d = ring("x,y,z,u,v,a,b,c,d", ZZ)
f, g, h = R.fateman_poly_F_1()
H, cff, cfg = modgcd_multivariate(f, g)
assert H == h and H*cff == f and H*cfg == g
R, x, y, z = ring("x,y,z", ZZ)
f, g, h = R.fateman_poly_F_2()
H, cff, cfg = modgcd_multivariate(f, g)
assert H == h and H*cff == f and H*cfg == g
f, g, h = R.fateman_poly_F_3()
H, cff, cfg = modgcd_multivariate(f, g)
assert H == h and H*cff == f and H*cfg == g
R, x, y, z, t = ring("x,y,z,t", ZZ)
f, g, h = R.fateman_poly_F_3()
H, cff, cfg = modgcd_multivariate(f, g)
assert H == h and H*cff == f and H*cfg == g
def test_to_ZZ_ANP_poly():
A = AlgebraicField(QQ, sqrt(2))
R, x = ring("x", A)
f = x*(sqrt(2) + 1)
T, x_, z_ = ring("x_, z_", ZZ)
f_ = x_*z_ + x_
assert _to_ZZ_poly(f, T) == f_
assert _to_ANP_poly(f_, R) == f
R, x, t, s = ring("x, t, s", A)
f = x*t**2 + x*s + sqrt(2)
D, t_, s_ = ring("t_, s_", ZZ)
T, x_, z_ = ring("x_, z_", D)
f_ = (t_**2 + s_)*x_ + z_
assert _to_ZZ_poly(f, T) == f_
assert _to_ANP_poly(f_, R) == f
def test_modgcd_algebraic_field():
A = AlgebraicField(QQ, sqrt(2))
R, x = ring("x", A)
one = A.one
f, g = 2*x, R(2)
assert func_field_modgcd(f, g) == (one, f, g)
f, g = 2*x, R(sqrt(2))
assert func_field_modgcd(f, g) == (one, f, g)
f, g = 2*x + 2, 6*x**2 - 6
assert func_field_modgcd(f, g) == (x + 1, R(2), 6*x - 6)
R, x, y = ring("x, y", A)
f, g = x + sqrt(2)*y, x + y
assert func_field_modgcd(f, g) == (one, f, g)
f, g = x*y + sqrt(2)*y**2, R(sqrt(2))*y
assert func_field_modgcd(f, g) == (y, x + sqrt(2)*y, R(sqrt(2)))
f, g = x**2 + 2*sqrt(2)*x*y + 2*y**2, x + sqrt(2)*y
assert func_field_modgcd(f, g) == (g, g, one)
A = AlgebraicField(QQ, sqrt(2), sqrt(3))
R, x, y, z = ring("x, y, z", A)
h = x**2*y**7 + sqrt(6)/21*z
f, g = h*(27*y**3 + 1), h*(y + x)
assert func_field_modgcd(f, g) == (h, 27*y**3+1, y+x)
h = x**13*y**3 + 1/2*x**10 + 1/sqrt(2)
f, g = h*(x + 1), h*sqrt(2)/sqrt(3)
assert func_field_modgcd(f, g) == (h, x + 1, R(sqrt(2)/sqrt(3)))
A = AlgebraicField(QQ, sqrt(2)**(-1)*sqrt(3))
R, x = ring("x", A)
f, g = x + 1, x - 1
assert func_field_modgcd(f, g) == (A.one, f, g)
# when func_field_modgcd suppors function fields, this test can be changed
def test_modgcd_func_field():
D, t = ring("t", ZZ)
R, x, z = ring("x, z", D)
minpoly = (z**2*t**2 + z**2*t - 1).drop(0)
f, g = x + 1, x - 1
assert _func_field_modgcd_m(f, g, minpoly) == R.one
| 9,007 | 26.631902 | 108 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/tests/test_distributedmodules.py
|
"""Tests for sparse distributed modules. """
from sympy.polys.distributedmodules import (
sdm_monomial_mul, sdm_monomial_deg, sdm_monomial_divides,
sdm_add, sdm_LM, sdm_LT, sdm_mul_term, sdm_zero, sdm_deg,
sdm_LC, sdm_from_dict,
sdm_spoly, sdm_ecart, sdm_nf_mora, sdm_groebner,
sdm_from_vector, sdm_to_vector, sdm_monomial_lcm
)
from sympy.polys.orderings import lex, grlex, InverseOrder
from sympy.polys.domains import QQ
from sympy.abc import x, y, z
from sympy.core.compatibility import range
def test_sdm_monomial_mul():
assert sdm_monomial_mul((1, 1, 0), (1, 3)) == (1, 2, 3)
def test_sdm_monomial_deg():
assert sdm_monomial_deg((5, 2, 1)) == 3
def test_sdm_monomial_lcm():
assert sdm_monomial_lcm((1, 2, 3), (1, 5, 0)) == (1, 5, 3)
def test_sdm_monomial_divides():
assert sdm_monomial_divides((1, 0, 0), (1, 0, 0)) is True
assert sdm_monomial_divides((1, 0, 0), (1, 2, 1)) is True
assert sdm_monomial_divides((5, 1, 1), (5, 2, 1)) is True
assert sdm_monomial_divides((1, 0, 0), (2, 0, 0)) is False
assert sdm_monomial_divides((1, 1, 0), (1, 0, 0)) is False
assert sdm_monomial_divides((5, 1, 2), (5, 0, 1)) is False
def test_sdm_LC():
assert sdm_LC([((1, 2, 3), QQ(5))], QQ) == QQ(5)
def test_sdm_from_dict():
dic = {(1, 2, 1, 1): QQ(1), (1, 1, 2, 1): QQ(1), (1, 0, 2, 1): QQ(1),
(1, 0, 0, 3): QQ(1), (1, 1, 1, 0): QQ(1)}
assert sdm_from_dict(dic, grlex) == \
[((1, 2, 1, 1), QQ(1)), ((1, 1, 2, 1), QQ(1)),
((1, 0, 2, 1), QQ(1)), ((1, 0, 0, 3), QQ(1)), ((1, 1, 1, 0), QQ(1))]
# TODO test to_dict?
def test_sdm_add():
assert sdm_add([((1, 1, 1), QQ(1))], [((2, 0, 0), QQ(1))], lex, QQ) == \
[((2, 0, 0), QQ(1)), ((1, 1, 1), QQ(1))]
assert sdm_add([((1, 1, 1), QQ(1))], [((1, 1, 1), QQ(-1))], lex, QQ) == []
assert sdm_add([((1, 0, 0), QQ(1))], [((1, 0, 0), QQ(2))], lex, QQ) == \
[((1, 0, 0), QQ(3))]
assert sdm_add([((1, 0, 1), QQ(1))], [((1, 1, 0), QQ(1))], lex, QQ) == \
[((1, 1, 0), QQ(1)), ((1, 0, 1), QQ(1))]
def test_sdm_LM():
dic = {(1, 2, 3): QQ(1), (4, 0, 0): QQ(1), (4, 0, 1): QQ(1)}
assert sdm_LM(sdm_from_dict(dic, lex)) == (4, 0, 1)
def test_sdm_LT():
dic = {(1, 2, 3): QQ(1), (4, 0, 0): QQ(2), (4, 0, 1): QQ(3)}
assert sdm_LT(sdm_from_dict(dic, lex)) == ((4, 0, 1), QQ(3))
def test_sdm_mul_term():
assert sdm_mul_term([((1, 0, 0), QQ(1))], ((0, 0), QQ(0)), lex, QQ) == []
assert sdm_mul_term([], ((1, 0), QQ(1)), lex, QQ) == []
assert sdm_mul_term([((1, 0, 0), QQ(1))], ((1, 0), QQ(1)), lex, QQ) == \
[((1, 1, 0), QQ(1))]
f = [((2, 0, 1), QQ(4)), ((1, 1, 0), QQ(3))]
assert sdm_mul_term(f, ((1, 1), QQ(2)), lex, QQ) == \
[((2, 1, 2), QQ(8)), ((1, 2, 1), QQ(6))]
def test_sdm_zero():
assert sdm_zero() == []
def test_sdm_deg():
assert sdm_deg([((1, 2, 3), 1), ((10, 0, 1), 1), ((2, 3, 4), 4)]) == 7
def test_sdm_spoly():
f = [((2, 1, 1), QQ(1)), ((1, 0, 1), QQ(1))]
g = [((2, 3, 0), QQ(1))]
h = [((1, 2, 3), QQ(1))]
assert sdm_spoly(f, h, lex, QQ) == []
assert sdm_spoly(f, g, lex, QQ) == [((1, 2, 1), QQ(1))]
def test_sdm_ecart():
assert sdm_ecart([((1, 2, 3), 1), ((1, 0, 1), 1)]) == 0
assert sdm_ecart([((2, 2, 1), 1), ((1, 5, 1), 1)]) == 3
def test_sdm_nf_mora():
f = sdm_from_dict({(1, 2, 1, 1): QQ(1), (1, 1, 2, 1): QQ(1),
(1, 0, 2, 1): QQ(1), (1, 0, 0, 3): QQ(1), (1, 1, 1, 0): QQ(1)},
grlex)
f1 = sdm_from_dict({(1, 1, 1, 0): QQ(1), (1, 0, 2, 0): QQ(1),
(1, 0, 0, 0): QQ(-1)}, grlex)
f2 = sdm_from_dict({(1, 1, 1, 0): QQ(1)}, grlex)
(id0, id1, id2) = [sdm_from_dict({(i, 0, 0, 0): QQ(1)}, grlex)
for i in range(3)]
assert sdm_nf_mora(f, [f1, f2], grlex, QQ, phantom=(id0, [id1, id2])) == \
([((1, 0, 2, 1), QQ(1)), ((1, 0, 0, 3), QQ(1)), ((1, 1, 1, 0), QQ(1)),
((1, 1, 0, 1), QQ(1))],
[((1, 1, 0, 1), QQ(-1)), ((0, 0, 0, 0), QQ(1))])
assert sdm_nf_mora(f, [f2, f1], grlex, QQ, phantom=(id0, [id2, id1])) == \
([((1, 0, 2, 1), QQ(1)), ((1, 0, 0, 3), QQ(1)), ((1, 1, 1, 0), QQ(1))],
[((2, 1, 0, 1), QQ(-1)), ((2, 0, 1, 1), QQ(-1)), ((0, 0, 0, 0), QQ(1))])
f = sdm_from_vector([x*z, y**2 + y*z - z, y], lex, QQ, gens=[x, y, z])
f1 = sdm_from_vector([x, y, 1], lex, QQ, gens=[x, y, z])
f2 = sdm_from_vector([x*y, z, z**2], lex, QQ, gens=[x, y, z])
assert sdm_nf_mora(f, [f1, f2], lex, QQ) == \
sdm_nf_mora(f, [f2, f1], lex, QQ) == \
[((1, 0, 1, 1), QQ(1)), ((1, 0, 0, 1), QQ(-1)), ((0, 1, 1, 0), QQ(-1)),
((0, 1, 0, 1), QQ(1))]
def test_conversion():
f = [x**2 + y**2, 2*z]
g = [((1, 0, 0, 1), QQ(2)), ((0, 2, 0, 0), QQ(1)), ((0, 0, 2, 0), QQ(1))]
assert sdm_to_vector(g, [x, y, z], QQ) == f
assert sdm_from_vector(f, lex, QQ) == g
assert sdm_from_vector(
[x, 1], lex, QQ) == [((1, 0), QQ(1)), ((0, 1), QQ(1))]
assert sdm_to_vector([((1, 1, 0, 0), 1)], [x, y, z], QQ, n=3) == [0, x, 0]
assert sdm_from_vector([0, 0], lex, QQ, gens=[x, y]) == sdm_zero()
def test_nontrivial():
gens = [x, y, z]
def contains(I, f):
S = [sdm_from_vector([g], lex, QQ, gens=gens) for g in I]
G = sdm_groebner(S, sdm_nf_mora, lex, QQ)
return sdm_nf_mora(sdm_from_vector([f], lex, QQ, gens=gens),
G, lex, QQ) == sdm_zero()
assert contains([x, y], x)
assert contains([x, y], x + y)
assert not contains([x, y], 1)
assert not contains([x, y], z)
assert contains([x**2 + y, x**2 + x], x - y)
assert not contains([x + y + z, x*y + x*z + y*z, x*y*z], x**2)
assert contains([x + y + z, x*y + x*z + y*z, x*y*z], x**3)
assert contains([x + y + z, x*y + x*z + y*z, x*y*z], x**4)
assert not contains([x + y + z, x*y + x*z + y*z, x*y*z], x*y**2)
assert contains([x + y + z, x*y + x*z + y*z, x*y*z], x**4 + y**3 + 2*z*y*x)
assert contains([x + y + z, x*y + x*z + y*z, x*y*z], x*y*z)
assert contains([x, 1 + x + y, 5 - 7*y], 1)
assert contains(
[x**3 + y**3, y**3 + z**3, z**3 + x**3, x**2*y + x**2*z + y**2*z],
x**3)
assert not contains(
[x**3 + y**3, y**3 + z**3, z**3 + x**3, x**2*y + x**2*z + y**2*z],
x**2 + y**2)
# compare local order
assert not contains([x*(1 + x + y), y*(1 + z)], x)
assert not contains([x*(1 + x + y), y*(1 + z)], x + y)
def test_local():
igrlex = InverseOrder(grlex)
gens = [x, y, z]
def contains(I, f):
S = [sdm_from_vector([g], igrlex, QQ, gens=gens) for g in I]
G = sdm_groebner(S, sdm_nf_mora, igrlex, QQ)
return sdm_nf_mora(sdm_from_vector([f], lex, QQ, gens=gens),
G, lex, QQ) == sdm_zero()
assert contains([x, y], x)
assert contains([x, y], x + y)
assert not contains([x, y], 1)
assert not contains([x, y], z)
assert contains([x**2 + y, x**2 + x], x - y)
assert not contains([x + y + z, x*y + x*z + y*z, x*y*z], x**2)
assert contains([x*(1 + x + y), y*(1 + z)], x)
assert contains([x*(1 + x + y), y*(1 + z)], x + y)
def test_uncovered_line():
gens = [x, y]
f1 = sdm_zero()
f2 = sdm_from_vector([x, 0], lex, QQ, gens=gens)
f3 = sdm_from_vector([0, y], lex, QQ, gens=gens)
assert sdm_spoly(f1, f2, lex, QQ) == sdm_zero()
assert sdm_spoly(f3, f2, lex, QQ) == sdm_zero()
def test_chain_criterion():
gens = [x]
f1 = sdm_from_vector([1, x], grlex, QQ, gens=gens)
f2 = sdm_from_vector([0, x - 2], grlex, QQ, gens=gens)
assert len(sdm_groebner([f1, f2], sdm_nf_mora, grlex, QQ)) == 2
| 7,682 | 35.585714 | 81 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/tests/test_densetools.py
|
"""Tests for dense recursive polynomials' tools. """
from sympy.polys.densebasic import (
dup_normal, dmp_normal,
dup_from_raw_dict,
dmp_convert, dmp_swap,
)
from sympy.polys.densearith import dmp_mul_ground
from sympy.polys.densetools import (
dup_clear_denoms, dmp_clear_denoms,
dup_integrate, dmp_integrate, dmp_integrate_in,
dup_diff, dmp_diff, dmp_diff_in,
dup_eval, dmp_eval, dmp_eval_in,
dmp_eval_tail, dmp_diff_eval_in,
dup_trunc, dmp_trunc, dmp_ground_trunc,
dup_monic, dmp_ground_monic,
dup_content, dmp_ground_content,
dup_primitive, dmp_ground_primitive,
dup_extract, dmp_ground_extract,
dup_real_imag,
dup_mirror, dup_scale, dup_shift,
dup_transform,
dup_compose, dmp_compose,
dup_decompose,
dmp_lift,
dup_sign_variations,
dup_revert, dmp_revert,
)
from sympy.polys.polyclasses import ANP
from sympy.polys.polyerrors import (
MultivariatePolynomialError,
ExactQuotientFailed,
NotReversible,
DomainError,
)
from sympy.polys.specialpolys import f_polys
from sympy.polys.domains import FF, ZZ, QQ, EX
from sympy.polys.rings import ring
from sympy import S, I, sin
from sympy.core.compatibility import long
from sympy.abc import x
from sympy.utilities.pytest import raises
f_0, f_1, f_2, f_3, f_4, f_5, f_6 = [ f.to_dense() for f in f_polys() ]
def test_dup_integrate():
assert dup_integrate([], 1, QQ) == []
assert dup_integrate([], 2, QQ) == []
assert dup_integrate([QQ(1)], 1, QQ) == [QQ(1), QQ(0)]
assert dup_integrate([QQ(1)], 2, QQ) == [QQ(1, 2), QQ(0), QQ(0)]
assert dup_integrate([QQ(1), QQ(2), QQ(3)], 0, QQ) == \
[QQ(1), QQ(2), QQ(3)]
assert dup_integrate([QQ(1), QQ(2), QQ(3)], 1, QQ) == \
[QQ(1, 3), QQ(1), QQ(3), QQ(0)]
assert dup_integrate([QQ(1), QQ(2), QQ(3)], 2, QQ) == \
[QQ(1, 12), QQ(1, 3), QQ(3, 2), QQ(0), QQ(0)]
assert dup_integrate([QQ(1), QQ(2), QQ(3)], 3, QQ) == \
[QQ(1, 60), QQ(1, 12), QQ(1, 2), QQ(0), QQ(0), QQ(0)]
assert dup_integrate(dup_from_raw_dict({29: QQ(17)}, QQ), 3, QQ) == \
dup_from_raw_dict({32: QQ(17, 29760)}, QQ)
assert dup_integrate(dup_from_raw_dict({29: QQ(17), 5: QQ(1, 2)}, QQ), 3, QQ) == \
dup_from_raw_dict({32: QQ(17, 29760), 8: QQ(1, 672)}, QQ)
def test_dmp_integrate():
assert dmp_integrate([[[]]], 1, 2, QQ) == [[[]]]
assert dmp_integrate([[[]]], 2, 2, QQ) == [[[]]]
assert dmp_integrate([[[QQ(1)]]], 1, 2, QQ) == [[[QQ(1)]], [[]]]
assert dmp_integrate([[[QQ(1)]]], 2, 2, QQ) == [[[QQ(1, 2)]], [[]], [[]]]
assert dmp_integrate([[QQ(1)], [QQ(2)], [QQ(3)]], 0, 1, QQ) == \
[[QQ(1)], [QQ(2)], [QQ(3)]]
assert dmp_integrate([[QQ(1)], [QQ(2)], [QQ(3)]], 1, 1, QQ) == \
[[QQ(1, 3)], [QQ(1)], [QQ(3)], []]
assert dmp_integrate([[QQ(1)], [QQ(2)], [QQ(3)]], 2, 1, QQ) == \
[[QQ(1, 12)], [QQ(1, 3)], [QQ(3, 2)], [], []]
assert dmp_integrate([[QQ(1)], [QQ(2)], [QQ(3)]], 3, 1, QQ) == \
[[QQ(1, 60)], [QQ(1, 12)], [QQ(1, 2)], [], [], []]
def test_dmp_integrate_in():
f = dmp_convert(f_6, 3, ZZ, QQ)
assert dmp_integrate_in(f, 2, 1, 3, QQ) == \
dmp_swap(
dmp_integrate(dmp_swap(f, 0, 1, 3, QQ), 2, 3, QQ), 0, 1, 3, QQ)
assert dmp_integrate_in(f, 3, 1, 3, QQ) == \
dmp_swap(
dmp_integrate(dmp_swap(f, 0, 1, 3, QQ), 3, 3, QQ), 0, 1, 3, QQ)
assert dmp_integrate_in(f, 2, 2, 3, QQ) == \
dmp_swap(
dmp_integrate(dmp_swap(f, 0, 2, 3, QQ), 2, 3, QQ), 0, 2, 3, QQ)
assert dmp_integrate_in(f, 3, 2, 3, QQ) == \
dmp_swap(
dmp_integrate(dmp_swap(f, 0, 2, 3, QQ), 3, 3, QQ), 0, 2, 3, QQ)
def test_dup_diff():
assert dup_diff([], 1, ZZ) == []
assert dup_diff([7], 1, ZZ) == []
assert dup_diff([2, 7], 1, ZZ) == [2]
assert dup_diff([1, 2, 1], 1, ZZ) == [2, 2]
assert dup_diff([1, 2, 3, 4], 1, ZZ) == [3, 4, 3]
assert dup_diff([1, -1, 0, 0, 2], 1, ZZ) == [4, -3, 0, 0]
f = dup_normal([17, 34, 56, -345, 23, 76, 0, 0, 12, 3, 7], ZZ)
assert dup_diff(f, 0, ZZ) == f
assert dup_diff(f, 1, ZZ) == dup_diff(f, 1, ZZ)
assert dup_diff(f, 2, ZZ) == dup_diff(dup_diff(f, 1, ZZ), 1, ZZ)
assert dup_diff(
f, 3, ZZ) == dup_diff(dup_diff(dup_diff(f, 1, ZZ), 1, ZZ), 1, ZZ)
K = FF(3)
f = dup_normal([17, 34, 56, -345, 23, 76, 0, 0, 12, 3, 7], K)
assert dup_diff(f, 1, K) == dup_normal([2, 0, 1, 0, 0, 2, 0, 0, 0, 0], K)
assert dup_diff(f, 2, K) == dup_normal([1, 0, 0, 2, 0, 0, 0], K)
assert dup_diff(f, 3, K) == dup_normal([], K)
assert dup_diff(f, 0, K) == f
assert dup_diff(f, 1, K) == dup_diff(f, 1, K)
assert dup_diff(f, 2, K) == dup_diff(dup_diff(f, 1, K), 1, K)
assert dup_diff(
f, 3, K) == dup_diff(dup_diff(dup_diff(f, 1, K), 1, K), 1, K)
def test_dmp_diff():
assert dmp_diff([], 1, 0, ZZ) == []
assert dmp_diff([[]], 1, 1, ZZ) == [[]]
assert dmp_diff([[[]]], 1, 2, ZZ) == [[[]]]
assert dmp_diff([[[1], [2]]], 1, 2, ZZ) == [[[]]]
assert dmp_diff([[[1]], [[]]], 1, 2, ZZ) == [[[1]]]
assert dmp_diff([[[3]], [[1]], [[]]], 1, 2, ZZ) == [[[6]], [[1]]]
assert dmp_diff([1, -1, 0, 0, 2], 1, 0, ZZ) == \
dup_diff([1, -1, 0, 0, 2], 1, ZZ)
assert dmp_diff(f_6, 0, 3, ZZ) == f_6
assert dmp_diff(f_6, 1, 3, ZZ) == dmp_diff(f_6, 1, 3, ZZ)
assert dmp_diff(
f_6, 2, 3, ZZ) == dmp_diff(dmp_diff(f_6, 1, 3, ZZ), 1, 3, ZZ)
assert dmp_diff(f_6, 3, 3, ZZ) == dmp_diff(
dmp_diff(dmp_diff(f_6, 1, 3, ZZ), 1, 3, ZZ), 1, 3, ZZ)
K = FF(23)
F_6 = dmp_normal(f_6, 3, K)
assert dmp_diff(F_6, 0, 3, K) == F_6
assert dmp_diff(F_6, 1, 3, K) == dmp_diff(F_6, 1, 3, K)
assert dmp_diff(F_6, 2, 3, K) == dmp_diff(dmp_diff(F_6, 1, 3, K), 1, 3, K)
assert dmp_diff(F_6, 3, 3, K) == dmp_diff(
dmp_diff(dmp_diff(F_6, 1, 3, K), 1, 3, K), 1, 3, K)
def test_dmp_diff_in():
assert dmp_diff_in(f_6, 2, 1, 3, ZZ) == \
dmp_swap(dmp_diff(dmp_swap(f_6, 0, 1, 3, ZZ), 2, 3, ZZ), 0, 1, 3, ZZ)
assert dmp_diff_in(f_6, 3, 1, 3, ZZ) == \
dmp_swap(dmp_diff(dmp_swap(f_6, 0, 1, 3, ZZ), 3, 3, ZZ), 0, 1, 3, ZZ)
assert dmp_diff_in(f_6, 2, 2, 3, ZZ) == \
dmp_swap(dmp_diff(dmp_swap(f_6, 0, 2, 3, ZZ), 2, 3, ZZ), 0, 2, 3, ZZ)
assert dmp_diff_in(f_6, 3, 2, 3, ZZ) == \
dmp_swap(dmp_diff(dmp_swap(f_6, 0, 2, 3, ZZ), 3, 3, ZZ), 0, 2, 3, ZZ)
def test_dup_eval():
assert dup_eval([], 7, ZZ) == 0
assert dup_eval([1, 2], 0, ZZ) == 2
assert dup_eval([1, 2, 3], 7, ZZ) == 66
def test_dmp_eval():
assert dmp_eval([], 3, 0, ZZ) == 0
assert dmp_eval([[]], 3, 1, ZZ) == []
assert dmp_eval([[[]]], 3, 2, ZZ) == [[]]
assert dmp_eval([[1, 2]], 0, 1, ZZ) == [1, 2]
assert dmp_eval([[[1]]], 3, 2, ZZ) == [[1]]
assert dmp_eval([[[1, 2]]], 3, 2, ZZ) == [[1, 2]]
assert dmp_eval([[3, 2], [1, 2]], 3, 1, ZZ) == [10, 8]
assert dmp_eval([[[3, 2]], [[1, 2]]], 3, 2, ZZ) == [[10, 8]]
def test_dmp_eval_in():
assert dmp_eval_in(
f_6, -2, 1, 3, ZZ) == dmp_eval(dmp_swap(f_6, 0, 1, 3, ZZ), -2, 3, ZZ)
assert dmp_eval_in(
f_6, 7, 1, 3, ZZ) == dmp_eval(dmp_swap(f_6, 0, 1, 3, ZZ), 7, 3, ZZ)
assert dmp_eval_in(f_6, -2, 2, 3, ZZ) == dmp_swap(
dmp_eval(dmp_swap(f_6, 0, 2, 3, ZZ), -2, 3, ZZ), 0, 1, 2, ZZ)
assert dmp_eval_in(f_6, 7, 2, 3, ZZ) == dmp_swap(
dmp_eval(dmp_swap(f_6, 0, 2, 3, ZZ), 7, 3, ZZ), 0, 1, 2, ZZ)
f = [[[long(45)]], [[]], [[]], [[long(-9)], [-1], [], [long(3), long(0), long(10), long(0)]]]
assert dmp_eval_in(f, -2, 2, 2, ZZ) == \
[[45], [], [], [-9, -1, 0, -44]]
def test_dmp_eval_tail():
assert dmp_eval_tail([[]], [1], 1, ZZ) == []
assert dmp_eval_tail([[[]]], [1], 2, ZZ) == [[]]
assert dmp_eval_tail([[[]]], [1, 2], 2, ZZ) == []
assert dmp_eval_tail(f_0, [], 2, ZZ) == f_0
assert dmp_eval_tail(f_0, [1, -17, 8], 2, ZZ) == 84496
assert dmp_eval_tail(f_0, [-17, 8], 2, ZZ) == [-1409, 3, 85902]
assert dmp_eval_tail(f_0, [8], 2, ZZ) == [[83, 2], [3], [302, 81, 1]]
assert dmp_eval_tail(f_1, [-17, 8], 2, ZZ) == [-136, 15699, 9166, -27144]
assert dmp_eval_tail(
f_2, [-12, 3], 2, ZZ) == [-1377, 0, -702, -1224, 0, -624]
assert dmp_eval_tail(
f_3, [-12, 3], 2, ZZ) == [144, 82, -5181, -28872, -14868, -540]
assert dmp_eval_tail(
f_4, [25, -1], 2, ZZ) == [152587890625, 9765625, -59605407714843750,
-3839159765625, -1562475, 9536712644531250, 610349546750, -4, 24414375000, 1562520]
assert dmp_eval_tail(f_5, [25, -1], 2, ZZ) == [-1, -78, -2028, -17576]
assert dmp_eval_tail(f_6, [0, 2, 4], 3, ZZ) == [5040, 0, 0, 4480]
def test_dmp_diff_eval_in():
assert dmp_diff_eval_in(f_6, 2, 7, 1, 3, ZZ) == \
dmp_eval(dmp_diff(dmp_swap(f_6, 0, 1, 3, ZZ), 2, 3, ZZ), 7, 3, ZZ)
def test_dup_revert():
f = [-QQ(1, 720), QQ(0), QQ(1, 24), QQ(0), -QQ(1, 2), QQ(0), QQ(1)]
g = [QQ(61, 720), QQ(0), QQ(5, 24), QQ(0), QQ(1, 2), QQ(0), QQ(1)]
assert dup_revert(f, 8, QQ) == g
raises(NotReversible, lambda: dup_revert([QQ(1), QQ(0)], 3, QQ))
def test_dmp_revert():
f = [-QQ(1, 720), QQ(0), QQ(1, 24), QQ(0), -QQ(1, 2), QQ(0), QQ(1)]
g = [QQ(61, 720), QQ(0), QQ(5, 24), QQ(0), QQ(1, 2), QQ(0), QQ(1)]
assert dmp_revert(f, 8, 0, QQ) == g
raises(MultivariatePolynomialError, lambda: dmp_revert([[1]], 2, 1, QQ))
def test_dup_trunc():
assert dup_trunc([1, 2, 3, 4, 5, 6], ZZ(3), ZZ) == [1, -1, 0, 1, -1, 0]
assert dup_trunc([6, 5, 4, 3, 2, 1], ZZ(3), ZZ) == [-1, 1, 0, -1, 1]
def test_dmp_trunc():
assert dmp_trunc([[]], [1, 2], 2, ZZ) == [[]]
assert dmp_trunc([[1, 2], [1, 4, 1], [1]], [1, 2], 1, ZZ) == [[-3], [1]]
def test_dmp_ground_trunc():
assert dmp_ground_trunc(f_0, ZZ(3), 2, ZZ) == \
dmp_normal(
[[[1, -1, 0], [-1]], [[]], [[1, -1, 0], [1, -1, 1], [1]]], 2, ZZ)
def test_dup_monic():
assert dup_monic([3, 6, 9], ZZ) == [1, 2, 3]
raises(ExactQuotientFailed, lambda: dup_monic([3, 4, 5], ZZ))
assert dup_monic([], QQ) == []
assert dup_monic([QQ(1)], QQ) == [QQ(1)]
assert dup_monic([QQ(7), QQ(1), QQ(21)], QQ) == [QQ(1), QQ(1, 7), QQ(3)]
def test_dmp_ground_monic():
assert dmp_ground_monic([[3], [6], [9]], 1, ZZ) == [[1], [2], [3]]
raises(
ExactQuotientFailed, lambda: dmp_ground_monic([[3], [4], [5]], 1, ZZ))
assert dmp_ground_monic([[]], 1, QQ) == [[]]
assert dmp_ground_monic([[QQ(1)]], 1, QQ) == [[QQ(1)]]
assert dmp_ground_monic(
[[QQ(7)], [QQ(1)], [QQ(21)]], 1, QQ) == [[QQ(1)], [QQ(1, 7)], [QQ(3)]]
def test_dup_content():
assert dup_content([], ZZ) == ZZ(0)
assert dup_content([1], ZZ) == ZZ(1)
assert dup_content([-1], ZZ) == ZZ(1)
assert dup_content([1, 1], ZZ) == ZZ(1)
assert dup_content([2, 2], ZZ) == ZZ(2)
assert dup_content([1, 2, 1], ZZ) == ZZ(1)
assert dup_content([2, 4, 2], ZZ) == ZZ(2)
assert dup_content([QQ(2, 3), QQ(4, 9)], QQ) == QQ(2, 9)
assert dup_content([QQ(2, 3), QQ(4, 5)], QQ) == QQ(2, 15)
def test_dmp_ground_content():
assert dmp_ground_content([[]], 1, ZZ) == ZZ(0)
assert dmp_ground_content([[]], 1, QQ) == QQ(0)
assert dmp_ground_content([[1]], 1, ZZ) == ZZ(1)
assert dmp_ground_content([[-1]], 1, ZZ) == ZZ(1)
assert dmp_ground_content([[1], [1]], 1, ZZ) == ZZ(1)
assert dmp_ground_content([[2], [2]], 1, ZZ) == ZZ(2)
assert dmp_ground_content([[1], [2], [1]], 1, ZZ) == ZZ(1)
assert dmp_ground_content([[2], [4], [2]], 1, ZZ) == ZZ(2)
assert dmp_ground_content([[QQ(2, 3)], [QQ(4, 9)]], 1, QQ) == QQ(2, 9)
assert dmp_ground_content([[QQ(2, 3)], [QQ(4, 5)]], 1, QQ) == QQ(2, 15)
assert dmp_ground_content(f_0, 2, ZZ) == ZZ(1)
assert dmp_ground_content(
dmp_mul_ground(f_0, ZZ(2), 2, ZZ), 2, ZZ) == ZZ(2)
assert dmp_ground_content(f_1, 2, ZZ) == ZZ(1)
assert dmp_ground_content(
dmp_mul_ground(f_1, ZZ(3), 2, ZZ), 2, ZZ) == ZZ(3)
assert dmp_ground_content(f_2, 2, ZZ) == ZZ(1)
assert dmp_ground_content(
dmp_mul_ground(f_2, ZZ(4), 2, ZZ), 2, ZZ) == ZZ(4)
assert dmp_ground_content(f_3, 2, ZZ) == ZZ(1)
assert dmp_ground_content(
dmp_mul_ground(f_3, ZZ(5), 2, ZZ), 2, ZZ) == ZZ(5)
assert dmp_ground_content(f_4, 2, ZZ) == ZZ(1)
assert dmp_ground_content(
dmp_mul_ground(f_4, ZZ(6), 2, ZZ), 2, ZZ) == ZZ(6)
assert dmp_ground_content(f_5, 2, ZZ) == ZZ(1)
assert dmp_ground_content(
dmp_mul_ground(f_5, ZZ(7), 2, ZZ), 2, ZZ) == ZZ(7)
assert dmp_ground_content(f_6, 3, ZZ) == ZZ(1)
assert dmp_ground_content(
dmp_mul_ground(f_6, ZZ(8), 3, ZZ), 3, ZZ) == ZZ(8)
def test_dup_primitive():
assert dup_primitive([], ZZ) == (ZZ(0), [])
assert dup_primitive([ZZ(1)], ZZ) == (ZZ(1), [ZZ(1)])
assert dup_primitive([ZZ(1), ZZ(1)], ZZ) == (ZZ(1), [ZZ(1), ZZ(1)])
assert dup_primitive([ZZ(2), ZZ(2)], ZZ) == (ZZ(2), [ZZ(1), ZZ(1)])
assert dup_primitive(
[ZZ(1), ZZ(2), ZZ(1)], ZZ) == (ZZ(1), [ZZ(1), ZZ(2), ZZ(1)])
assert dup_primitive(
[ZZ(2), ZZ(4), ZZ(2)], ZZ) == (ZZ(2), [ZZ(1), ZZ(2), ZZ(1)])
assert dup_primitive([], QQ) == (QQ(0), [])
assert dup_primitive([QQ(1)], QQ) == (QQ(1), [QQ(1)])
assert dup_primitive([QQ(1), QQ(1)], QQ) == (QQ(1), [QQ(1), QQ(1)])
assert dup_primitive([QQ(2), QQ(2)], QQ) == (QQ(2), [QQ(1), QQ(1)])
assert dup_primitive(
[QQ(1), QQ(2), QQ(1)], QQ) == (QQ(1), [QQ(1), QQ(2), QQ(1)])
assert dup_primitive(
[QQ(2), QQ(4), QQ(2)], QQ) == (QQ(2), [QQ(1), QQ(2), QQ(1)])
assert dup_primitive(
[QQ(2, 3), QQ(4, 9)], QQ) == (QQ(2, 9), [QQ(3), QQ(2)])
assert dup_primitive(
[QQ(2, 3), QQ(4, 5)], QQ) == (QQ(2, 15), [QQ(5), QQ(6)])
def test_dmp_ground_primitive():
assert dmp_ground_primitive([[]], 1, ZZ) == (ZZ(0), [[]])
assert dmp_ground_primitive(f_0, 2, ZZ) == (ZZ(1), f_0)
assert dmp_ground_primitive(
dmp_mul_ground(f_0, ZZ(2), 2, ZZ), 2, ZZ) == (ZZ(2), f_0)
assert dmp_ground_primitive(f_1, 2, ZZ) == (ZZ(1), f_1)
assert dmp_ground_primitive(
dmp_mul_ground(f_1, ZZ(3), 2, ZZ), 2, ZZ) == (ZZ(3), f_1)
assert dmp_ground_primitive(f_2, 2, ZZ) == (ZZ(1), f_2)
assert dmp_ground_primitive(
dmp_mul_ground(f_2, ZZ(4), 2, ZZ), 2, ZZ) == (ZZ(4), f_2)
assert dmp_ground_primitive(f_3, 2, ZZ) == (ZZ(1), f_3)
assert dmp_ground_primitive(
dmp_mul_ground(f_3, ZZ(5), 2, ZZ), 2, ZZ) == (ZZ(5), f_3)
assert dmp_ground_primitive(f_4, 2, ZZ) == (ZZ(1), f_4)
assert dmp_ground_primitive(
dmp_mul_ground(f_4, ZZ(6), 2, ZZ), 2, ZZ) == (ZZ(6), f_4)
assert dmp_ground_primitive(f_5, 2, ZZ) == (ZZ(1), f_5)
assert dmp_ground_primitive(
dmp_mul_ground(f_5, ZZ(7), 2, ZZ), 2, ZZ) == (ZZ(7), f_5)
assert dmp_ground_primitive(f_6, 3, ZZ) == (ZZ(1), f_6)
assert dmp_ground_primitive(
dmp_mul_ground(f_6, ZZ(8), 3, ZZ), 3, ZZ) == (ZZ(8), f_6)
assert dmp_ground_primitive([[ZZ(2)]], 1, ZZ) == (ZZ(2), [[ZZ(1)]])
assert dmp_ground_primitive([[QQ(2)]], 1, QQ) == (QQ(2), [[QQ(1)]])
assert dmp_ground_primitive(
[[QQ(2, 3)], [QQ(4, 9)]], 1, QQ) == (QQ(2, 9), [[QQ(3)], [QQ(2)]])
assert dmp_ground_primitive(
[[QQ(2, 3)], [QQ(4, 5)]], 1, QQ) == (QQ(2, 15), [[QQ(5)], [QQ(6)]])
def test_dup_extract():
f = dup_normal([2930944, 0, 2198208, 0, 549552, 0, 45796], ZZ)
g = dup_normal([17585664, 0, 8792832, 0, 1099104, 0], ZZ)
F = dup_normal([64, 0, 48, 0, 12, 0, 1], ZZ)
G = dup_normal([384, 0, 192, 0, 24, 0], ZZ)
assert dup_extract(f, g, ZZ) == (45796, F, G)
def test_dmp_ground_extract():
f = dmp_normal(
[[2930944], [], [2198208], [], [549552], [], [45796]], 1, ZZ)
g = dmp_normal([[17585664], [], [8792832], [], [1099104], []], 1, ZZ)
F = dmp_normal([[64], [], [48], [], [12], [], [1]], 1, ZZ)
G = dmp_normal([[384], [], [192], [], [24], []], 1, ZZ)
assert dmp_ground_extract(f, g, 1, ZZ) == (45796, F, G)
def test_dup_real_imag():
assert dup_real_imag([], ZZ) == ([[]], [[]])
assert dup_real_imag([1], ZZ) == ([[1]], [[]])
assert dup_real_imag([1, 1], ZZ) == ([[1], [1]], [[1, 0]])
assert dup_real_imag([1, 2], ZZ) == ([[1], [2]], [[1, 0]])
assert dup_real_imag(
[1, 2, 3], ZZ) == ([[1], [2], [-1, 0, 3]], [[2, 0], [2, 0]])
raises(DomainError, lambda: dup_real_imag([EX(1), EX(2)], EX))
def test_dup_mirror():
assert dup_mirror([], ZZ) == []
assert dup_mirror([1], ZZ) == [1]
assert dup_mirror([1, 2, 3, 4, 5], ZZ) == [1, -2, 3, -4, 5]
assert dup_mirror([1, 2, 3, 4, 5, 6], ZZ) == [-1, 2, -3, 4, -5, 6]
def test_dup_scale():
assert dup_scale([], -1, ZZ) == []
assert dup_scale([1], -1, ZZ) == [1]
assert dup_scale([1, 2, 3, 4, 5], -1, ZZ) == [1, -2, 3, -4, 5]
assert dup_scale([1, 2, 3, 4, 5], -7, ZZ) == [2401, -686, 147, -28, 5]
def test_dup_shift():
assert dup_shift([], 1, ZZ) == []
assert dup_shift([1], 1, ZZ) == [1]
assert dup_shift([1, 2, 3, 4, 5], 1, ZZ) == [1, 6, 15, 20, 15]
assert dup_shift([1, 2, 3, 4, 5], 7, ZZ) == [1, 30, 339, 1712, 3267]
def test_dup_transform():
assert dup_transform([], [], [1, 1], ZZ) == []
assert dup_transform([], [1], [1, 1], ZZ) == []
assert dup_transform([], [1, 2], [1, 1], ZZ) == []
assert dup_transform([6, -5, 4, -3, 17], [1, -3, 4], [2, -3], ZZ) == \
[6, -82, 541, -2205, 6277, -12723, 17191, -13603, 4773]
def test_dup_compose():
assert dup_compose([], [], ZZ) == []
assert dup_compose([], [1], ZZ) == []
assert dup_compose([], [1, 2], ZZ) == []
assert dup_compose([1], [], ZZ) == [1]
assert dup_compose([1, 2, 0], [], ZZ) == []
assert dup_compose([1, 2, 1], [], ZZ) == [1]
assert dup_compose([1, 2, 1], [1], ZZ) == [4]
assert dup_compose([1, 2, 1], [7], ZZ) == [64]
assert dup_compose([1, 2, 1], [1, -1], ZZ) == [1, 0, 0]
assert dup_compose([1, 2, 1], [1, 1], ZZ) == [1, 4, 4]
assert dup_compose([1, 2, 1], [1, 2, 1], ZZ) == [1, 4, 8, 8, 4]
def test_dmp_compose():
assert dmp_compose([1, 2, 1], [1, 2, 1], 0, ZZ) == [1, 4, 8, 8, 4]
assert dmp_compose([[[]]], [[[]]], 2, ZZ) == [[[]]]
assert dmp_compose([[[]]], [[[1]]], 2, ZZ) == [[[]]]
assert dmp_compose([[[]]], [[[1]], [[2]]], 2, ZZ) == [[[]]]
assert dmp_compose([[[1]]], [], 2, ZZ) == [[[1]]]
assert dmp_compose([[1], [2], [ ]], [[]], 1, ZZ) == [[]]
assert dmp_compose([[1], [2], [1]], [[]], 1, ZZ) == [[1]]
assert dmp_compose([[1], [2], [1]], [[1]], 1, ZZ) == [[4]]
assert dmp_compose([[1], [2], [1]], [[7]], 1, ZZ) == [[64]]
assert dmp_compose([[1], [2], [1]], [[1], [-1]], 1, ZZ) == [[1], [ ], [ ]]
assert dmp_compose([[1], [2], [1]], [[1], [ 1]], 1, ZZ) == [[1], [4], [4]]
assert dmp_compose(
[[1], [2], [1]], [[1], [2], [1]], 1, ZZ) == [[1], [4], [8], [8], [4]]
def test_dup_decompose():
assert dup_decompose([1], ZZ) == [[1]]
assert dup_decompose([1, 0], ZZ) == [[1, 0]]
assert dup_decompose([1, 0, 0, 0], ZZ) == [[1, 0, 0, 0]]
assert dup_decompose([1, 0, 0, 0, 0], ZZ) == [[1, 0, 0], [1, 0, 0]]
assert dup_decompose(
[1, 0, 0, 0, 0, 0, 0], ZZ) == [[1, 0, 0, 0], [1, 0, 0]]
assert dup_decompose([7, 0, 0, 0, 1], ZZ) == [[7, 0, 1], [1, 0, 0]]
assert dup_decompose([4, 0, 3, 0, 2], ZZ) == [[4, 3, 2], [1, 0, 0]]
f = [1, 0, 20, 0, 150, 0, 500, 0, 625, -2, 0, -10, 9]
assert dup_decompose(f, ZZ) == [[1, 0, 0, -2, 9], [1, 0, 5, 0]]
f = [2, 0, 40, 0, 300, 0, 1000, 0, 1250, -4, 0, -20, 18]
assert dup_decompose(f, ZZ) == [[2, 0, 0, -4, 18], [1, 0, 5, 0]]
f = [1, 0, 20, -8, 150, -120, 524, -600, 865, -1034, 600, -170, 29]
assert dup_decompose(f, ZZ) == [[1, -8, 24, -34, 29], [1, 0, 5, 0]]
R, t = ring("t", ZZ)
f = [6*t**2 - 42,
48*t**2 + 96,
144*t**2 + 648*t + 288,
624*t**2 + 864*t + 384,
108*t**3 + 312*t**2 + 432*t + 192]
assert dup_decompose(f, R.to_domain()) == [f]
def test_dmp_lift():
q = [QQ(1, 1), QQ(0, 1), QQ(1, 1)]
f = [ANP([QQ(1, 1)], q, QQ), ANP([], q, QQ), ANP([], q, QQ),
ANP([QQ(1, 1), QQ(0, 1)], q, QQ), ANP([QQ(17, 1), QQ(0, 1)], q, QQ)]
assert dmp_lift(f, 0, QQ.algebraic_field(I)) == \
[QQ(1), QQ(0), QQ(0), QQ(0), QQ(0), QQ(0), QQ(2), QQ(0), QQ(578),
QQ(0), QQ(0), QQ(0), QQ(1), QQ(0), QQ(-578), QQ(0), QQ(83521)]
raises(DomainError, lambda: dmp_lift([EX(1), EX(2)], 0, EX))
def test_dup_sign_variations():
assert dup_sign_variations([], ZZ) == 0
assert dup_sign_variations([1, 0], ZZ) == 0
assert dup_sign_variations([1, 0, 2], ZZ) == 0
assert dup_sign_variations([1, 0, 3, 0], ZZ) == 0
assert dup_sign_variations([1, 0, 4, 0, 5], ZZ) == 0
assert dup_sign_variations([-1, 0, 2], ZZ) == 1
assert dup_sign_variations([-1, 0, 3, 0], ZZ) == 1
assert dup_sign_variations([-1, 0, 4, 0, 5], ZZ) == 1
assert dup_sign_variations([-1, -4, -5], ZZ) == 0
assert dup_sign_variations([ 1, -4, -5], ZZ) == 1
assert dup_sign_variations([ 1, 4, -5], ZZ) == 1
assert dup_sign_variations([ 1, -4, 5], ZZ) == 2
assert dup_sign_variations([-1, 4, -5], ZZ) == 2
assert dup_sign_variations([-1, 4, 5], ZZ) == 1
assert dup_sign_variations([-1, -4, 5], ZZ) == 1
assert dup_sign_variations([ 1, 4, 5], ZZ) == 0
assert dup_sign_variations([-1, 0, -4, 0, -5], ZZ) == 0
assert dup_sign_variations([ 1, 0, -4, 0, -5], ZZ) == 1
assert dup_sign_variations([ 1, 0, 4, 0, -5], ZZ) == 1
assert dup_sign_variations([ 1, 0, -4, 0, 5], ZZ) == 2
assert dup_sign_variations([-1, 0, 4, 0, -5], ZZ) == 2
assert dup_sign_variations([-1, 0, 4, 0, 5], ZZ) == 1
assert dup_sign_variations([-1, 0, -4, 0, 5], ZZ) == 1
assert dup_sign_variations([ 1, 0, 4, 0, 5], ZZ) == 0
def test_dup_clear_denoms():
assert dup_clear_denoms([], QQ, ZZ) == (ZZ(1), [])
assert dup_clear_denoms([QQ(1)], QQ, ZZ) == (ZZ(1), [QQ(1)])
assert dup_clear_denoms([QQ(7)], QQ, ZZ) == (ZZ(1), [QQ(7)])
assert dup_clear_denoms([QQ(7, 3)], QQ) == (ZZ(3), [QQ(7)])
assert dup_clear_denoms([QQ(7, 3)], QQ, ZZ) == (ZZ(3), [QQ(7)])
assert dup_clear_denoms(
[QQ(3), QQ(1), QQ(0)], QQ, ZZ) == (ZZ(1), [QQ(3), QQ(1), QQ(0)])
assert dup_clear_denoms(
[QQ(1), QQ(1, 2), QQ(0)], QQ, ZZ) == (ZZ(2), [QQ(2), QQ(1), QQ(0)])
assert dup_clear_denoms([QQ(3), QQ(
1), QQ(0)], QQ, ZZ, convert=True) == (ZZ(1), [ZZ(3), ZZ(1), ZZ(0)])
assert dup_clear_denoms([QQ(1), QQ(
1, 2), QQ(0)], QQ, ZZ, convert=True) == (ZZ(2), [ZZ(2), ZZ(1), ZZ(0)])
assert dup_clear_denoms(
[EX(S(3)/2), EX(S(9)/4)], EX) == (EX(4), [EX(6), EX(9)])
assert dup_clear_denoms([EX(7)], EX) == (EX(1), [EX(7)])
assert dup_clear_denoms([EX(sin(x)/x), EX(0)], EX) == (EX(x), [EX(sin(x)), EX(0)])
def test_dmp_clear_denoms():
assert dmp_clear_denoms([[]], 1, QQ, ZZ) == (ZZ(1), [[]])
assert dmp_clear_denoms([[QQ(1)]], 1, QQ, ZZ) == (ZZ(1), [[QQ(1)]])
assert dmp_clear_denoms([[QQ(7)]], 1, QQ, ZZ) == (ZZ(1), [[QQ(7)]])
assert dmp_clear_denoms([[QQ(7, 3)]], 1, QQ) == (ZZ(3), [[QQ(7)]])
assert dmp_clear_denoms([[QQ(7, 3)]], 1, QQ, ZZ) == (ZZ(3), [[QQ(7)]])
assert dmp_clear_denoms(
[[QQ(3)], [QQ(1)], []], 1, QQ, ZZ) == (ZZ(1), [[QQ(3)], [QQ(1)], []])
assert dmp_clear_denoms([[QQ(
1)], [QQ(1, 2)], []], 1, QQ, ZZ) == (ZZ(2), [[QQ(2)], [QQ(1)], []])
assert dmp_clear_denoms([QQ(3), QQ(
1), QQ(0)], 0, QQ, ZZ, convert=True) == (ZZ(1), [ZZ(3), ZZ(1), ZZ(0)])
assert dmp_clear_denoms([QQ(1), QQ(1, 2), QQ(
0)], 0, QQ, ZZ, convert=True) == (ZZ(2), [ZZ(2), ZZ(1), ZZ(0)])
assert dmp_clear_denoms([[QQ(3)], [QQ(
1)], []], 1, QQ, ZZ, convert=True) == (ZZ(1), [[QQ(3)], [QQ(1)], []])
assert dmp_clear_denoms([[QQ(1)], [QQ(1, 2)], []], 1, QQ, ZZ,
convert=True) == (ZZ(2), [[QQ(2)], [QQ(1)], []])
assert dmp_clear_denoms(
[[EX(S(3)/2)], [EX(S(9)/4)]], 1, EX) == (EX(4), [[EX(6)], [EX(9)]])
assert dmp_clear_denoms([[EX(7)]], 1, EX) == (EX(1), [[EX(7)]])
assert dmp_clear_denoms([[EX(sin(x)/x), EX(0)]], 1, EX) == (EX(x), [[EX(sin(x)), EX(0)]])
| 24,378 | 35.605105 | 97 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/tests/test_polyutils.py
|
"""Tests for useful utilities for higher level polynomial classes. """
from sympy import (S, Integer, sin, cos, sqrt, symbols, pi,
Eq, Integral, exp, Mul)
from sympy.utilities.pytest import raises
from sympy.polys.polyutils import (
_nsort,
_sort_gens,
_unify_gens,
_analyze_gens,
_sort_factors,
parallel_dict_from_expr,
dict_from_expr,
)
from sympy.polys.polyerrors import (
GeneratorsNeeded,
PolynomialError,
)
from sympy.polys.domains import ZZ
x, y, z, p, q, r, s, t, u, v, w = symbols('x,y,z,p,q,r,s,t,u,v,w')
A, B = symbols('A,B', commutative=False)
def test__nsort():
# issue 6137
r = S('''[3/2 + sqrt(-14/3 - 2*(-415/216 + 13*I/12)**(1/3) - 4/sqrt(-7/3 +
61/(18*(-415/216 + 13*I/12)**(1/3)) + 2*(-415/216 + 13*I/12)**(1/3)) -
61/(18*(-415/216 + 13*I/12)**(1/3)))/2 - sqrt(-7/3 + 61/(18*(-415/216
+ 13*I/12)**(1/3)) + 2*(-415/216 + 13*I/12)**(1/3))/2, 3/2 - sqrt(-7/3
+ 61/(18*(-415/216 + 13*I/12)**(1/3)) + 2*(-415/216 +
13*I/12)**(1/3))/2 - sqrt(-14/3 - 2*(-415/216 + 13*I/12)**(1/3) -
4/sqrt(-7/3 + 61/(18*(-415/216 + 13*I/12)**(1/3)) + 2*(-415/216 +
13*I/12)**(1/3)) - 61/(18*(-415/216 + 13*I/12)**(1/3)))/2, 3/2 +
sqrt(-14/3 - 2*(-415/216 + 13*I/12)**(1/3) + 4/sqrt(-7/3 +
61/(18*(-415/216 + 13*I/12)**(1/3)) + 2*(-415/216 + 13*I/12)**(1/3)) -
61/(18*(-415/216 + 13*I/12)**(1/3)))/2 + sqrt(-7/3 + 61/(18*(-415/216
+ 13*I/12)**(1/3)) + 2*(-415/216 + 13*I/12)**(1/3))/2, 3/2 + sqrt(-7/3
+ 61/(18*(-415/216 + 13*I/12)**(1/3)) + 2*(-415/216 +
13*I/12)**(1/3))/2 - sqrt(-14/3 - 2*(-415/216 + 13*I/12)**(1/3) +
4/sqrt(-7/3 + 61/(18*(-415/216 + 13*I/12)**(1/3)) + 2*(-415/216 +
13*I/12)**(1/3)) - 61/(18*(-415/216 + 13*I/12)**(1/3)))/2]''')
ans = [r[1], r[0], r[-1], r[-2]]
assert _nsort(r) == ans
assert len(_nsort(r, separated=True)[0]) == 0
b, c, a = exp(-1000), exp(-999), exp(-1001)
assert _nsort((b, c, a)) == [a, b, c]
def test__sort_gens():
assert _sort_gens([]) == ()
assert _sort_gens([x]) == (x,)
assert _sort_gens([p]) == (p,)
assert _sort_gens([q]) == (q,)
assert _sort_gens([x, p]) == (x, p)
assert _sort_gens([p, x]) == (x, p)
assert _sort_gens([q, p]) == (p, q)
assert _sort_gens([q, p, x]) == (x, p, q)
assert _sort_gens([x, p, q], wrt=x) == (x, p, q)
assert _sort_gens([x, p, q], wrt=p) == (p, x, q)
assert _sort_gens([x, p, q], wrt=q) == (q, x, p)
assert _sort_gens([x, p, q], wrt='x') == (x, p, q)
assert _sort_gens([x, p, q], wrt='p') == (p, x, q)
assert _sort_gens([x, p, q], wrt='q') == (q, x, p)
assert _sort_gens([x, p, q], wrt='x,q') == (x, q, p)
assert _sort_gens([x, p, q], wrt='q,x') == (q, x, p)
assert _sort_gens([x, p, q], wrt='p,q') == (p, q, x)
assert _sort_gens([x, p, q], wrt='q,p') == (q, p, x)
assert _sort_gens([x, p, q], wrt='x, q') == (x, q, p)
assert _sort_gens([x, p, q], wrt='q, x') == (q, x, p)
assert _sort_gens([x, p, q], wrt='p, q') == (p, q, x)
assert _sort_gens([x, p, q], wrt='q, p') == (q, p, x)
assert _sort_gens([x, p, q], wrt=[x, 'q']) == (x, q, p)
assert _sort_gens([x, p, q], wrt=[q, 'x']) == (q, x, p)
assert _sort_gens([x, p, q], wrt=[p, 'q']) == (p, q, x)
assert _sort_gens([x, p, q], wrt=[q, 'p']) == (q, p, x)
assert _sort_gens([x, p, q], wrt=['x', 'q']) == (x, q, p)
assert _sort_gens([x, p, q], wrt=['q', 'x']) == (q, x, p)
assert _sort_gens([x, p, q], wrt=['p', 'q']) == (p, q, x)
assert _sort_gens([x, p, q], wrt=['q', 'p']) == (q, p, x)
assert _sort_gens([x, p, q], sort='x > p > q') == (x, p, q)
assert _sort_gens([x, p, q], sort='p > x > q') == (p, x, q)
assert _sort_gens([x, p, q], sort='p > q > x') == (p, q, x)
assert _sort_gens([x, p, q], wrt='x', sort='q > p') == (x, q, p)
assert _sort_gens([x, p, q], wrt='p', sort='q > x') == (p, q, x)
assert _sort_gens([x, p, q], wrt='q', sort='p > x') == (q, p, x)
X = symbols('x0,x1,x2,x10,x11,x12,x20,x21,x22')
assert _sort_gens(X) == X
def test__unify_gens():
assert _unify_gens([], []) == ()
assert _unify_gens([x], [x]) == (x,)
assert _unify_gens([y], [y]) == (y,)
assert _unify_gens([x, y], [x]) == (x, y)
assert _unify_gens([x], [x, y]) == (x, y)
assert _unify_gens([x, y], [x, y]) == (x, y)
assert _unify_gens([y, x], [y, x]) == (y, x)
assert _unify_gens([x], [y]) == (x, y)
assert _unify_gens([y], [x]) == (y, x)
assert _unify_gens([x], [y, x]) == (y, x)
assert _unify_gens([y, x], [x]) == (y, x)
assert _unify_gens([x, y, z], [x, y, z]) == (x, y, z)
assert _unify_gens([z, y, x], [x, y, z]) == (z, y, x)
assert _unify_gens([x, y, z], [z, y, x]) == (x, y, z)
assert _unify_gens([z, y, x], [z, y, x]) == (z, y, x)
assert _unify_gens([x, y, z], [t, x, p, q, z]) == (t, x, y, p, q, z)
def test__analyze_gens():
assert _analyze_gens((x, y, z)) == (x, y, z)
assert _analyze_gens([x, y, z]) == (x, y, z)
assert _analyze_gens(([x, y, z],)) == (x, y, z)
assert _analyze_gens(((x, y, z),)) == (x, y, z)
def test__sort_factors():
assert _sort_factors([], multiple=True) == []
assert _sort_factors([], multiple=False) == []
F = [[1, 2, 3], [1, 2], [1]]
G = [[1], [1, 2], [1, 2, 3]]
assert _sort_factors(F, multiple=False) == G
F = [[1, 2], [1, 2, 3], [1, 2], [1]]
G = [[1], [1, 2], [1, 2], [1, 2, 3]]
assert _sort_factors(F, multiple=False) == G
F = [[2, 2], [1, 2, 3], [1, 2], [1]]
G = [[1], [1, 2], [2, 2], [1, 2, 3]]
assert _sort_factors(F, multiple=False) == G
F = [([1, 2, 3], 1), ([1, 2], 1), ([1], 1)]
G = [([1], 1), ([1, 2], 1), ([1, 2, 3], 1)]
assert _sort_factors(F, multiple=True) == G
F = [([1, 2], 1), ([1, 2, 3], 1), ([1, 2], 1), ([1], 1)]
G = [([1], 1), ([1, 2], 1), ([1, 2], 1), ([1, 2, 3], 1)]
assert _sort_factors(F, multiple=True) == G
F = [([2, 2], 1), ([1, 2, 3], 1), ([1, 2], 1), ([1], 1)]
G = [([1], 1), ([1, 2], 1), ([2, 2], 1), ([1, 2, 3], 1)]
assert _sort_factors(F, multiple=True) == G
F = [([2, 2], 1), ([1, 2, 3], 1), ([1, 2], 2), ([1], 1)]
G = [([1], 1), ([2, 2], 1), ([1, 2], 2), ([1, 2, 3], 1)]
assert _sort_factors(F, multiple=True) == G
def test__dict_from_expr_if_gens():
assert dict_from_expr(
Integer(17), gens=(x,)) == ({(0,): Integer(17)}, (x,))
assert dict_from_expr(
Integer(17), gens=(x, y)) == ({(0, 0): Integer(17)}, (x, y))
assert dict_from_expr(
Integer(17), gens=(x, y, z)) == ({(0, 0, 0): Integer(17)}, (x, y, z))
assert dict_from_expr(
Integer(-17), gens=(x,)) == ({(0,): Integer(-17)}, (x,))
assert dict_from_expr(
Integer(-17), gens=(x, y)) == ({(0, 0): Integer(-17)}, (x, y))
assert dict_from_expr(Integer(
-17), gens=(x, y, z)) == ({(0, 0, 0): Integer(-17)}, (x, y, z))
assert dict_from_expr(
Integer(17)*x, gens=(x,)) == ({(1,): Integer(17)}, (x,))
assert dict_from_expr(
Integer(17)*x, gens=(x, y)) == ({(1, 0): Integer(17)}, (x, y))
assert dict_from_expr(Integer(
17)*x, gens=(x, y, z)) == ({(1, 0, 0): Integer(17)}, (x, y, z))
assert dict_from_expr(
Integer(17)*x**7, gens=(x,)) == ({(7,): Integer(17)}, (x,))
assert dict_from_expr(
Integer(17)*x**7*y, gens=(x, y)) == ({(7, 1): Integer(17)}, (x, y))
assert dict_from_expr(Integer(17)*x**7*y*z**12, gens=(
x, y, z)) == ({(7, 1, 12): Integer(17)}, (x, y, z))
assert dict_from_expr(x + 2*y + 3*z, gens=(x,)) == \
({(1,): Integer(1), (0,): 2*y + 3*z}, (x,))
assert dict_from_expr(x + 2*y + 3*z, gens=(x, y)) == \
({(1, 0): Integer(1), (0, 1): Integer(2), (0, 0): 3*z}, (x, y))
assert dict_from_expr(x + 2*y + 3*z, gens=(x, y, z)) == \
({(1, 0, 0): Integer(
1), (0, 1, 0): Integer(2), (0, 0, 1): Integer(3)}, (x, y, z))
assert dict_from_expr(x*y + 2*x*z + 3*y*z, gens=(x,)) == \
({(1,): y + 2*z, (0,): 3*y*z}, (x,))
assert dict_from_expr(x*y + 2*x*z + 3*y*z, gens=(x, y)) == \
({(1, 1): Integer(1), (1, 0): 2*z, (0, 1): 3*z}, (x, y))
assert dict_from_expr(x*y + 2*x*z + 3*y*z, gens=(x, y, z)) == \
({(1, 1, 0): Integer(
1), (1, 0, 1): Integer(2), (0, 1, 1): Integer(3)}, (x, y, z))
assert dict_from_expr(2**y*x, gens=(x,)) == ({(1,): 2**y}, (x,))
assert dict_from_expr(Integral(x, (x, 1, 2)) + x) == (
{(0, 1): 1, (1, 0): 1}, (x, Integral(x, (x, 1, 2))))
raises(PolynomialError, lambda: dict_from_expr(2**y*x, gens=(x, y)))
def test__dict_from_expr_no_gens():
assert dict_from_expr(Integer(17)) == ({(): Integer(17)}, ())
assert dict_from_expr(x) == ({(1,): Integer(1)}, (x,))
assert dict_from_expr(y) == ({(1,): Integer(1)}, (y,))
assert dict_from_expr(x*y) == ({(1, 1): Integer(1)}, (x, y))
assert dict_from_expr(
x + y) == ({(1, 0): Integer(1), (0, 1): Integer(1)}, (x, y))
assert dict_from_expr(sqrt(2)) == ({(1,): Integer(1)}, (sqrt(2),))
assert dict_from_expr(sqrt(2), greedy=False) == ({(): sqrt(2)}, ())
assert dict_from_expr(x*y, domain=ZZ[x]) == ({(1,): x}, (y,))
assert dict_from_expr(x*y, domain=ZZ[y]) == ({(1,): y}, (x,))
assert dict_from_expr(3*sqrt(
2)*pi*x*y, extension=None) == ({(1, 1, 1, 1): 3}, (x, y, pi, sqrt(2)))
assert dict_from_expr(3*sqrt(
2)*pi*x*y, extension=True) == ({(1, 1, 1): 3*sqrt(2)}, (x, y, pi))
assert dict_from_expr(3*sqrt(
2)*pi*x*y, extension=True) == ({(1, 1, 1): 3*sqrt(2)}, (x, y, pi))
f = cos(x)*sin(x) + cos(x)*sin(y) + cos(y)*sin(x) + cos(y)*sin(y)
assert dict_from_expr(f) == ({(0, 1, 0, 1): 1, (0, 1, 1, 0): 1,
(1, 0, 0, 1): 1, (1, 0, 1, 0): 1}, (cos(x), cos(y), sin(x), sin(y)))
def test__parallel_dict_from_expr_if_gens():
assert parallel_dict_from_expr([x + 2*y + 3*z, Integer(7)], gens=(x,)) == \
([{(1,): Integer(1), (0,): 2*y + 3*z}, {(0,): Integer(7)}], (x,))
def test__parallel_dict_from_expr_no_gens():
assert parallel_dict_from_expr([x*y, Integer(3)]) == \
([{(1, 1): Integer(1)}, {(0, 0): Integer(3)}], (x, y))
assert parallel_dict_from_expr([x*y, 2*z, Integer(3)]) == \
([{(1, 1, 0): Integer(
1)}, {(0, 0, 1): Integer(2)}, {(0, 0, 0): Integer(3)}], (x, y, z))
assert parallel_dict_from_expr((Mul(x, x**2, evaluate=False),)) == \
([{(3,): 1}], (x,))
def test_parallel_dict_from_expr():
assert parallel_dict_from_expr([Eq(x, 1), Eq(
x**2, 2)]) == ([{(0,): -Integer(1), (1,): Integer(1)},
{(0,): -Integer(2), (2,): Integer(1)}], (x,))
raises(PolynomialError, lambda: parallel_dict_from_expr([A*B - B*A]))
def test_dict_from_expr():
assert dict_from_expr(Eq(x, 1)) == \
({(0,): -Integer(1), (1,): Integer(1)}, (x,))
raises(PolynomialError, lambda: dict_from_expr(A*B - B*A))
raises(PolynomialError, lambda: dict_from_expr(S.true))
| 11,013 | 37.110727 | 79 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/tests/test_fields.py
|
"""Test sparse rational functions. """
from sympy.polys.fields import field, sfield, FracField
from sympy.polys.rings import ring
from sympy.polys.domains import ZZ, QQ
from sympy.polys.orderings import lex
from sympy.utilities.pytest import raises, XFAIL
from sympy.core import symbols, E
from sympy import sqrt, Rational, exp, log
def test_FracField___init__():
F1 = FracField("x,y", ZZ, lex)
F2 = FracField("x,y", ZZ, lex)
F3 = FracField("x,y,z", ZZ, lex)
assert F1.x == F1.gens[0]
assert F1.y == F1.gens[1]
assert F1.x == F2.x
assert F1.y == F2.y
assert F1.x != F3.x
assert F1.y != F3.y
def test_FracField___hash__():
F, x, y, z = field("x,y,z", QQ)
assert hash(F)
def test_FracField___eq__():
assert field("x,y,z", QQ)[0] == field("x,y,z", QQ)[0]
assert field("x,y,z", QQ)[0] is field("x,y,z", QQ)[0]
assert field("x,y,z", QQ)[0] != field("x,y,z", ZZ)[0]
assert field("x,y,z", QQ)[0] is not field("x,y,z", ZZ)[0]
assert field("x,y,z", ZZ)[0] != field("x,y,z", QQ)[0]
assert field("x,y,z", ZZ)[0] is not field("x,y,z", QQ)[0]
assert field("x,y,z", QQ)[0] != field("x,y", QQ)[0]
assert field("x,y,z", QQ)[0] is not field("x,y", QQ)[0]
assert field("x,y", QQ)[0] != field("x,y,z", QQ)[0]
assert field("x,y", QQ)[0] is not field("x,y,z", QQ)[0]
def test_sfield():
x = symbols("x")
F = FracField((E, exp(exp(x)), exp(x)), ZZ, lex)
e, exex, ex = F.gens
assert sfield(exp(x)*exp(exp(x) + 1 + log(exp(x) + 3)/2)**2/(exp(x) + 3)) \
== (F, e**2*exex**2*ex)
F = FracField((x, exp(1/x), log(x), x**QQ(1, 3)), ZZ, lex)
_, ex, lg, x3 = F.gens
assert sfield(((x-3)*log(x)+4*x**2)*exp(1/x+log(x)/3)/x**2) == \
(F, (4*F.x**2*ex + F.x*ex*lg - 3*ex*lg)/x3**5)
F = FracField((x, log(x), sqrt(x + log(x))), ZZ, lex)
_, lg, srt = F.gens
assert sfield((x + 1) / (x * (x + log(x))**QQ(3, 2)) - 1/(x * log(x)**2)) \
== (F, (F.x*lg**2 - F.x*srt + lg**2 - lg*srt)/
(F.x**2*lg**2*srt + F.x*lg**3*srt))
def test_FracElement___hash__():
F, x, y, z = field("x,y,z", QQ)
assert hash(x*y/z)
def test_FracElement_copy():
F, x, y, z = field("x,y,z", ZZ)
f = x*y/3*z
g = f.copy()
assert f == g
g.numer[(1, 1, 1)] = 7
assert f != g
def test_FracElement_as_expr():
F, x, y, z = field("x,y,z", ZZ)
f = (3*x**2*y - x*y*z)/(7*z**3 + 1)
X, Y, Z = F.symbols
g = (3*X**2*Y - X*Y*Z)/(7*Z**3 + 1)
assert f != g
assert f.as_expr() == g
X, Y, Z = symbols("x,y,z")
g = (3*X**2*Y - X*Y*Z)/(7*Z**3 + 1)
assert f != g
assert f.as_expr(X, Y, Z) == g
raises(ValueError, lambda: f.as_expr(X))
def test_FracElement_from_expr():
x, y, z = symbols("x,y,z")
F, X, Y, Z = field((x, y, z), ZZ)
f = F.from_expr(1)
assert f == 1 and isinstance(f, F.dtype)
f = F.from_expr(Rational(3, 7))
assert f == F(3)/7 and isinstance(f, F.dtype)
f = F.from_expr(x)
assert f == X and isinstance(f, F.dtype)
f = F.from_expr(Rational(3,7)*x)
assert f == 3*X/7 and isinstance(f, F.dtype)
f = F.from_expr(1/x)
assert f == 1/X and isinstance(f, F.dtype)
f = F.from_expr(x*y*z)
assert f == X*Y*Z and isinstance(f, F.dtype)
f = F.from_expr(x*y/z)
assert f == X*Y/Z and isinstance(f, F.dtype)
f = F.from_expr(x*y*z + x*y + x)
assert f == X*Y*Z + X*Y + X and isinstance(f, F.dtype)
f = F.from_expr((x*y*z + x*y + x)/(x*y + 7))
assert f == (X*Y*Z + X*Y + X)/(X*Y + 7) and isinstance(f, F.dtype)
f = F.from_expr(x**3*y*z + x**2*y**7 + 1)
assert f == X**3*Y*Z + X**2*Y**7 + 1 and isinstance(f, F.dtype)
raises(ValueError, lambda: F.from_expr(2**x))
raises(ValueError, lambda: F.from_expr(7*x + sqrt(2)))
def test_FracElement__lt_le_gt_ge__():
F, x, y = field("x,y", ZZ)
assert F(1) < 1/x < 1/x**2 < 1/x**3
assert F(1) <= 1/x <= 1/x**2 <= 1/x**3
assert -7/x < 1/x < 3/x < y/x < 1/x**2
assert -7/x <= 1/x <= 3/x <= y/x <= 1/x**2
assert 1/x**3 > 1/x**2 > 1/x > F(1)
assert 1/x**3 >= 1/x**2 >= 1/x >= F(1)
assert 1/x**2 > y/x > 3/x > 1/x > -7/x
assert 1/x**2 >= y/x >= 3/x >= 1/x >= -7/x
def test_FracElement___neg__():
F, x,y = field("x,y", QQ)
f = (7*x - 9)/y
g = (-7*x + 9)/y
assert -f == g
assert -g == f
def test_FracElement___add__():
F, x,y = field("x,y", QQ)
f, g = 1/x, 1/y
assert f + g == g + f == (x + y)/(x*y)
assert x + F.ring.gens[0] == F.ring.gens[0] + x == 2*x
F, x,y = field("x,y", ZZ)
assert x + 3 == 3 + x
assert x + QQ(3,7) == QQ(3,7) + x == (7*x + 3)/7
Fuv, u,v = field("u,v", ZZ)
Fxyzt, x,y,z,t = field("x,y,z,t", Fuv)
f = (u*v + x)/(y + u*v)
assert dict(f.numer) == {(1, 0, 0, 0): 1, (0, 0, 0, 0): u*v}
assert dict(f.denom) == {(0, 1, 0, 0): 1, (0, 0, 0, 0): u*v}
Ruv, u,v = ring("u,v", ZZ)
Fxyzt, x,y,z,t = field("x,y,z,t", Ruv)
f = (u*v + x)/(y + u*v)
assert dict(f.numer) == {(1, 0, 0, 0): 1, (0, 0, 0, 0): u*v}
assert dict(f.denom) == {(0, 1, 0, 0): 1, (0, 0, 0, 0): u*v}
def test_FracElement___sub__():
F, x,y = field("x,y", QQ)
f, g = 1/x, 1/y
assert f - g == (-x + y)/(x*y)
assert x - F.ring.gens[0] == F.ring.gens[0] - x == 0
F, x,y = field("x,y", ZZ)
assert x - 3 == -(3 - x)
assert x - QQ(3,7) == -(QQ(3,7) - x) == (7*x - 3)/7
Fuv, u,v = field("u,v", ZZ)
Fxyzt, x,y,z,t = field("x,y,z,t", Fuv)
f = (u*v - x)/(y - u*v)
assert dict(f.numer) == {(1, 0, 0, 0):-1, (0, 0, 0, 0): u*v}
assert dict(f.denom) == {(0, 1, 0, 0): 1, (0, 0, 0, 0):-u*v}
Ruv, u,v = ring("u,v", ZZ)
Fxyzt, x,y,z,t = field("x,y,z,t", Ruv)
f = (u*v - x)/(y - u*v)
assert dict(f.numer) == {(1, 0, 0, 0):-1, (0, 0, 0, 0): u*v}
assert dict(f.denom) == {(0, 1, 0, 0): 1, (0, 0, 0, 0):-u*v}
def test_FracElement___mul__():
F, x,y = field("x,y", QQ)
f, g = 1/x, 1/y
assert f*g == g*f == 1/(x*y)
assert x*F.ring.gens[0] == F.ring.gens[0]*x == x**2
F, x,y = field("x,y", ZZ)
assert x*3 == 3*x
assert x*QQ(3,7) == QQ(3,7)*x == 3*x/7
Fuv, u,v = field("u,v", ZZ)
Fxyzt, x,y,z,t = field("x,y,z,t", Fuv)
f = ((u + 1)*x*y + 1)/((v - 1)*z - t*u*v - 1)
assert dict(f.numer) == {(1, 1, 0, 0): u + 1, (0, 0, 0, 0): 1}
assert dict(f.denom) == {(0, 0, 1, 0): v - 1, (0, 0, 0, 1): -u*v, (0, 0, 0, 0): -1}
Ruv, u,v = ring("u,v", ZZ)
Fxyzt, x,y,z,t = field("x,y,z,t", Ruv)
f = ((u + 1)*x*y + 1)/((v - 1)*z - t*u*v - 1)
assert dict(f.numer) == {(1, 1, 0, 0): u + 1, (0, 0, 0, 0): 1}
assert dict(f.denom) == {(0, 0, 1, 0): v - 1, (0, 0, 0, 1): -u*v, (0, 0, 0, 0): -1}
def test_FracElement___div__():
F, x,y = field("x,y", QQ)
f, g = 1/x, 1/y
assert f/g == y/x
assert x/F.ring.gens[0] == F.ring.gens[0]/x == 1
F, x,y = field("x,y", ZZ)
assert x*3 == 3*x
assert x/QQ(3,7) == (QQ(3,7)/x)**-1 == 7*x/3
raises(ZeroDivisionError, lambda: x/0)
raises(ZeroDivisionError, lambda: 1/(x - x))
raises(ZeroDivisionError, lambda: x/(x - x))
Fuv, u,v = field("u,v", ZZ)
Fxyzt, x,y,z,t = field("x,y,z,t", Fuv)
f = (u*v)/(x*y)
assert dict(f.numer) == {(0, 0, 0, 0): u*v}
assert dict(f.denom) == {(1, 1, 0, 0): 1}
g = (x*y)/(u*v)
assert dict(g.numer) == {(1, 1, 0, 0): 1}
assert dict(g.denom) == {(0, 0, 0, 0): u*v}
Ruv, u,v = ring("u,v", ZZ)
Fxyzt, x,y,z,t = field("x,y,z,t", Ruv)
f = (u*v)/(x*y)
assert dict(f.numer) == {(0, 0, 0, 0): u*v}
assert dict(f.denom) == {(1, 1, 0, 0): 1}
g = (x*y)/(u*v)
assert dict(g.numer) == {(1, 1, 0, 0): 1}
assert dict(g.denom) == {(0, 0, 0, 0): u*v}
def test_FracElement___pow__():
F, x,y = field("x,y", QQ)
f, g = 1/x, 1/y
assert f**3 == 1/x**3
assert g**3 == 1/y**3
assert (f*g)**3 == 1/(x**3*y**3)
assert (f*g)**-3 == (x*y)**3
raises(ZeroDivisionError, lambda: (x - x)**-3)
def test_FracElement_diff():
F, x,y,z = field("x,y,z", ZZ)
assert ((x**2 + y)/(z + 1)).diff(x) == 2*x/(z + 1)
@XFAIL
def test_FracElement___call__():
F, x,y,z = field("x,y,z", ZZ)
f = (x**2 + 3*y)/z
r = f(1, 1, 1)
assert r == 4 and not isinstance(r, FracElement)
raises(ZeroDivisionError, lambda: f(1, 1, 0))
def test_FracElement_evaluate():
F, x,y,z = field("x,y,z", ZZ)
Fyz = field("y,z", ZZ)[0]
f = (x**2 + 3*y)/z
assert f.evaluate(x, 0) == 3*Fyz.y/Fyz.z
raises(ZeroDivisionError, lambda: f.evaluate(z, 0))
def test_FracElement_subs():
F, x,y,z = field("x,y,z", ZZ)
f = (x**2 + 3*y)/z
assert f.subs(x, 0) == 3*y/z
raises(ZeroDivisionError, lambda: f.subs(z, 0))
def test_FracElement_compose():
pass
| 8,769 | 26.753165 | 87 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/tests/test_polyfuncs.py
|
"""Tests for high-level polynomials manipulation functions. """
from sympy.polys.polyfuncs import (
symmetrize, horner, interpolate, rational_interpolate, viete,
)
from sympy.polys.polyerrors import (
MultivariatePolynomialError,
)
from sympy import symbols
from sympy.utilities.pytest import raises
from sympy.abc import a, b, c, d, e, x, y, z
def test_symmetrize():
assert symmetrize(0, x, y, z) == (0, 0)
assert symmetrize(1, x, y, z) == (1, 0)
s1 = x + y + z
s2 = x*y + x*z + y*z
s3 = x*y*z
assert symmetrize(1) == (1, 0)
assert symmetrize(1, formal=True) == (1, 0, [])
assert symmetrize(x) == (x, 0)
assert symmetrize(x + 1) == (x + 1, 0)
assert symmetrize(x, x, y) == (x + y, -y)
assert symmetrize(x + 1, x, y) == (x + y + 1, -y)
assert symmetrize(x, x, y, z) == (s1, -y - z)
assert symmetrize(x + 1, x, y, z) == (s1 + 1, -y - z)
assert symmetrize(x**2, x, y, z) == (s1**2 - 2*s2, -y**2 - z**2)
assert symmetrize(x**2 + y**2) == (-2*x*y + (x + y)**2, 0)
assert symmetrize(x**2 - y**2) == (-2*x*y + (x + y)**2, -2*y**2)
assert symmetrize(x**3 + y**2 + a*x**2 + b*y**3, x, y) == \
(-3*x*y*(x + y) - 2*a*x*y + a*(x + y)**2 + (x + y)**3,
y**2*(1 - a) + y**3*(b - 1))
U = [u0, u1, u2] = symbols('u:3')
assert symmetrize(x + 1, x, y, z, formal=True, symbols=U) == \
(u0 + 1, -y - z, [(u0, x + y + z), (u1, x*y + x*z + y*z), (u2, x*y*z)])
assert symmetrize([1, 2, 3]) == [(1, 0), (2, 0), (3, 0)]
assert symmetrize([1, 2, 3], formal=True) == ([(1, 0), (2, 0), (3, 0)], [])
assert symmetrize([x + y, x - y]) == [(x + y, 0), (x + y, -2*y)]
def test_horner():
assert horner(0) == 0
assert horner(1) == 1
assert horner(x) == x
assert horner(x + 1) == x + 1
assert horner(x**2 + 1) == x**2 + 1
assert horner(x**2 + x) == (x + 1)*x
assert horner(x**2 + x + 1) == (x + 1)*x + 1
assert horner(
9*x**4 + 8*x**3 + 7*x**2 + 6*x + 5) == (((9*x + 8)*x + 7)*x + 6)*x + 5
assert horner(
a*x**4 + b*x**3 + c*x**2 + d*x + e) == (((a*x + b)*x + c)*x + d)*x + e
assert horner(4*x**2*y**2 + 2*x**2*y + 2*x*y**2 + x*y, wrt=x) == ((
4*y + 2)*x*y + (2*y + 1)*y)*x
assert horner(4*x**2*y**2 + 2*x**2*y + 2*x*y**2 + x*y, wrt=y) == ((
4*x + 2)*y*x + (2*x + 1)*x)*y
def test_interpolate():
assert interpolate([1, 4, 9, 16], x) == x**2
assert interpolate([(1, 1), (2, 4), (3, 9)], x) == x**2
assert interpolate([(1, 2), (2, 5), (3, 10)], x) == 1 + x**2
assert interpolate({1: 2, 2: 5, 3: 10}, x) == 1 + x**2
def test_rational_interpolate():
x, y = symbols('x,y')
xdata = [1, 2, 3, 4, 5, 6]
ydata1 = [120, 150, 200, 255, 312, 370]
ydata2 = [-210, -35, 105, 231, 350, 465]
assert rational_interpolate(list(zip(xdata, ydata1)), 2) == (
(60*x**2 + 60)/x )
assert rational_interpolate(list(zip(xdata, ydata1)), 3) == (
(60*x**2 + 60)/x )
assert rational_interpolate(list(zip(xdata, ydata2)), 2, X=y) == (
(105*y**2 - 525)/(y + 1) )
xdata = list(range(1,11))
ydata = [-1923885361858460, -5212158811973685, -9838050145867125,
-15662936261217245, -22469424125057910, -30073793365223685,
-38332297297028735, -47132954289530109, -56387719094026320,
-66026548943876885]
assert rational_interpolate(list(zip(xdata, ydata)), 5) == (
(-12986226192544605*x**4 +
8657484128363070*x**3 - 30301194449270745*x**2 + 4328742064181535*x
- 4328742064181535)/(x**3 + 9*x**2 - 3*x + 11))
def test_viete():
r1, r2 = symbols('r1, r2')
assert viete(
a*x**2 + b*x + c, [r1, r2], x) == [(r1 + r2, -b/a), (r1*r2, c/a)]
raises(ValueError, lambda: viete(1, [], x))
raises(ValueError, lambda: viete(x**2 + 1, [r1]))
raises(MultivariatePolynomialError, lambda: viete(x + y, [r1]))
| 3,883 | 32.196581 | 79 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/tests/__init__.py
| 0 | 0 | 0 |
py
|
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/tests/test_rootoftools.py
|
"""Tests for the implementation of RootOf class and related tools. """
from sympy.polys.polytools import Poly
from sympy.polys.rootoftools import rootof, RootOf, CRootOf, RootSum
from sympy.polys.polyerrors import (
MultivariatePolynomialError,
GeneratorsNeeded,
PolynomialError,
)
from sympy import (
S, sqrt, I, Rational, Float, Lambda, log, exp, tan, Function, Eq,
solve, legendre_poly
)
from sympy.utilities.pytest import raises
from sympy.core.compatibility import range
from sympy.abc import a, b, x, y, z, r
def test_CRootOf___new__():
assert rootof(x, 0) == 0
assert rootof(x, -1) == 0
assert rootof(x, S.Zero) == 0
assert rootof(x - 1, 0) == 1
assert rootof(x - 1, -1) == 1
assert rootof(x + 1, 0) == -1
assert rootof(x + 1, -1) == -1
assert rootof(x**2 + 2*x + 3, 0) == -1 - I*sqrt(2)
assert rootof(x**2 + 2*x + 3, 1) == -1 + I*sqrt(2)
assert rootof(x**2 + 2*x + 3, -1) == -1 + I*sqrt(2)
assert rootof(x**2 + 2*x + 3, -2) == -1 - I*sqrt(2)
r = rootof(x**2 + 2*x + 3, 0, radicals=False)
assert isinstance(r, RootOf) is True
r = rootof(x**2 + 2*x + 3, 1, radicals=False)
assert isinstance(r, RootOf) is True
r = rootof(x**2 + 2*x + 3, -1, radicals=False)
assert isinstance(r, RootOf) is True
r = rootof(x**2 + 2*x + 3, -2, radicals=False)
assert isinstance(r, RootOf) is True
assert rootof((x - 1)*(x + 1), 0, radicals=False) == -1
assert rootof((x - 1)*(x + 1), 1, radicals=False) == 1
assert rootof((x - 1)*(x + 1), -1, radicals=False) == 1
assert rootof((x - 1)*(x + 1), -2, radicals=False) == -1
assert rootof((x - 1)*(x + 1), 0, radicals=True) == -1
assert rootof((x - 1)*(x + 1), 1, radicals=True) == 1
assert rootof((x - 1)*(x + 1), -1, radicals=True) == 1
assert rootof((x - 1)*(x + 1), -2, radicals=True) == -1
assert rootof((x - 1)*(x**3 + x + 3), 0) == rootof(x**3 + x + 3, 0)
assert rootof((x - 1)*(x**3 + x + 3), 1) == 1
assert rootof((x - 1)*(x**3 + x + 3), 2) == rootof(x**3 + x + 3, 1)
assert rootof((x - 1)*(x**3 + x + 3), 3) == rootof(x**3 + x + 3, 2)
assert rootof((x - 1)*(x**3 + x + 3), -1) == rootof(x**3 + x + 3, 2)
assert rootof((x - 1)*(x**3 + x + 3), -2) == rootof(x**3 + x + 3, 1)
assert rootof((x - 1)*(x**3 + x + 3), -3) == 1
assert rootof((x - 1)*(x**3 + x + 3), -4) == rootof(x**3 + x + 3, 0)
assert rootof(x**4 + 3*x**3, 0) == -3
assert rootof(x**4 + 3*x**3, 1) == 0
assert rootof(x**4 + 3*x**3, 2) == 0
assert rootof(x**4 + 3*x**3, 3) == 0
raises(GeneratorsNeeded, lambda: rootof(0, 0))
raises(GeneratorsNeeded, lambda: rootof(1, 0))
raises(PolynomialError, lambda: rootof(Poly(0, x), 0))
raises(PolynomialError, lambda: rootof(Poly(1, x), 0))
raises(PolynomialError, lambda: rootof(x - y, 0))
raises(NotImplementedError, lambda: rootof(x**3 - x + sqrt(2), 0))
raises(NotImplementedError, lambda: rootof(x**3 - x + I, 0))
raises(IndexError, lambda: rootof(x**2 - 1, -4))
raises(IndexError, lambda: rootof(x**2 - 1, -3))
raises(IndexError, lambda: rootof(x**2 - 1, 2))
raises(IndexError, lambda: rootof(x**2 - 1, 3))
raises(ValueError, lambda: rootof(x**2 - 1, x))
assert rootof(Poly(x - y, x), 0) == y
assert rootof(Poly(x**2 - y, x), 0) == -sqrt(y)
assert rootof(Poly(x**2 - y, x), 1) == sqrt(y)
assert rootof(Poly(x**3 - y, x), 0) == y**Rational(1, 3)
assert rootof(y*x**3 + y*x + 2*y, x, 0) == -1
raises(NotImplementedError, lambda: rootof(x**3 + x + 2*y, x, 0))
assert rootof(x**3 + x + 1, 0).is_commutative is True
def test_CRootOf_attributes():
r = rootof(x**3 + x + 3, 0)
assert r.is_number
assert r.free_symbols == set()
# if the following assertion fails then multivariate polynomials
# are apparently supported and the RootOf.free_symbols routine
# should be changed to return whatever symbols would not be
# the PurePoly dummy symbol
raises(NotImplementedError, lambda: rootof(Poly(x**3 + y*x + 1, x), 0))
def test_CRootOf___eq__():
assert (rootof(x**3 + x + 3, 0) == rootof(x**3 + x + 3, 0)) is True
assert (rootof(x**3 + x + 3, 0) == rootof(x**3 + x + 3, 1)) is False
assert (rootof(x**3 + x + 3, 1) == rootof(x**3 + x + 3, 1)) is True
assert (rootof(x**3 + x + 3, 1) == rootof(x**3 + x + 3, 2)) is False
assert (rootof(x**3 + x + 3, 2) == rootof(x**3 + x + 3, 2)) is True
assert (rootof(x**3 + x + 3, 0) == rootof(y**3 + y + 3, 0)) is True
assert (rootof(x**3 + x + 3, 0) == rootof(y**3 + y + 3, 1)) is False
assert (rootof(x**3 + x + 3, 1) == rootof(y**3 + y + 3, 1)) is True
assert (rootof(x**3 + x + 3, 1) == rootof(y**3 + y + 3, 2)) is False
assert (rootof(x**3 + x + 3, 2) == rootof(y**3 + y + 3, 2)) is True
def test_CRootOf___eval_Eq__():
f = Function('f')
r = rootof(x**3 + x + 3, 2)
r1 = rootof(x**3 + x + 3, 1)
assert Eq(r, r1) is S.false
assert Eq(r, r) is S.true
assert Eq(r, x) is S.false
assert Eq(r, 0) is S.false
assert Eq(r, S.Infinity) is S.false
assert Eq(r, I) is S.false
assert Eq(r, f(0)) is S.false
assert Eq(r, f(0)) is S.false
sol = solve(r.expr)
for s in sol:
if s.is_real:
assert Eq(r, s) is S.false
r = rootof(r.expr, 0)
for s in sol:
if s.is_real:
assert Eq(r, s) is S.true
eq = (x**3 + x + 1)
assert [Eq(rootof(eq,i), j) for i in range(3) for j in solve(eq)] == [
False, False, True, False, True, False, True, False, False]
assert Eq(rootof(eq, 0), 1 + S.ImaginaryUnit) == False
def test_CRootOf_is_real():
assert rootof(x**3 + x + 3, 0).is_real is True
assert rootof(x**3 + x + 3, 1).is_real is False
assert rootof(x**3 + x + 3, 2).is_real is False
def test_CRootOf_is_complex():
assert rootof(x**3 + x + 3, 0).is_complex is True
def test_CRootOf_subs():
assert rootof(x**3 + x + 1, 0).subs(x, y) == rootof(y**3 + y + 1, 0)
def test_CRootOf_diff():
assert rootof(x**3 + x + 1, 0).diff(x) == 0
assert rootof(x**3 + x + 1, 0).diff(y) == 0
def test_CRootOf_evalf():
real = rootof(x**3 + x + 3, 0).evalf(n=20)
assert real.epsilon_eq(Float("-1.2134116627622296341"))
re, im = rootof(x**3 + x + 3, 1).evalf(n=20).as_real_imag()
assert re.epsilon_eq( Float("0.60670583138111481707"))
assert im.epsilon_eq(-Float("1.45061224918844152650"))
re, im = rootof(x**3 + x + 3, 2).evalf(n=20).as_real_imag()
assert re.epsilon_eq(Float("0.60670583138111481707"))
assert im.epsilon_eq(Float("1.45061224918844152650"))
p = legendre_poly(4, x, polys=True)
roots = [str(r.n(17)) for r in p.real_roots()]
assert roots == [
"-0.86113631159405258",
"-0.33998104358485626",
"0.33998104358485626",
"0.86113631159405258",
]
re = rootof(x**5 - 5*x + 12, 0).evalf(n=20)
assert re.epsilon_eq(Float("-1.84208596619025438271"))
re, im = rootof(x**5 - 5*x + 12, 1).evalf(n=20).as_real_imag()
assert re.epsilon_eq(Float("-0.351854240827371999559"))
assert im.epsilon_eq(Float("-1.709561043370328882010"))
re, im = rootof(x**5 - 5*x + 12, 2).evalf(n=20).as_real_imag()
assert re.epsilon_eq(Float("-0.351854240827371999559"))
assert im.epsilon_eq(Float("+1.709561043370328882010"))
re, im = rootof(x**5 - 5*x + 12, 3).evalf(n=20).as_real_imag()
assert re.epsilon_eq(Float("+1.272897223922499190910"))
assert im.epsilon_eq(Float("-0.719798681483861386681"))
re, im = rootof(x**5 - 5*x + 12, 4).evalf(n=20).as_real_imag()
assert re.epsilon_eq(Float("+1.272897223922499190910"))
assert im.epsilon_eq(Float("+0.719798681483861386681"))
# issue 6393
assert str(rootof(x**5 + 2*x**4 + x**3 - 68719476736, 0).n(3)) == '147.'
eq = (531441*x**11 + 3857868*x**10 + 13730229*x**9 + 32597882*x**8 +
55077472*x**7 + 60452000*x**6 + 32172064*x**5 - 4383808*x**4 -
11942912*x**3 - 1506304*x**2 + 1453312*x + 512)
a, b = rootof(eq, 1).n(2).as_real_imag()
c, d = rootof(eq, 2).n(2).as_real_imag()
assert a == c
assert b < d
assert b == -d
# issue 6451
r = rootof(legendre_poly(64, x), 7)
assert r.n(2) == r.n(100).n(2)
# issue 8617
ans = [w.n(2) for w in solve(x**3 - x - 4)]
assert rootof(exp(x)**3 - exp(x) - 4, 0).n(2) in ans
# issue 9019
r0 = rootof(x**2 + 1, 0, radicals=False)
r1 = rootof(x**2 + 1, 1, radicals=False)
assert r0.n(4) == -1.0*I
assert r1.n(4) == 1.0*I
# make sure verification is used in case a max/min traps the "root"
assert str(rootof(4*x**5 + 16*x**3 + 12*x**2 + 7, 0).n(3)) == '-0.976'
# watch out for UnboundLocalError
c = CRootOf(90720*x**6 - 4032*x**4 + 84*x**2 - 1, 0)
assert str(c._eval_evalf(2)) == '-0.e-1'
def test_CRootOf_evalf_caching_bug():
r = rootof(x**5 - 5*x + 12, 1)
r.n()
a = r._get_interval()
r = rootof(x**5 - 5*x + 12, 1)
r.n()
b = r._get_interval()
assert a == b
def test_CRootOf_real_roots():
assert Poly(x**5 + x + 1).real_roots() == [rootof(x**3 - x**2 + 1, 0)]
assert Poly(x**5 + x + 1).real_roots(radicals=False) == [rootof(
x**3 - x**2 + 1, 0)]
def test_CRootOf_all_roots():
assert Poly(x**5 + x + 1).all_roots() == [
rootof(x**3 - x**2 + 1, 0),
-S(1)/2 - sqrt(3)*I/2,
-S(1)/2 + sqrt(3)*I/2,
rootof(x**3 - x**2 + 1, 1),
rootof(x**3 - x**2 + 1, 2),
]
assert Poly(x**5 + x + 1).all_roots(radicals=False) == [
rootof(x**3 - x**2 + 1, 0),
rootof(x**2 + x + 1, 0, radicals=False),
rootof(x**2 + x + 1, 1, radicals=False),
rootof(x**3 - x**2 + 1, 1),
rootof(x**3 - x**2 + 1, 2),
]
def test_CRootOf_eval_rational():
p = legendre_poly(4, x, polys=True)
roots = [r.eval_rational(S(1)/10**20) for r in p.real_roots()]
for r in roots:
assert isinstance(r, Rational)
# All we know is that the Rational instance will be at most 1/10^20 from
# the exact root. So if we evaluate to 17 digits, it must be exactly equal
# to:
roots = [str(r.n(17)) for r in roots]
assert roots == [
"-0.86113631159405258",
"-0.33998104358485626",
"0.33998104358485626",
"0.86113631159405258",
]
def test_RootSum___new__():
f = x**3 + x + 3
g = Lambda(r, log(r*x))
s = RootSum(f, g)
assert isinstance(s, RootSum) is True
assert RootSum(f**2, g) == 2*RootSum(f, g)
assert RootSum((x - 7)*f**3, g) == log(7*x) + 3*RootSum(f, g)
# issue 5571
assert hash(RootSum((x - 7)*f**3, g)) == hash(log(7*x) + 3*RootSum(f, g))
raises(MultivariatePolynomialError, lambda: RootSum(x**3 + x + y))
raises(ValueError, lambda: RootSum(x**2 + 3, lambda x: x))
assert RootSum(f, exp) == RootSum(f, Lambda(x, exp(x)))
assert RootSum(f, log) == RootSum(f, Lambda(x, log(x)))
assert isinstance(RootSum(f, auto=False), RootSum) is True
assert RootSum(f) == 0
assert RootSum(f, Lambda(x, x)) == 0
assert RootSum(f, Lambda(x, x**2)) == -2
assert RootSum(f, Lambda(x, 1)) == 3
assert RootSum(f, Lambda(x, 2)) == 6
assert RootSum(f, auto=False).is_commutative is True
assert RootSum(f, Lambda(x, 1/(x + x**2))) == S(11)/3
assert RootSum(f, Lambda(x, y/(x + x**2))) == S(11)/3*y
assert RootSum(x**2 - 1, Lambda(x, 3*x**2), x) == 6
assert RootSum(x**2 - y, Lambda(x, 3*x**2), x) == 6*y
assert RootSum(x**2 - 1, Lambda(x, z*x**2), x) == 2*z
assert RootSum(x**2 - y, Lambda(x, z*x**2), x) == 2*z*y
assert RootSum(
x**2 - 1, Lambda(x, exp(x)), quadratic=True) == exp(-1) + exp(1)
assert RootSum(x**3 + a*x + a**3, tan, x) == \
RootSum(x**3 + x + 1, Lambda(x, tan(a*x)))
assert RootSum(a**3*x**3 + a*x + 1, tan, x) == \
RootSum(x**3 + x + 1, Lambda(x, tan(x/a)))
def test_RootSum_free_symbols():
assert RootSum(x**3 + x + 3, Lambda(r, exp(r))).free_symbols == set()
assert RootSum(x**3 + x + 3, Lambda(r, exp(a*r))).free_symbols == {a}
assert RootSum(
x**3 + x + y, Lambda(r, exp(a*r)), x).free_symbols == {a, y}
def test_RootSum___eq__():
f = Lambda(x, exp(x))
assert (RootSum(x**3 + x + 1, f) == RootSum(x**3 + x + 1, f)) is True
assert (RootSum(x**3 + x + 1, f) == RootSum(y**3 + y + 1, f)) is True
assert (RootSum(x**3 + x + 1, f) == RootSum(x**3 + x + 2, f)) is False
assert (RootSum(x**3 + x + 1, f) == RootSum(y**3 + y + 2, f)) is False
def test_RootSum_doit():
rs = RootSum(x**2 + 1, exp)
assert isinstance(rs, RootSum) is True
assert rs.doit() == exp(-I) + exp(I)
rs = RootSum(x**2 + a, exp, x)
assert isinstance(rs, RootSum) is True
assert rs.doit() == exp(-sqrt(-a)) + exp(sqrt(-a))
def test_RootSum_evalf():
rs = RootSum(x**2 + 1, exp)
assert rs.evalf(n=20, chop=True).epsilon_eq(
Float("1.0806046117362794348", 20), Float("1e-20")) is S.true
assert rs.evalf(n=15, chop=True).epsilon_eq(
Float("1.08060461173628", 15), Float("1e-15")) is S.true
rs = RootSum(x**2 + a, exp, x)
assert rs.evalf() == rs
def test_RootSum_diff():
f = x**3 + x + 3
g = Lambda(r, exp(r*x))
h = Lambda(r, r*exp(r*x))
assert RootSum(f, g).diff(x) == RootSum(f, h)
def test_RootSum_subs():
f = x**3 + x + 3
g = Lambda(r, exp(r*x))
F = y**3 + y + 3
G = Lambda(r, exp(r*y))
assert RootSum(f, g).subs(y, 1) == RootSum(f, g)
assert RootSum(f, g).subs(x, y) == RootSum(F, G)
def test_RootSum_rational():
assert RootSum(
z**5 - z + 1, Lambda(z, z/(x - z))) == (4*x - 5)/(x**5 - x + 1)
f = 161*z**3 + 115*z**2 + 19*z + 1
g = Lambda(z, z*log(
-3381*z**4/4 - 3381*z**3/4 - 625*z**2/2 - 125*z/2 - 5 + exp(x)))
assert RootSum(f, g).diff(x) == -(
(5*exp(2*x) - 6*exp(x) + 4)*exp(x)/(exp(3*x) - exp(2*x) + 1))/7
def test_RootSum_independent():
f = (x**3 - a)**2*(x**4 - b)**3
g = Lambda(x, 5*tan(x) + 7)
h = Lambda(x, tan(x))
r0 = RootSum(x**3 - a, h, x)
r1 = RootSum(x**4 - b, h, x)
assert RootSum(f, g, x).as_ordered_terms() == [10*r0, 15*r1, 126]
def test_issue_7876():
l1 = Poly(x**6 - x + 1, x).all_roots()
l2 = [rootof(x**6 - x + 1, i) for i in range(6)]
assert frozenset(l1) == frozenset(l2)
def test_issue_8316():
f = Poly(7*x**8 - 9)
assert len(f.all_roots()) == 8
f = Poly(7*x**8 - 10)
assert len(f.all_roots()) == 8
| 14,596 | 31.655481 | 78 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/tests/test_polyoptions.py
|
"""Tests for options manager for :class:`Poly` and public API functions. """
from sympy.polys.polyoptions import (
Options, Expand, Gens, Wrt, Sort, Order, Field, Greedy, Domain,
Split, Gaussian, Extension, Modulus, Symmetric, Strict, Auto,
Frac, Formal, Polys, Include, All, Gen, Symbols, Method)
from sympy.polys.orderings import lex
from sympy.polys.domains import FF, GF, ZZ, QQ, EX
from sympy.polys.polyerrors import OptionError, GeneratorsError
from sympy import Integer, Symbol, I, sqrt
from sympy.utilities.pytest import raises
from sympy.abc import x, y, z
def test_Options_clone():
opt = Options((x, y, z), {'domain': 'ZZ'})
assert opt.gens == (x, y, z)
assert opt.domain == ZZ
assert ('order' in opt) is False
new_opt = opt.clone({'gens': (x, y), 'order': 'lex'})
assert opt.gens == (x, y, z)
assert opt.domain == ZZ
assert ('order' in opt) is False
assert new_opt.gens == (x, y)
assert new_opt.domain == ZZ
assert ('order' in new_opt) is True
def test_Expand_preprocess():
assert Expand.preprocess(False) is False
assert Expand.preprocess(True) is True
assert Expand.preprocess(0) is False
assert Expand.preprocess(1) is True
raises(OptionError, lambda: Expand.preprocess(x))
def test_Expand_postprocess():
opt = {'expand': True}
Expand.postprocess(opt)
assert opt == {'expand': True}
def test_Gens_preprocess():
assert Gens.preprocess((None,)) == ()
assert Gens.preprocess((x, y, z)) == (x, y, z)
assert Gens.preprocess(((x, y, z),)) == (x, y, z)
a = Symbol('a', commutative=False)
raises(GeneratorsError, lambda: Gens.preprocess((x, x, y)))
raises(GeneratorsError, lambda: Gens.preprocess((x, y, a)))
def test_Gens_postprocess():
opt = {'gens': (x, y)}
Gens.postprocess(opt)
assert opt == {'gens': (x, y)}
def test_Wrt_preprocess():
assert Wrt.preprocess(x) == ['x']
assert Wrt.preprocess('') == []
assert Wrt.preprocess(' ') == []
assert Wrt.preprocess('x,y') == ['x', 'y']
assert Wrt.preprocess('x y') == ['x', 'y']
assert Wrt.preprocess('x, y') == ['x', 'y']
assert Wrt.preprocess('x , y') == ['x', 'y']
assert Wrt.preprocess(' x, y') == ['x', 'y']
assert Wrt.preprocess(' x, y') == ['x', 'y']
assert Wrt.preprocess([x, y]) == ['x', 'y']
raises(OptionError, lambda: Wrt.preprocess(','))
raises(OptionError, lambda: Wrt.preprocess(0))
def test_Wrt_postprocess():
opt = {'wrt': ['x']}
Wrt.postprocess(opt)
assert opt == {'wrt': ['x']}
def test_Sort_preprocess():
assert Sort.preprocess([x, y, z]) == ['x', 'y', 'z']
assert Sort.preprocess((x, y, z)) == ['x', 'y', 'z']
assert Sort.preprocess('x > y > z') == ['x', 'y', 'z']
assert Sort.preprocess('x>y>z') == ['x', 'y', 'z']
raises(OptionError, lambda: Sort.preprocess(0))
raises(OptionError, lambda: Sort.preprocess({x, y, z}))
def test_Sort_postprocess():
opt = {'sort': 'x > y'}
Sort.postprocess(opt)
assert opt == {'sort': 'x > y'}
def test_Order_preprocess():
assert Order.preprocess('lex') == lex
def test_Order_postprocess():
opt = {'order': True}
Order.postprocess(opt)
assert opt == {'order': True}
def test_Field_preprocess():
assert Field.preprocess(False) is False
assert Field.preprocess(True) is True
assert Field.preprocess(0) is False
assert Field.preprocess(1) is True
raises(OptionError, lambda: Field.preprocess(x))
def test_Field_postprocess():
opt = {'field': True}
Field.postprocess(opt)
assert opt == {'field': True}
def test_Greedy_preprocess():
assert Greedy.preprocess(False) is False
assert Greedy.preprocess(True) is True
assert Greedy.preprocess(0) is False
assert Greedy.preprocess(1) is True
raises(OptionError, lambda: Greedy.preprocess(x))
def test_Greedy_postprocess():
opt = {'greedy': True}
Greedy.postprocess(opt)
assert opt == {'greedy': True}
def test_Domain_preprocess():
assert Domain.preprocess(ZZ) == ZZ
assert Domain.preprocess(QQ) == QQ
assert Domain.preprocess(EX) == EX
assert Domain.preprocess(FF(2)) == FF(2)
assert Domain.preprocess(ZZ[x, y]) == ZZ[x, y]
assert Domain.preprocess('Z') == ZZ
assert Domain.preprocess('Q') == QQ
assert Domain.preprocess('ZZ') == ZZ
assert Domain.preprocess('QQ') == QQ
assert Domain.preprocess('EX') == EX
assert Domain.preprocess('FF(23)') == FF(23)
assert Domain.preprocess('GF(23)') == GF(23)
raises(OptionError, lambda: Domain.preprocess('Z[]'))
assert Domain.preprocess('Z[x]') == ZZ[x]
assert Domain.preprocess('Q[x]') == QQ[x]
assert Domain.preprocess('ZZ[x]') == ZZ[x]
assert Domain.preprocess('QQ[x]') == QQ[x]
assert Domain.preprocess('Z[x,y]') == ZZ[x, y]
assert Domain.preprocess('Q[x,y]') == QQ[x, y]
assert Domain.preprocess('ZZ[x,y]') == ZZ[x, y]
assert Domain.preprocess('QQ[x,y]') == QQ[x, y]
raises(OptionError, lambda: Domain.preprocess('Z()'))
assert Domain.preprocess('Z(x)') == ZZ.frac_field(x)
assert Domain.preprocess('Q(x)') == QQ.frac_field(x)
assert Domain.preprocess('ZZ(x)') == ZZ.frac_field(x)
assert Domain.preprocess('QQ(x)') == QQ.frac_field(x)
assert Domain.preprocess('Z(x,y)') == ZZ.frac_field(x, y)
assert Domain.preprocess('Q(x,y)') == QQ.frac_field(x, y)
assert Domain.preprocess('ZZ(x,y)') == ZZ.frac_field(x, y)
assert Domain.preprocess('QQ(x,y)') == QQ.frac_field(x, y)
assert Domain.preprocess('Q<I>') == QQ.algebraic_field(I)
assert Domain.preprocess('QQ<I>') == QQ.algebraic_field(I)
assert Domain.preprocess('Q<sqrt(2), I>') == QQ.algebraic_field(sqrt(2), I)
assert Domain.preprocess(
'QQ<sqrt(2), I>') == QQ.algebraic_field(sqrt(2), I)
raises(OptionError, lambda: Domain.preprocess('abc'))
def test_Domain_postprocess():
raises(GeneratorsError, lambda: Domain.postprocess({'gens': (x, y),
'domain': ZZ[y, z]}))
raises(GeneratorsError, lambda: Domain.postprocess({'gens': (),
'domain': EX}))
raises(GeneratorsError, lambda: Domain.postprocess({'domain': EX}))
def test_Split_preprocess():
assert Split.preprocess(False) is False
assert Split.preprocess(True) is True
assert Split.preprocess(0) is False
assert Split.preprocess(1) is True
raises(OptionError, lambda: Split.preprocess(x))
def test_Split_postprocess():
raises(NotImplementedError, lambda: Split.postprocess({'split': True}))
def test_Gaussian_preprocess():
assert Gaussian.preprocess(False) is False
assert Gaussian.preprocess(True) is True
assert Gaussian.preprocess(0) is False
assert Gaussian.preprocess(1) is True
raises(OptionError, lambda: Gaussian.preprocess(x))
def test_Gaussian_postprocess():
opt = {'gaussian': True}
Gaussian.postprocess(opt)
assert opt == {
'gaussian': True,
'extension': {I},
'domain': QQ.algebraic_field(I),
}
def test_Extension_preprocess():
assert Extension.preprocess(True) is True
assert Extension.preprocess(1) is True
assert Extension.preprocess([]) is None
assert Extension.preprocess(sqrt(2)) == {sqrt(2)}
assert Extension.preprocess([sqrt(2)]) == {sqrt(2)}
assert Extension.preprocess([sqrt(2), I]) == {sqrt(2), I}
raises(OptionError, lambda: Extension.preprocess(False))
raises(OptionError, lambda: Extension.preprocess(0))
def test_Extension_postprocess():
opt = {'extension': {sqrt(2)}}
Extension.postprocess(opt)
assert opt == {
'extension': {sqrt(2)},
'domain': QQ.algebraic_field(sqrt(2)),
}
opt = {'extension': True}
Extension.postprocess(opt)
assert opt == {'extension': True}
def test_Modulus_preprocess():
assert Modulus.preprocess(23) == 23
assert Modulus.preprocess(Integer(23)) == 23
raises(OptionError, lambda: Modulus.preprocess(0))
raises(OptionError, lambda: Modulus.preprocess(x))
def test_Modulus_postprocess():
opt = {'modulus': 5}
Modulus.postprocess(opt)
assert opt == {
'modulus': 5,
'domain': FF(5),
}
opt = {'modulus': 5, 'symmetric': False}
Modulus.postprocess(opt)
assert opt == {
'modulus': 5,
'domain': FF(5, False),
'symmetric': False,
}
def test_Symmetric_preprocess():
assert Symmetric.preprocess(False) is False
assert Symmetric.preprocess(True) is True
assert Symmetric.preprocess(0) is False
assert Symmetric.preprocess(1) is True
raises(OptionError, lambda: Symmetric.preprocess(x))
def test_Symmetric_postprocess():
opt = {'symmetric': True}
Symmetric.postprocess(opt)
assert opt == {'symmetric': True}
def test_Strict_preprocess():
assert Strict.preprocess(False) is False
assert Strict.preprocess(True) is True
assert Strict.preprocess(0) is False
assert Strict.preprocess(1) is True
raises(OptionError, lambda: Strict.preprocess(x))
def test_Strict_postprocess():
opt = {'strict': True}
Strict.postprocess(opt)
assert opt == {'strict': True}
def test_Auto_preprocess():
assert Auto.preprocess(False) is False
assert Auto.preprocess(True) is True
assert Auto.preprocess(0) is False
assert Auto.preprocess(1) is True
raises(OptionError, lambda: Auto.preprocess(x))
def test_Auto_postprocess():
opt = {'auto': True}
Auto.postprocess(opt)
assert opt == {'auto': True}
def test_Frac_preprocess():
assert Frac.preprocess(False) is False
assert Frac.preprocess(True) is True
assert Frac.preprocess(0) is False
assert Frac.preprocess(1) is True
raises(OptionError, lambda: Frac.preprocess(x))
def test_Frac_postprocess():
opt = {'frac': True}
Frac.postprocess(opt)
assert opt == {'frac': True}
def test_Formal_preprocess():
assert Formal.preprocess(False) is False
assert Formal.preprocess(True) is True
assert Formal.preprocess(0) is False
assert Formal.preprocess(1) is True
raises(OptionError, lambda: Formal.preprocess(x))
def test_Formal_postprocess():
opt = {'formal': True}
Formal.postprocess(opt)
assert opt == {'formal': True}
def test_Polys_preprocess():
assert Polys.preprocess(False) is False
assert Polys.preprocess(True) is True
assert Polys.preprocess(0) is False
assert Polys.preprocess(1) is True
raises(OptionError, lambda: Polys.preprocess(x))
def test_Polys_postprocess():
opt = {'polys': True}
Polys.postprocess(opt)
assert opt == {'polys': True}
def test_Include_preprocess():
assert Include.preprocess(False) is False
assert Include.preprocess(True) is True
assert Include.preprocess(0) is False
assert Include.preprocess(1) is True
raises(OptionError, lambda: Include.preprocess(x))
def test_Include_postprocess():
opt = {'include': True}
Include.postprocess(opt)
assert opt == {'include': True}
def test_All_preprocess():
assert All.preprocess(False) is False
assert All.preprocess(True) is True
assert All.preprocess(0) is False
assert All.preprocess(1) is True
raises(OptionError, lambda: All.preprocess(x))
def test_All_postprocess():
opt = {'all': True}
All.postprocess(opt)
assert opt == {'all': True}
def test_Gen_postprocess():
opt = {'gen': x}
Gen.postprocess(opt)
assert opt == {'gen': x}
def test_Symbols_preprocess():
raises(OptionError, lambda: Symbols.preprocess(x))
def test_Symbols_postprocess():
opt = {'symbols': [x, y, z]}
Symbols.postprocess(opt)
assert opt == {'symbols': [x, y, z]}
def test_Method_preprocess():
raises(OptionError, lambda: Method.preprocess(10))
def test_Method_postprocess():
opt = {'method': 'f5b'}
Method.postprocess(opt)
assert opt == {'method': 'f5b'}
| 11,959 | 24.073375 | 79 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/tests/test_polytools.py
|
"""Tests for user-friendly public interface to polynomial functions. """
from sympy.polys.polytools import (
Poly, PurePoly, poly,
parallel_poly_from_expr,
degree, degree_list,
LC, LM, LT,
pdiv, prem, pquo, pexquo,
div, rem, quo, exquo,
half_gcdex, gcdex, invert,
subresultants,
resultant, discriminant,
terms_gcd, cofactors,
gcd, gcd_list,
lcm, lcm_list,
trunc,
monic, content, primitive,
compose, decompose,
sturm,
gff_list, gff,
sqf_norm, sqf_part, sqf_list, sqf,
factor_list, factor,
intervals, refine_root, count_roots,
real_roots, nroots, ground_roots,
nth_power_roots_poly,
cancel, reduced, groebner,
GroebnerBasis, is_zero_dimensional,
_torational_factor_list,
to_rational_coeffs)
from sympy.polys.polyerrors import (
MultivariatePolynomialError,
ExactQuotientFailed,
PolificationFailed,
ComputationFailed,
UnificationFailed,
RefinementFailed,
GeneratorsNeeded,
GeneratorsError,
PolynomialError,
CoercionFailed,
DomainError,
OptionError,
FlagError)
from sympy.polys.polyclasses import DMP
from sympy.polys.fields import field
from sympy.polys.domains import FF, ZZ, QQ, RR, EX
from sympy.polys.domains.realfield import RealField
from sympy.polys.orderings import lex, grlex, grevlex
from sympy import (
S, Integer, Rational, Float, Mul, Symbol, sqrt, Piecewise, Derivative,
exp, sin, tanh, expand, oo, I, pi, re, im, rootof, Eq, Tuple, Expr, diff)
from sympy.core.basic import _aresame
from sympy.core.compatibility import iterable
from sympy.core.mul import _keep_coeff
from sympy.utilities.pytest import raises, XFAIL
from sympy.simplify import simplify
from sympy.abc import a, b, c, d, p, q, t, w, x, y, z
from sympy import MatrixSymbol
def _epsilon_eq(a, b):
for x, y in zip(a, b):
if abs(x - y) > 1e-10:
return False
return True
def _strict_eq(a, b):
if type(a) == type(b):
if iterable(a):
if len(a) == len(b):
return all(_strict_eq(c, d) for c, d in zip(a, b))
else:
return False
else:
return isinstance(a, Poly) and a.eq(b, strict=True)
else:
return False
def test_Poly_from_dict():
K = FF(3)
assert Poly.from_dict(
{0: 1, 1: 2}, gens=x, domain=K).rep == DMP([K(2), K(1)], K)
assert Poly.from_dict(
{0: 1, 1: 5}, gens=x, domain=K).rep == DMP([K(2), K(1)], K)
assert Poly.from_dict(
{(0,): 1, (1,): 2}, gens=x, domain=K).rep == DMP([K(2), K(1)], K)
assert Poly.from_dict(
{(0,): 1, (1,): 5}, gens=x, domain=K).rep == DMP([K(2), K(1)], K)
assert Poly.from_dict({(0, 0): 1, (1, 1): 2}, gens=(
x, y), domain=K).rep == DMP([[K(2), K(0)], [K(1)]], K)
assert Poly.from_dict({0: 1, 1: 2}, gens=x).rep == DMP([ZZ(2), ZZ(1)], ZZ)
assert Poly.from_dict(
{0: 1, 1: 2}, gens=x, field=True).rep == DMP([QQ(2), QQ(1)], QQ)
assert Poly.from_dict(
{0: 1, 1: 2}, gens=x, domain=ZZ).rep == DMP([ZZ(2), ZZ(1)], ZZ)
assert Poly.from_dict(
{0: 1, 1: 2}, gens=x, domain=QQ).rep == DMP([QQ(2), QQ(1)], QQ)
assert Poly.from_dict(
{(0,): 1, (1,): 2}, gens=x).rep == DMP([ZZ(2), ZZ(1)], ZZ)
assert Poly.from_dict(
{(0,): 1, (1,): 2}, gens=x, field=True).rep == DMP([QQ(2), QQ(1)], QQ)
assert Poly.from_dict(
{(0,): 1, (1,): 2}, gens=x, domain=ZZ).rep == DMP([ZZ(2), ZZ(1)], ZZ)
assert Poly.from_dict(
{(0,): 1, (1,): 2}, gens=x, domain=QQ).rep == DMP([QQ(2), QQ(1)], QQ)
assert Poly.from_dict({(1,): sin(y)}, gens=x, composite=False) == \
Poly(sin(y)*x, x, domain='EX')
assert Poly.from_dict({(1,): y}, gens=x, composite=False) == \
Poly(y*x, x, domain='EX')
assert Poly.from_dict({(1, 1): 1}, gens=(x, y), composite=False) == \
Poly(x*y, x, y, domain='ZZ')
assert Poly.from_dict({(1, 0): y}, gens=(x, z), composite=False) == \
Poly(y*x, x, z, domain='EX')
def test_Poly_from_list():
K = FF(3)
assert Poly.from_list([2, 1], gens=x, domain=K).rep == DMP([K(2), K(1)], K)
assert Poly.from_list([5, 1], gens=x, domain=K).rep == DMP([K(2), K(1)], K)
assert Poly.from_list([2, 1], gens=x).rep == DMP([ZZ(2), ZZ(1)], ZZ)
assert Poly.from_list([2, 1], gens=x, field=True).rep == DMP([QQ(2), QQ(1)], QQ)
assert Poly.from_list([2, 1], gens=x, domain=ZZ).rep == DMP([ZZ(2), ZZ(1)], ZZ)
assert Poly.from_list([2, 1], gens=x, domain=QQ).rep == DMP([QQ(2), QQ(1)], QQ)
assert Poly.from_list([0, 1.0], gens=x).rep == DMP([RR(1.0)], RR)
assert Poly.from_list([1.0, 0], gens=x).rep == DMP([RR(1.0), RR(0.0)], RR)
raises(MultivariatePolynomialError, lambda: Poly.from_list([[]], gens=(x, y)))
def test_Poly_from_poly():
f = Poly(x + 7, x, domain=ZZ)
g = Poly(x + 2, x, modulus=3)
h = Poly(x + y, x, y, domain=ZZ)
K = FF(3)
assert Poly.from_poly(f) == f
assert Poly.from_poly(f, domain=K).rep == DMP([K(1), K(1)], K)
assert Poly.from_poly(f, domain=ZZ).rep == DMP([1, 7], ZZ)
assert Poly.from_poly(f, domain=QQ).rep == DMP([1, 7], QQ)
assert Poly.from_poly(f, gens=x) == f
assert Poly.from_poly(f, gens=x, domain=K).rep == DMP([K(1), K(1)], K)
assert Poly.from_poly(f, gens=x, domain=ZZ).rep == DMP([1, 7], ZZ)
assert Poly.from_poly(f, gens=x, domain=QQ).rep == DMP([1, 7], QQ)
assert Poly.from_poly(f, gens=y) == Poly(x + 7, y, domain='ZZ[x]')
raises(CoercionFailed, lambda: Poly.from_poly(f, gens=y, domain=K))
raises(CoercionFailed, lambda: Poly.from_poly(f, gens=y, domain=ZZ))
raises(CoercionFailed, lambda: Poly.from_poly(f, gens=y, domain=QQ))
assert Poly.from_poly(f, gens=(x, y)) == Poly(x + 7, x, y, domain='ZZ')
assert Poly.from_poly(
f, gens=(x, y), domain=ZZ) == Poly(x + 7, x, y, domain='ZZ')
assert Poly.from_poly(
f, gens=(x, y), domain=QQ) == Poly(x + 7, x, y, domain='QQ')
assert Poly.from_poly(
f, gens=(x, y), modulus=3) == Poly(x + 7, x, y, domain='FF(3)')
K = FF(2)
assert Poly.from_poly(g) == g
assert Poly.from_poly(g, domain=ZZ).rep == DMP([1, -1], ZZ)
raises(CoercionFailed, lambda: Poly.from_poly(g, domain=QQ))
assert Poly.from_poly(g, domain=K).rep == DMP([K(1), K(0)], K)
assert Poly.from_poly(g, gens=x) == g
assert Poly.from_poly(g, gens=x, domain=ZZ).rep == DMP([1, -1], ZZ)
raises(CoercionFailed, lambda: Poly.from_poly(g, gens=x, domain=QQ))
assert Poly.from_poly(g, gens=x, domain=K).rep == DMP([K(1), K(0)], K)
K = FF(3)
assert Poly.from_poly(h) == h
assert Poly.from_poly(
h, domain=ZZ).rep == DMP([[ZZ(1)], [ZZ(1), ZZ(0)]], ZZ)
assert Poly.from_poly(
h, domain=QQ).rep == DMP([[QQ(1)], [QQ(1), QQ(0)]], QQ)
assert Poly.from_poly(h, domain=K).rep == DMP([[K(1)], [K(1), K(0)]], K)
assert Poly.from_poly(h, gens=x) == Poly(x + y, x, domain=ZZ[y])
raises(CoercionFailed, lambda: Poly.from_poly(h, gens=x, domain=ZZ))
assert Poly.from_poly(
h, gens=x, domain=ZZ[y]) == Poly(x + y, x, domain=ZZ[y])
raises(CoercionFailed, lambda: Poly.from_poly(h, gens=x, domain=QQ))
assert Poly.from_poly(
h, gens=x, domain=QQ[y]) == Poly(x + y, x, domain=QQ[y])
raises(CoercionFailed, lambda: Poly.from_poly(h, gens=x, modulus=3))
assert Poly.from_poly(h, gens=y) == Poly(x + y, y, domain=ZZ[x])
raises(CoercionFailed, lambda: Poly.from_poly(h, gens=y, domain=ZZ))
assert Poly.from_poly(
h, gens=y, domain=ZZ[x]) == Poly(x + y, y, domain=ZZ[x])
raises(CoercionFailed, lambda: Poly.from_poly(h, gens=y, domain=QQ))
assert Poly.from_poly(
h, gens=y, domain=QQ[x]) == Poly(x + y, y, domain=QQ[x])
raises(CoercionFailed, lambda: Poly.from_poly(h, gens=y, modulus=3))
assert Poly.from_poly(h, gens=(x, y)) == h
assert Poly.from_poly(
h, gens=(x, y), domain=ZZ).rep == DMP([[ZZ(1)], [ZZ(1), ZZ(0)]], ZZ)
assert Poly.from_poly(
h, gens=(x, y), domain=QQ).rep == DMP([[QQ(1)], [QQ(1), QQ(0)]], QQ)
assert Poly.from_poly(
h, gens=(x, y), domain=K).rep == DMP([[K(1)], [K(1), K(0)]], K)
assert Poly.from_poly(
h, gens=(y, x)).rep == DMP([[ZZ(1)], [ZZ(1), ZZ(0)]], ZZ)
assert Poly.from_poly(
h, gens=(y, x), domain=ZZ).rep == DMP([[ZZ(1)], [ZZ(1), ZZ(0)]], ZZ)
assert Poly.from_poly(
h, gens=(y, x), domain=QQ).rep == DMP([[QQ(1)], [QQ(1), QQ(0)]], QQ)
assert Poly.from_poly(
h, gens=(y, x), domain=K).rep == DMP([[K(1)], [K(1), K(0)]], K)
assert Poly.from_poly(
h, gens=(x, y), field=True).rep == DMP([[QQ(1)], [QQ(1), QQ(0)]], QQ)
assert Poly.from_poly(
h, gens=(x, y), field=True).rep == DMP([[QQ(1)], [QQ(1), QQ(0)]], QQ)
def test_Poly_from_expr():
raises(GeneratorsNeeded, lambda: Poly.from_expr(S(0)))
raises(GeneratorsNeeded, lambda: Poly.from_expr(S(7)))
F3 = FF(3)
assert Poly.from_expr(x + 5, domain=F3).rep == DMP([F3(1), F3(2)], F3)
assert Poly.from_expr(y + 5, domain=F3).rep == DMP([F3(1), F3(2)], F3)
assert Poly.from_expr(x + 5, x, domain=F3).rep == DMP([F3(1), F3(2)], F3)
assert Poly.from_expr(y + 5, y, domain=F3).rep == DMP([F3(1), F3(2)], F3)
assert Poly.from_expr(x + y, domain=F3).rep == DMP([[F3(1)], [F3(1), F3(0)]], F3)
assert Poly.from_expr(x + y, x, y, domain=F3).rep == DMP([[F3(1)], [F3(1), F3(0)]], F3)
assert Poly.from_expr(x + 5).rep == DMP([1, 5], ZZ)
assert Poly.from_expr(y + 5).rep == DMP([1, 5], ZZ)
assert Poly.from_expr(x + 5, x).rep == DMP([1, 5], ZZ)
assert Poly.from_expr(y + 5, y).rep == DMP([1, 5], ZZ)
assert Poly.from_expr(x + 5, domain=ZZ).rep == DMP([1, 5], ZZ)
assert Poly.from_expr(y + 5, domain=ZZ).rep == DMP([1, 5], ZZ)
assert Poly.from_expr(x + 5, x, domain=ZZ).rep == DMP([1, 5], ZZ)
assert Poly.from_expr(y + 5, y, domain=ZZ).rep == DMP([1, 5], ZZ)
assert Poly.from_expr(x + 5, x, y, domain=ZZ).rep == DMP([[1], [5]], ZZ)
assert Poly.from_expr(y + 5, x, y, domain=ZZ).rep == DMP([[1, 5]], ZZ)
def test_Poly__new__():
raises(GeneratorsError, lambda: Poly(x + 1, x, x))
raises(GeneratorsError, lambda: Poly(x + y, x, y, domain=ZZ[x]))
raises(GeneratorsError, lambda: Poly(x + y, x, y, domain=ZZ[y]))
raises(OptionError, lambda: Poly(x, x, symmetric=True))
raises(OptionError, lambda: Poly(x + 2, x, modulus=3, domain=QQ))
raises(OptionError, lambda: Poly(x + 2, x, domain=ZZ, gaussian=True))
raises(OptionError, lambda: Poly(x + 2, x, modulus=3, gaussian=True))
raises(OptionError, lambda: Poly(x + 2, x, domain=ZZ, extension=[sqrt(3)]))
raises(OptionError, lambda: Poly(x + 2, x, modulus=3, extension=[sqrt(3)]))
raises(OptionError, lambda: Poly(x + 2, x, domain=ZZ, extension=True))
raises(OptionError, lambda: Poly(x + 2, x, modulus=3, extension=True))
raises(OptionError, lambda: Poly(x + 2, x, domain=ZZ, greedy=True))
raises(OptionError, lambda: Poly(x + 2, x, domain=QQ, field=True))
raises(OptionError, lambda: Poly(x + 2, x, domain=ZZ, greedy=False))
raises(OptionError, lambda: Poly(x + 2, x, domain=QQ, field=False))
raises(NotImplementedError, lambda: Poly(x + 1, x, modulus=3, order='grlex'))
raises(NotImplementedError, lambda: Poly(x + 1, x, order='grlex'))
raises(GeneratorsNeeded, lambda: Poly({1: 2, 0: 1}))
raises(GeneratorsNeeded, lambda: Poly([2, 1]))
raises(GeneratorsNeeded, lambda: Poly((2, 1)))
raises(GeneratorsNeeded, lambda: Poly(1))
f = a*x**2 + b*x + c
assert Poly({2: a, 1: b, 0: c}, x) == f
assert Poly(iter([a, b, c]), x) == f
assert Poly([a, b, c], x) == f
assert Poly((a, b, c), x) == f
f = Poly({}, x, y, z)
assert f.gens == (x, y, z) and f.as_expr() == 0
assert Poly(Poly(a*x + b*y, x, y), x) == Poly(a*x + b*y, x)
assert Poly(3*x**2 + 2*x + 1, domain='ZZ').all_coeffs() == [3, 2, 1]
assert Poly(3*x**2 + 2*x + 1, domain='QQ').all_coeffs() == [3, 2, 1]
assert Poly(3*x**2 + 2*x + 1, domain='RR').all_coeffs() == [3.0, 2.0, 1.0]
raises(CoercionFailed, lambda: Poly(3*x**2/5 + 2*x/5 + 1, domain='ZZ'))
assert Poly(
3*x**2/5 + 2*x/5 + 1, domain='QQ').all_coeffs() == [S(3)/5, S(2)/5, 1]
assert _epsilon_eq(
Poly(3*x**2/5 + 2*x/5 + 1, domain='RR').all_coeffs(), [0.6, 0.4, 1.0])
assert Poly(3.0*x**2 + 2.0*x + 1, domain='ZZ').all_coeffs() == [3, 2, 1]
assert Poly(3.0*x**2 + 2.0*x + 1, domain='QQ').all_coeffs() == [3, 2, 1]
assert Poly(
3.0*x**2 + 2.0*x + 1, domain='RR').all_coeffs() == [3.0, 2.0, 1.0]
raises(CoercionFailed, lambda: Poly(3.1*x**2 + 2.1*x + 1, domain='ZZ'))
assert Poly(3.1*x**2 + 2.1*x + 1, domain='QQ').all_coeffs() == [S(31)/10, S(21)/10, 1]
assert Poly(3.1*x**2 + 2.1*x + 1, domain='RR').all_coeffs() == [3.1, 2.1, 1.0]
assert Poly({(2, 1): 1, (1, 2): 2, (1, 1): 3}, x, y) == \
Poly(x**2*y + 2*x*y**2 + 3*x*y, x, y)
assert Poly(x**2 + 1, extension=I).get_domain() == QQ.algebraic_field(I)
f = 3*x**5 - x**4 + x**3 - x** 2 + 65538
assert Poly(f, x, modulus=65537, symmetric=True) == \
Poly(3*x**5 - x**4 + x**3 - x** 2 + 1, x, modulus=65537,
symmetric=True)
assert Poly(f, x, modulus=65537, symmetric=False) == \
Poly(3*x**5 + 65536*x**4 + x**3 + 65536*x** 2 + 1, x,
modulus=65537, symmetric=False)
assert isinstance(Poly(x**2 + x + 1.0).get_domain(), RealField)
def test_Poly__args():
assert Poly(x**2 + 1).args == (x**2 + 1,)
def test_Poly__gens():
assert Poly((x - p)*(x - q), x).gens == (x,)
assert Poly((x - p)*(x - q), p).gens == (p,)
assert Poly((x - p)*(x - q), q).gens == (q,)
assert Poly((x - p)*(x - q), x, p).gens == (x, p)
assert Poly((x - p)*(x - q), x, q).gens == (x, q)
assert Poly((x - p)*(x - q), x, p, q).gens == (x, p, q)
assert Poly((x - p)*(x - q), p, x, q).gens == (p, x, q)
assert Poly((x - p)*(x - q), p, q, x).gens == (p, q, x)
assert Poly((x - p)*(x - q)).gens == (x, p, q)
assert Poly((x - p)*(x - q), sort='x > p > q').gens == (x, p, q)
assert Poly((x - p)*(x - q), sort='p > x > q').gens == (p, x, q)
assert Poly((x - p)*(x - q), sort='p > q > x').gens == (p, q, x)
assert Poly((x - p)*(x - q), x, p, q, sort='p > q > x').gens == (x, p, q)
assert Poly((x - p)*(x - q), wrt='x').gens == (x, p, q)
assert Poly((x - p)*(x - q), wrt='p').gens == (p, x, q)
assert Poly((x - p)*(x - q), wrt='q').gens == (q, x, p)
assert Poly((x - p)*(x - q), wrt=x).gens == (x, p, q)
assert Poly((x - p)*(x - q), wrt=p).gens == (p, x, q)
assert Poly((x - p)*(x - q), wrt=q).gens == (q, x, p)
assert Poly((x - p)*(x - q), x, p, q, wrt='p').gens == (x, p, q)
assert Poly((x - p)*(x - q), wrt='p', sort='q > x').gens == (p, q, x)
assert Poly((x - p)*(x - q), wrt='q', sort='p > x').gens == (q, p, x)
def test_Poly_zero():
assert Poly(x).zero == Poly(0, x, domain=ZZ)
assert Poly(x/2).zero == Poly(0, x, domain=QQ)
def test_Poly_one():
assert Poly(x).one == Poly(1, x, domain=ZZ)
assert Poly(x/2).one == Poly(1, x, domain=QQ)
def test_Poly__unify():
raises(UnificationFailed, lambda: Poly(x)._unify(y))
F3 = FF(3)
F5 = FF(5)
assert Poly(x, x, modulus=3)._unify(Poly(y, y, modulus=3))[2:] == (
DMP([[F3(1)], []], F3), DMP([[F3(1), F3(0)]], F3))
assert Poly(x, x, modulus=3)._unify(Poly(y, y, modulus=5))[2:] == (
DMP([[F5(1)], []], F5), DMP([[F5(1), F5(0)]], F5))
assert Poly(y, x, y)._unify(Poly(x, x, modulus=3))[2:] == (DMP([[F3(1), F3(0)]], F3), DMP([[F3(1)], []], F3))
assert Poly(x, x, modulus=3)._unify(Poly(y, x, y))[2:] == (DMP([[F3(1)], []], F3), DMP([[F3(1), F3(0)]], F3))
assert Poly(x + 1, x)._unify(Poly(x + 2, x))[2:] == (DMP([1, 1], ZZ), DMP([1, 2], ZZ))
assert Poly(x + 1, x, domain='QQ')._unify(Poly(x + 2, x))[2:] == (DMP([1, 1], QQ), DMP([1, 2], QQ))
assert Poly(x + 1, x)._unify(Poly(x + 2, x, domain='QQ'))[2:] == (DMP([1, 1], QQ), DMP([1, 2], QQ))
assert Poly(x + 1, x)._unify(Poly(x + 2, x, y))[2:] == (DMP([[1], [1]], ZZ), DMP([[1], [2]], ZZ))
assert Poly(x + 1, x, domain='QQ')._unify(Poly(x + 2, x, y))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ))
assert Poly(x + 1, x)._unify(Poly(x + 2, x, y, domain='QQ'))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ))
assert Poly(x + 1, x, y)._unify(Poly(x + 2, x))[2:] == (DMP([[1], [1]], ZZ), DMP([[1], [2]], ZZ))
assert Poly(x + 1, x, y, domain='QQ')._unify(Poly(x + 2, x))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ))
assert Poly(x + 1, x, y)._unify(Poly(x + 2, x, domain='QQ'))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ))
assert Poly(x + 1, x, y)._unify(Poly(x + 2, x, y))[2:] == (DMP([[1], [1]], ZZ), DMP([[1], [2]], ZZ))
assert Poly(x + 1, x, y, domain='QQ')._unify(Poly(x + 2, x, y))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ))
assert Poly(x + 1, x, y)._unify(Poly(x + 2, x, y, domain='QQ'))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ))
assert Poly(x + 1, x)._unify(Poly(x + 2, y, x))[2:] == (DMP([[1, 1]], ZZ), DMP([[1, 2]], ZZ))
assert Poly(x + 1, x, domain='QQ')._unify(Poly(x + 2, y, x))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ))
assert Poly(x + 1, x)._unify(Poly(x + 2, y, x, domain='QQ'))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ))
assert Poly(x + 1, y, x)._unify(Poly(x + 2, x))[2:] == (DMP([[1, 1]], ZZ), DMP([[1, 2]], ZZ))
assert Poly(x + 1, y, x, domain='QQ')._unify(Poly(x + 2, x))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ))
assert Poly(x + 1, y, x)._unify(Poly(x + 2, x, domain='QQ'))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ))
assert Poly(x + 1, x, y)._unify(Poly(x + 2, y, x))[2:] == (DMP([[1], [1]], ZZ), DMP([[1], [2]], ZZ))
assert Poly(x + 1, x, y, domain='QQ')._unify(Poly(x + 2, y, x))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ))
assert Poly(x + 1, x, y)._unify(Poly(x + 2, y, x, domain='QQ'))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ))
assert Poly(x + 1, y, x)._unify(Poly(x + 2, x, y))[2:] == (DMP([[1, 1]], ZZ), DMP([[1, 2]], ZZ))
assert Poly(x + 1, y, x, domain='QQ')._unify(Poly(x + 2, x, y))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ))
assert Poly(x + 1, y, x)._unify(Poly(x + 2, x, y, domain='QQ'))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ))
F, A, B = field("a,b", ZZ)
assert Poly(a*x, x, domain='ZZ[a]')._unify(Poly(a*b*x, x, domain='ZZ(a,b)'))[2:] == \
(DMP([A, F(0)], F.to_domain()), DMP([A*B, F(0)], F.to_domain()))
assert Poly(a*x, x, domain='ZZ(a)')._unify(Poly(a*b*x, x, domain='ZZ(a,b)'))[2:] == \
(DMP([A, F(0)], F.to_domain()), DMP([A*B, F(0)], F.to_domain()))
raises(CoercionFailed, lambda: Poly(Poly(x**2 + x**2*z, y, field=True), domain='ZZ(x)'))
f = Poly(t**2 + t/3 + x, t, domain='QQ(x)')
g = Poly(t**2 + t/3 + x, t, domain='QQ[x]')
assert f._unify(g)[2:] == (f.rep, f.rep)
def test_Poly_free_symbols():
assert Poly(x**2 + 1).free_symbols == {x}
assert Poly(x**2 + y*z).free_symbols == {x, y, z}
assert Poly(x**2 + y*z, x).free_symbols == {x, y, z}
assert Poly(x**2 + sin(y*z)).free_symbols == {x, y, z}
assert Poly(x**2 + sin(y*z), x).free_symbols == {x, y, z}
assert Poly(x**2 + sin(y*z), x, domain=EX).free_symbols == {x, y, z}
def test_PurePoly_free_symbols():
assert PurePoly(x**2 + 1).free_symbols == set([])
assert PurePoly(x**2 + y*z).free_symbols == set([])
assert PurePoly(x**2 + y*z, x).free_symbols == {y, z}
assert PurePoly(x**2 + sin(y*z)).free_symbols == set([])
assert PurePoly(x**2 + sin(y*z), x).free_symbols == {y, z}
assert PurePoly(x**2 + sin(y*z), x, domain=EX).free_symbols == {y, z}
def test_Poly__eq__():
assert (Poly(x, x) == Poly(x, x)) is True
assert (Poly(x, x, domain=QQ) == Poly(x, x)) is True
assert (Poly(x, x) == Poly(x, x, domain=QQ)) is True
assert (Poly(x, x, domain=ZZ[a]) == Poly(x, x)) is True
assert (Poly(x, x) == Poly(x, x, domain=ZZ[a])) is True
assert (Poly(x*y, x, y) == Poly(x, x)) is False
assert (Poly(x, x, y) == Poly(x, x)) is False
assert (Poly(x, x) == Poly(x, x, y)) is False
assert (Poly(x**2 + 1, x) == Poly(y**2 + 1, y)) is False
assert (Poly(y**2 + 1, y) == Poly(x**2 + 1, x)) is False
f = Poly(x, x, domain=ZZ)
g = Poly(x, x, domain=QQ)
assert f.eq(g) is True
assert f.ne(g) is False
assert f.eq(g, strict=True) is False
assert f.ne(g, strict=True) is True
t0 = Symbol('t0')
f = Poly((t0/2 + x**2)*t**2 - x**2*t, t, domain='QQ[x,t0]')
g = Poly((t0/2 + x**2)*t**2 - x**2*t, t, domain='ZZ(x,t0)')
assert (f == g) is True
def test_PurePoly__eq__():
assert (PurePoly(x, x) == PurePoly(x, x)) is True
assert (PurePoly(x, x, domain=QQ) == PurePoly(x, x)) is True
assert (PurePoly(x, x) == PurePoly(x, x, domain=QQ)) is True
assert (PurePoly(x, x, domain=ZZ[a]) == PurePoly(x, x)) is True
assert (PurePoly(x, x) == PurePoly(x, x, domain=ZZ[a])) is True
assert (PurePoly(x*y, x, y) == PurePoly(x, x)) is False
assert (PurePoly(x, x, y) == PurePoly(x, x)) is False
assert (PurePoly(x, x) == PurePoly(x, x, y)) is False
assert (PurePoly(x**2 + 1, x) == PurePoly(y**2 + 1, y)) is True
assert (PurePoly(y**2 + 1, y) == PurePoly(x**2 + 1, x)) is True
f = PurePoly(x, x, domain=ZZ)
g = PurePoly(x, x, domain=QQ)
assert f.eq(g) is True
assert f.ne(g) is False
assert f.eq(g, strict=True) is False
assert f.ne(g, strict=True) is True
f = PurePoly(x, x, domain=ZZ)
g = PurePoly(y, y, domain=QQ)
assert f.eq(g) is True
assert f.ne(g) is False
assert f.eq(g, strict=True) is False
assert f.ne(g, strict=True) is True
def test_PurePoly_Poly():
assert isinstance(PurePoly(Poly(x**2 + 1)), PurePoly) is True
assert isinstance(Poly(PurePoly(x**2 + 1)), Poly) is True
def test_Poly_get_domain():
assert Poly(2*x).get_domain() == ZZ
assert Poly(2*x, domain='ZZ').get_domain() == ZZ
assert Poly(2*x, domain='QQ').get_domain() == QQ
assert Poly(x/2).get_domain() == QQ
raises(CoercionFailed, lambda: Poly(x/2, domain='ZZ'))
assert Poly(x/2, domain='QQ').get_domain() == QQ
assert isinstance(Poly(0.2*x).get_domain(), RealField)
def test_Poly_set_domain():
assert Poly(2*x + 1).set_domain(ZZ) == Poly(2*x + 1)
assert Poly(2*x + 1).set_domain('ZZ') == Poly(2*x + 1)
assert Poly(2*x + 1).set_domain(QQ) == Poly(2*x + 1, domain='QQ')
assert Poly(2*x + 1).set_domain('QQ') == Poly(2*x + 1, domain='QQ')
assert Poly(S(2)/10*x + S(1)/10).set_domain('RR') == Poly(0.2*x + 0.1)
assert Poly(0.2*x + 0.1).set_domain('QQ') == Poly(S(2)/10*x + S(1)/10)
raises(CoercionFailed, lambda: Poly(x/2 + 1).set_domain(ZZ))
raises(CoercionFailed, lambda: Poly(x + 1, modulus=2).set_domain(QQ))
raises(GeneratorsError, lambda: Poly(x*y, x, y).set_domain(ZZ[y]))
def test_Poly_get_modulus():
assert Poly(x**2 + 1, modulus=2).get_modulus() == 2
raises(PolynomialError, lambda: Poly(x**2 + 1).get_modulus())
def test_Poly_set_modulus():
assert Poly(
x**2 + 1, modulus=2).set_modulus(7) == Poly(x**2 + 1, modulus=7)
assert Poly(
x**2 + 5, modulus=7).set_modulus(2) == Poly(x**2 + 1, modulus=2)
assert Poly(x**2 + 1).set_modulus(2) == Poly(x**2 + 1, modulus=2)
raises(CoercionFailed, lambda: Poly(x/2 + 1).set_modulus(2))
def test_Poly_add_ground():
assert Poly(x + 1).add_ground(2) == Poly(x + 3)
def test_Poly_sub_ground():
assert Poly(x + 1).sub_ground(2) == Poly(x - 1)
def test_Poly_mul_ground():
assert Poly(x + 1).mul_ground(2) == Poly(2*x + 2)
def test_Poly_quo_ground():
assert Poly(2*x + 4).quo_ground(2) == Poly(x + 2)
assert Poly(2*x + 3).quo_ground(2) == Poly(x + 1)
def test_Poly_exquo_ground():
assert Poly(2*x + 4).exquo_ground(2) == Poly(x + 2)
raises(ExactQuotientFailed, lambda: Poly(2*x + 3).exquo_ground(2))
def test_Poly_abs():
assert Poly(-x + 1, x).abs() == abs(Poly(-x + 1, x)) == Poly(x + 1, x)
def test_Poly_neg():
assert Poly(-x + 1, x).neg() == -Poly(-x + 1, x) == Poly(x - 1, x)
def test_Poly_add():
assert Poly(0, x).add(Poly(0, x)) == Poly(0, x)
assert Poly(0, x) + Poly(0, x) == Poly(0, x)
assert Poly(1, x).add(Poly(0, x)) == Poly(1, x)
assert Poly(1, x, y) + Poly(0, x) == Poly(1, x, y)
assert Poly(0, x).add(Poly(1, x, y)) == Poly(1, x, y)
assert Poly(0, x, y) + Poly(1, x, y) == Poly(1, x, y)
assert Poly(1, x) + x == Poly(x + 1, x)
assert Poly(1, x) + sin(x) == 1 + sin(x)
assert Poly(x, x) + 1 == Poly(x + 1, x)
assert 1 + Poly(x, x) == Poly(x + 1, x)
def test_Poly_sub():
assert Poly(0, x).sub(Poly(0, x)) == Poly(0, x)
assert Poly(0, x) - Poly(0, x) == Poly(0, x)
assert Poly(1, x).sub(Poly(0, x)) == Poly(1, x)
assert Poly(1, x, y) - Poly(0, x) == Poly(1, x, y)
assert Poly(0, x).sub(Poly(1, x, y)) == Poly(-1, x, y)
assert Poly(0, x, y) - Poly(1, x, y) == Poly(-1, x, y)
assert Poly(1, x) - x == Poly(1 - x, x)
assert Poly(1, x) - sin(x) == 1 - sin(x)
assert Poly(x, x) - 1 == Poly(x - 1, x)
assert 1 - Poly(x, x) == Poly(1 - x, x)
def test_Poly_mul():
assert Poly(0, x).mul(Poly(0, x)) == Poly(0, x)
assert Poly(0, x) * Poly(0, x) == Poly(0, x)
assert Poly(2, x).mul(Poly(4, x)) == Poly(8, x)
assert Poly(2, x, y) * Poly(4, x) == Poly(8, x, y)
assert Poly(4, x).mul(Poly(2, x, y)) == Poly(8, x, y)
assert Poly(4, x, y) * Poly(2, x, y) == Poly(8, x, y)
assert Poly(1, x) * x == Poly(x, x)
assert Poly(1, x) * sin(x) == sin(x)
assert Poly(x, x) * 2 == Poly(2*x, x)
assert 2 * Poly(x, x) == Poly(2*x, x)
def test_Poly_sqr():
assert Poly(x*y, x, y).sqr() == Poly(x**2*y**2, x, y)
def test_Poly_pow():
assert Poly(x, x).pow(10) == Poly(x**10, x)
assert Poly(x, x).pow(Integer(10)) == Poly(x**10, x)
assert Poly(2*y, x, y).pow(4) == Poly(16*y**4, x, y)
assert Poly(2*y, x, y).pow(Integer(4)) == Poly(16*y**4, x, y)
assert Poly(7*x*y, x, y)**3 == Poly(343*x**3*y**3, x, y)
assert Poly(x*y + 1, x, y)**(-1) == (x*y + 1)**(-1)
assert Poly(x*y + 1, x, y)**x == (x*y + 1)**x
def test_Poly_divmod():
f, g = Poly(x**2), Poly(x)
q, r = g, Poly(0, x)
assert divmod(f, g) == (q, r)
assert f // g == q
assert f % g == r
assert divmod(f, x) == (q, r)
assert f // x == q
assert f % x == r
q, r = Poly(0, x), Poly(2, x)
assert divmod(2, g) == (q, r)
assert 2 // g == q
assert 2 % g == r
assert Poly(x)/Poly(x) == 1
assert Poly(x**2)/Poly(x) == x
assert Poly(x)/Poly(x**2) == 1/x
def test_Poly_eq_ne():
assert (Poly(x + y, x, y) == Poly(x + y, x, y)) is True
assert (Poly(x + y, x) == Poly(x + y, x, y)) is False
assert (Poly(x + y, x, y) == Poly(x + y, x)) is False
assert (Poly(x + y, x) == Poly(x + y, x)) is True
assert (Poly(x + y, y) == Poly(x + y, y)) is True
assert (Poly(x + y, x, y) == x + y) is True
assert (Poly(x + y, x) == x + y) is True
assert (Poly(x + y, x, y) == x + y) is True
assert (Poly(x + y, x) == x + y) is True
assert (Poly(x + y, y) == x + y) is True
assert (Poly(x + y, x, y) != Poly(x + y, x, y)) is False
assert (Poly(x + y, x) != Poly(x + y, x, y)) is True
assert (Poly(x + y, x, y) != Poly(x + y, x)) is True
assert (Poly(x + y, x) != Poly(x + y, x)) is False
assert (Poly(x + y, y) != Poly(x + y, y)) is False
assert (Poly(x + y, x, y) != x + y) is False
assert (Poly(x + y, x) != x + y) is False
assert (Poly(x + y, x, y) != x + y) is False
assert (Poly(x + y, x) != x + y) is False
assert (Poly(x + y, y) != x + y) is False
assert (Poly(x, x) == sin(x)) is False
assert (Poly(x, x) != sin(x)) is True
def test_Poly_nonzero():
assert not bool(Poly(0, x)) is True
assert not bool(Poly(1, x)) is False
def test_Poly_properties():
assert Poly(0, x).is_zero is True
assert Poly(1, x).is_zero is False
assert Poly(1, x).is_one is True
assert Poly(2, x).is_one is False
assert Poly(x - 1, x).is_sqf is True
assert Poly((x - 1)**2, x).is_sqf is False
assert Poly(x - 1, x).is_monic is True
assert Poly(2*x - 1, x).is_monic is False
assert Poly(3*x + 2, x).is_primitive is True
assert Poly(4*x + 2, x).is_primitive is False
assert Poly(1, x).is_ground is True
assert Poly(x, x).is_ground is False
assert Poly(x + y + z + 1).is_linear is True
assert Poly(x*y*z + 1).is_linear is False
assert Poly(x*y + z + 1).is_quadratic is True
assert Poly(x*y*z + 1).is_quadratic is False
assert Poly(x*y).is_monomial is True
assert Poly(x*y + 1).is_monomial is False
assert Poly(x**2 + x*y).is_homogeneous is True
assert Poly(x**3 + x*y).is_homogeneous is False
assert Poly(x).is_univariate is True
assert Poly(x*y).is_univariate is False
assert Poly(x*y).is_multivariate is True
assert Poly(x).is_multivariate is False
assert Poly(
x**16 + x**14 - x**10 + x**8 - x**6 + x**2 + 1).is_cyclotomic is False
assert Poly(
x**16 + x**14 - x**10 - x**8 - x**6 + x**2 + 1).is_cyclotomic is True
def test_Poly_is_irreducible():
assert Poly(x**2 + x + 1).is_irreducible is True
assert Poly(x**2 + 2*x + 1).is_irreducible is False
assert Poly(7*x + 3, modulus=11).is_irreducible is True
assert Poly(7*x**2 + 3*x + 1, modulus=11).is_irreducible is False
def test_Poly_subs():
assert Poly(x + 1).subs(x, 0) == 1
assert Poly(x + 1).subs(x, x) == Poly(x + 1)
assert Poly(x + 1).subs(x, y) == Poly(y + 1)
assert Poly(x*y, x).subs(y, x) == x**2
assert Poly(x*y, x).subs(x, y) == y**2
def test_Poly_replace():
assert Poly(x + 1).replace(x) == Poly(x + 1)
assert Poly(x + 1).replace(y) == Poly(y + 1)
raises(PolynomialError, lambda: Poly(x + y).replace(z))
assert Poly(x + 1).replace(x, x) == Poly(x + 1)
assert Poly(x + 1).replace(x, y) == Poly(y + 1)
assert Poly(x + y).replace(x, x) == Poly(x + y)
assert Poly(x + y).replace(x, z) == Poly(z + y, z, y)
assert Poly(x + y).replace(y, y) == Poly(x + y)
assert Poly(x + y).replace(y, z) == Poly(x + z, x, z)
raises(PolynomialError, lambda: Poly(x + y).replace(x, y))
raises(PolynomialError, lambda: Poly(x + y).replace(z, t))
assert Poly(x + y, x).replace(x, z) == Poly(z + y, z)
assert Poly(x + y, y).replace(y, z) == Poly(x + z, z)
raises(PolynomialError, lambda: Poly(x + y, x).replace(x, y))
raises(PolynomialError, lambda: Poly(x + y, y).replace(y, x))
def test_Poly_reorder():
raises(PolynomialError, lambda: Poly(x + y).reorder(x, z))
assert Poly(x + y, x, y).reorder(x, y) == Poly(x + y, x, y)
assert Poly(x + y, x, y).reorder(y, x) == Poly(x + y, y, x)
assert Poly(x + y, y, x).reorder(x, y) == Poly(x + y, x, y)
assert Poly(x + y, y, x).reorder(y, x) == Poly(x + y, y, x)
assert Poly(x + y, x, y).reorder(wrt=x) == Poly(x + y, x, y)
assert Poly(x + y, x, y).reorder(wrt=y) == Poly(x + y, y, x)
def test_Poly_ltrim():
f = Poly(y**2 + y*z**2, x, y, z).ltrim(y)
assert f.as_expr() == y**2 + y*z**2 and f.gens == (y, z)
raises(PolynomialError, lambda: Poly(x*y**2 + y**2, x, y).ltrim(y))
def test_Poly_has_only_gens():
assert Poly(x*y + 1, x, y, z).has_only_gens(x, y) is True
assert Poly(x*y + z, x, y, z).has_only_gens(x, y) is False
raises(GeneratorsError, lambda: Poly(x*y**2 + y**2, x, y).has_only_gens(t))
def test_Poly_to_ring():
assert Poly(2*x + 1, domain='ZZ').to_ring() == Poly(2*x + 1, domain='ZZ')
assert Poly(2*x + 1, domain='QQ').to_ring() == Poly(2*x + 1, domain='ZZ')
raises(CoercionFailed, lambda: Poly(x/2 + 1).to_ring())
raises(DomainError, lambda: Poly(2*x + 1, modulus=3).to_ring())
def test_Poly_to_field():
assert Poly(2*x + 1, domain='ZZ').to_field() == Poly(2*x + 1, domain='QQ')
assert Poly(2*x + 1, domain='QQ').to_field() == Poly(2*x + 1, domain='QQ')
assert Poly(x/2 + 1, domain='QQ').to_field() == Poly(x/2 + 1, domain='QQ')
assert Poly(2*x + 1, modulus=3).to_field() == Poly(2*x + 1, modulus=3)
assert Poly(2.0*x + 1.0).to_field() == Poly(2.0*x + 1.0)
def test_Poly_to_exact():
assert Poly(2*x).to_exact() == Poly(2*x)
assert Poly(x/2).to_exact() == Poly(x/2)
assert Poly(0.1*x).to_exact() == Poly(x/10)
def test_Poly_retract():
f = Poly(x**2 + 1, x, domain=QQ[y])
assert f.retract() == Poly(x**2 + 1, x, domain='ZZ')
assert f.retract(field=True) == Poly(x**2 + 1, x, domain='QQ')
assert Poly(0, x, y).retract() == Poly(0, x, y)
def test_Poly_slice():
f = Poly(x**3 + 2*x**2 + 3*x + 4)
assert f.slice(0, 0) == Poly(0, x)
assert f.slice(0, 1) == Poly(4, x)
assert f.slice(0, 2) == Poly(3*x + 4, x)
assert f.slice(0, 3) == Poly(2*x**2 + 3*x + 4, x)
assert f.slice(0, 4) == Poly(x**3 + 2*x**2 + 3*x + 4, x)
assert f.slice(x, 0, 0) == Poly(0, x)
assert f.slice(x, 0, 1) == Poly(4, x)
assert f.slice(x, 0, 2) == Poly(3*x + 4, x)
assert f.slice(x, 0, 3) == Poly(2*x**2 + 3*x + 4, x)
assert f.slice(x, 0, 4) == Poly(x**3 + 2*x**2 + 3*x + 4, x)
def test_Poly_coeffs():
assert Poly(0, x).coeffs() == [0]
assert Poly(1, x).coeffs() == [1]
assert Poly(2*x + 1, x).coeffs() == [2, 1]
assert Poly(7*x**2 + 2*x + 1, x).coeffs() == [7, 2, 1]
assert Poly(7*x**4 + 2*x + 1, x).coeffs() == [7, 2, 1]
assert Poly(x*y**7 + 2*x**2*y**3).coeffs('lex') == [2, 1]
assert Poly(x*y**7 + 2*x**2*y**3).coeffs('grlex') == [1, 2]
def test_Poly_monoms():
assert Poly(0, x).monoms() == [(0,)]
assert Poly(1, x).monoms() == [(0,)]
assert Poly(2*x + 1, x).monoms() == [(1,), (0,)]
assert Poly(7*x**2 + 2*x + 1, x).monoms() == [(2,), (1,), (0,)]
assert Poly(7*x**4 + 2*x + 1, x).monoms() == [(4,), (1,), (0,)]
assert Poly(x*y**7 + 2*x**2*y**3).monoms('lex') == [(2, 3), (1, 7)]
assert Poly(x*y**7 + 2*x**2*y**3).monoms('grlex') == [(1, 7), (2, 3)]
def test_Poly_terms():
assert Poly(0, x).terms() == [((0,), 0)]
assert Poly(1, x).terms() == [((0,), 1)]
assert Poly(2*x + 1, x).terms() == [((1,), 2), ((0,), 1)]
assert Poly(7*x**2 + 2*x + 1, x).terms() == [((2,), 7), ((1,), 2), ((0,), 1)]
assert Poly(7*x**4 + 2*x + 1, x).terms() == [((4,), 7), ((1,), 2), ((0,), 1)]
assert Poly(
x*y**7 + 2*x**2*y**3).terms('lex') == [((2, 3), 2), ((1, 7), 1)]
assert Poly(
x*y**7 + 2*x**2*y**3).terms('grlex') == [((1, 7), 1), ((2, 3), 2)]
def test_Poly_all_coeffs():
assert Poly(0, x).all_coeffs() == [0]
assert Poly(1, x).all_coeffs() == [1]
assert Poly(2*x + 1, x).all_coeffs() == [2, 1]
assert Poly(7*x**2 + 2*x + 1, x).all_coeffs() == [7, 2, 1]
assert Poly(7*x**4 + 2*x + 1, x).all_coeffs() == [7, 0, 0, 2, 1]
def test_Poly_all_monoms():
assert Poly(0, x).all_monoms() == [(0,)]
assert Poly(1, x).all_monoms() == [(0,)]
assert Poly(2*x + 1, x).all_monoms() == [(1,), (0,)]
assert Poly(7*x**2 + 2*x + 1, x).all_monoms() == [(2,), (1,), (0,)]
assert Poly(7*x**4 + 2*x + 1, x).all_monoms() == [(4,), (3,), (2,), (1,), (0,)]
def test_Poly_all_terms():
assert Poly(0, x).all_terms() == [((0,), 0)]
assert Poly(1, x).all_terms() == [((0,), 1)]
assert Poly(2*x + 1, x).all_terms() == [((1,), 2), ((0,), 1)]
assert Poly(7*x**2 + 2*x + 1, x).all_terms() == \
[((2,), 7), ((1,), 2), ((0,), 1)]
assert Poly(7*x**4 + 2*x + 1, x).all_terms() == \
[((4,), 7), ((3,), 0), ((2,), 0), ((1,), 2), ((0,), 1)]
def test_Poly_termwise():
f = Poly(x**2 + 20*x + 400)
g = Poly(x**2 + 2*x + 4)
def func(monom, coeff):
(k,) = monom
return coeff//10**(2 - k)
assert f.termwise(func) == g
def func(monom, coeff):
(k,) = monom
return (k,), coeff//10**(2 - k)
assert f.termwise(func) == g
def test_Poly_length():
assert Poly(0, x).length() == 0
assert Poly(1, x).length() == 1
assert Poly(x, x).length() == 1
assert Poly(x + 1, x).length() == 2
assert Poly(x**2 + 1, x).length() == 2
assert Poly(x**2 + x + 1, x).length() == 3
def test_Poly_as_dict():
assert Poly(0, x).as_dict() == {}
assert Poly(0, x, y, z).as_dict() == {}
assert Poly(1, x).as_dict() == {(0,): 1}
assert Poly(1, x, y, z).as_dict() == {(0, 0, 0): 1}
assert Poly(x**2 + 3, x).as_dict() == {(2,): 1, (0,): 3}
assert Poly(x**2 + 3, x, y, z).as_dict() == {(2, 0, 0): 1, (0, 0, 0): 3}
assert Poly(3*x**2*y*z**3 + 4*x*y + 5*x*z).as_dict() == {(2, 1, 3): 3,
(1, 1, 0): 4, (1, 0, 1): 5}
def test_Poly_as_expr():
assert Poly(0, x).as_expr() == 0
assert Poly(0, x, y, z).as_expr() == 0
assert Poly(1, x).as_expr() == 1
assert Poly(1, x, y, z).as_expr() == 1
assert Poly(x**2 + 3, x).as_expr() == x**2 + 3
assert Poly(x**2 + 3, x, y, z).as_expr() == x**2 + 3
assert Poly(
3*x**2*y*z**3 + 4*x*y + 5*x*z).as_expr() == 3*x**2*y*z**3 + 4*x*y + 5*x*z
f = Poly(x**2 + 2*x*y**2 - y, x, y)
assert f.as_expr() == -y + x**2 + 2*x*y**2
assert f.as_expr({x: 5}) == 25 - y + 10*y**2
assert f.as_expr({y: 6}) == -6 + 72*x + x**2
assert f.as_expr({x: 5, y: 6}) == 379
assert f.as_expr(5, 6) == 379
raises(GeneratorsError, lambda: f.as_expr({z: 7}))
def test_Poly_lift():
assert Poly(x**4 - I*x + 17*I, x, gaussian=True).lift() == \
Poly(x**16 + 2*x**10 + 578*x**8 + x**4 - 578*x**2 + 83521,
x, domain='QQ')
def test_Poly_deflate():
assert Poly(0, x).deflate() == ((1,), Poly(0, x))
assert Poly(1, x).deflate() == ((1,), Poly(1, x))
assert Poly(x, x).deflate() == ((1,), Poly(x, x))
assert Poly(x**2, x).deflate() == ((2,), Poly(x, x))
assert Poly(x**17, x).deflate() == ((17,), Poly(x, x))
assert Poly(
x**2*y*z**11 + x**4*z**11).deflate() == ((2, 1, 11), Poly(x*y*z + x**2*z))
def test_Poly_inject():
f = Poly(x**2*y + x*y**3 + x*y + 1, x)
assert f.inject() == Poly(x**2*y + x*y**3 + x*y + 1, x, y)
assert f.inject(front=True) == Poly(y**3*x + y*x**2 + y*x + 1, y, x)
def test_Poly_eject():
f = Poly(x**2*y + x*y**3 + x*y + 1, x, y)
assert f.eject(x) == Poly(x*y**3 + (x**2 + x)*y + 1, y, domain='ZZ[x]')
assert f.eject(y) == Poly(y*x**2 + (y**3 + y)*x + 1, x, domain='ZZ[y]')
ex = x + y + z + t + w
g = Poly(ex, x, y, z, t, w)
assert g.eject(x) == Poly(ex, y, z, t, w, domain='ZZ[x]')
assert g.eject(x, y) == Poly(ex, z, t, w, domain='ZZ[x, y]')
assert g.eject(x, y, z) == Poly(ex, t, w, domain='ZZ[x, y, z]')
assert g.eject(w) == Poly(ex, x, y, z, t, domain='ZZ[w]')
assert g.eject(t, w) == Poly(ex, x, y, z, domain='ZZ[w, t]')
assert g.eject(z, t, w) == Poly(ex, x, y, domain='ZZ[w, t, z]')
raises(DomainError, lambda: Poly(x*y, x, y, domain=ZZ[z]).eject(y))
raises(NotImplementedError, lambda: Poly(x*y, x, y, z).eject(y))
def test_Poly_exclude():
assert Poly(x, x, y).exclude() == Poly(x, x)
assert Poly(x*y, x, y).exclude() == Poly(x*y, x, y)
assert Poly(1, x, y).exclude() == Poly(1, x, y)
def test_Poly__gen_to_level():
assert Poly(1, x, y)._gen_to_level(-2) == 0
assert Poly(1, x, y)._gen_to_level(-1) == 1
assert Poly(1, x, y)._gen_to_level( 0) == 0
assert Poly(1, x, y)._gen_to_level( 1) == 1
raises(PolynomialError, lambda: Poly(1, x, y)._gen_to_level(-3))
raises(PolynomialError, lambda: Poly(1, x, y)._gen_to_level( 2))
assert Poly(1, x, y)._gen_to_level(x) == 0
assert Poly(1, x, y)._gen_to_level(y) == 1
assert Poly(1, x, y)._gen_to_level('x') == 0
assert Poly(1, x, y)._gen_to_level('y') == 1
raises(PolynomialError, lambda: Poly(1, x, y)._gen_to_level(z))
raises(PolynomialError, lambda: Poly(1, x, y)._gen_to_level('z'))
def test_Poly_degree():
assert Poly(0, x).degree() == -oo
assert Poly(1, x).degree() == 0
assert Poly(x, x).degree() == 1
assert Poly(0, x).degree(gen=0) == -oo
assert Poly(1, x).degree(gen=0) == 0
assert Poly(x, x).degree(gen=0) == 1
assert Poly(0, x).degree(gen=x) == -oo
assert Poly(1, x).degree(gen=x) == 0
assert Poly(x, x).degree(gen=x) == 1
assert Poly(0, x).degree(gen='x') == -oo
assert Poly(1, x).degree(gen='x') == 0
assert Poly(x, x).degree(gen='x') == 1
raises(PolynomialError, lambda: Poly(1, x).degree(gen=1))
raises(PolynomialError, lambda: Poly(1, x).degree(gen=y))
raises(PolynomialError, lambda: Poly(1, x).degree(gen='y'))
assert Poly(1, x, y).degree() == 0
assert Poly(2*y, x, y).degree() == 0
assert Poly(x*y, x, y).degree() == 1
assert Poly(1, x, y).degree(gen=x) == 0
assert Poly(2*y, x, y).degree(gen=x) == 0
assert Poly(x*y, x, y).degree(gen=x) == 1
assert Poly(1, x, y).degree(gen=y) == 0
assert Poly(2*y, x, y).degree(gen=y) == 1
assert Poly(x*y, x, y).degree(gen=y) == 1
assert degree(1, x) == 0
assert degree(x, x) == 1
assert degree(x*y**2, gen=x) == 1
assert degree(x*y**2, gen=y) == 2
assert degree(x*y**2, x, y) == 1
assert degree(x*y**2, y, x) == 2
raises(ComputationFailed, lambda: degree(1))
def test_Poly_degree_list():
assert Poly(0, x).degree_list() == (-oo,)
assert Poly(0, x, y).degree_list() == (-oo, -oo)
assert Poly(0, x, y, z).degree_list() == (-oo, -oo, -oo)
assert Poly(1, x).degree_list() == (0,)
assert Poly(1, x, y).degree_list() == (0, 0)
assert Poly(1, x, y, z).degree_list() == (0, 0, 0)
assert Poly(x**2*y + x**3*z**2 + 1).degree_list() == (3, 1, 2)
assert degree_list(1, x) == (0,)
assert degree_list(x, x) == (1,)
assert degree_list(x*y**2) == (1, 2)
raises(ComputationFailed, lambda: degree_list(1))
def test_Poly_total_degree():
assert Poly(x**2*y + x**3*z**2 + 1).total_degree() == 5
assert Poly(x**2 + z**3).total_degree() == 3
assert Poly(x*y*z + z**4).total_degree() == 4
assert Poly(x**3 + x + 1).total_degree() == 3
def test_Poly_homogenize():
assert Poly(x**2+y).homogenize(z) == Poly(x**2+y*z)
assert Poly(x+y).homogenize(z) == Poly(x+y, x, y, z)
assert Poly(x+y**2).homogenize(y) == Poly(x*y+y**2)
def test_Poly_homogeneous_order():
assert Poly(0, x, y).homogeneous_order() == -oo
assert Poly(1, x, y).homogeneous_order() == 0
assert Poly(x, x, y).homogeneous_order() == 1
assert Poly(x*y, x, y).homogeneous_order() == 2
assert Poly(x + 1, x, y).homogeneous_order() is None
assert Poly(x*y + x, x, y).homogeneous_order() is None
assert Poly(x**5 + 2*x**3*y**2 + 9*x*y**4).homogeneous_order() == 5
assert Poly(x**5 + 2*x**3*y**3 + 9*x*y**4).homogeneous_order() is None
def test_Poly_LC():
assert Poly(0, x).LC() == 0
assert Poly(1, x).LC() == 1
assert Poly(2*x**2 + x, x).LC() == 2
assert Poly(x*y**7 + 2*x**2*y**3).LC('lex') == 2
assert Poly(x*y**7 + 2*x**2*y**3).LC('grlex') == 1
assert LC(x*y**7 + 2*x**2*y**3, order='lex') == 2
assert LC(x*y**7 + 2*x**2*y**3, order='grlex') == 1
def test_Poly_TC():
assert Poly(0, x).TC() == 0
assert Poly(1, x).TC() == 1
assert Poly(2*x**2 + x, x).TC() == 0
def test_Poly_EC():
assert Poly(0, x).EC() == 0
assert Poly(1, x).EC() == 1
assert Poly(2*x**2 + x, x).EC() == 1
assert Poly(x*y**7 + 2*x**2*y**3).EC('lex') == 1
assert Poly(x*y**7 + 2*x**2*y**3).EC('grlex') == 2
def test_Poly_coeff():
assert Poly(0, x).coeff_monomial(1) == 0
assert Poly(0, x).coeff_monomial(x) == 0
assert Poly(1, x).coeff_monomial(1) == 1
assert Poly(1, x).coeff_monomial(x) == 0
assert Poly(x**8, x).coeff_monomial(1) == 0
assert Poly(x**8, x).coeff_monomial(x**7) == 0
assert Poly(x**8, x).coeff_monomial(x**8) == 1
assert Poly(x**8, x).coeff_monomial(x**9) == 0
assert Poly(3*x*y**2 + 1, x, y).coeff_monomial(1) == 1
assert Poly(3*x*y**2 + 1, x, y).coeff_monomial(x*y**2) == 3
p = Poly(24*x*y*exp(8) + 23*x, x, y)
assert p.coeff_monomial(x) == 23
assert p.coeff_monomial(y) == 0
assert p.coeff_monomial(x*y) == 24*exp(8)
assert p.as_expr().coeff(x) == 24*y*exp(8) + 23
raises(NotImplementedError, lambda: p.coeff(x))
raises(ValueError, lambda: Poly(x + 1).coeff_monomial(0))
raises(ValueError, lambda: Poly(x + 1).coeff_monomial(3*x))
raises(ValueError, lambda: Poly(x + 1).coeff_monomial(3*x*y))
def test_Poly_nth():
assert Poly(0, x).nth(0) == 0
assert Poly(0, x).nth(1) == 0
assert Poly(1, x).nth(0) == 1
assert Poly(1, x).nth(1) == 0
assert Poly(x**8, x).nth(0) == 0
assert Poly(x**8, x).nth(7) == 0
assert Poly(x**8, x).nth(8) == 1
assert Poly(x**8, x).nth(9) == 0
assert Poly(3*x*y**2 + 1, x, y).nth(0, 0) == 1
assert Poly(3*x*y**2 + 1, x, y).nth(1, 2) == 3
raises(ValueError, lambda: Poly(x*y + 1, x, y).nth(1))
def test_Poly_LM():
assert Poly(0, x).LM() == (0,)
assert Poly(1, x).LM() == (0,)
assert Poly(2*x**2 + x, x).LM() == (2,)
assert Poly(x*y**7 + 2*x**2*y**3).LM('lex') == (2, 3)
assert Poly(x*y**7 + 2*x**2*y**3).LM('grlex') == (1, 7)
assert LM(x*y**7 + 2*x**2*y**3, order='lex') == x**2*y**3
assert LM(x*y**7 + 2*x**2*y**3, order='grlex') == x*y**7
def test_Poly_LM_custom_order():
f = Poly(x**2*y**3*z + x**2*y*z**3 + x*y*z + 1)
rev_lex = lambda monom: tuple(reversed(monom))
assert f.LM(order='lex') == (2, 3, 1)
assert f.LM(order=rev_lex) == (2, 1, 3)
def test_Poly_EM():
assert Poly(0, x).EM() == (0,)
assert Poly(1, x).EM() == (0,)
assert Poly(2*x**2 + x, x).EM() == (1,)
assert Poly(x*y**7 + 2*x**2*y**3).EM('lex') == (1, 7)
assert Poly(x*y**7 + 2*x**2*y**3).EM('grlex') == (2, 3)
def test_Poly_LT():
assert Poly(0, x).LT() == ((0,), 0)
assert Poly(1, x).LT() == ((0,), 1)
assert Poly(2*x**2 + x, x).LT() == ((2,), 2)
assert Poly(x*y**7 + 2*x**2*y**3).LT('lex') == ((2, 3), 2)
assert Poly(x*y**7 + 2*x**2*y**3).LT('grlex') == ((1, 7), 1)
assert LT(x*y**7 + 2*x**2*y**3, order='lex') == 2*x**2*y**3
assert LT(x*y**7 + 2*x**2*y**3, order='grlex') == x*y**7
def test_Poly_ET():
assert Poly(0, x).ET() == ((0,), 0)
assert Poly(1, x).ET() == ((0,), 1)
assert Poly(2*x**2 + x, x).ET() == ((1,), 1)
assert Poly(x*y**7 + 2*x**2*y**3).ET('lex') == ((1, 7), 1)
assert Poly(x*y**7 + 2*x**2*y**3).ET('grlex') == ((2, 3), 2)
def test_Poly_max_norm():
assert Poly(-1, x).max_norm() == 1
assert Poly( 0, x).max_norm() == 0
assert Poly( 1, x).max_norm() == 1
def test_Poly_l1_norm():
assert Poly(-1, x).l1_norm() == 1
assert Poly( 0, x).l1_norm() == 0
assert Poly( 1, x).l1_norm() == 1
def test_Poly_clear_denoms():
coeff, poly = Poly(x + 2, x).clear_denoms()
assert coeff == 1 and poly == Poly(
x + 2, x, domain='ZZ') and poly.get_domain() == ZZ
coeff, poly = Poly(x/2 + 1, x).clear_denoms()
assert coeff == 2 and poly == Poly(
x + 2, x, domain='QQ') and poly.get_domain() == QQ
coeff, poly = Poly(x/2 + 1, x).clear_denoms(convert=True)
assert coeff == 2 and poly == Poly(
x + 2, x, domain='ZZ') and poly.get_domain() == ZZ
coeff, poly = Poly(x/y + 1, x).clear_denoms(convert=True)
assert coeff == y and poly == Poly(
x + y, x, domain='ZZ[y]') and poly.get_domain() == ZZ[y]
coeff, poly = Poly(x/3 + sqrt(2), x, domain='EX').clear_denoms()
assert coeff == 3 and poly == Poly(
x + 3*sqrt(2), x, domain='EX') and poly.get_domain() == EX
coeff, poly = Poly(
x/3 + sqrt(2), x, domain='EX').clear_denoms(convert=True)
assert coeff == 3 and poly == Poly(
x + 3*sqrt(2), x, domain='EX') and poly.get_domain() == EX
def test_Poly_rat_clear_denoms():
f = Poly(x**2/y + 1, x)
g = Poly(x**3 + y, x)
assert f.rat_clear_denoms(g) == \
(Poly(x**2 + y, x), Poly(y*x**3 + y**2, x))
f = f.set_domain(EX)
g = g.set_domain(EX)
assert f.rat_clear_denoms(g) == (f, g)
def test_Poly_integrate():
assert Poly(x + 1).integrate() == Poly(x**2/2 + x)
assert Poly(x + 1).integrate(x) == Poly(x**2/2 + x)
assert Poly(x + 1).integrate((x, 1)) == Poly(x**2/2 + x)
assert Poly(x*y + 1).integrate(x) == Poly(x**2*y/2 + x)
assert Poly(x*y + 1).integrate(y) == Poly(x*y**2/2 + y)
assert Poly(x*y + 1).integrate(x, x) == Poly(x**3*y/6 + x**2/2)
assert Poly(x*y + 1).integrate(y, y) == Poly(x*y**3/6 + y**2/2)
assert Poly(x*y + 1).integrate((x, 2)) == Poly(x**3*y/6 + x**2/2)
assert Poly(x*y + 1).integrate((y, 2)) == Poly(x*y**3/6 + y**2/2)
assert Poly(x*y + 1).integrate(x, y) == Poly(x**2*y**2/4 + x*y)
assert Poly(x*y + 1).integrate(y, x) == Poly(x**2*y**2/4 + x*y)
def test_Poly_diff():
assert Poly(x**2 + x).diff() == Poly(2*x + 1)
assert Poly(x**2 + x).diff(x) == Poly(2*x + 1)
assert Poly(x**2 + x).diff((x, 1)) == Poly(2*x + 1)
assert Poly(x**2*y**2 + x*y).diff(x) == Poly(2*x*y**2 + y)
assert Poly(x**2*y**2 + x*y).diff(y) == Poly(2*x**2*y + x)
assert Poly(x**2*y**2 + x*y).diff(x, x) == Poly(2*y**2, x, y)
assert Poly(x**2*y**2 + x*y).diff(y, y) == Poly(2*x**2, x, y)
assert Poly(x**2*y**2 + x*y).diff((x, 2)) == Poly(2*y**2, x, y)
assert Poly(x**2*y**2 + x*y).diff((y, 2)) == Poly(2*x**2, x, y)
assert Poly(x**2*y**2 + x*y).diff(x, y) == Poly(4*x*y + 1)
assert Poly(x**2*y**2 + x*y).diff(y, x) == Poly(4*x*y + 1)
def test_issue_9585():
assert diff(Poly(x**2 + x)) == Poly(2*x + 1)
assert diff(Poly(x**2 + x), x, evaluate=False) == \
Derivative(Poly(x**2 + x), x)
assert Derivative(Poly(x**2 + x), x).doit() == Poly(2*x + 1)
def test_Poly_eval():
assert Poly(0, x).eval(7) == 0
assert Poly(1, x).eval(7) == 1
assert Poly(x, x).eval(7) == 7
assert Poly(0, x).eval(0, 7) == 0
assert Poly(1, x).eval(0, 7) == 1
assert Poly(x, x).eval(0, 7) == 7
assert Poly(0, x).eval(x, 7) == 0
assert Poly(1, x).eval(x, 7) == 1
assert Poly(x, x).eval(x, 7) == 7
assert Poly(0, x).eval('x', 7) == 0
assert Poly(1, x).eval('x', 7) == 1
assert Poly(x, x).eval('x', 7) == 7
raises(PolynomialError, lambda: Poly(1, x).eval(1, 7))
raises(PolynomialError, lambda: Poly(1, x).eval(y, 7))
raises(PolynomialError, lambda: Poly(1, x).eval('y', 7))
assert Poly(123, x, y).eval(7) == Poly(123, y)
assert Poly(2*y, x, y).eval(7) == Poly(2*y, y)
assert Poly(x*y, x, y).eval(7) == Poly(7*y, y)
assert Poly(123, x, y).eval(x, 7) == Poly(123, y)
assert Poly(2*y, x, y).eval(x, 7) == Poly(2*y, y)
assert Poly(x*y, x, y).eval(x, 7) == Poly(7*y, y)
assert Poly(123, x, y).eval(y, 7) == Poly(123, x)
assert Poly(2*y, x, y).eval(y, 7) == Poly(14, x)
assert Poly(x*y, x, y).eval(y, 7) == Poly(7*x, x)
assert Poly(x*y + y, x, y).eval({x: 7}) == Poly(8*y, y)
assert Poly(x*y + y, x, y).eval({y: 7}) == Poly(7*x + 7, x)
assert Poly(x*y + y, x, y).eval({x: 6, y: 7}) == 49
assert Poly(x*y + y, x, y).eval({x: 7, y: 6}) == 48
assert Poly(x*y + y, x, y).eval((6, 7)) == 49
assert Poly(x*y + y, x, y).eval([6, 7]) == 49
assert Poly(x + 1, domain='ZZ').eval(S(1)/2) == S(3)/2
assert Poly(x + 1, domain='ZZ').eval(sqrt(2)) == sqrt(2) + 1
raises(ValueError, lambda: Poly(x*y + y, x, y).eval((6, 7, 8)))
raises(DomainError, lambda: Poly(x + 1, domain='ZZ').eval(S(1)/2, auto=False))
# issue 6344
alpha = Symbol('alpha')
result = (2*alpha*z - 2*alpha + z**2 + 3)/(z**2 - 2*z + 1)
f = Poly(x**2 + (alpha - 1)*x - alpha + 1, x, domain='ZZ[alpha]')
assert f.eval((z + 1)/(z - 1)) == result
g = Poly(x**2 + (alpha - 1)*x - alpha + 1, x, y, domain='ZZ[alpha]')
assert g.eval((z + 1)/(z - 1)) == Poly(result, y, domain='ZZ(alpha,z)')
def test_Poly___call__():
f = Poly(2*x*y + 3*x + y + 2*z)
assert f(2) == Poly(5*y + 2*z + 6)
assert f(2, 5) == Poly(2*z + 31)
assert f(2, 5, 7) == 45
def test_parallel_poly_from_expr():
assert parallel_poly_from_expr(
[x - 1, x**2 - 1], x)[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[Poly(x - 1, x), x**2 - 1], x)[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[x - 1, Poly(x**2 - 1, x)], x)[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr([Poly(
x - 1, x), Poly(x**2 - 1, x)], x)[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[x - 1, x**2 - 1], x, y)[0] == [Poly(x - 1, x, y), Poly(x**2 - 1, x, y)]
assert parallel_poly_from_expr([Poly(
x - 1, x), x**2 - 1], x, y)[0] == [Poly(x - 1, x, y), Poly(x**2 - 1, x, y)]
assert parallel_poly_from_expr([x - 1, Poly(
x**2 - 1, x)], x, y)[0] == [Poly(x - 1, x, y), Poly(x**2 - 1, x, y)]
assert parallel_poly_from_expr([Poly(x - 1, x), Poly(
x**2 - 1, x)], x, y)[0] == [Poly(x - 1, x, y), Poly(x**2 - 1, x, y)]
assert parallel_poly_from_expr(
[x - 1, x**2 - 1])[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[Poly(x - 1, x), x**2 - 1])[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[x - 1, Poly(x**2 - 1, x)])[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[Poly(x - 1, x), Poly(x**2 - 1, x)])[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[1, x**2 - 1])[0] == [Poly(1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[1, x**2 - 1])[0] == [Poly(1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[1, Poly(x**2 - 1, x)])[0] == [Poly(1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[1, Poly(x**2 - 1, x)])[0] == [Poly(1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[x**2 - 1, 1])[0] == [Poly(x**2 - 1, x), Poly(1, x)]
assert parallel_poly_from_expr(
[x**2 - 1, 1])[0] == [Poly(x**2 - 1, x), Poly(1, x)]
assert parallel_poly_from_expr(
[Poly(x**2 - 1, x), 1])[0] == [Poly(x**2 - 1, x), Poly(1, x)]
assert parallel_poly_from_expr(
[Poly(x**2 - 1, x), 1])[0] == [Poly(x**2 - 1, x), Poly(1, x)]
assert parallel_poly_from_expr([Poly(x, x, y), Poly(y, x, y)], x, y, order='lex')[0] == \
[Poly(x, x, y, domain='ZZ'), Poly(y, x, y, domain='ZZ')]
raises(PolificationFailed, lambda: parallel_poly_from_expr([0, 1]))
def test_pdiv():
f, g = x**2 - y**2, x - y
q, r = x + y, 0
F, G, Q, R = [ Poly(h, x, y) for h in (f, g, q, r) ]
assert F.pdiv(G) == (Q, R)
assert F.prem(G) == R
assert F.pquo(G) == Q
assert F.pexquo(G) == Q
assert pdiv(f, g) == (q, r)
assert prem(f, g) == r
assert pquo(f, g) == q
assert pexquo(f, g) == q
assert pdiv(f, g, x, y) == (q, r)
assert prem(f, g, x, y) == r
assert pquo(f, g, x, y) == q
assert pexquo(f, g, x, y) == q
assert pdiv(f, g, (x, y)) == (q, r)
assert prem(f, g, (x, y)) == r
assert pquo(f, g, (x, y)) == q
assert pexquo(f, g, (x, y)) == q
assert pdiv(F, G) == (Q, R)
assert prem(F, G) == R
assert pquo(F, G) == Q
assert pexquo(F, G) == Q
assert pdiv(f, g, polys=True) == (Q, R)
assert prem(f, g, polys=True) == R
assert pquo(f, g, polys=True) == Q
assert pexquo(f, g, polys=True) == Q
assert pdiv(F, G, polys=False) == (q, r)
assert prem(F, G, polys=False) == r
assert pquo(F, G, polys=False) == q
assert pexquo(F, G, polys=False) == q
raises(ComputationFailed, lambda: pdiv(4, 2))
raises(ComputationFailed, lambda: prem(4, 2))
raises(ComputationFailed, lambda: pquo(4, 2))
raises(ComputationFailed, lambda: pexquo(4, 2))
def test_div():
f, g = x**2 - y**2, x - y
q, r = x + y, 0
F, G, Q, R = [ Poly(h, x, y) for h in (f, g, q, r) ]
assert F.div(G) == (Q, R)
assert F.rem(G) == R
assert F.quo(G) == Q
assert F.exquo(G) == Q
assert div(f, g) == (q, r)
assert rem(f, g) == r
assert quo(f, g) == q
assert exquo(f, g) == q
assert div(f, g, x, y) == (q, r)
assert rem(f, g, x, y) == r
assert quo(f, g, x, y) == q
assert exquo(f, g, x, y) == q
assert div(f, g, (x, y)) == (q, r)
assert rem(f, g, (x, y)) == r
assert quo(f, g, (x, y)) == q
assert exquo(f, g, (x, y)) == q
assert div(F, G) == (Q, R)
assert rem(F, G) == R
assert quo(F, G) == Q
assert exquo(F, G) == Q
assert div(f, g, polys=True) == (Q, R)
assert rem(f, g, polys=True) == R
assert quo(f, g, polys=True) == Q
assert exquo(f, g, polys=True) == Q
assert div(F, G, polys=False) == (q, r)
assert rem(F, G, polys=False) == r
assert quo(F, G, polys=False) == q
assert exquo(F, G, polys=False) == q
raises(ComputationFailed, lambda: div(4, 2))
raises(ComputationFailed, lambda: rem(4, 2))
raises(ComputationFailed, lambda: quo(4, 2))
raises(ComputationFailed, lambda: exquo(4, 2))
f, g = x**2 + 1, 2*x - 4
qz, rz = 0, x**2 + 1
qq, rq = x/2 + 1, 5
assert div(f, g) == (qq, rq)
assert div(f, g, auto=True) == (qq, rq)
assert div(f, g, auto=False) == (qz, rz)
assert div(f, g, domain=ZZ) == (qz, rz)
assert div(f, g, domain=QQ) == (qq, rq)
assert div(f, g, domain=ZZ, auto=True) == (qq, rq)
assert div(f, g, domain=ZZ, auto=False) == (qz, rz)
assert div(f, g, domain=QQ, auto=True) == (qq, rq)
assert div(f, g, domain=QQ, auto=False) == (qq, rq)
assert rem(f, g) == rq
assert rem(f, g, auto=True) == rq
assert rem(f, g, auto=False) == rz
assert rem(f, g, domain=ZZ) == rz
assert rem(f, g, domain=QQ) == rq
assert rem(f, g, domain=ZZ, auto=True) == rq
assert rem(f, g, domain=ZZ, auto=False) == rz
assert rem(f, g, domain=QQ, auto=True) == rq
assert rem(f, g, domain=QQ, auto=False) == rq
assert quo(f, g) == qq
assert quo(f, g, auto=True) == qq
assert quo(f, g, auto=False) == qz
assert quo(f, g, domain=ZZ) == qz
assert quo(f, g, domain=QQ) == qq
assert quo(f, g, domain=ZZ, auto=True) == qq
assert quo(f, g, domain=ZZ, auto=False) == qz
assert quo(f, g, domain=QQ, auto=True) == qq
assert quo(f, g, domain=QQ, auto=False) == qq
f, g, q = x**2, 2*x, x/2
assert exquo(f, g) == q
assert exquo(f, g, auto=True) == q
raises(ExactQuotientFailed, lambda: exquo(f, g, auto=False))
raises(ExactQuotientFailed, lambda: exquo(f, g, domain=ZZ))
assert exquo(f, g, domain=QQ) == q
assert exquo(f, g, domain=ZZ, auto=True) == q
raises(ExactQuotientFailed, lambda: exquo(f, g, domain=ZZ, auto=False))
assert exquo(f, g, domain=QQ, auto=True) == q
assert exquo(f, g, domain=QQ, auto=False) == q
f, g = Poly(x**2), Poly(x)
q, r = f.div(g)
assert q.get_domain().is_ZZ and r.get_domain().is_ZZ
r = f.rem(g)
assert r.get_domain().is_ZZ
q = f.quo(g)
assert q.get_domain().is_ZZ
q = f.exquo(g)
assert q.get_domain().is_ZZ
f, g = Poly(x+y, x), Poly(2*x+y, x)
q, r = f.div(g)
assert q.get_domain().is_Frac and r.get_domain().is_Frac
def test_gcdex():
f, g = 2*x, x**2 - 16
s, t, h = x/32, -Rational(1, 16), 1
F, G, S, T, H = [ Poly(u, x, domain='QQ') for u in (f, g, s, t, h) ]
assert F.half_gcdex(G) == (S, H)
assert F.gcdex(G) == (S, T, H)
assert F.invert(G) == S
assert half_gcdex(f, g) == (s, h)
assert gcdex(f, g) == (s, t, h)
assert invert(f, g) == s
assert half_gcdex(f, g, x) == (s, h)
assert gcdex(f, g, x) == (s, t, h)
assert invert(f, g, x) == s
assert half_gcdex(f, g, (x,)) == (s, h)
assert gcdex(f, g, (x,)) == (s, t, h)
assert invert(f, g, (x,)) == s
assert half_gcdex(F, G) == (S, H)
assert gcdex(F, G) == (S, T, H)
assert invert(F, G) == S
assert half_gcdex(f, g, polys=True) == (S, H)
assert gcdex(f, g, polys=True) == (S, T, H)
assert invert(f, g, polys=True) == S
assert half_gcdex(F, G, polys=False) == (s, h)
assert gcdex(F, G, polys=False) == (s, t, h)
assert invert(F, G, polys=False) == s
assert half_gcdex(100, 2004) == (-20, 4)
assert gcdex(100, 2004) == (-20, 1, 4)
assert invert(3, 7) == 5
raises(DomainError, lambda: half_gcdex(x + 1, 2*x + 1, auto=False))
raises(DomainError, lambda: gcdex(x + 1, 2*x + 1, auto=False))
raises(DomainError, lambda: invert(x + 1, 2*x + 1, auto=False))
def test_revert():
f = Poly(1 - x**2/2 + x**4/24 - x**6/720)
g = Poly(61*x**6/720 + 5*x**4/24 + x**2/2 + 1)
assert f.revert(8) == g
def test_subresultants():
f, g, h = x**2 - 2*x + 1, x**2 - 1, 2*x - 2
F, G, H = Poly(f), Poly(g), Poly(h)
assert F.subresultants(G) == [F, G, H]
assert subresultants(f, g) == [f, g, h]
assert subresultants(f, g, x) == [f, g, h]
assert subresultants(f, g, (x,)) == [f, g, h]
assert subresultants(F, G) == [F, G, H]
assert subresultants(f, g, polys=True) == [F, G, H]
assert subresultants(F, G, polys=False) == [f, g, h]
raises(ComputationFailed, lambda: subresultants(4, 2))
def test_resultant():
f, g, h = x**2 - 2*x + 1, x**2 - 1, 0
F, G = Poly(f), Poly(g)
assert F.resultant(G) == h
assert resultant(f, g) == h
assert resultant(f, g, x) == h
assert resultant(f, g, (x,)) == h
assert resultant(F, G) == h
assert resultant(f, g, polys=True) == h
assert resultant(F, G, polys=False) == h
assert resultant(f, g, includePRS=True) == (h, [f, g, 2*x - 2])
f, g, h = x - a, x - b, a - b
F, G, H = Poly(f), Poly(g), Poly(h)
assert F.resultant(G) == H
assert resultant(f, g) == h
assert resultant(f, g, x) == h
assert resultant(f, g, (x,)) == h
assert resultant(F, G) == H
assert resultant(f, g, polys=True) == H
assert resultant(F, G, polys=False) == h
raises(ComputationFailed, lambda: resultant(4, 2))
def test_discriminant():
f, g = x**3 + 3*x**2 + 9*x - 13, -11664
F = Poly(f)
assert F.discriminant() == g
assert discriminant(f) == g
assert discriminant(f, x) == g
assert discriminant(f, (x,)) == g
assert discriminant(F) == g
assert discriminant(f, polys=True) == g
assert discriminant(F, polys=False) == g
f, g = a*x**2 + b*x + c, b**2 - 4*a*c
F, G = Poly(f), Poly(g)
assert F.discriminant() == G
assert discriminant(f) == g
assert discriminant(f, x, a, b, c) == g
assert discriminant(f, (x, a, b, c)) == g
assert discriminant(F) == G
assert discriminant(f, polys=True) == G
assert discriminant(F, polys=False) == g
raises(ComputationFailed, lambda: discriminant(4))
def test_dispersion():
# We test only the API here. For more mathematical
# tests see the dedicated test file.
fp = poly((x + 1)*(x + 2), x)
assert sorted(fp.dispersionset()) == [0, 1]
assert fp.dispersion() == 1
fp = poly(x**4 - 3*x**2 + 1, x)
gp = fp.shift(-3)
assert sorted(fp.dispersionset(gp)) == [2, 3, 4]
assert fp.dispersion(gp) == 4
def test_gcd_list():
F = [x**3 - 1, x**2 - 1, x**2 - 3*x + 2]
assert gcd_list(F) == x - 1
assert gcd_list(F, polys=True) == Poly(x - 1)
assert gcd_list([]) == 0
assert gcd_list([1, 2]) == 1
assert gcd_list([4, 6, 8]) == 2
assert gcd_list([x*(y + 42) - x*y - x*42]) == 0
gcd = gcd_list([], x)
assert gcd.is_Number and gcd is S.Zero
gcd = gcd_list([], x, polys=True)
assert gcd.is_Poly and gcd.is_zero
raises(ComputationFailed, lambda: gcd_list([], polys=True))
def test_lcm_list():
F = [x**3 - 1, x**2 - 1, x**2 - 3*x + 2]
assert lcm_list(F) == x**5 - x**4 - 2*x**3 - x**2 + x + 2
assert lcm_list(F, polys=True) == Poly(x**5 - x**4 - 2*x**3 - x**2 + x + 2)
assert lcm_list([]) == 1
assert lcm_list([1, 2]) == 2
assert lcm_list([4, 6, 8]) == 24
assert lcm_list([x*(y + 42) - x*y - x*42]) == 0
lcm = lcm_list([], x)
assert lcm.is_Number and lcm is S.One
lcm = lcm_list([], x, polys=True)
assert lcm.is_Poly and lcm.is_one
raises(ComputationFailed, lambda: lcm_list([], polys=True))
def test_gcd():
f, g = x**3 - 1, x**2 - 1
s, t = x**2 + x + 1, x + 1
h, r = x - 1, x**4 + x**3 - x - 1
F, G, S, T, H, R = [ Poly(u) for u in (f, g, s, t, h, r) ]
assert F.cofactors(G) == (H, S, T)
assert F.gcd(G) == H
assert F.lcm(G) == R
assert cofactors(f, g) == (h, s, t)
assert gcd(f, g) == h
assert lcm(f, g) == r
assert cofactors(f, g, x) == (h, s, t)
assert gcd(f, g, x) == h
assert lcm(f, g, x) == r
assert cofactors(f, g, (x,)) == (h, s, t)
assert gcd(f, g, (x,)) == h
assert lcm(f, g, (x,)) == r
assert cofactors(F, G) == (H, S, T)
assert gcd(F, G) == H
assert lcm(F, G) == R
assert cofactors(f, g, polys=True) == (H, S, T)
assert gcd(f, g, polys=True) == H
assert lcm(f, g, polys=True) == R
assert cofactors(F, G, polys=False) == (h, s, t)
assert gcd(F, G, polys=False) == h
assert lcm(F, G, polys=False) == r
f, g = 1.0*x**2 - 1.0, 1.0*x - 1.0
h, s, t = g, 1.0*x + 1.0, 1.0
assert cofactors(f, g) == (h, s, t)
assert gcd(f, g) == h
assert lcm(f, g) == f
f, g = 1.0*x**2 - 1.0, 1.0*x - 1.0
h, s, t = g, 1.0*x + 1.0, 1.0
assert cofactors(f, g) == (h, s, t)
assert gcd(f, g) == h
assert lcm(f, g) == f
assert cofactors(8, 6) == (2, 4, 3)
assert gcd(8, 6) == 2
assert lcm(8, 6) == 24
f, g = x**2 - 3*x - 4, x**3 - 4*x**2 + x - 4
l = x**4 - 3*x**3 - 3*x**2 - 3*x - 4
h, s, t = x - 4, x + 1, x**2 + 1
assert cofactors(f, g, modulus=11) == (h, s, t)
assert gcd(f, g, modulus=11) == h
assert lcm(f, g, modulus=11) == l
f, g = x**2 + 8*x + 7, x**3 + 7*x**2 + x + 7
l = x**4 + 8*x**3 + 8*x**2 + 8*x + 7
h, s, t = x + 7, x + 1, x**2 + 1
assert cofactors(f, g, modulus=11, symmetric=False) == (h, s, t)
assert gcd(f, g, modulus=11, symmetric=False) == h
assert lcm(f, g, modulus=11, symmetric=False) == l
raises(TypeError, lambda: gcd(x))
raises(TypeError, lambda: lcm(x))
def test_gcd_numbers_vs_polys():
assert isinstance(gcd(3, 9), Integer)
assert isinstance(gcd(3*x, 9), Integer)
assert gcd(3, 9) == 3
assert gcd(3*x, 9) == 3
assert isinstance(gcd(S(3)/2, S(9)/4), Rational)
assert isinstance(gcd(S(3)/2*x, S(9)/4), Rational)
assert gcd(S(3)/2, S(9)/4) == S(3)/4
assert gcd(S(3)/2*x, S(9)/4) == 1
assert isinstance(gcd(3.0, 9.0), Float)
assert isinstance(gcd(3.0*x, 9.0), Float)
assert gcd(3.0, 9.0) == 1.0
assert gcd(3.0*x, 9.0) == 1.0
def test_terms_gcd():
assert terms_gcd(1) == 1
assert terms_gcd(1, x) == 1
assert terms_gcd(x - 1) == x - 1
assert terms_gcd(-x - 1) == -x - 1
assert terms_gcd(2*x + 3) == 2*x + 3
assert terms_gcd(6*x + 4) == Mul(2, 3*x + 2, evaluate=False)
assert terms_gcd(x**3*y + x*y**3) == x*y*(x**2 + y**2)
assert terms_gcd(2*x**3*y + 2*x*y**3) == 2*x*y*(x**2 + y**2)
assert terms_gcd(x**3*y/2 + x*y**3/2) == x*y/2*(x**2 + y**2)
assert terms_gcd(x**3*y + 2*x*y**3) == x*y*(x**2 + 2*y**2)
assert terms_gcd(2*x**3*y + 4*x*y**3) == 2*x*y*(x**2 + 2*y**2)
assert terms_gcd(2*x**3*y/3 + 4*x*y**3/5) == 2*x*y/15*(5*x**2 + 6*y**2)
assert terms_gcd(2.0*x**3*y + 4.1*x*y**3) == x*y*(2.0*x**2 + 4.1*y**2)
assert _aresame(terms_gcd(2.0*x + 3), 2.0*x + 3)
assert terms_gcd((3 + 3*x)*(x + x*y), expand=False) == \
(3*x + 3)*(x*y + x)
assert terms_gcd((3 + 3*x)*(x + x*sin(3 + 3*y)), expand=False, deep=True) == \
3*x*(x + 1)*(sin(Mul(3, y + 1, evaluate=False)) + 1)
assert terms_gcd(sin(x + x*y), deep=True) == \
sin(x*(y + 1))
eq = Eq(2*x, 2*y + 2*z*y)
assert terms_gcd(eq) == eq
assert terms_gcd(eq, deep=True) == Eq(2*x, 2*y*(z + 1))
def test_trunc():
f, g = x**5 + 2*x**4 + 3*x**3 + 4*x**2 + 5*x + 6, x**5 - x**4 + x**2 - x
F, G = Poly(f), Poly(g)
assert F.trunc(3) == G
assert trunc(f, 3) == g
assert trunc(f, 3, x) == g
assert trunc(f, 3, (x,)) == g
assert trunc(F, 3) == G
assert trunc(f, 3, polys=True) == G
assert trunc(F, 3, polys=False) == g
f, g = 6*x**5 + 5*x**4 + 4*x**3 + 3*x**2 + 2*x + 1, -x**4 + x**3 - x + 1
F, G = Poly(f), Poly(g)
assert F.trunc(3) == G
assert trunc(f, 3) == g
assert trunc(f, 3, x) == g
assert trunc(f, 3, (x,)) == g
assert trunc(F, 3) == G
assert trunc(f, 3, polys=True) == G
assert trunc(F, 3, polys=False) == g
f = Poly(x**2 + 2*x + 3, modulus=5)
assert f.trunc(2) == Poly(x**2 + 1, modulus=5)
def test_monic():
f, g = 2*x - 1, x - S(1)/2
F, G = Poly(f, domain='QQ'), Poly(g)
assert F.monic() == G
assert monic(f) == g
assert monic(f, x) == g
assert monic(f, (x,)) == g
assert monic(F) == G
assert monic(f, polys=True) == G
assert monic(F, polys=False) == g
raises(ComputationFailed, lambda: monic(4))
assert monic(2*x**2 + 6*x + 4, auto=False) == x**2 + 3*x + 2
raises(ExactQuotientFailed, lambda: monic(2*x + 6*x + 1, auto=False))
assert monic(2.0*x**2 + 6.0*x + 4.0) == 1.0*x**2 + 3.0*x + 2.0
assert monic(2*x**2 + 3*x + 4, modulus=5) == x**2 - x + 2
def test_content():
f, F = 4*x + 2, Poly(4*x + 2)
assert F.content() == 2
assert content(f) == 2
raises(ComputationFailed, lambda: content(4))
f = Poly(2*x, modulus=3)
assert f.content() == 1
def test_primitive():
f, g = 4*x + 2, 2*x + 1
F, G = Poly(f), Poly(g)
assert F.primitive() == (2, G)
assert primitive(f) == (2, g)
assert primitive(f, x) == (2, g)
assert primitive(f, (x,)) == (2, g)
assert primitive(F) == (2, G)
assert primitive(f, polys=True) == (2, G)
assert primitive(F, polys=False) == (2, g)
raises(ComputationFailed, lambda: primitive(4))
f = Poly(2*x, modulus=3)
g = Poly(2.0*x, domain=RR)
assert f.primitive() == (1, f)
assert g.primitive() == (1.0, g)
assert primitive(S('-3*x/4 + y + 11/8')) == \
S('(1/8, -6*x + 8*y + 11)')
def test_compose():
f = x**12 + 20*x**10 + 150*x**8 + 500*x**6 + 625*x**4 - 2*x**3 - 10*x + 9
g = x**4 - 2*x + 9
h = x**3 + 5*x
F, G, H = map(Poly, (f, g, h))
assert G.compose(H) == F
assert compose(g, h) == f
assert compose(g, h, x) == f
assert compose(g, h, (x,)) == f
assert compose(G, H) == F
assert compose(g, h, polys=True) == F
assert compose(G, H, polys=False) == f
assert F.decompose() == [G, H]
assert decompose(f) == [g, h]
assert decompose(f, x) == [g, h]
assert decompose(f, (x,)) == [g, h]
assert decompose(F) == [G, H]
assert decompose(f, polys=True) == [G, H]
assert decompose(F, polys=False) == [g, h]
raises(ComputationFailed, lambda: compose(4, 2))
raises(ComputationFailed, lambda: decompose(4))
assert compose(x**2 - y**2, x - y, x, y) == x**2 - 2*x*y
assert compose(x**2 - y**2, x - y, y, x) == -y**2 + 2*x*y
def test_shift():
assert Poly(x**2 - 2*x + 1, x).shift(2) == Poly(x**2 + 2*x + 1, x)
def test_transform():
# Also test that 3-way unification is done correctly
assert Poly(x**2 - 2*x + 1, x).transform(Poly(x + 1), Poly(x - 1)) == \
Poly(4, x) == \
cancel((x - 1)**2*(x**2 - 2*x + 1).subs(x, (x + 1)/(x - 1)))
assert Poly(x**2 - x/2 + 1, x).transform(Poly(x + 1), Poly(x - 1)) == \
Poly(3*x**2/2 + S(5)/2, x) == \
cancel((x - 1)**2*(x**2 - x/2 + 1).subs(x, (x + 1)/(x - 1)))
assert Poly(x**2 - 2*x + 1, x).transform(Poly(x + S(1)/2), Poly(x - 1)) == \
Poly(S(9)/4, x) == \
cancel((x - 1)**2*(x**2 - 2*x + 1).subs(x, (x + S(1)/2)/(x - 1)))
assert Poly(x**2 - 2*x + 1, x).transform(Poly(x + 1), Poly(x - S(1)/2)) == \
Poly(S(9)/4, x) == \
cancel((x - S(1)/2)**2*(x**2 - 2*x + 1).subs(x, (x + 1)/(x - S(1)/2)))
# Unify ZZ, QQ, and RR
assert Poly(x**2 - 2*x + 1, x).transform(Poly(x + 1.0), Poly(x - S(1)/2)) == \
Poly(9/4, x) == \
cancel((x - S(1)/2)**2*(x**2 - 2*x + 1).subs(x, (x + 1.0)/(x - S(1)/2)))
raises(ValueError, lambda: Poly(x*y).transform(Poly(x + 1), Poly(x - 1)))
raises(ValueError, lambda: Poly(x).transform(Poly(y + 1), Poly(x - 1)))
raises(ValueError, lambda: Poly(x).transform(Poly(x + 1), Poly(y - 1)))
raises(ValueError, lambda: Poly(x).transform(Poly(x*y + 1), Poly(x - 1)))
raises(ValueError, lambda: Poly(x).transform(Poly(x + 1), Poly(x*y - 1)))
def test_sturm():
f, F = x, Poly(x, domain='QQ')
g, G = 1, Poly(1, x, domain='QQ')
assert F.sturm() == [F, G]
assert sturm(f) == [f, g]
assert sturm(f, x) == [f, g]
assert sturm(f, (x,)) == [f, g]
assert sturm(F) == [F, G]
assert sturm(f, polys=True) == [F, G]
assert sturm(F, polys=False) == [f, g]
raises(ComputationFailed, lambda: sturm(4))
raises(DomainError, lambda: sturm(f, auto=False))
f = Poly(S(1024)/(15625*pi**8)*x**5
- S(4096)/(625*pi**8)*x**4
+ S(32)/(15625*pi**4)*x**3
- S(128)/(625*pi**4)*x**2
+ S(1)/62500*x
- S(1)/625, x, domain='ZZ(pi)')
assert sturm(f) == \
[Poly(x**3 - 100*x**2 + pi**4/64*x - 25*pi**4/16, x, domain='ZZ(pi)'),
Poly(3*x**2 - 200*x + pi**4/64, x, domain='ZZ(pi)'),
Poly((S(20000)/9 - pi**4/96)*x + 25*pi**4/18, x, domain='ZZ(pi)'),
Poly((-3686400000000*pi**4 - 11520000*pi**8 - 9*pi**12)/(26214400000000 - 245760000*pi**4 + 576*pi**8), x, domain='ZZ(pi)')]
def test_gff():
f = x**5 + 2*x**4 - x**3 - 2*x**2
assert Poly(f).gff_list() == [(Poly(x), 1), (Poly(x + 2), 4)]
assert gff_list(f) == [(x, 1), (x + 2, 4)]
raises(NotImplementedError, lambda: gff(f))
f = x*(x - 1)**3*(x - 2)**2*(x - 4)**2*(x - 5)
assert Poly(f).gff_list() == [(
Poly(x**2 - 5*x + 4), 1), (Poly(x**2 - 5*x + 4), 2), (Poly(x), 3)]
assert gff_list(f) == [(x**2 - 5*x + 4, 1), (x**2 - 5*x + 4, 2), (x, 3)]
raises(NotImplementedError, lambda: gff(f))
def test_sqf_norm():
assert sqf_norm(x**2 - 2, extension=sqrt(3)) == \
(1, x**2 - 2*sqrt(3)*x + 1, x**4 - 10*x**2 + 1)
assert sqf_norm(x**2 - 3, extension=sqrt(2)) == \
(1, x**2 - 2*sqrt(2)*x - 1, x**4 - 10*x**2 + 1)
assert Poly(x**2 - 2, extension=sqrt(3)).sqf_norm() == \
(1, Poly(x**2 - 2*sqrt(3)*x + 1, x, extension=sqrt(3)),
Poly(x**4 - 10*x**2 + 1, x, domain='QQ'))
assert Poly(x**2 - 3, extension=sqrt(2)).sqf_norm() == \
(1, Poly(x**2 - 2*sqrt(2)*x - 1, x, extension=sqrt(2)),
Poly(x**4 - 10*x**2 + 1, x, domain='QQ'))
def test_sqf():
f = x**5 - x**3 - x**2 + 1
g = x**3 + 2*x**2 + 2*x + 1
h = x - 1
p = x**4 + x**3 - x - 1
F, G, H, P = map(Poly, (f, g, h, p))
assert F.sqf_part() == P
assert sqf_part(f) == p
assert sqf_part(f, x) == p
assert sqf_part(f, (x,)) == p
assert sqf_part(F) == P
assert sqf_part(f, polys=True) == P
assert sqf_part(F, polys=False) == p
assert F.sqf_list() == (1, [(G, 1), (H, 2)])
assert sqf_list(f) == (1, [(g, 1), (h, 2)])
assert sqf_list(f, x) == (1, [(g, 1), (h, 2)])
assert sqf_list(f, (x,)) == (1, [(g, 1), (h, 2)])
assert sqf_list(F) == (1, [(G, 1), (H, 2)])
assert sqf_list(f, polys=True) == (1, [(G, 1), (H, 2)])
assert sqf_list(F, polys=False) == (1, [(g, 1), (h, 2)])
assert F.sqf_list_include() == [(G, 1), (H, 2)]
raises(ComputationFailed, lambda: sqf_part(4))
assert sqf(1) == 1
assert sqf_list(1) == (1, [])
assert sqf((2*x**2 + 2)**7) == 128*(x**2 + 1)**7
assert sqf(f) == g*h**2
assert sqf(f, x) == g*h**2
assert sqf(f, (x,)) == g*h**2
d = x**2 + y**2
assert sqf(f/d) == (g*h**2)/d
assert sqf(f/d, x) == (g*h**2)/d
assert sqf(f/d, (x,)) == (g*h**2)/d
assert sqf(x - 1) == x - 1
assert sqf(-x - 1) == -x - 1
assert sqf(x - 1) == x - 1
assert sqf(6*x - 10) == Mul(2, 3*x - 5, evaluate=False)
assert sqf((6*x - 10)/(3*x - 6)) == S(2)/3*((3*x - 5)/(x - 2))
assert sqf(Poly(x**2 - 2*x + 1)) == (x - 1)**2
f = 3 + x - x*(1 + x) + x**2
assert sqf(f) == 3
f = (x**2 + 2*x + 1)**20000000000
assert sqf(f) == (x + 1)**40000000000
assert sqf_list(f) == (1, [(x + 1, 40000000000)])
def test_factor():
f = x**5 - x**3 - x**2 + 1
u = x + 1
v = x - 1
w = x**2 + x + 1
F, U, V, W = map(Poly, (f, u, v, w))
assert F.factor_list() == (1, [(U, 1), (V, 2), (W, 1)])
assert factor_list(f) == (1, [(u, 1), (v, 2), (w, 1)])
assert factor_list(f, x) == (1, [(u, 1), (v, 2), (w, 1)])
assert factor_list(f, (x,)) == (1, [(u, 1), (v, 2), (w, 1)])
assert factor_list(F) == (1, [(U, 1), (V, 2), (W, 1)])
assert factor_list(f, polys=True) == (1, [(U, 1), (V, 2), (W, 1)])
assert factor_list(F, polys=False) == (1, [(u, 1), (v, 2), (w, 1)])
assert F.factor_list_include() == [(U, 1), (V, 2), (W, 1)]
assert factor_list(1) == (1, [])
assert factor_list(6) == (6, [])
assert factor_list(sqrt(3), x) == (sqrt(3), [])
assert factor_list((-1)**x, x) == (1, [(-1, x)])
assert factor_list((2*x)**y, x) == (1, [(2, y), (x, y)])
assert factor_list(sqrt(x*y), x) == (1, [(x*y, S.Half)])
assert factor(6) == 6 and factor(6).is_Integer
assert factor_list(3*x) == (3, [(x, 1)])
assert factor_list(3*x**2) == (3, [(x, 2)])
assert factor(3*x) == 3*x
assert factor(3*x**2) == 3*x**2
assert factor((2*x**2 + 2)**7) == 128*(x**2 + 1)**7
assert factor(f) == u*v**2*w
assert factor(f, x) == u*v**2*w
assert factor(f, (x,)) == u*v**2*w
g, p, q, r = x**2 - y**2, x - y, x + y, x**2 + 1
assert factor(f/g) == (u*v**2*w)/(p*q)
assert factor(f/g, x) == (u*v**2*w)/(p*q)
assert factor(f/g, (x,)) == (u*v**2*w)/(p*q)
p = Symbol('p', positive=True)
i = Symbol('i', integer=True)
r = Symbol('r', real=True)
assert factor(sqrt(x*y)).is_Pow is True
assert factor(sqrt(3*x**2 - 3)) == sqrt(3)*sqrt((x - 1)*(x + 1))
assert factor(sqrt(3*x**2 + 3)) == sqrt(3)*sqrt(x**2 + 1)
assert factor((y*x**2 - y)**i) == y**i*(x - 1)**i*(x + 1)**i
assert factor((y*x**2 + y)**i) == y**i*(x**2 + 1)**i
assert factor((y*x**2 - y)**t) == (y*(x - 1)*(x + 1))**t
assert factor((y*x**2 + y)**t) == (y*(x**2 + 1))**t
f = sqrt(expand((r**2 + 1)*(p + 1)*(p - 1)*(p - 2)**3))
g = sqrt((p - 2)**3*(p - 1))*sqrt(p + 1)*sqrt(r**2 + 1)
assert factor(f) == g
assert factor(g) == g
g = (x - 1)**5*(r**2 + 1)
f = sqrt(expand(g))
assert factor(f) == sqrt(g)
f = Poly(sin(1)*x + 1, x, domain=EX)
assert f.factor_list() == (1, [(f, 1)])
f = x**4 + 1
assert factor(f) == f
assert factor(f, extension=I) == (x**2 - I)*(x**2 + I)
assert factor(f, gaussian=True) == (x**2 - I)*(x**2 + I)
assert factor(
f, extension=sqrt(2)) == (x**2 + sqrt(2)*x + 1)*(x**2 - sqrt(2)*x + 1)
f = x**2 + 2*sqrt(2)*x + 2
assert factor(f, extension=sqrt(2)) == (x + sqrt(2))**2
assert factor(f**3, extension=sqrt(2)) == (x + sqrt(2))**6
assert factor(x**2 - 2*y**2, extension=sqrt(2)) == \
(x + sqrt(2)*y)*(x - sqrt(2)*y)
assert factor(2*x**2 - 4*y**2, extension=sqrt(2)) == \
2*((x + sqrt(2)*y)*(x - sqrt(2)*y))
assert factor(x - 1) == x - 1
assert factor(-x - 1) == -x - 1
assert factor(x - 1) == x - 1
assert factor(6*x - 10) == Mul(2, 3*x - 5, evaluate=False)
assert factor(x**11 + x + 1, modulus=65537, symmetric=True) == \
(x**2 + x + 1)*(x**9 - x**8 + x**6 - x**5 + x**3 - x** 2 + 1)
assert factor(x**11 + x + 1, modulus=65537, symmetric=False) == \
(x**2 + x + 1)*(x**9 + 65536*x**8 + x**6 + 65536*x**5 +
x**3 + 65536*x** 2 + 1)
f = x/pi + x*sin(x)/pi
g = y/(pi**2 + 2*pi + 1) + y*sin(x)/(pi**2 + 2*pi + 1)
assert factor(f) == x*(sin(x) + 1)/pi
assert factor(g) == y*(sin(x) + 1)/(pi + 1)**2
assert factor(Eq(
x**2 + 2*x + 1, x**3 + 1)) == Eq((x + 1)**2, (x + 1)*(x**2 - x + 1))
f = (x**2 - 1)/(x**2 + 4*x + 4)
assert factor(f) == (x + 1)*(x - 1)/(x + 2)**2
assert factor(f, x) == (x + 1)*(x - 1)/(x + 2)**2
f = 3 + x - x*(1 + x) + x**2
assert factor(f) == 3
assert factor(f, x) == 3
assert factor(1/(x**2 + 2*x + 1/x) - 1) == -((1 - x + 2*x**2 +
x**3)/(1 + 2*x**2 + x**3))
assert factor(f, expand=False) == f
raises(PolynomialError, lambda: factor(f, x, expand=False))
raises(FlagError, lambda: factor(x**2 - 1, polys=True))
assert factor([x, Eq(x**2 - y**2, Tuple(x**2 - z**2, 1/x + 1/y))]) == \
[x, Eq((x - y)*(x + y), Tuple((x - z)*(x + z), (x + y)/x/y))]
assert not isinstance(
Poly(x**3 + x + 1).factor_list()[1][0][0], PurePoly) is True
assert isinstance(
PurePoly(x**3 + x + 1).factor_list()[1][0][0], PurePoly) is True
assert factor(sqrt(-x)) == sqrt(-x)
# issue 5917
e = (-2*x*(-x + 1)*(x - 1)*(-x*(-x + 1)*(x - 1) - x*(x - 1)**2)*(x**2*(x -
1) - x*(x - 1) - x) - (-2*x**2*(x - 1)**2 - x*(-x + 1)*(-x*(-x + 1) +
x*(x - 1)))*(x**2*(x - 1)**4 - x*(-x*(-x + 1)*(x - 1) - x*(x - 1)**2)))
assert factor(e) == 0
# deep option
assert factor(sin(x**2 + x) + x, deep=True) == sin(x*(x + 1)) + x
assert factor(sqrt(x**2)) == sqrt(x**2)
def test_factor_large():
f = (x**2 + 4*x + 4)**10000000*(x**2 + 1)*(x**2 + 2*x + 1)**1234567
g = ((x**2 + 2*x + 1)**3000*y**2 + (x**2 + 2*x + 1)**3000*2*y + (
x**2 + 2*x + 1)**3000)
assert factor(f) == (x + 2)**20000000*(x**2 + 1)*(x + 1)**2469134
assert factor(g) == (x + 1)**6000*(y + 1)**2
assert factor_list(
f) == (1, [(x + 1, 2469134), (x + 2, 20000000), (x**2 + 1, 1)])
assert factor_list(g) == (1, [(y + 1, 2), (x + 1, 6000)])
f = (x**2 - y**2)**200000*(x**7 + 1)
g = (x**2 + y**2)**200000*(x**7 + 1)
assert factor(f) == \
(x + 1)*(x - y)**200000*(x + y)**200000*(x**6 - x**5 +
x**4 - x**3 + x**2 - x + 1)
assert factor(g, gaussian=True) == \
(x + 1)*(x - I*y)**200000*(x + I*y)**200000*(x**6 - x**5 +
x**4 - x**3 + x**2 - x + 1)
assert factor_list(f) == \
(1, [(x + 1, 1), (x - y, 200000), (x + y, 200000), (x**6 -
x**5 + x**4 - x**3 + x**2 - x + 1, 1)])
assert factor_list(g, gaussian=True) == \
(1, [(x + 1, 1), (x - I*y, 200000), (x + I*y, 200000), (
x**6 - x**5 + x**4 - x**3 + x**2 - x + 1, 1)])
@XFAIL
def test_factor_noeval():
assert factor(6*x - 10) == 2*(3*x - 5)
assert factor((6*x - 10)/(3*x - 6)) == S(2)/3*((3*x - 5)/(x - 2))
def test_intervals():
assert intervals(0) == []
assert intervals(1) == []
assert intervals(x, sqf=True) == [(0, 0)]
assert intervals(x) == [((0, 0), 1)]
assert intervals(x**128) == [((0, 0), 128)]
assert intervals([x**2, x**4]) == [((0, 0), {0: 2, 1: 4})]
f = Poly((2*x/5 - S(17)/3)*(4*x + S(1)/257))
assert f.intervals(sqf=True) == [(-1, 0), (14, 15)]
assert f.intervals() == [((-1, 0), 1), ((14, 15), 1)]
assert f.intervals(fast=True, sqf=True) == [(-1, 0), (14, 15)]
assert f.intervals(fast=True) == [((-1, 0), 1), ((14, 15), 1)]
assert f.intervals(eps=S(1)/10) == f.intervals(eps=0.1) == \
[((-S(1)/258, 0), 1), ((S(85)/6, S(85)/6), 1)]
assert f.intervals(eps=S(1)/100) == f.intervals(eps=0.01) == \
[((-S(1)/258, 0), 1), ((S(85)/6, S(85)/6), 1)]
assert f.intervals(eps=S(1)/1000) == f.intervals(eps=0.001) == \
[((-S(1)/1002, 0), 1), ((S(85)/6, S(85)/6), 1)]
assert f.intervals(eps=S(1)/10000) == f.intervals(eps=0.0001) == \
[((-S(1)/1028, -S(1)/1028), 1), ((S(85)/6, S(85)/6), 1)]
f = (2*x/5 - S(17)/3)*(4*x + S(1)/257)
assert intervals(f, sqf=True) == [(-1, 0), (14, 15)]
assert intervals(f) == [((-1, 0), 1), ((14, 15), 1)]
assert intervals(f, eps=S(1)/10) == intervals(f, eps=0.1) == \
[((-S(1)/258, 0), 1), ((S(85)/6, S(85)/6), 1)]
assert intervals(f, eps=S(1)/100) == intervals(f, eps=0.01) == \
[((-S(1)/258, 0), 1), ((S(85)/6, S(85)/6), 1)]
assert intervals(f, eps=S(1)/1000) == intervals(f, eps=0.001) == \
[((-S(1)/1002, 0), 1), ((S(85)/6, S(85)/6), 1)]
assert intervals(f, eps=S(1)/10000) == intervals(f, eps=0.0001) == \
[((-S(1)/1028, -S(1)/1028), 1), ((S(85)/6, S(85)/6), 1)]
f = Poly((x**2 - 2)*(x**2 - 3)**7*(x + 1)*(7*x + 3)**3)
assert f.intervals() == \
[((-2, -S(3)/2), 7), ((-S(3)/2, -1), 1),
((-1, -1), 1), ((-1, 0), 3),
((1, S(3)/2), 1), ((S(3)/2, 2), 7)]
assert intervals([x**5 - 200, x**5 - 201]) == \
[((S(75)/26, S(101)/35), {0: 1}), ((S(309)/107, S(26)/9), {1: 1})]
assert intervals([x**5 - 200, x**5 - 201], fast=True) == \
[((S(75)/26, S(101)/35), {0: 1}), ((S(309)/107, S(26)/9), {1: 1})]
assert intervals([x**2 - 200, x**2 - 201]) == \
[((-S(71)/5, -S(85)/6), {1: 1}), ((-S(85)/6, -14), {0: 1}),
((14, S(85)/6), {0: 1}), ((S(85)/6, S(71)/5), {1: 1})]
assert intervals([x + 1, x + 2, x - 1, x + 1, 1, x - 1, x - 1, (x - 2)**2]) == \
[((-2, -2), {1: 1}), ((-1, -1), {0: 1, 3: 1}), ((1, 1), {2:
1, 5: 1, 6: 1}), ((2, 2), {7: 2})]
f, g, h = x**2 - 2, x**4 - 4*x**2 + 4, x - 1
assert intervals(f, inf=S(7)/4, sqf=True) == []
assert intervals(f, inf=S(7)/5, sqf=True) == [(S(7)/5, S(3)/2)]
assert intervals(f, sup=S(7)/4, sqf=True) == [(-2, -1), (1, S(3)/2)]
assert intervals(f, sup=S(7)/5, sqf=True) == [(-2, -1)]
assert intervals(g, inf=S(7)/4) == []
assert intervals(g, inf=S(7)/5) == [((S(7)/5, S(3)/2), 2)]
assert intervals(g, sup=S(7)/4) == [((-2, -1), 2), ((1, S(3)/2), 2)]
assert intervals(g, sup=S(7)/5) == [((-2, -1), 2)]
assert intervals([g, h], inf=S(7)/4) == []
assert intervals([g, h], inf=S(7)/5) == [((S(7)/5, S(3)/2), {0: 2})]
assert intervals([g, h], sup=S(
7)/4) == [((-2, -1), {0: 2}), ((1, 1), {1: 1}), ((1, S(3)/2), {0: 2})]
assert intervals(
[g, h], sup=S(7)/5) == [((-2, -1), {0: 2}), ((1, 1), {1: 1})]
assert intervals([x + 2, x**2 - 2]) == \
[((-2, -2), {0: 1}), ((-2, -1), {1: 1}), ((1, 2), {1: 1})]
assert intervals([x + 2, x**2 - 2], strict=True) == \
[((-2, -2), {0: 1}), ((-S(3)/2, -1), {1: 1}), ((1, 2), {1: 1})]
f = 7*z**4 - 19*z**3 + 20*z**2 + 17*z + 20
assert intervals(f) == []
real_part, complex_part = intervals(f, all=True, sqf=True)
assert real_part == []
assert all(re(a) < re(r) < re(b) and im(
a) < im(r) < im(b) for (a, b), r in zip(complex_part, nroots(f)))
assert complex_part == [(-S(40)/7 - 40*I/7, 0), (-S(40)/7, 40*I/7),
(-40*I/7, S(40)/7), (0, S(40)/7 + 40*I/7)]
real_part, complex_part = intervals(f, all=True, sqf=True, eps=S(1)/10)
assert real_part == []
assert all(re(a) < re(r) < re(b) and im(
a) < im(r) < im(b) for (a, b), r in zip(complex_part, nroots(f)))
raises(ValueError, lambda: intervals(x**2 - 2, eps=10**-100000))
raises(ValueError, lambda: Poly(x**2 - 2).intervals(eps=10**-100000))
raises(
ValueError, lambda: intervals([x**2 - 2, x**2 - 3], eps=10**-100000))
def test_refine_root():
f = Poly(x**2 - 2)
assert f.refine_root(1, 2, steps=0) == (1, 2)
assert f.refine_root(-2, -1, steps=0) == (-2, -1)
assert f.refine_root(1, 2, steps=None) == (1, S(3)/2)
assert f.refine_root(-2, -1, steps=None) == (-S(3)/2, -1)
assert f.refine_root(1, 2, steps=1) == (1, S(3)/2)
assert f.refine_root(-2, -1, steps=1) == (-S(3)/2, -1)
assert f.refine_root(1, 2, steps=1, fast=True) == (1, S(3)/2)
assert f.refine_root(-2, -1, steps=1, fast=True) == (-S(3)/2, -1)
assert f.refine_root(1, 2, eps=S(1)/100) == (S(24)/17, S(17)/12)
assert f.refine_root(1, 2, eps=1e-2) == (S(24)/17, S(17)/12)
raises(PolynomialError, lambda: (f**2).refine_root(1, 2, check_sqf=True))
raises(RefinementFailed, lambda: (f**2).refine_root(1, 2))
raises(RefinementFailed, lambda: (f**2).refine_root(2, 3))
f = x**2 - 2
assert refine_root(f, 1, 2, steps=1) == (1, S(3)/2)
assert refine_root(f, -2, -1, steps=1) == (-S(3)/2, -1)
assert refine_root(f, 1, 2, steps=1, fast=True) == (1, S(3)/2)
assert refine_root(f, -2, -1, steps=1, fast=True) == (-S(3)/2, -1)
assert refine_root(f, 1, 2, eps=S(1)/100) == (S(24)/17, S(17)/12)
assert refine_root(f, 1, 2, eps=1e-2) == (S(24)/17, S(17)/12)
raises(PolynomialError, lambda: refine_root(1, 7, 8, eps=S(1)/100))
raises(ValueError, lambda: Poly(f).refine_root(1, 2, eps=10**-100000))
raises(ValueError, lambda: refine_root(f, 1, 2, eps=10**-100000))
def test_count_roots():
assert count_roots(x**2 - 2) == 2
assert count_roots(x**2 - 2, inf=-oo) == 2
assert count_roots(x**2 - 2, sup=+oo) == 2
assert count_roots(x**2 - 2, inf=-oo, sup=+oo) == 2
assert count_roots(x**2 - 2, inf=-2) == 2
assert count_roots(x**2 - 2, inf=-1) == 1
assert count_roots(x**2 - 2, sup=1) == 1
assert count_roots(x**2 - 2, sup=2) == 2
assert count_roots(x**2 - 2, inf=-1, sup=1) == 0
assert count_roots(x**2 - 2, inf=-2, sup=2) == 2
assert count_roots(x**2 - 2, inf=-1, sup=1) == 0
assert count_roots(x**2 - 2, inf=-2, sup=2) == 2
assert count_roots(x**2 + 2) == 0
assert count_roots(x**2 + 2, inf=-2*I) == 2
assert count_roots(x**2 + 2, sup=+2*I) == 2
assert count_roots(x**2 + 2, inf=-2*I, sup=+2*I) == 2
assert count_roots(x**2 + 2, inf=0) == 0
assert count_roots(x**2 + 2, sup=0) == 0
assert count_roots(x**2 + 2, inf=-I) == 1
assert count_roots(x**2 + 2, sup=+I) == 1
assert count_roots(x**2 + 2, inf=+I/2, sup=+I) == 0
assert count_roots(x**2 + 2, inf=-I, sup=-I/2) == 0
raises(PolynomialError, lambda: count_roots(1))
def test_Poly_root():
f = Poly(2*x**3 - 7*x**2 + 4*x + 4)
assert f.root(0) == -S(1)/2
assert f.root(1) == 2
assert f.root(2) == 2
raises(IndexError, lambda: f.root(3))
assert Poly(x**5 + x + 1).root(0) == rootof(x**3 - x**2 + 1, 0)
def test_real_roots():
assert real_roots(x) == [0]
assert real_roots(x, multiple=False) == [(0, 1)]
assert real_roots(x**3) == [0, 0, 0]
assert real_roots(x**3, multiple=False) == [(0, 3)]
assert real_roots(x*(x**3 + x + 3)) == [rootof(x**3 + x + 3, 0), 0]
assert real_roots(x*(x**3 + x + 3), multiple=False) == [(rootof(
x**3 + x + 3, 0), 1), (0, 1)]
assert real_roots(
x**3*(x**3 + x + 3)) == [rootof(x**3 + x + 3, 0), 0, 0, 0]
assert real_roots(x**3*(x**3 + x + 3), multiple=False) == [(rootof(
x**3 + x + 3, 0), 1), (0, 3)]
f = 2*x**3 - 7*x**2 + 4*x + 4
g = x**3 + x + 1
assert Poly(f).real_roots() == [-S(1)/2, 2, 2]
assert Poly(g).real_roots() == [rootof(g, 0)]
def test_all_roots():
f = 2*x**3 - 7*x**2 + 4*x + 4
g = x**3 + x + 1
assert Poly(f).all_roots() == [-S(1)/2, 2, 2]
assert Poly(g).all_roots() == [rootof(g, 0), rootof(g, 1), rootof(g, 2)]
def test_nroots():
assert Poly(0, x).nroots() == []
assert Poly(1, x).nroots() == []
assert Poly(x**2 - 1, x).nroots() == [-1.0, 1.0]
assert Poly(x**2 + 1, x).nroots() == [-1.0*I, 1.0*I]
roots = Poly(x**2 - 1, x).nroots()
assert roots == [-1.0, 1.0]
roots = Poly(x**2 + 1, x).nroots()
assert roots == [-1.0*I, 1.0*I]
roots = Poly(x**2/3 - S(1)/3, x).nroots()
assert roots == [-1.0, 1.0]
roots = Poly(x**2/3 + S(1)/3, x).nroots()
assert roots == [-1.0*I, 1.0*I]
assert Poly(x**2 + 2*I, x).nroots() == [-1.0 + 1.0*I, 1.0 - 1.0*I]
assert Poly(
x**2 + 2*I, x, extension=I).nroots() == [-1.0 + 1.0*I, 1.0 - 1.0*I]
assert Poly(0.2*x + 0.1).nroots() == [-0.5]
roots = nroots(x**5 + x + 1, n=5)
eps = Float("1e-5")
assert re(roots[0]).epsilon_eq(-0.75487, eps) is S.true
assert im(roots[0]) == 0.0
assert re(roots[1]) == -0.5
assert im(roots[1]).epsilon_eq(-0.86602, eps) is S.true
assert re(roots[2]) == -0.5
assert im(roots[2]).epsilon_eq(+0.86602, eps) is S.true
assert re(roots[3]).epsilon_eq(+0.87743, eps) is S.true
assert im(roots[3]).epsilon_eq(-0.74486, eps) is S.true
assert re(roots[4]).epsilon_eq(+0.87743, eps) is S.true
assert im(roots[4]).epsilon_eq(+0.74486, eps) is S.true
eps = Float("1e-6")
assert re(roots[0]).epsilon_eq(-0.75487, eps) is S.false
assert im(roots[0]) == 0.0
assert re(roots[1]) == -0.5
assert im(roots[1]).epsilon_eq(-0.86602, eps) is S.false
assert re(roots[2]) == -0.5
assert im(roots[2]).epsilon_eq(+0.86602, eps) is S.false
assert re(roots[3]).epsilon_eq(+0.87743, eps) is S.false
assert im(roots[3]).epsilon_eq(-0.74486, eps) is S.false
assert re(roots[4]).epsilon_eq(+0.87743, eps) is S.false
assert im(roots[4]).epsilon_eq(+0.74486, eps) is S.false
raises(DomainError, lambda: Poly(x + y, x).nroots())
raises(MultivariatePolynomialError, lambda: Poly(x + y).nroots())
assert nroots(x**2 - 1) == [-1.0, 1.0]
roots = nroots(x**2 - 1)
assert roots == [-1.0, 1.0]
assert nroots(x + I) == [-1.0*I]
assert nroots(x + 2*I) == [-2.0*I]
raises(PolynomialError, lambda: nroots(0))
# issue 8296
f = Poly(x**4 - 1)
assert f.nroots(2) == [w.n(2) for w in f.all_roots()]
def test_ground_roots():
f = x**6 - 4*x**4 + 4*x**3 - x**2
assert Poly(f).ground_roots() == {S(1): 2, S(0): 2}
assert ground_roots(f) == {S(1): 2, S(0): 2}
def test_nth_power_roots_poly():
f = x**4 - x**2 + 1
f_2 = (x**2 - x + 1)**2
f_3 = (x**2 + 1)**2
f_4 = (x**2 + x + 1)**2
f_12 = (x - 1)**4
assert nth_power_roots_poly(f, 1) == f
raises(ValueError, lambda: nth_power_roots_poly(f, 0))
raises(ValueError, lambda: nth_power_roots_poly(f, x))
assert factor(nth_power_roots_poly(f, 2)) == f_2
assert factor(nth_power_roots_poly(f, 3)) == f_3
assert factor(nth_power_roots_poly(f, 4)) == f_4
assert factor(nth_power_roots_poly(f, 12)) == f_12
raises(MultivariatePolynomialError, lambda: nth_power_roots_poly(
x + y, 2, x, y))
def test_torational_factor_list():
p = expand(((x**2-1)*(x-2)).subs({x:x*(1 + sqrt(2))}))
assert _torational_factor_list(p, x) == (-2, [
(-x*(1 + sqrt(2))/2 + 1, 1),
(-x*(1 + sqrt(2)) - 1, 1),
(-x*(1 + sqrt(2)) + 1, 1)])
p = expand(((x**2-1)*(x-2)).subs({x:x*(1 + 2**Rational(1, 4))}))
assert _torational_factor_list(p, x) is None
def test_cancel():
assert cancel(0) == 0
assert cancel(7) == 7
assert cancel(x) == x
assert cancel(oo) == oo
assert cancel((2, 3)) == (1, 2, 3)
assert cancel((1, 0), x) == (1, 1, 0)
assert cancel((0, 1), x) == (1, 0, 1)
f, g, p, q = 4*x**2 - 4, 2*x - 2, 2*x + 2, 1
F, G, P, Q = [ Poly(u, x) for u in (f, g, p, q) ]
assert F.cancel(G) == (1, P, Q)
assert cancel((f, g)) == (1, p, q)
assert cancel((f, g), x) == (1, p, q)
assert cancel((f, g), (x,)) == (1, p, q)
assert cancel((F, G)) == (1, P, Q)
assert cancel((f, g), polys=True) == (1, P, Q)
assert cancel((F, G), polys=False) == (1, p, q)
f = (x**2 - 2)/(x + sqrt(2))
assert cancel(f) == f
assert cancel(f, greedy=False) == x - sqrt(2)
f = (x**2 - 2)/(x - sqrt(2))
assert cancel(f) == f
assert cancel(f, greedy=False) == x + sqrt(2)
assert cancel((x**2/4 - 1, x/2 - 1)) == (S(1)/2, x + 2, 1)
assert cancel((x**2 - y)/(x - y)) == 1/(x - y)*(x**2 - y)
assert cancel((x**2 - y**2)/(x - y), x) == x + y
assert cancel((x**2 - y**2)/(x - y), y) == x + y
assert cancel((x**2 - y**2)/(x - y)) == x + y
assert cancel((x**3 - 1)/(x**2 - 1)) == (x**2 + x + 1)/(x + 1)
assert cancel((x**3/2 - S(1)/2)/(x**2 - 1)) == (x**2 + x + 1)/(2*x + 2)
assert cancel((exp(2*x) + 2*exp(x) + 1)/(exp(x) + 1)) == exp(x) + 1
f = Poly(x**2 - a**2, x)
g = Poly(x - a, x)
F = Poly(x + a, x)
G = Poly(1, x)
assert cancel((f, g)) == (1, F, G)
f = x**3 + (sqrt(2) - 2)*x**2 - (2*sqrt(2) + 3)*x - 3*sqrt(2)
g = x**2 - 2
assert cancel((f, g), extension=True) == (1, x**2 - 2*x - 3, x - sqrt(2))
f = Poly(-2*x + 3, x)
g = Poly(-x**9 + x**8 + x**6 - x**5 + 2*x**2 - 3*x + 1, x)
assert cancel((f, g)) == (1, -f, -g)
f = Poly(y, y, domain='ZZ(x)')
g = Poly(1, y, domain='ZZ[x]')
assert f.cancel(
g) == (1, Poly(y, y, domain='ZZ(x)'), Poly(1, y, domain='ZZ(x)'))
assert f.cancel(g, include=True) == (
Poly(y, y, domain='ZZ(x)'), Poly(1, y, domain='ZZ(x)'))
f = Poly(5*x*y + x, y, domain='ZZ(x)')
g = Poly(2*x**2*y, y, domain='ZZ(x)')
assert f.cancel(g, include=True) == (
Poly(5*y + 1, y, domain='ZZ(x)'), Poly(2*x*y, y, domain='ZZ(x)'))
f = -(-2*x - 4*y + 0.005*(z - y)**2)/((z - y)*(-z + y + 2))
assert cancel(f).is_Mul == True
P = tanh(x - 3.0)
Q = tanh(x + 3.0)
f = ((-2*P**2 + 2)*(-P**2 + 1)*Q**2/2 + (-2*P**2 + 2)*(-2*Q**2 + 2)*P*Q - (-2*P**2 + 2)*P**2*Q**2 + (-2*Q**2 + 2)*(-Q**2 + 1)*P**2/2 - (-2*Q**2 + 2)*P**2*Q**2)/(2*sqrt(P**2*Q**2 + 0.0001)) \
+ (-(-2*P**2 + 2)*P*Q**2/2 - (-2*Q**2 + 2)*P**2*Q/2)*((-2*P**2 + 2)*P*Q**2/2 + (-2*Q**2 + 2)*P**2*Q/2)/(2*(P**2*Q**2 + 0.0001)**(S(3)/2))
assert cancel(f).is_Mul == True
# issue 7022
A = Symbol('A', commutative=False)
p1 = Piecewise((A*(x**2 - 1)/(x + 1), x > 1), ((x + 2)/(x**2 + 2*x), True))
p2 = Piecewise((A*(x - 1), x > 1), (1/x, True))
assert cancel(p1) == p2
assert cancel(2*p1) == 2*p2
assert cancel(1 + p1) == 1 + p2
assert cancel((x**2 - 1)/(x + 1)*p1) == (x - 1)*p2
assert cancel((x**2 - 1)/(x + 1) + p1) == (x - 1) + p2
p3 = Piecewise(((x**2 - 1)/(x + 1), x > 1), ((x + 2)/(x**2 + 2*x), True))
p4 = Piecewise(((x - 1), x > 1), (1/x, True))
assert cancel(p3) == p4
assert cancel(2*p3) == 2*p4
assert cancel(1 + p3) == 1 + p4
assert cancel((x**2 - 1)/(x + 1)*p3) == (x - 1)*p4
assert cancel((x**2 - 1)/(x + 1) + p3) == (x - 1) + p4
# issue 9363
M = MatrixSymbol('M', 5, 5)
assert cancel(M[0,0] + 7) == M[0,0] + 7
expr = sin(M[1, 4] + M[2, 1] * 5 * M[4, 0]) - 5 * M[1, 2] / z
assert cancel(expr) == (z*sin(M[1, 4] + M[2, 1] * 5 * M[4, 0]) - 5 * M[1, 2]) / z
def test_reduced():
f = 2*x**4 + y**2 - x**2 + y**3
G = [x**3 - x, y**3 - y]
Q = [2*x, 1]
r = x**2 + y**2 + y
assert reduced(f, G) == (Q, r)
assert reduced(f, G, x, y) == (Q, r)
H = groebner(G)
assert H.reduce(f) == (Q, r)
Q = [Poly(2*x, x, y), Poly(1, x, y)]
r = Poly(x**2 + y**2 + y, x, y)
assert _strict_eq(reduced(f, G, polys=True), (Q, r))
assert _strict_eq(reduced(f, G, x, y, polys=True), (Q, r))
H = groebner(G, polys=True)
assert _strict_eq(H.reduce(f), (Q, r))
f = 2*x**3 + y**3 + 3*y
G = groebner([x**2 + y**2 - 1, x*y - 2])
Q = [x**2 - x*y**3/2 + x*y/2 + y**6/4 - y**4/2 + y**2/4, -y**5/4 + y**3/2 + 3*y/4]
r = 0
assert reduced(f, G) == (Q, r)
assert G.reduce(f) == (Q, r)
assert reduced(f, G, auto=False)[1] != 0
assert G.reduce(f, auto=False)[1] != 0
assert G.contains(f) is True
assert G.contains(f + 1) is False
assert reduced(1, [1], x) == ([1], 0)
raises(ComputationFailed, lambda: reduced(1, [1]))
def test_groebner():
assert groebner([], x, y, z) == []
assert groebner([x**2 + 1, y**4*x + x**3], x, y, order='lex') == [1 + x**2, -1 + y**4]
assert groebner([x**2 + 1, y**4*x + x**3, x*y*z**3], x, y, z, order='grevlex') == [-1 + y**4, z**3, 1 + x**2]
assert groebner([x**2 + 1, y**4*x + x**3], x, y, order='lex', polys=True) == \
[Poly(1 + x**2, x, y), Poly(-1 + y**4, x, y)]
assert groebner([x**2 + 1, y**4*x + x**3, x*y*z**3], x, y, z, order='grevlex', polys=True) == \
[Poly(-1 + y**4, x, y, z), Poly(z**3, x, y, z), Poly(1 + x**2, x, y, z)]
assert groebner([x**3 - 1, x**2 - 1]) == [x - 1]
assert groebner([Eq(x**3, 1), Eq(x**2, 1)]) == [x - 1]
F = [3*x**2 + y*z - 5*x - 1, 2*x + 3*x*y + y**2, x - 3*y + x*z - 2*z**2]
f = z**9 - x**2*y**3 - 3*x*y**2*z + 11*y*z**2 + x**2*z**2 - 5
G = groebner(F, x, y, z, modulus=7, symmetric=False)
assert G == [1 + x + y + 3*z + 2*z**2 + 2*z**3 + 6*z**4 + z**5,
1 + 3*y + y**2 + 6*z**2 + 3*z**3 + 3*z**4 + 3*z**5 + 4*z**6,
1 + 4*y + 4*z + y*z + 4*z**3 + z**4 + z**6,
6 + 6*z + z**2 + 4*z**3 + 3*z**4 + 6*z**5 + 3*z**6 + z**7]
Q, r = reduced(f, G, x, y, z, modulus=7, symmetric=False, polys=True)
assert sum([ q*g for q, g in zip(Q, G.polys)], r) == Poly(f, modulus=7)
F = [x*y - 2*y, 2*y**2 - x**2]
assert groebner(F, x, y, order='grevlex') == \
[y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y]
assert groebner(F, y, x, order='grevlex') == \
[x**3 - 2*x**2, -x**2 + 2*y**2, x*y - 2*y]
assert groebner(F, order='grevlex', field=True) == \
[y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y]
assert groebner([1], x) == [1]
assert groebner([x**2 + 2.0*y], x, y) == [1.0*x**2 + 2.0*y]
raises(ComputationFailed, lambda: groebner([1]))
assert groebner([x**2 - 1, x**3 + 1], method='buchberger') == [x + 1]
assert groebner([x**2 - 1, x**3 + 1], method='f5b') == [x + 1]
raises(ValueError, lambda: groebner([x, y], method='unknown'))
def test_fglm():
F = [a + b + c + d, a*b + a*d + b*c + b*d, a*b*c + a*b*d + a*c*d + b*c*d, a*b*c*d - 1]
G = groebner(F, a, b, c, d, order=grlex)
B = [
4*a + 3*d**9 - 4*d**5 - 3*d,
4*b + 4*c - 3*d**9 + 4*d**5 + 7*d,
4*c**2 + 3*d**10 - 4*d**6 - 3*d**2,
4*c*d**4 + 4*c - d**9 + 4*d**5 + 5*d,
d**12 - d**8 - d**4 + 1,
]
assert groebner(F, a, b, c, d, order=lex) == B
assert G.fglm(lex) == B
F = [9*x**8 + 36*x**7 - 32*x**6 - 252*x**5 - 78*x**4 + 468*x**3 + 288*x**2 - 108*x + 9,
-72*t*x**7 - 252*t*x**6 + 192*t*x**5 + 1260*t*x**4 + 312*t*x**3 - 404*t*x**2 - 576*t*x + \
108*t - 72*x**7 - 256*x**6 + 192*x**5 + 1280*x**4 + 312*x**3 - 576*x + 96]
G = groebner(F, t, x, order=grlex)
B = [
203577793572507451707*t + 627982239411707112*x**7 - 666924143779443762*x**6 - \
10874593056632447619*x**5 + 5119998792707079562*x**4 + 72917161949456066376*x**3 + \
20362663855832380362*x**2 - 142079311455258371571*x + 183756699868981873194,
9*x**8 + 36*x**7 - 32*x**6 - 252*x**5 - 78*x**4 + 468*x**3 + 288*x**2 - 108*x + 9,
]
assert groebner(F, t, x, order=lex) == B
assert G.fglm(lex) == B
F = [x**2 - x - 3*y + 1, -2*x + y**2 + y - 1]
G = groebner(F, x, y, order=lex)
B = [
x**2 - x - 3*y + 1,
y**2 - 2*x + y - 1,
]
assert groebner(F, x, y, order=grlex) == B
assert G.fglm(grlex) == B
def test_is_zero_dimensional():
assert is_zero_dimensional([x, y], x, y) is True
assert is_zero_dimensional([x**3 + y**2], x, y) is False
assert is_zero_dimensional([x, y, z], x, y, z) is True
assert is_zero_dimensional([x, y, z], x, y, z, t) is False
F = [x*y - z, y*z - x, x*y - y]
assert is_zero_dimensional(F, x, y, z) is True
F = [x**2 - 2*x*z + 5, x*y**2 + y*z**3, 3*y**2 - 8*z**2]
assert is_zero_dimensional(F, x, y, z) is True
def test_GroebnerBasis():
F = [x*y - 2*y, 2*y**2 - x**2]
G = groebner(F, x, y, order='grevlex')
H = [y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y]
P = [ Poly(h, x, y) for h in H ]
assert groebner(F + [0], x, y, order='grevlex') == G
assert isinstance(G, GroebnerBasis) is True
assert len(G) == 3
assert G[0] == H[0] and not G[0].is_Poly
assert G[1] == H[1] and not G[1].is_Poly
assert G[2] == H[2] and not G[2].is_Poly
assert G[1:] == H[1:] and not any(g.is_Poly for g in G[1:])
assert G[:2] == H[:2] and not any(g.is_Poly for g in G[1:])
assert G.exprs == H
assert G.polys == P
assert G.gens == (x, y)
assert G.domain == ZZ
assert G.order == grevlex
assert G == H
assert G == tuple(H)
assert G == P
assert G == tuple(P)
assert G != []
G = groebner(F, x, y, order='grevlex', polys=True)
assert G[0] == P[0] and G[0].is_Poly
assert G[1] == P[1] and G[1].is_Poly
assert G[2] == P[2] and G[2].is_Poly
assert G[1:] == P[1:] and all(g.is_Poly for g in G[1:])
assert G[:2] == P[:2] and all(g.is_Poly for g in G[1:])
def test_poly():
assert poly(x) == Poly(x, x)
assert poly(y) == Poly(y, y)
assert poly(x + y) == Poly(x + y, x, y)
assert poly(x + sin(x)) == Poly(x + sin(x), x, sin(x))
assert poly(x + y, wrt=y) == Poly(x + y, y, x)
assert poly(x + sin(x), wrt=sin(x)) == Poly(x + sin(x), sin(x), x)
assert poly(x*y + 2*x*z**2 + 17) == Poly(x*y + 2*x*z**2 + 17, x, y, z)
assert poly(2*(y + z)**2 - 1) == Poly(2*y**2 + 4*y*z + 2*z**2 - 1, y, z)
assert poly(
x*(y + z)**2 - 1) == Poly(x*y**2 + 2*x*y*z + x*z**2 - 1, x, y, z)
assert poly(2*x*(
y + z)**2 - 1) == Poly(2*x*y**2 + 4*x*y*z + 2*x*z**2 - 1, x, y, z)
assert poly(2*(
y + z)**2 - x - 1) == Poly(2*y**2 + 4*y*z + 2*z**2 - x - 1, x, y, z)
assert poly(x*(
y + z)**2 - x - 1) == Poly(x*y**2 + 2*x*y*z + x*z**2 - x - 1, x, y, z)
assert poly(2*x*(y + z)**2 - x - 1) == Poly(2*x*y**2 + 4*x*y*z + 2*
x*z**2 - x - 1, x, y, z)
assert poly(x*y + (x + y)**2 + (x + z)**2) == \
Poly(2*x*z + 3*x*y + y**2 + z**2 + 2*x**2, x, y, z)
assert poly(x*y*(x + y)*(x + z)**2) == \
Poly(x**3*y**2 + x*y**2*z**2 + y*x**2*z**2 + 2*z*x**2*
y**2 + 2*y*z*x**3 + y*x**4, x, y, z)
assert poly(Poly(x + y + z, y, x, z)) == Poly(x + y + z, y, x, z)
assert poly((x + y)**2, x) == Poly(x**2 + 2*x*y + y**2, x, domain=ZZ[y])
assert poly((x + y)**2, y) == Poly(x**2 + 2*x*y + y**2, y, domain=ZZ[x])
assert poly(1, x) == Poly(1, x)
raises(GeneratorsNeeded, lambda: poly(1))
# issue 6184
assert poly(x + y, x, y) == Poly(x + y, x, y)
assert poly(x + y, y, x) == Poly(x + y, y, x)
def test_keep_coeff():
u = Mul(2, x + 1, evaluate=False)
assert _keep_coeff(S(1), x) == x
assert _keep_coeff(S(-1), x) == -x
assert _keep_coeff(S(1.0), x) == 1.0*x
assert _keep_coeff(S(-1.0), x) == -1.0*x
assert _keep_coeff(S(1), 2*x) == 2*x
assert _keep_coeff(S(2), x/2) == x
assert _keep_coeff(S(2), sin(x)) == 2*sin(x)
assert _keep_coeff(S(2), x + 1) == u
assert _keep_coeff(x, 1/x) == 1
assert _keep_coeff(x + 1, S(2)) == u
@XFAIL
def test_poly_matching_consistency():
# Test for this issue:
# https://github.com/sympy/sympy/issues/5514
assert I * Poly(x, x) == Poly(I*x, x)
assert Poly(x, x) * I == Poly(I*x, x)
@XFAIL
def test_issue_5786():
assert expand(factor(expand(
(x - I*y)*(z - I*t)), extension=[I])) == -I*t*x - t*y + x*z - I*y*z
def test_noncommutative():
class foo(Expr):
is_commutative=False
e = x/(x + x*y)
c = 1/( 1 + y)
assert cancel(foo(e)) == foo(c)
assert cancel(e + foo(e)) == c + foo(c)
assert cancel(e*foo(c)) == c*foo(c)
def test_to_rational_coeffs():
assert to_rational_coeffs(
Poly(x**3 + y*x**2 + sqrt(y), x, domain='EX')) == None
def test_factor_terms():
# issue 7067
assert factor_list(x*(x + y)) == (1, [(x, 1), (x + y, 1)])
assert sqf_list(x*(x + y)) == (1, [(x, 1), (x + y, 1)])
def test_issue_11198():
assert factor_list(sqrt(2)*x) == (sqrt(2), [(x, 1)])
assert factor_list(sqrt(2)*sin(x), sin(x)) == (sqrt(2), [(sin(x), 1)])
def test_Poly_precision():
# Make sure Poly doesn't lose precision
p = Poly(pi.evalf(100)*x)
assert p.as_expr() == pi.evalf(100)*x
| 108,460 | 32.788474 | 194 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/tests/test_specialpolys.py
|
"""Tests for functions for generating interesting polynomials. """
from sympy import Poly, ZZ, symbols
from sympy.utilities.pytest import raises
from sympy.polys.specialpolys import (
swinnerton_dyer_poly,
cyclotomic_poly,
symmetric_poly,
random_poly,
interpolating_poly,
fateman_poly_F_1,
dmp_fateman_poly_F_1,
fateman_poly_F_2,
dmp_fateman_poly_F_2,
fateman_poly_F_3,
dmp_fateman_poly_F_3,
)
from sympy.abc import x, y, z
def test_swinnerton_dyer_poly():
raises(ValueError, lambda: swinnerton_dyer_poly(0, x))
assert swinnerton_dyer_poly(1, x, polys=True) == Poly(x**2 - 2)
assert swinnerton_dyer_poly(1, x) == x**2 - 2
assert swinnerton_dyer_poly(2, x) == x**4 - 10*x**2 + 1
assert swinnerton_dyer_poly(
3, x) == x**8 - 40*x**6 + 352*x**4 - 960*x**2 + 576
def test_cyclotomic_poly():
raises(ValueError, lambda: cyclotomic_poly(0, x))
assert cyclotomic_poly(1, x, polys=True) == Poly(x - 1)
assert cyclotomic_poly(1, x) == x - 1
assert cyclotomic_poly(2, x) == x + 1
assert cyclotomic_poly(3, x) == x**2 + x + 1
assert cyclotomic_poly(4, x) == x**2 + 1
assert cyclotomic_poly(5, x) == x**4 + x**3 + x**2 + x + 1
assert cyclotomic_poly(6, x) == x**2 - x + 1
def test_symmetric_poly():
raises(ValueError, lambda: symmetric_poly(-1, x, y, z))
raises(ValueError, lambda: symmetric_poly(5, x, y, z))
assert symmetric_poly(1, x, y, z, polys=True) == Poly(x + y + z)
assert symmetric_poly(1, (x, y, z), polys=True) == Poly(x + y + z)
assert symmetric_poly(0, x, y, z) == 1
assert symmetric_poly(1, x, y, z) == x + y + z
assert symmetric_poly(2, x, y, z) == x*y + x*z + y*z
assert symmetric_poly(3, x, y, z) == x*y*z
def test_random_poly():
poly = random_poly(x, 10, -100, 100, polys=False)
assert Poly(poly).degree() == 10
assert all(-100 <= coeff <= 100 for coeff in Poly(poly).coeffs()) is True
poly = random_poly(x, 10, -100, 100, polys=True)
assert poly.degree() == 10
assert all(-100 <= coeff <= 100 for coeff in poly.coeffs()) is True
def test_interpolating_poly():
x0, x1, x2, y0, y1, y2 = symbols('x:3, y:3')
assert interpolating_poly(0, x) == 0
assert interpolating_poly(1, x) == y0
assert interpolating_poly(2, x) == \
y0*(x - x1)/(x0 - x1) + y1*(x - x0)/(x1 - x0)
assert interpolating_poly(3, x) == \
y0*(x - x1)*(x - x2)/((x0 - x1)*(x0 - x2)) + \
y1*(x - x0)*(x - x2)/((x1 - x0)*(x1 - x2)) + \
y2*(x - x0)*(x - x1)/((x2 - x0)*(x2 - x1))
def test_fateman_poly_F_1():
f, g, h = fateman_poly_F_1(1)
F, G, H = dmp_fateman_poly_F_1(1, ZZ)
assert [ t.rep.rep for t in [f, g, h] ] == [F, G, H]
f, g, h = fateman_poly_F_1(3)
F, G, H = dmp_fateman_poly_F_1(3, ZZ)
assert [ t.rep.rep for t in [f, g, h] ] == [F, G, H]
def test_fateman_poly_F_2():
f, g, h = fateman_poly_F_2(1)
F, G, H = dmp_fateman_poly_F_2(1, ZZ)
assert [ t.rep.rep for t in [f, g, h] ] == [F, G, H]
f, g, h = fateman_poly_F_2(3)
F, G, H = dmp_fateman_poly_F_2(3, ZZ)
assert [ t.rep.rep for t in [f, g, h] ] == [F, G, H]
def test_fateman_poly_F_3():
f, g, h = fateman_poly_F_3(1)
F, G, H = dmp_fateman_poly_F_3(1, ZZ)
assert [ t.rep.rep for t in [f, g, h] ] == [F, G, H]
f, g, h = fateman_poly_F_3(3)
F, G, H = dmp_fateman_poly_F_3(3, ZZ)
assert [ t.rep.rep for t in [f, g, h] ] == [F, G, H]
| 3,481 | 27.77686 | 77 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/tests/test_subresultants_qq_zz.py
|
from sympy import var, sturm, subresultants, prem, pquo
from sympy.matrices import Matrix, eye
from sympy.polys.subresultants_qq_zz import (sylvester, bezout,
subresultants_bezout, modified_subresultants_bezout,
process_bezout_output, backward_eye,
sturm_pg, sturm_q, sturm_amv, euclid_pg, euclid_q,
euclid_amv, modified_subresultants_pg, subresultants_pg,
subresultants_amv_q, quo_z, rem_z, subresultants_amv,
modified_subresultants_amv, subresultants_rem,
subresultants_vv, subresultants_vv_2)
def test_sylvester():
x = var('x')
assert sylvester(x**3 -7, 0, x) == sylvester(x**3 -7, 0, x, 1) == Matrix([[0]])
assert sylvester(0, x**3 -7, x) == sylvester(0, x**3 -7, x, 1) == Matrix([[0]])
assert sylvester(x**3 -7, 0, x, 2) == Matrix([[0]])
assert sylvester(0, x**3 -7, x, 2) == Matrix([[0]])
assert sylvester(x**3 -7, 7, x).det() == sylvester(x**3 -7, 7, x, 1).det() == 343
assert sylvester(7, x**3 -7, x).det() == sylvester(7, x**3 -7, x, 1).det() == 343
assert sylvester(x**3 -7, 7, x, 2).det() == -343
assert sylvester(7, x**3 -7, x, 2).det() == 343
assert sylvester(3, 7, x).det() == sylvester(3, 7, x, 1).det() == sylvester(3, 7, x, 2).det() == 1
assert sylvester(3, 0, x).det() == sylvester(3, 0, x, 1).det() == sylvester(3, 0, x, 2).det() == 1
assert sylvester(x - 3, x - 8, x) == sylvester(x - 3, x - 8, x, 1) == sylvester(x - 3, x - 8, x, 2) == Matrix([[1, -3], [1, -8]])
assert sylvester(x**3 - 7*x + 7, 3*x**2 - 7, x) == sylvester(x**3 - 7*x + 7, 3*x**2 - 7, x, 1) == Matrix([[1, 0, -7, 7, 0], [0, 1, 0, -7, 7], [3, 0, -7, 0, 0], [0, 3, 0, -7, 0], [0, 0, 3, 0, -7]])
assert sylvester(x**3 - 7*x + 7, 3*x**2 - 7, x, 2) == Matrix([
[1, 0, -7, 7, 0, 0], [0, 3, 0, -7, 0, 0], [0, 1, 0, -7, 7, 0], [0, 0, 3, 0, -7, 0], [0, 0, 1, 0, -7, 7], [0, 0, 0, 3, 0, -7]])
def test_bezout():
x = var('x')
p = -2*x**5+7*x**3+9*x**2-3*x+1
q = -10*x**4+21*x**2+18*x-3
assert bezout(p, q, x, 'bz').det() == sylvester(p, q, x, 2).det()
assert bezout(p, q, x, 'bz').det() != sylvester(p, q, x, 1).det()
assert bezout(p, q, x, 'prs') == backward_eye(5) * bezout(p, q, x, 'bz') * backward_eye(5)
def test_subresultants_bezout():
x = var('x')
p = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5
q = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21
assert subresultants_bezout(p, q, x) == subresultants(p, q, x)
assert subresultants_bezout(p, q, x)[-1] == sylvester(p, q, x).det()
assert subresultants_bezout(p, q, x) != euclid_amv(p, q, x)
amv_factors = [1, 1, -1, 1, -1, 1]
assert subresultants_bezout(p, q, x) == [i*j for i, j in zip(amv_factors, modified_subresultants_amv(p, q, x))]
p = x**3 - 7*x + 7
q = 3*x**2 - 7
assert subresultants_bezout(p, q, x) == euclid_amv(p, q, x)
def test_modified_subresultants_bezout():
x = var('x')
p = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5
q = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21
amv_factors = [1, 1, -1, 1, -1, 1]
assert modified_subresultants_bezout(p, q, x) == [i*j for i, j in zip(amv_factors, subresultants_amv(p, q, x))]
assert modified_subresultants_bezout(p, q, x)[-1] != sylvester(p + x**8, q, x).det()
assert modified_subresultants_bezout(p, q, x) != sturm_amv(p, q, x)
p = x**3 - 7*x + 7
q = 3*x**2 - 7
assert modified_subresultants_bezout(p, q, x) == sturm_amv(p, q, x)
assert modified_subresultants_bezout(-p, q, x) != sturm_amv(-p, q, x)
def test_sturm_pg():
x = var('x')
p = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5
q = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21
assert sturm_pg(p, q, x)[-1] != sylvester(p, q, x, 2).det()
sam_factors = [1, 1, -1, -1, 1, 1]
assert sturm_pg(p, q, x) == [i*j for i,j in zip(sam_factors, euclid_pg(p, q, x))]
p = -9*x**5 - 5*x**3 - 9
q = -45*x**4 - 15*x**2
assert sturm_pg(p, q, x, 1)[-1] == sylvester(p, q, x, 1).det()
assert sturm_pg(p, q, x)[-1] != sylvester(p, q, x, 2).det()
assert sturm_pg(-p, q, x)[-1] == sylvester(-p, q, x, 2).det()
assert sturm_pg(-p, q, x) == modified_subresultants_pg(-p, q, x)
def test_sturm_q():
x = var('x')
p = x**3 - 7*x + 7
q = 3*x**2 - 7
assert sturm_q(p, q, x) == sturm(p)
assert sturm_q(-p, -q, x) != sturm(-p)
def test_sturm_amv():
x = var('x')
p = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5
q = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21
assert sturm_amv(p, q, x)[-1] != sylvester(p, q, x, 2).det()
sam_factors = [1, 1, -1, -1, 1, 1]
assert sturm_amv(p, q, x) == [i*j for i,j in zip(sam_factors, euclid_amv(p, q, x))]
p = -9*x**5 - 5*x**3 - 9
q = -45*x**4 - 15*x**2
assert sturm_amv(p, q, x, 1)[-1] == sylvester(p, q, x, 1).det()
assert sturm_amv(p, q, x)[-1] != sylvester(p, q, x, 2).det()
assert sturm_amv(-p, q, x)[-1] == sylvester(-p, q, x, 2).det()
assert sturm_pg(-p, q, x) == modified_subresultants_pg(-p, q, x)
def test_euclid_pg():
x = var('x')
p = x**6+x**5-x**4-x**3+x**2-x+1
q = 6*x**5+5*x**4-4*x**3-3*x**2+2*x-1
assert euclid_pg(p, q, x)[-1] == sylvester(p, q, x).det()
assert euclid_pg(p, q, x) == subresultants_pg(p, q, x)
p = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5
q = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21
assert euclid_pg(p, q, x)[-1] != sylvester(p, q, x, 2).det()
sam_factors = [1, 1, -1, -1, 1, 1]
assert euclid_pg(p, q, x) == [i*j for i,j in zip(sam_factors, sturm_pg(p, q, x))]
def test_euclid_q():
x = var('x')
p = x**3 - 7*x + 7
q = 3*x**2 - 7
assert euclid_q(p, q, x)[-1] == -sturm(p)[-1]
def test_euclid_amv():
x = var('x')
p = x**3 - 7*x + 7
q = 3*x**2 - 7
assert euclid_amv(p, q, x)[-1] == sylvester(p, q, x).det()
assert euclid_amv(p, q, x) == subresultants_amv(p, q, x)
p = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5
q = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21
assert euclid_amv(p, q, x)[-1] != sylvester(p, q, x, 2).det()
sam_factors = [1, 1, -1, -1, 1, 1]
assert euclid_amv(p, q, x) == [i*j for i,j in zip(sam_factors, sturm_amv(p, q, x))]
def test_modified_subresultants_pg():
x = var('x')
p = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5
q = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21
amv_factors = [1, 1, -1, 1, -1, 1]
assert modified_subresultants_pg(p, q, x) == [i*j for i, j in zip(amv_factors, subresultants_pg(p, q, x))]
assert modified_subresultants_pg(p, q, x)[-1] != sylvester(p + x**8, q, x).det()
assert modified_subresultants_pg(p, q, x) != sturm_pg(p, q, x)
p = x**3 - 7*x + 7
q = 3*x**2 - 7
assert modified_subresultants_pg(p, q, x) == sturm_pg(p, q, x)
assert modified_subresultants_pg(-p, q, x) != sturm_pg(-p, q, x)
def test_subresultants_pg():
x = var('x')
p = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5
q = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21
assert subresultants_pg(p, q, x) == subresultants(p, q, x)
assert subresultants_pg(p, q, x)[-1] == sylvester(p, q, x).det()
assert subresultants_pg(p, q, x) != euclid_pg(p, q, x)
amv_factors = [1, 1, -1, 1, -1, 1]
assert subresultants_pg(p, q, x) == [i*j for i, j in zip(amv_factors, modified_subresultants_amv(p, q, x))]
p = x**3 - 7*x + 7
q = 3*x**2 - 7
assert subresultants_pg(p, q, x) == euclid_pg(p, q, x)
def test_subresultants_amv_q():
x = var('x')
p = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5
q = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21
assert subresultants_amv_q(p, q, x) == subresultants(p, q, x)
assert subresultants_amv_q(p, q, x)[-1] == sylvester(p, q, x).det()
assert subresultants_amv_q(p, q, x) != euclid_amv(p, q, x)
amv_factors = [1, 1, -1, 1, -1, 1]
assert subresultants_amv_q(p, q, x) == [i*j for i, j in zip(amv_factors, modified_subresultants_amv(p, q, x))]
p = x**3 - 7*x + 7
q = 3*x**2 - 7
assert subresultants_amv(p, q, x) == euclid_amv(p, q, x)
def test_rem_z():
x = var('x')
p = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5
q = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21
assert rem_z(p, -q, x) != prem(p, -q, x)
def test_quo_z():
x = var('x')
p = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5
q = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21
assert quo_z(p, -q, x) != pquo(p, -q, x)
def test_subresultants_amv():
x = var('x')
p = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5
q = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21
assert subresultants_amv(p, q, x) == subresultants(p, q, x)
assert subresultants_amv(p, q, x)[-1] == sylvester(p, q, x).det()
assert subresultants_amv(p, q, x) != euclid_amv(p, q, x)
amv_factors = [1, 1, -1, 1, -1, 1]
assert subresultants_amv(p, q, x) == [i*j for i, j in zip(amv_factors, modified_subresultants_amv(p, q, x))]
p = x**3 - 7*x + 7
q = 3*x**2 - 7
assert subresultants_amv(p, q, x) == euclid_amv(p, q, x)
def test_modified_subresultants_amv():
x = var('x')
p = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5
q = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21
amv_factors = [1, 1, -1, 1, -1, 1]
assert modified_subresultants_amv(p, q, x) == [i*j for i, j in zip(amv_factors, subresultants_amv(p, q, x))]
assert modified_subresultants_amv(p, q, x)[-1] != sylvester(p + x**8, q, x).det()
assert modified_subresultants_amv(p, q, x) != sturm_amv(p, q, x)
p = x**3 - 7*x + 7
q = 3*x**2 - 7
assert modified_subresultants_amv(p, q, x) == sturm_amv(p, q, x)
assert modified_subresultants_amv(-p, q, x) != sturm_amv(-p, q, x)
def test_subresultants_rem():
x = var('x')
p = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5
q = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21
assert subresultants_rem(p, q, x) == subresultants(p, q, x)
assert subresultants_rem(p, q, x)[-1] == sylvester(p, q, x).det()
assert subresultants_rem(p, q, x) != euclid_amv(p, q, x)
amv_factors = [1, 1, -1, 1, -1, 1]
assert subresultants_rem(p, q, x) == [i*j for i, j in zip(amv_factors, modified_subresultants_amv(p, q, x))]
p = x**3 - 7*x + 7
q = 3*x**2 - 7
assert subresultants_rem(p, q, x) == euclid_amv(p, q, x)
def test_subresultants_vv():
x = var('x')
p = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5
q = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21
assert subresultants_vv(p, q, x) == subresultants(p, q, x)
assert subresultants_vv(p, q, x)[-1] == sylvester(p, q, x).det()
assert subresultants_vv(p, q, x) != euclid_amv(p, q, x)
amv_factors = [1, 1, -1, 1, -1, 1]
assert subresultants_vv(p, q, x) == [i*j for i, j in zip(amv_factors, modified_subresultants_amv(p, q, x))]
p = x**3 - 7*x + 7
q = 3*x**2 - 7
assert subresultants_vv(p, q, x) == euclid_amv(p, q, x)
def test_subresultants_vv_2():
x = var('x')
p = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5
q = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21
assert subresultants_vv_2(p, q, x) == subresultants(p, q, x)
assert subresultants_vv_2(p, q, x)[-1] == sylvester(p, q, x).det()
assert subresultants_vv_2(p, q, x) != euclid_amv(p, q, x)
amv_factors = [1, 1, -1, 1, -1, 1]
assert subresultants_vv_2(p, q, x) == [i*j for i, j in zip(amv_factors, modified_subresultants_amv(p, q, x))]
p = x**3 - 7*x + 7
q = 3*x**2 - 7
assert subresultants_vv_2(p, q, x) == euclid_amv(p, q, x)
| 11,438 | 37.64527 | 210 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/tests/test_sqfreetools.py
|
"""Tests for square-free decomposition algorithms and related tools. """
from sympy.polys.rings import ring
from sympy.polys.domains import FF, ZZ, QQ
from sympy.polys.specialpolys import f_polys
from sympy.utilities.pytest import raises
f_0, f_1, f_2, f_3, f_4, f_5, f_6 = f_polys()
def test_dup_sqf():
R, x = ring("x", ZZ)
assert R.dup_sqf_part(0) == 0
assert R.dup_sqf_p(0) is True
assert R.dup_sqf_part(7) == 1
assert R.dup_sqf_p(7) is True
assert R.dup_sqf_part(2*x + 2) == x + 1
assert R.dup_sqf_p(2*x + 2) is True
assert R.dup_sqf_part(x**3 + x + 1) == x**3 + x + 1
assert R.dup_sqf_p(x**3 + x + 1) is True
assert R.dup_sqf_part(-x**3 + x + 1) == x**3 - x - 1
assert R.dup_sqf_p(-x**3 + x + 1) is True
assert R.dup_sqf_part(2*x**3 + 3*x**2) == 2*x**2 + 3*x
assert R.dup_sqf_p(2*x**3 + 3*x**2) is False
assert R.dup_sqf_part(-2*x**3 + 3*x**2) == 2*x**2 - 3*x
assert R.dup_sqf_p(-2*x**3 + 3*x**2) is False
assert R.dup_sqf_list(0) == (0, [])
assert R.dup_sqf_list(1) == (1, [])
assert R.dup_sqf_list(x) == (1, [(x, 1)])
assert R.dup_sqf_list(2*x**2) == (2, [(x, 2)])
assert R.dup_sqf_list(3*x**3) == (3, [(x, 3)])
assert R.dup_sqf_list(-x**5 + x**4 + x - 1) == \
(-1, [(x**3 + x**2 + x + 1, 1), (x - 1, 2)])
assert R.dup_sqf_list(x**8 + 6*x**6 + 12*x**4 + 8*x**2) == \
( 1, [(x, 2), (x**2 + 2, 3)])
assert R.dup_sqf_list(2*x**2 + 4*x + 2) == (2, [(x + 1, 2)])
R, x = ring("x", QQ)
assert R.dup_sqf_list(2*x**2 + 4*x + 2) == (2, [(x + 1, 2)])
R, x = ring("x", FF(2))
assert R.dup_sqf_list(x**2 + 1) == (1, [(x + 1, 2)])
R, x = ring("x", FF(3))
assert R.dup_sqf_list(x**10 + 2*x**7 + 2*x**4 + x) == \
(1, [(x, 1),
(x + 1, 3),
(x + 2, 6)])
R1, x = ring("x", ZZ)
R2, y = ring("y", FF(3))
f = x**3 + 1
g = y**3 + 1
assert R1.dup_sqf_part(f) == f
assert R2.dup_sqf_part(g) == y + 1
assert R1.dup_sqf_p(f) is True
assert R2.dup_sqf_p(g) is False
R, x, y = ring("x,y", ZZ)
A = x**4 - 3*x**2 + 6
D = x**6 - 5*x**4 + 5*x**2 + 4
f, g = D, R.dmp_sub(A, R.dmp_mul(R.dmp_diff(D, 1), y))
res = R.dmp_resultant(f, g)
h = (4*y**2 + 1).drop(x)
assert R.drop(x).dup_sqf_list(res) == (45796, [(h, 3)])
Rt, t = ring("t", ZZ)
R, x = ring("x", Rt)
assert R.dup_sqf_list_include(t**3*x**2) == [(t**3, 1), (x, 2)]
def test_dmp_sqf():
R, x, y = ring("x,y", ZZ)
assert R.dmp_sqf_part(0) == 0
assert R.dmp_sqf_p(0) is True
assert R.dmp_sqf_part(7) == 1
assert R.dmp_sqf_p(7) is True
assert R.dmp_sqf_list(3) == (3, [])
assert R.dmp_sqf_list_include(3) == [(3, 1)]
R, x, y, z = ring("x,y,z", ZZ)
assert R.dmp_sqf_p(f_0) is True
assert R.dmp_sqf_p(f_0**2) is False
assert R.dmp_sqf_p(f_1) is True
assert R.dmp_sqf_p(f_1**2) is False
assert R.dmp_sqf_p(f_2) is True
assert R.dmp_sqf_p(f_2**2) is False
assert R.dmp_sqf_p(f_3) is True
assert R.dmp_sqf_p(f_3**2) is False
assert R.dmp_sqf_p(f_5) is False
assert R.dmp_sqf_p(f_5**2) is False
assert R.dmp_sqf_p(f_4) is True
assert R.dmp_sqf_part(f_4) == -f_4
assert R.dmp_sqf_part(f_5) == x + y - z
R, x, y, z, t = ring("x,y,z,t", ZZ)
assert R.dmp_sqf_p(f_6) is True
assert R.dmp_sqf_part(f_6) == f_6
R, x = ring("x", ZZ)
f = -x**5 + x**4 + x - 1
assert R.dmp_sqf_list(f) == (-1, [(x**3 + x**2 + x + 1, 1), (x - 1, 2)])
assert R.dmp_sqf_list_include(f) == [(-x**3 - x**2 - x - 1, 1), (x - 1, 2)]
R, x, y = ring("x,y", ZZ)
f = -x**5 + x**4 + x - 1
assert R.dmp_sqf_list(f) == (-1, [(x**3 + x**2 + x + 1, 1), (x - 1, 2)])
assert R.dmp_sqf_list_include(f) == [(-x**3 - x**2 - x - 1, 1), (x - 1, 2)]
f = -x**2 + 2*x - 1
assert R.dmp_sqf_list_include(f) == [(-1, 1), (x - 1, 2)]
R, x, y = ring("x,y", FF(2))
raises(NotImplementedError, lambda: R.dmp_sqf_list(y**2 + 1))
def test_dup_gff_list():
R, x = ring("x", ZZ)
f = x**5 + 2*x**4 - x**3 - 2*x**2
assert R.dup_gff_list(f) == [(x, 1), (x + 2, 4)]
g = x**9 - 20*x**8 + 166*x**7 - 744*x**6 + 1965*x**5 - 3132*x**4 + 2948*x**3 - 1504*x**2 + 320*x
assert R.dup_gff_list(g) == [(x**2 - 5*x + 4, 1), (x**2 - 5*x + 4, 2), (x, 3)]
raises(ValueError, lambda: R.dup_gff_list(0))
| 4,389 | 28.266667 | 100 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/tests/test_heuristicgcd.py
|
from sympy.polys.rings import ring
from sympy.polys.domains import ZZ
from sympy.polys.heuristicgcd import heugcd
def test_heugcd_univariate_integers():
R, x = ring("x", ZZ)
f = x**4 + 8*x**3 + 21*x**2 + 22*x + 8
g = x**3 + 6*x**2 + 11*x + 6
h = x**2 + 3*x + 2
cff = x**2 + 5*x + 4
cfg = x + 3
assert heugcd(f, g) == (h, cff, cfg)
f = x**4 - 4
g = x**4 + 4*x**2 + 4
h = x**2 + 2
cff = x**2 - 2
cfg = x**2 + 2
assert heugcd(f, g) == (h, cff, cfg)
f = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5
g = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21
h = 1
cff = f
cfg = g
assert heugcd(f, g) == (h, cff, cfg)
f = - 352518131239247345597970242177235495263669787845475025293906825864749649589178600387510272*x**49 \
+ 46818041807522713962450042363465092040687472354933295397472942006618953623327997952*x**42 \
+ 378182690892293941192071663536490788434899030680411695933646320291525827756032*x**35 \
+ 112806468807371824947796775491032386836656074179286744191026149539708928*x**28 \
- 12278371209708240950316872681744825481125965781519138077173235712*x**21 \
+ 289127344604779611146960547954288113529690984687482920704*x**14 \
+ 19007977035740498977629742919480623972236450681*x**7 \
+ 311973482284542371301330321821976049
g = 365431878023781158602430064717380211405897160759702125019136*x**21 \
+ 197599133478719444145775798221171663643171734081650688*x**14 \
- 9504116979659010018253915765478924103928886144*x**7 \
- 311973482284542371301330321821976049
# TODO: assert heugcd(f, f.diff(x))[0] == g
f = 1317378933230047068160*x + 2945748836994210856960
g = 120352542776360960*x + 269116466014453760
h = 120352542776360960*x + 269116466014453760
cff = 10946
cfg = 1
assert heugcd(f, g) == (h, cff, cfg)
def test_heugcd_multivariate_integers():
R, x, y = ring("x,y", ZZ)
f, g = 2*x**2 + 4*x + 2, x + 1
assert heugcd(f, g) == (x + 1, 2*x + 2, 1)
f, g = x + 1, 2*x**2 + 4*x + 2
assert heugcd(f, g) == (x + 1, 1, 2*x + 2)
R, x, y, z, u = ring("x,y,z,u", ZZ)
f, g = u**2 + 2*u + 1, 2*u + 2
assert heugcd(f, g) == (u + 1, u + 1, 2)
f, g = z**2*u**2 + 2*z**2*u + z**2 + z*u + z, u**2 + 2*u + 1
h, cff, cfg = u + 1, z**2*u + z**2 + z, u + 1
assert heugcd(f, g) == (h, cff, cfg)
assert heugcd(g, f) == (h, cfg, cff)
R, x, y, z = ring("x,y,z", ZZ)
f, g, h = R.fateman_poly_F_1()
H, cff, cfg = heugcd(f, g)
assert H == h and H*cff == f and H*cfg == g
R, x, y, z, u, v = ring("x,y,z,u,v", ZZ)
f, g, h = R.fateman_poly_F_1()
H, cff, cfg = heugcd(f, g)
assert H == h and H*cff == f and H*cfg == g
R, x, y, z, u, v, a, b = ring("x,y,z,u,v,a,b", ZZ)
f, g, h = R.fateman_poly_F_1()
H, cff, cfg = heugcd(f, g)
assert H == h and H*cff == f and H*cfg == g
R, x, y, z, u, v, a, b, c, d = ring("x,y,z,u,v,a,b,c,d", ZZ)
f, g, h = R.fateman_poly_F_1()
H, cff, cfg = heugcd(f, g)
assert H == h and H*cff == f and H*cfg == g
R, x, y, z = ring("x,y,z", ZZ)
f, g, h = R.fateman_poly_F_2()
H, cff, cfg = heugcd(f, g)
assert H == h and H*cff == f and H*cfg == g
f, g, h = R.fateman_poly_F_3()
H, cff, cfg = heugcd(f, g)
assert H == h and H*cff == f and H*cfg == g
R, x, y, z, t = ring("x,y,z,t", ZZ)
f, g, h = R.fateman_poly_F_3()
H, cff, cfg = heugcd(f, g)
assert H == h and H*cff == f and H*cfg == g
| 3,554 | 26.55814 | 108 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/tests/test_dispersion.py
|
from sympy.core import Symbol, S, oo
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.polys import poly
from sympy.polys.dispersion import dispersion, dispersionset
def test_dispersion():
x = Symbol("x")
a = Symbol("a")
fp = poly(S(0), x)
assert sorted(dispersionset(fp)) == [0]
fp = poly(S(2), x)
assert sorted(dispersionset(fp)) == [0]
fp = poly(x + 1, x)
assert sorted(dispersionset(fp)) == [0]
assert dispersion(fp) == 0
fp = poly((x + 1)*(x + 2), x)
assert sorted(dispersionset(fp)) == [0, 1]
assert dispersion(fp) == 1
fp = poly(x*(x + 3), x)
assert sorted(dispersionset(fp)) == [0, 3]
assert dispersion(fp) == 3
fp = poly((x - 3)*(x + 3), x)
assert sorted(dispersionset(fp)) == [0, 6]
assert dispersion(fp) == 6
fp = poly(x**4 - 3*x**2 + 1, x)
gp = fp.shift(-3)
assert sorted(dispersionset(fp, gp)) == [2, 3, 4]
assert dispersion(fp, gp) == 4
assert sorted(dispersionset(gp, fp)) == []
assert dispersion(gp, fp) == -oo
fp = poly(x*(3*x**2+a)*(x-2536)*(x**3+a), x)
gp = fp.as_expr().subs(x, x-345).as_poly(x)
assert sorted(dispersionset(fp, gp)) == [345, 2881]
assert sorted(dispersionset(gp, fp)) == [2191]
gp = poly((x-2)**2*(x-3)**3*(x-5)**3, x)
assert sorted(dispersionset(gp)) == [0, 1, 2, 3]
assert sorted(dispersionset(gp, (gp+4)**2)) == [1, 2]
fp = poly(x*(x+2)*(x-1), x)
assert sorted(dispersionset(fp)) == [0, 1, 2, 3]
fp = poly(x**2 + sqrt(5)*x - 1, x, domain='QQ<sqrt(5)>')
gp = poly(x**2 + (2 + sqrt(5))*x + sqrt(5), x, domain='QQ<sqrt(5)>')
assert sorted(dispersionset(fp, gp)) == [2]
assert sorted(dispersionset(gp, fp)) == [1, 4]
# There are some difficulties if we compute over Z[a]
# and alpha happenes to lie in Z[a] instead of simply Z.
# Hence we can not decide if alpha is indeed integral
# in general.
fp = poly(4*x**4 + (4*a + 8)*x**3 + (a**2 + 6*a + 4)*x**2 + (a**2 + 2*a)*x, x)
assert sorted(dispersionset(fp)) == [0, 1]
# For any specific value of a, the dispersion is 3*a
# but the algorithm can not find this in general.
# This is the point where the resultant based Ansatz
# is superior to the current one.
fp = poly(a**2*x**3 + (a**3 + a**2 + a + 1)*x, x)
gp = fp.as_expr().subs(x, x - 3*a).as_poly(x)
assert sorted(dispersionset(fp, gp)) == []
fpa = fp.as_expr().subs(a, 2).as_poly(x)
gpa = gp.as_expr().subs(a, 2).as_poly(x)
assert sorted(dispersionset(fpa, gpa)) == [6]
# Work with Expr instead of Poly
f = (x + 1)*(x + 2)
assert sorted(dispersionset(f)) == [0, 1]
assert dispersion(f) == 1
f = x**4 - 3*x**2 + 1
g = x**4 - 12*x**3 + 51*x**2 - 90*x + 55
assert sorted(dispersionset(f, g)) == [2, 3, 4]
assert dispersion(f, g) == 4
# Work with Expr and specify a generator
f = (x + 1)*(x + 2)
assert sorted(dispersionset(f, None, x)) == [0, 1]
assert dispersion(f, None, x) == 1
f = x**4 - 3*x**2 + 1
g = x**4 - 12*x**3 + 51*x**2 - 90*x + 55
assert sorted(dispersionset(f, g, x)) == [2, 3, 4]
assert dispersion(f, g, x) == 4
| 3,181 | 32.145833 | 82 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/tests/test_orderings.py
|
"""Tests of monomial orderings. """
from sympy.polys.orderings import (
monomial_key, lex, grlex, grevlex, ilex, igrlex,
LexOrder, InverseOrder, ProductOrder, build_product_order,
)
from sympy.abc import x, y, z, t
from sympy.core import S
from sympy.utilities.pytest import raises
def test_lex_order():
assert lex((1, 2, 3)) == (1, 2, 3)
assert str(lex) == 'lex'
assert lex((1, 2, 3)) == lex((1, 2, 3))
assert lex((2, 2, 3)) > lex((1, 2, 3))
assert lex((1, 3, 3)) > lex((1, 2, 3))
assert lex((1, 2, 4)) > lex((1, 2, 3))
assert lex((0, 2, 3)) < lex((1, 2, 3))
assert lex((1, 1, 3)) < lex((1, 2, 3))
assert lex((1, 2, 2)) < lex((1, 2, 3))
assert lex.is_global is True
assert lex == LexOrder()
assert lex != grlex
def test_grlex_order():
assert grlex((1, 2, 3)) == (6, (1, 2, 3))
assert str(grlex) == 'grlex'
assert grlex((1, 2, 3)) == grlex((1, 2, 3))
assert grlex((2, 2, 3)) > grlex((1, 2, 3))
assert grlex((1, 3, 3)) > grlex((1, 2, 3))
assert grlex((1, 2, 4)) > grlex((1, 2, 3))
assert grlex((0, 2, 3)) < grlex((1, 2, 3))
assert grlex((1, 1, 3)) < grlex((1, 2, 3))
assert grlex((1, 2, 2)) < grlex((1, 2, 3))
assert grlex((2, 2, 3)) > grlex((1, 2, 4))
assert grlex((1, 3, 3)) > grlex((1, 2, 4))
assert grlex((0, 2, 3)) < grlex((1, 2, 2))
assert grlex((1, 1, 3)) < grlex((1, 2, 2))
assert grlex((0, 1, 1)) > grlex((0, 0, 2))
assert grlex((0, 3, 1)) < grlex((2, 2, 1))
assert grlex.is_global is True
def test_grevlex_order():
assert grevlex((1, 2, 3)) == (6, (-3, -2, -1))
assert str(grevlex) == 'grevlex'
assert grevlex((1, 2, 3)) == grevlex((1, 2, 3))
assert grevlex((2, 2, 3)) > grevlex((1, 2, 3))
assert grevlex((1, 3, 3)) > grevlex((1, 2, 3))
assert grevlex((1, 2, 4)) > grevlex((1, 2, 3))
assert grevlex((0, 2, 3)) < grevlex((1, 2, 3))
assert grevlex((1, 1, 3)) < grevlex((1, 2, 3))
assert grevlex((1, 2, 2)) < grevlex((1, 2, 3))
assert grevlex((2, 2, 3)) > grevlex((1, 2, 4))
assert grevlex((1, 3, 3)) > grevlex((1, 2, 4))
assert grevlex((0, 2, 3)) < grevlex((1, 2, 2))
assert grevlex((1, 1, 3)) < grevlex((1, 2, 2))
assert grevlex((0, 1, 1)) > grevlex((0, 0, 2))
assert grevlex((0, 3, 1)) < grevlex((2, 2, 1))
assert grevlex.is_global is True
def test_InverseOrder():
ilex = InverseOrder(lex)
igrlex = InverseOrder(grlex)
assert ilex((1, 2, 3)) > ilex((2, 0, 3))
assert igrlex((1, 2, 3)) < igrlex((0, 2, 3))
assert str(ilex) == "ilex"
assert str(igrlex) == "igrlex"
assert ilex.is_global is False
assert igrlex.is_global is False
assert ilex != igrlex
assert ilex == InverseOrder(LexOrder())
def test_ProductOrder():
P = ProductOrder((grlex, lambda m: m[:2]), (grlex, lambda m: m[2:]))
assert P((1, 3, 3, 4, 5)) > P((2, 1, 5, 5, 5))
assert str(P) == "ProductOrder(grlex, grlex)"
assert P.is_global is True
assert ProductOrder((grlex, None), (ilex, None)).is_global is None
assert ProductOrder((igrlex, None), (ilex, None)).is_global is False
def test_monomial_key():
assert monomial_key() == lex
assert monomial_key('lex') == lex
assert monomial_key('grlex') == grlex
assert monomial_key('grevlex') == grevlex
raises(ValueError, lambda: monomial_key('foo'))
raises(ValueError, lambda: monomial_key(1))
M = [x, x**2*z**2, x*y, x**2, S(1), y**2, x**3, y, z, x*y**2*z, x**2*y**2]
assert sorted(M, key=monomial_key('lex', [z, y, x])) == \
[S(1), x, x**2, x**3, y, x*y, y**2, x**2*y**2, z, x*y**2*z, x**2*z**2]
assert sorted(M, key=monomial_key('grlex', [z, y, x])) == \
[S(1), x, y, z, x**2, x*y, y**2, x**3, x**2*y**2, x*y**2*z, x**2*z**2]
assert sorted(M, key=monomial_key('grevlex', [z, y, x])) == \
[S(1), x, y, z, x**2, x*y, y**2, x**3, x**2*y**2, x**2*z**2, x*y**2*z]
def test_build_product_order():
assert build_product_order((("grlex", x, y), ("grlex", z, t)), [x, y, z, t])((4, 5, 6, 7)) == \
((9, (4, 5)), (13, (6, 7)))
assert build_product_order((("grlex", x, y), ("grlex", z, t)), [x, y, z, t]) == \
build_product_order((("grlex", x, y), ("grlex", z, t)), [x, y, z, t])
| 4,252 | 33.024 | 99 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/tests/test_galoistools.py
|
from sympy.polys.galoistools import (
gf_crt, gf_crt1, gf_crt2, gf_int,
gf_degree, gf_strip, gf_trunc, gf_normal,
gf_from_dict, gf_to_dict,
gf_from_int_poly, gf_to_int_poly,
gf_neg, gf_add_ground, gf_sub_ground, gf_mul_ground,
gf_add, gf_sub, gf_add_mul, gf_sub_mul, gf_mul, gf_sqr,
gf_div, gf_rem, gf_quo, gf_exquo,
gf_lshift, gf_rshift, gf_expand,
gf_pow, gf_pow_mod,
gf_gcdex, gf_gcd, gf_lcm, gf_cofactors,
gf_LC, gf_TC, gf_monic,
gf_eval, gf_multi_eval,
gf_compose, gf_compose_mod,
gf_trace_map,
gf_diff,
gf_irreducible, gf_irreducible_p,
gf_irred_p_ben_or, gf_irred_p_rabin,
gf_sqf_list, gf_sqf_part, gf_sqf_p,
gf_Qmatrix, gf_Qbasis,
gf_ddf_zassenhaus, gf_ddf_shoup,
gf_edf_zassenhaus, gf_edf_shoup,
gf_berlekamp,
gf_factor_sqf, gf_factor,
gf_value, linear_congruence, csolve_prime, gf_csolve,
gf_frobenius_map, gf_frobenius_monomial_base
)
from sympy.polys.polyerrors import (
ExactQuotientFailed,
)
from sympy.polys import polyconfig as config
from sympy.polys.domains import ZZ
from sympy import pi, nextprime
from sympy.utilities.pytest import raises
def test_gf_crt():
U = [49, 76, 65]
M = [99, 97, 95]
p = 912285
u = 639985
assert gf_crt(U, M, ZZ) == u
E = [9215, 9405, 9603]
S = [62, 24, 12]
assert gf_crt1(M, ZZ) == (p, E, S)
assert gf_crt2(U, M, p, E, S, ZZ) == u
def test_gf_int():
assert gf_int(0, 5) == 0
assert gf_int(1, 5) == 1
assert gf_int(2, 5) == 2
assert gf_int(3, 5) == -2
assert gf_int(4, 5) == -1
assert gf_int(5, 5) == 0
def test_gf_degree():
assert gf_degree([]) == -1
assert gf_degree([1]) == 0
assert gf_degree([1, 0]) == 1
assert gf_degree([1, 0, 0, 0, 1]) == 4
def test_gf_strip():
assert gf_strip([]) == []
assert gf_strip([0]) == []
assert gf_strip([0, 0, 0]) == []
assert gf_strip([1]) == [1]
assert gf_strip([0, 1]) == [1]
assert gf_strip([0, 0, 0, 1]) == [1]
assert gf_strip([1, 2, 0]) == [1, 2, 0]
assert gf_strip([0, 1, 2, 0]) == [1, 2, 0]
assert gf_strip([0, 0, 0, 1, 2, 0]) == [1, 2, 0]
def test_gf_trunc():
assert gf_trunc([], 11) == []
assert gf_trunc([1], 11) == [1]
assert gf_trunc([22], 11) == []
assert gf_trunc([12], 11) == [1]
assert gf_trunc([11, 22, 17, 1, 0], 11) == [6, 1, 0]
assert gf_trunc([12, 23, 17, 1, 0], 11) == [1, 1, 6, 1, 0]
def test_gf_normal():
assert gf_normal([11, 22, 17, 1, 0], 11, ZZ) == [6, 1, 0]
def test_gf_from_to_dict():
f = {11: 12, 6: 2, 0: 25}
F = {11: 1, 6: 2, 0: 3}
g = [1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 3]
assert gf_from_dict(f, 11, ZZ) == g
assert gf_to_dict(g, 11) == F
f = {11: -5, 4: 0, 3: 1, 0: 12}
F = {11: -5, 3: 1, 0: 1}
g = [6, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1]
assert gf_from_dict(f, 11, ZZ) == g
assert gf_to_dict(g, 11) == F
assert gf_to_dict([10], 11, symmetric=True) == {0: -1}
assert gf_to_dict([10], 11, symmetric=False) == {0: 10}
def test_gf_from_to_int_poly():
assert gf_from_int_poly([1, 0, 7, 2, 20], 5) == [1, 0, 2, 2, 0]
assert gf_to_int_poly([1, 0, 4, 2, 3], 5) == [1, 0, -1, 2, -2]
assert gf_to_int_poly([10], 11, symmetric=True) == [-1]
assert gf_to_int_poly([10], 11, symmetric=False) == [10]
def test_gf_LC():
assert gf_LC([], ZZ) == 0
assert gf_LC([1], ZZ) == 1
assert gf_LC([1, 2], ZZ) == 1
def test_gf_TC():
assert gf_TC([], ZZ) == 0
assert gf_TC([1], ZZ) == 1
assert gf_TC([1, 2], ZZ) == 2
def test_gf_monic():
assert gf_monic(ZZ.map([]), 11, ZZ) == (0, [])
assert gf_monic(ZZ.map([1]), 11, ZZ) == (1, [1])
assert gf_monic(ZZ.map([2]), 11, ZZ) == (2, [1])
assert gf_monic(ZZ.map([1, 2, 3, 4]), 11, ZZ) == (1, [1, 2, 3, 4])
assert gf_monic(ZZ.map([2, 3, 4, 5]), 11, ZZ) == (2, [1, 7, 2, 8])
def test_gf_arith():
assert gf_neg([], 11, ZZ) == []
assert gf_neg([1], 11, ZZ) == [10]
assert gf_neg([1, 2, 3], 11, ZZ) == [10, 9, 8]
assert gf_add_ground([], 0, 11, ZZ) == []
assert gf_sub_ground([], 0, 11, ZZ) == []
assert gf_add_ground([], 3, 11, ZZ) == [3]
assert gf_sub_ground([], 3, 11, ZZ) == [8]
assert gf_add_ground([1], 3, 11, ZZ) == [4]
assert gf_sub_ground([1], 3, 11, ZZ) == [9]
assert gf_add_ground([8], 3, 11, ZZ) == []
assert gf_sub_ground([3], 3, 11, ZZ) == []
assert gf_add_ground([1, 2, 3], 3, 11, ZZ) == [1, 2, 6]
assert gf_sub_ground([1, 2, 3], 3, 11, ZZ) == [1, 2, 0]
assert gf_mul_ground([], 0, 11, ZZ) == []
assert gf_mul_ground([], 1, 11, ZZ) == []
assert gf_mul_ground([1], 0, 11, ZZ) == []
assert gf_mul_ground([1], 1, 11, ZZ) == [1]
assert gf_mul_ground([1, 2, 3], 0, 11, ZZ) == []
assert gf_mul_ground([1, 2, 3], 1, 11, ZZ) == [1, 2, 3]
assert gf_mul_ground([1, 2, 3], 7, 11, ZZ) == [7, 3, 10]
assert gf_add([], [], 11, ZZ) == []
assert gf_add([1], [], 11, ZZ) == [1]
assert gf_add([], [1], 11, ZZ) == [1]
assert gf_add([1], [1], 11, ZZ) == [2]
assert gf_add([1], [2], 11, ZZ) == [3]
assert gf_add([1, 2], [1], 11, ZZ) == [1, 3]
assert gf_add([1], [1, 2], 11, ZZ) == [1, 3]
assert gf_add([1, 2, 3], [8, 9, 10], 11, ZZ) == [9, 0, 2]
assert gf_sub([], [], 11, ZZ) == []
assert gf_sub([1], [], 11, ZZ) == [1]
assert gf_sub([], [1], 11, ZZ) == [10]
assert gf_sub([1], [1], 11, ZZ) == []
assert gf_sub([1], [2], 11, ZZ) == [10]
assert gf_sub([1, 2], [1], 11, ZZ) == [1, 1]
assert gf_sub([1], [1, 2], 11, ZZ) == [10, 10]
assert gf_sub([3, 2, 1], [8, 9, 10], 11, ZZ) == [6, 4, 2]
assert gf_add_mul(
[1, 5, 6], [7, 3], [8, 0, 6, 1], 11, ZZ) == [1, 2, 10, 8, 9]
assert gf_sub_mul(
[1, 5, 6], [7, 3], [8, 0, 6, 1], 11, ZZ) == [10, 9, 3, 2, 3]
assert gf_mul([], [], 11, ZZ) == []
assert gf_mul([], [1], 11, ZZ) == []
assert gf_mul([1], [], 11, ZZ) == []
assert gf_mul([1], [1], 11, ZZ) == [1]
assert gf_mul([5], [7], 11, ZZ) == [2]
assert gf_mul([3, 0, 0, 6, 1, 2], [4, 0, 1, 0], 11, ZZ) == [1, 0,
3, 2, 4, 3, 1, 2, 0]
assert gf_mul([4, 0, 1, 0], [3, 0, 0, 6, 1, 2], 11, ZZ) == [1, 0,
3, 2, 4, 3, 1, 2, 0]
assert gf_mul([2, 0, 0, 1, 7], [2, 0, 0, 1, 7], 11, ZZ) == [4, 0,
0, 4, 6, 0, 1, 3, 5]
assert gf_sqr([], 11, ZZ) == []
assert gf_sqr([2], 11, ZZ) == [4]
assert gf_sqr([1, 2], 11, ZZ) == [1, 4, 4]
assert gf_sqr([2, 0, 0, 1, 7], 11, ZZ) == [4, 0, 0, 4, 6, 0, 1, 3, 5]
def test_gf_division():
raises(ZeroDivisionError, lambda: gf_div([1, 2, 3], [], 11, ZZ))
raises(ZeroDivisionError, lambda: gf_rem([1, 2, 3], [], 11, ZZ))
raises(ZeroDivisionError, lambda: gf_quo([1, 2, 3], [], 11, ZZ))
raises(ZeroDivisionError, lambda: gf_quo([1, 2, 3], [], 11, ZZ))
assert gf_div([1], [1, 2, 3], 7, ZZ) == ([], [1])
assert gf_rem([1], [1, 2, 3], 7, ZZ) == [1]
assert gf_quo([1], [1, 2, 3], 7, ZZ) == []
f = ZZ.map([5, 4, 3, 2, 1, 0])
g = ZZ.map([1, 2, 3])
q = [5, 1, 0, 6]
r = [3, 3]
assert gf_div(f, g, 7, ZZ) == (q, r)
assert gf_rem(f, g, 7, ZZ) == r
assert gf_quo(f, g, 7, ZZ) == q
raises(ExactQuotientFailed, lambda: gf_exquo(f, g, 7, ZZ))
f = ZZ.map([5, 4, 3, 2, 1, 0])
g = ZZ.map([1, 2, 3, 0])
q = [5, 1, 0]
r = [6, 1, 0]
assert gf_div(f, g, 7, ZZ) == (q, r)
assert gf_rem(f, g, 7, ZZ) == r
assert gf_quo(f, g, 7, ZZ) == q
raises(ExactQuotientFailed, lambda: gf_exquo(f, g, 7, ZZ))
assert gf_quo(ZZ.map([1, 2, 1]), ZZ.map([1, 1]), 11, ZZ) == [1, 1]
def test_gf_shift():
f = [1, 2, 3, 4, 5]
assert gf_lshift([], 5, ZZ) == []
assert gf_rshift([], 5, ZZ) == ([], [])
assert gf_lshift(f, 1, ZZ) == [1, 2, 3, 4, 5, 0]
assert gf_lshift(f, 2, ZZ) == [1, 2, 3, 4, 5, 0, 0]
assert gf_rshift(f, 0, ZZ) == (f, [])
assert gf_rshift(f, 1, ZZ) == ([1, 2, 3, 4], [5])
assert gf_rshift(f, 3, ZZ) == ([1, 2], [3, 4, 5])
assert gf_rshift(f, 5, ZZ) == ([], f)
def test_gf_expand():
F = [([1, 1], 2), ([1, 2], 3)]
assert gf_expand(F, 11, ZZ) == [1, 8, 3, 5, 6, 8]
assert gf_expand((4, F), 11, ZZ) == [4, 10, 1, 9, 2, 10]
def test_gf_powering():
assert gf_pow([1, 0, 0, 1, 8], 0, 11, ZZ) == [1]
assert gf_pow([1, 0, 0, 1, 8], 1, 11, ZZ) == [1, 0, 0, 1, 8]
assert gf_pow([1, 0, 0, 1, 8], 2, 11, ZZ) == [1, 0, 0, 2, 5, 0, 1, 5, 9]
assert gf_pow([1, 0, 0, 1, 8], 5, 11, ZZ) == \
[1, 0, 0, 5, 7, 0, 10, 6, 2, 10, 9, 6, 10, 6, 6, 0, 5, 2, 5, 9, 10]
assert gf_pow([1, 0, 0, 1, 8], 8, 11, ZZ) == \
[1, 0, 0, 8, 9, 0, 6, 8, 10, 1, 2, 5, 10, 7, 7, 9, 1, 2, 0, 0, 6, 2,
5, 2, 5, 7, 7, 9, 10, 10, 7, 5, 5]
assert gf_pow([1, 0, 0, 1, 8], 45, 11, ZZ) == \
[ 1, 0, 0, 1, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 4, 10, 0, 0, 0, 0, 0, 0,
10, 0, 0, 10, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6, 0, 0, 6, 4, 0, 0, 0, 0, 0, 0, 8, 0, 0, 8, 9, 0, 0, 0, 0, 0, 0,
10, 0, 0, 10, 3, 0, 0, 0, 0, 0, 0, 4, 0, 0, 4, 10, 0, 0, 0, 0, 0, 0,
8, 0, 0, 8, 9, 0, 0, 0, 0, 0, 0, 9, 0, 0, 9, 6, 0, 0, 0, 0, 0, 0,
3, 0, 0, 3, 2, 0, 0, 0, 0, 0, 0, 10, 0, 0, 10, 3, 0, 0, 0, 0, 0, 0,
10, 0, 0, 10, 3, 0, 0, 0, 0, 0, 0, 2, 0, 0, 2, 5, 0, 0, 0, 0, 0, 0,
4, 0, 0, 4, 10]
assert gf_pow_mod(ZZ.map([1, 0, 0, 1, 8]), 0, ZZ.map([2, 0, 7]), 11, ZZ) == [1]
assert gf_pow_mod(ZZ.map([1, 0, 0, 1, 8]), 1, ZZ.map([2, 0, 7]), 11, ZZ) == [1, 1]
assert gf_pow_mod(ZZ.map([1, 0, 0, 1, 8]), 2, ZZ.map([2, 0, 7]), 11, ZZ) == [2, 3]
assert gf_pow_mod(ZZ.map([1, 0, 0, 1, 8]), 5, ZZ.map([2, 0, 7]), 11, ZZ) == [7, 8]
assert gf_pow_mod(ZZ.map([1, 0, 0, 1, 8]), 8, ZZ.map([2, 0, 7]), 11, ZZ) == [1, 5]
assert gf_pow_mod(ZZ.map([1, 0, 0, 1, 8]), 45, ZZ.map([2, 0, 7]), 11, ZZ) == [5, 4]
def test_gf_gcdex():
assert gf_gcdex(ZZ.map([]), ZZ.map([]), 11, ZZ) == ([1], [], [])
assert gf_gcdex(ZZ.map([2]), ZZ.map([]), 11, ZZ) == ([6], [], [1])
assert gf_gcdex(ZZ.map([]), ZZ.map([2]), 11, ZZ) == ([], [6], [1])
assert gf_gcdex(ZZ.map([2]), ZZ.map([2]), 11, ZZ) == ([], [6], [1])
assert gf_gcdex(ZZ.map([]), ZZ.map([3, 0]), 11, ZZ) == ([], [4], [1, 0])
assert gf_gcdex(ZZ.map([3, 0]), ZZ.map([]), 11, ZZ) == ([4], [], [1, 0])
assert gf_gcdex(ZZ.map([3, 0]), ZZ.map([3, 0]), 11, ZZ) == ([], [4], [1, 0])
assert gf_gcdex(ZZ.map([1, 8, 7]), ZZ.map([1, 7, 1, 7]), 11, ZZ) == ([5, 6], [6], [1, 7])
def test_gf_gcd():
assert gf_gcd(ZZ.map([]), ZZ.map([]), 11, ZZ) == []
assert gf_gcd(ZZ.map([2]), ZZ.map([]), 11, ZZ) == [1]
assert gf_gcd(ZZ.map([]), ZZ.map([2]), 11, ZZ) == [1]
assert gf_gcd(ZZ.map([2]), ZZ.map([2]), 11, ZZ) == [1]
assert gf_gcd(ZZ.map([]), ZZ.map([1, 0]), 11, ZZ) == [1, 0]
assert gf_gcd(ZZ.map([1, 0]), ZZ.map([]), 11, ZZ) == [1, 0]
assert gf_gcd(ZZ.map([3, 0]), ZZ.map([3, 0]), 11, ZZ) == [1, 0]
assert gf_gcd(ZZ.map([1, 8, 7]), ZZ.map([1, 7, 1, 7]), 11, ZZ) == [1, 7]
def test_gf_lcm():
assert gf_lcm(ZZ.map([]), ZZ.map([]), 11, ZZ) == []
assert gf_lcm(ZZ.map([2]), ZZ.map([]), 11, ZZ) == []
assert gf_lcm(ZZ.map([]), ZZ.map([2]), 11, ZZ) == []
assert gf_lcm(ZZ.map([2]), ZZ.map([2]), 11, ZZ) == [1]
assert gf_lcm(ZZ.map([]), ZZ.map([1, 0]), 11, ZZ) == []
assert gf_lcm(ZZ.map([1, 0]), ZZ.map([]), 11, ZZ) == []
assert gf_lcm(ZZ.map([3, 0]), ZZ.map([3, 0]), 11, ZZ) == [1, 0]
assert gf_lcm(ZZ.map([1, 8, 7]), ZZ.map([1, 7, 1, 7]), 11, ZZ) == [1, 8, 8, 8, 7]
def test_gf_cofactors():
assert gf_cofactors(ZZ.map([]), ZZ.map([]), 11, ZZ) == ([], [], [])
assert gf_cofactors(ZZ.map([2]), ZZ.map([]), 11, ZZ) == ([1], [2], [])
assert gf_cofactors(ZZ.map([]), ZZ.map([2]), 11, ZZ) == ([1], [], [2])
assert gf_cofactors(ZZ.map([2]), ZZ.map([2]), 11, ZZ) == ([1], [2], [2])
assert gf_cofactors(ZZ.map([]), ZZ.map([1, 0]), 11, ZZ) == ([1, 0], [], [1])
assert gf_cofactors(ZZ.map([1, 0]), ZZ.map([]), 11, ZZ) == ([1, 0], [1], [])
assert gf_cofactors(ZZ.map([3, 0]), ZZ.map([3, 0]), 11, ZZ) == (
[1, 0], [3], [3])
assert gf_cofactors(ZZ.map([1, 8, 7]), ZZ.map([1, 7, 1, 7]), 11, ZZ) == (
([1, 7], [1, 1], [1, 0, 1]))
def test_gf_diff():
assert gf_diff([], 11, ZZ) == []
assert gf_diff([7], 11, ZZ) == []
assert gf_diff([7, 3], 11, ZZ) == [7]
assert gf_diff([7, 3, 1], 11, ZZ) == [3, 3]
assert gf_diff([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], 11, ZZ) == []
def test_gf_eval():
assert gf_eval([], 4, 11, ZZ) == 0
assert gf_eval([], 27, 11, ZZ) == 0
assert gf_eval([7], 4, 11, ZZ) == 7
assert gf_eval([7], 27, 11, ZZ) == 7
assert gf_eval([1, 0, 3, 2, 4, 3, 1, 2, 0], 0, 11, ZZ) == 0
assert gf_eval([1, 0, 3, 2, 4, 3, 1, 2, 0], 4, 11, ZZ) == 9
assert gf_eval([1, 0, 3, 2, 4, 3, 1, 2, 0], 27, 11, ZZ) == 5
assert gf_eval([4, 0, 0, 4, 6, 0, 1, 3, 5], 0, 11, ZZ) == 5
assert gf_eval([4, 0, 0, 4, 6, 0, 1, 3, 5], 4, 11, ZZ) == 3
assert gf_eval([4, 0, 0, 4, 6, 0, 1, 3, 5], 27, 11, ZZ) == 9
assert gf_multi_eval([3, 2, 1], [0, 1, 2, 3], 11, ZZ) == [1, 6, 6, 1]
def test_gf_compose():
assert gf_compose([], [1, 0], 11, ZZ) == []
assert gf_compose_mod([], [1, 0], [1, 0], 11, ZZ) == []
assert gf_compose([1], [], 11, ZZ) == [1]
assert gf_compose([1, 0], [], 11, ZZ) == []
assert gf_compose([1, 0], [1, 0], 11, ZZ) == [1, 0]
f = ZZ.map([1, 1, 4, 9, 1])
g = ZZ.map([1, 1, 1])
h = ZZ.map([1, 0, 0, 2])
assert gf_compose(g, h, 11, ZZ) == [1, 0, 0, 5, 0, 0, 7]
assert gf_compose_mod(g, h, f, 11, ZZ) == [3, 9, 6, 10]
def test_gf_trace_map():
f = ZZ.map([1, 1, 4, 9, 1])
a = [1, 1, 1]
c = ZZ.map([1, 0])
b = gf_pow_mod(c, 11, f, 11, ZZ)
assert gf_trace_map(a, b, c, 0, f, 11, ZZ) == \
([1, 1, 1], [1, 1, 1])
assert gf_trace_map(a, b, c, 1, f, 11, ZZ) == \
([5, 2, 10, 3], [5, 3, 0, 4])
assert gf_trace_map(a, b, c, 2, f, 11, ZZ) == \
([5, 9, 5, 3], [10, 1, 5, 7])
assert gf_trace_map(a, b, c, 3, f, 11, ZZ) == \
([1, 10, 6, 0], [7])
assert gf_trace_map(a, b, c, 4, f, 11, ZZ) == \
([1, 1, 1], [1, 1, 8])
assert gf_trace_map(a, b, c, 5, f, 11, ZZ) == \
([5, 2, 10, 3], [5, 3, 0, 0])
assert gf_trace_map(a, b, c, 11, f, 11, ZZ) == \
([1, 10, 6, 0], [10])
def test_gf_irreducible():
assert gf_irreducible_p(gf_irreducible(1, 11, ZZ), 11, ZZ) is True
assert gf_irreducible_p(gf_irreducible(2, 11, ZZ), 11, ZZ) is True
assert gf_irreducible_p(gf_irreducible(3, 11, ZZ), 11, ZZ) is True
assert gf_irreducible_p(gf_irreducible(4, 11, ZZ), 11, ZZ) is True
assert gf_irreducible_p(gf_irreducible(5, 11, ZZ), 11, ZZ) is True
assert gf_irreducible_p(gf_irreducible(6, 11, ZZ), 11, ZZ) is True
assert gf_irreducible_p(gf_irreducible(7, 11, ZZ), 11, ZZ) is True
def test_gf_irreducible_p():
assert gf_irred_p_ben_or(ZZ.map([7]), 11, ZZ) is True
assert gf_irred_p_ben_or(ZZ.map([7, 3]), 11, ZZ) is True
assert gf_irred_p_ben_or(ZZ.map([7, 3, 1]), 11, ZZ) is False
assert gf_irred_p_rabin(ZZ.map([7]), 11, ZZ) is True
assert gf_irred_p_rabin(ZZ.map([7, 3]), 11, ZZ) is True
assert gf_irred_p_rabin(ZZ.map([7, 3, 1]), 11, ZZ) is False
config.setup('GF_IRRED_METHOD', 'ben-or')
assert gf_irreducible_p(ZZ.map([7]), 11, ZZ) is True
assert gf_irreducible_p(ZZ.map([7, 3]), 11, ZZ) is True
assert gf_irreducible_p(ZZ.map([7, 3, 1]), 11, ZZ) is False
config.setup('GF_IRRED_METHOD', 'rabin')
assert gf_irreducible_p(ZZ.map([7]), 11, ZZ) is True
assert gf_irreducible_p(ZZ.map([7, 3]), 11, ZZ) is True
assert gf_irreducible_p(ZZ.map([7, 3, 1]), 11, ZZ) is False
config.setup('GF_IRRED_METHOD', 'other')
raises(KeyError, lambda: gf_irreducible_p([7], 11, ZZ))
config.setup('GF_IRRED_METHOD')
f = ZZ.map([1, 9, 9, 13, 16, 15, 6, 7, 7, 7, 10])
g = ZZ.map([1, 7, 16, 7, 15, 13, 13, 11, 16, 10, 9])
h = gf_mul(f, g, 17, ZZ)
assert gf_irred_p_ben_or(f, 17, ZZ) is True
assert gf_irred_p_ben_or(g, 17, ZZ) is True
assert gf_irred_p_ben_or(h, 17, ZZ) is False
assert gf_irred_p_rabin(f, 17, ZZ) is True
assert gf_irred_p_rabin(g, 17, ZZ) is True
assert gf_irred_p_rabin(h, 17, ZZ) is False
def test_gf_squarefree():
assert gf_sqf_list([], 11, ZZ) == (0, [])
assert gf_sqf_list([1], 11, ZZ) == (1, [])
assert gf_sqf_list([1, 1], 11, ZZ) == (1, [([1, 1], 1)])
assert gf_sqf_p([], 11, ZZ) is True
assert gf_sqf_p([1], 11, ZZ) is True
assert gf_sqf_p([1, 1], 11, ZZ) is True
f = gf_from_dict({11: 1, 0: 1}, 11, ZZ)
assert gf_sqf_p(f, 11, ZZ) is False
assert gf_sqf_list(f, 11, ZZ) == \
(1, [([1, 1], 11)])
f = [1, 5, 8, 4]
assert gf_sqf_p(f, 11, ZZ) is False
assert gf_sqf_list(f, 11, ZZ) == \
(1, [([1, 1], 1),
([1, 2], 2)])
assert gf_sqf_part(f, 11, ZZ) == [1, 3, 2]
f = [1, 0, 0, 2, 0, 0, 2, 0, 0, 1, 0]
assert gf_sqf_list(f, 3, ZZ) == \
(1, [([1, 0], 1),
([1, 1], 3),
([1, 2], 6)])
def test_gf_frobenius_map():
f = ZZ.map([2, 0, 1, 0, 2, 2, 0, 2, 2, 2])
g = ZZ.map([1,1,0,2,0,1,0,2,0,1])
p = 3
n = 4
b = gf_frobenius_monomial_base(g, p, ZZ)
h = gf_frobenius_map(f, g, b, p, ZZ)
h1 = gf_pow_mod(f, p, g, p, ZZ)
assert h == h1
def test_gf_berlekamp():
f = gf_from_int_poly([1, -3, 1, -3, -1, -3, 1], 11)
Q = [[1, 0, 0, 0, 0, 0],
[3, 5, 8, 8, 6, 5],
[3, 6, 6, 1, 10, 0],
[9, 4, 10, 3, 7, 9],
[7, 8, 10, 0, 0, 8],
[8, 10, 7, 8, 10, 8]]
V = [[1, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 0],
[0, 0, 7, 9, 0, 1]]
assert gf_Qmatrix(f, 11, ZZ) == Q
assert gf_Qbasis(Q, 11, ZZ) == V
assert gf_berlekamp(f, 11, ZZ) == \
[[1, 1], [1, 5, 3], [1, 2, 3, 4]]
f = ZZ.map([1, 0, 1, 0, 10, 10, 8, 2, 8])
Q = ZZ.map([[1, 0, 0, 0, 0, 0, 0, 0],
[2, 1, 7, 11, 10, 12, 5, 11],
[3, 6, 4, 3, 0, 4, 7, 2],
[4, 3, 6, 5, 1, 6, 2, 3],
[2, 11, 8, 8, 3, 1, 3, 11],
[6, 11, 8, 6, 2, 7, 10, 9],
[5, 11, 7, 10, 0, 11, 7, 12],
[3, 3, 12, 5, 0, 11, 9, 12]])
V = [[1, 0, 0, 0, 0, 0, 0, 0],
[0, 5, 5, 0, 9, 5, 1, 0],
[0, 9, 11, 9, 10, 12, 0, 1]]
assert gf_Qmatrix(f, 13, ZZ) == Q
assert gf_Qbasis(Q, 13, ZZ) == V
assert gf_berlekamp(f, 13, ZZ) == \
[[1, 3], [1, 8, 4, 12], [1, 2, 3, 4, 6]]
def test_gf_ddf():
f = gf_from_dict({15: ZZ(1), 0: ZZ(-1)}, 11, ZZ)
g = [([1, 0, 0, 0, 0, 10], 1),
([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], 2)]
assert gf_ddf_zassenhaus(f, 11, ZZ) == g
assert gf_ddf_shoup(f, 11, ZZ) == g
f = gf_from_dict({63: ZZ(1), 0: ZZ(1)}, 2, ZZ)
g = [([1, 1], 1),
([1, 1, 1], 2),
([1, 1, 1, 1, 1, 1, 1], 3),
([1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0,
0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0,
0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1], 6)]
assert gf_ddf_zassenhaus(f, 2, ZZ) == g
assert gf_ddf_shoup(f, 2, ZZ) == g
f = gf_from_dict({6: ZZ(1), 5: ZZ(-1), 4: ZZ(1), 3: ZZ(1), 1: ZZ(-1)}, 3, ZZ)
g = [([1, 1, 0], 1),
([1, 1, 0, 1, 2], 2)]
assert gf_ddf_zassenhaus(f, 3, ZZ) == g
assert gf_ddf_shoup(f, 3, ZZ) == g
f = ZZ.map([1, 2, 5, 26, 677, 436, 791, 325, 456, 24, 577])
g = [([1, 701], 1),
([1, 110, 559, 532, 694, 151, 110, 70, 735, 122], 9)]
assert gf_ddf_zassenhaus(f, 809, ZZ) == g
assert gf_ddf_shoup(f, 809, ZZ) == g
p = ZZ(nextprime(int((2**15 * pi).evalf())))
f = gf_from_dict({15: 1, 1: 1, 0: 1}, p, ZZ)
g = [([1, 22730, 68144], 2),
([1, 64876, 83977, 10787, 12561, 68608, 52650, 88001, 84356], 4),
([1, 15347, 95022, 84569, 94508, 92335], 5)]
assert gf_ddf_zassenhaus(f, p, ZZ) == g
assert gf_ddf_shoup(f, p, ZZ) == g
def test_gf_edf():
f = ZZ.map([1, 1, 0, 1, 2])
g = ZZ.map([[1, 0, 1], [1, 1, 2]])
assert gf_edf_zassenhaus(f, 2, 3, ZZ) == g
assert gf_edf_shoup(f, 2, 3, ZZ) == g
def test_gf_factor():
assert gf_factor([], 11, ZZ) == (0, [])
assert gf_factor([1], 11, ZZ) == (1, [])
assert gf_factor([1, 1], 11, ZZ) == (1, [([1, 1], 1)])
assert gf_factor_sqf([], 11, ZZ) == (0, [])
assert gf_factor_sqf([1], 11, ZZ) == (1, [])
assert gf_factor_sqf([1, 1], 11, ZZ) == (1, [[1, 1]])
config.setup('GF_FACTOR_METHOD', 'berlekamp')
assert gf_factor_sqf([], 11, ZZ) == (0, [])
assert gf_factor_sqf([1], 11, ZZ) == (1, [])
assert gf_factor_sqf([1, 1], 11, ZZ) == (1, [[1, 1]])
config.setup('GF_FACTOR_METHOD', 'zassenhaus')
assert gf_factor_sqf([], 11, ZZ) == (0, [])
assert gf_factor_sqf([1], 11, ZZ) == (1, [])
assert gf_factor_sqf([1, 1], 11, ZZ) == (1, [[1, 1]])
config.setup('GF_FACTOR_METHOD', 'shoup')
assert gf_factor_sqf(ZZ.map([]), 11, ZZ) == (0, [])
assert gf_factor_sqf(ZZ.map([1]), 11, ZZ) == (1, [])
assert gf_factor_sqf(ZZ.map([1, 1]), 11, ZZ) == (1, [[1, 1]])
f, p = ZZ.map([1, 0, 0, 1, 0]), 2
g = (1, [([1, 0], 1),
([1, 1], 1),
([1, 1, 1], 1)])
config.setup('GF_FACTOR_METHOD', 'berlekamp')
assert gf_factor(f, p, ZZ) == g
config.setup('GF_FACTOR_METHOD', 'zassenhaus')
assert gf_factor(f, p, ZZ) == g
config.setup('GF_FACTOR_METHOD', 'shoup')
assert gf_factor(f, p, ZZ) == g
g = (1, [[1, 0],
[1, 1],
[1, 1, 1]])
config.setup('GF_FACTOR_METHOD', 'berlekamp')
assert gf_factor_sqf(f, p, ZZ) == g
config.setup('GF_FACTOR_METHOD', 'zassenhaus')
assert gf_factor_sqf(f, p, ZZ) == g
config.setup('GF_FACTOR_METHOD', 'shoup')
assert gf_factor_sqf(f, p, ZZ) == g
f, p = gf_from_int_poly([1, -3, 1, -3, -1, -3, 1], 11), 11
g = (1, [([1, 1], 1),
([1, 5, 3], 1),
([1, 2, 3, 4], 1)])
config.setup('GF_FACTOR_METHOD', 'berlekamp')
assert gf_factor(f, p, ZZ) == g
config.setup('GF_FACTOR_METHOD', 'zassenhaus')
assert gf_factor(f, p, ZZ) == g
config.setup('GF_FACTOR_METHOD', 'shoup')
assert gf_factor(f, p, ZZ) == g
f, p = [1, 5, 8, 4], 11
g = (1, [([1, 1], 1), ([1, 2], 2)])
config.setup('GF_FACTOR_METHOD', 'berlekamp')
assert gf_factor(f, p, ZZ) == g
config.setup('GF_FACTOR_METHOD', 'zassenhaus')
assert gf_factor(f, p, ZZ) == g
config.setup('GF_FACTOR_METHOD', 'shoup')
assert gf_factor(f, p, ZZ) == g
f, p = [1, 1, 10, 1, 0, 10, 10, 10, 0, 0], 11
g = (1, [([1, 0], 2), ([1, 9, 5], 1), ([1, 3, 0, 8, 5, 2], 1)])
config.setup('GF_FACTOR_METHOD', 'berlekamp')
assert gf_factor(f, p, ZZ) == g
config.setup('GF_FACTOR_METHOD', 'zassenhaus')
assert gf_factor(f, p, ZZ) == g
config.setup('GF_FACTOR_METHOD', 'shoup')
assert gf_factor(f, p, ZZ) == g
f, p = gf_from_dict({32: 1, 0: 1}, 11, ZZ), 11
g = (1, [([1, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 10], 1),
([1, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 10], 1)])
config.setup('GF_FACTOR_METHOD', 'berlekamp')
assert gf_factor(f, p, ZZ) == g
config.setup('GF_FACTOR_METHOD', 'zassenhaus')
assert gf_factor(f, p, ZZ) == g
config.setup('GF_FACTOR_METHOD', 'shoup')
assert gf_factor(f, p, ZZ) == g
f, p = gf_from_dict({32: ZZ(8), 0: ZZ(5)}, 11, ZZ), 11
g = (8, [([1, 3], 1),
([1, 8], 1),
([1, 0, 9], 1),
([1, 2, 2], 1),
([1, 9, 2], 1),
([1, 0, 5, 0, 7], 1),
([1, 0, 6, 0, 7], 1),
([1, 0, 0, 0, 1, 0, 0, 0, 6], 1),
([1, 0, 0, 0, 10, 0, 0, 0, 6], 1)])
config.setup('GF_FACTOR_METHOD', 'berlekamp')
assert gf_factor(f, p, ZZ) == g
config.setup('GF_FACTOR_METHOD', 'zassenhaus')
assert gf_factor(f, p, ZZ) == g
config.setup('GF_FACTOR_METHOD', 'shoup')
assert gf_factor(f, p, ZZ) == g
f, p = gf_from_dict({63: ZZ(8), 0: ZZ(5)}, 11, ZZ), 11
g = (8, [([1, 7], 1),
([1, 4, 5], 1),
([1, 6, 8, 2], 1),
([1, 9, 9, 2], 1),
([1, 0, 0, 9, 0, 0, 4], 1),
([1, 2, 0, 8, 4, 6, 4], 1),
([1, 2, 3, 8, 0, 6, 4], 1),
([1, 2, 6, 0, 8, 4, 4], 1),
([1, 3, 3, 1, 6, 8, 4], 1),
([1, 5, 6, 0, 8, 6, 4], 1),
([1, 6, 2, 7, 9, 8, 4], 1),
([1, 10, 4, 7, 10, 7, 4], 1),
([1, 10, 10, 1, 4, 9, 4], 1)])
config.setup('GF_FACTOR_METHOD', 'berlekamp')
assert gf_factor(f, p, ZZ) == g
config.setup('GF_FACTOR_METHOD', 'zassenhaus')
assert gf_factor(f, p, ZZ) == g
config.setup('GF_FACTOR_METHOD', 'shoup')
assert gf_factor(f, p, ZZ) == g
# Gathen polynomials: x**n + x + 1 (mod p > 2**n * pi)
p = ZZ(nextprime(int((2**15 * pi).evalf())))
f = gf_from_dict({15: 1, 1: 1, 0: 1}, p, ZZ)
assert gf_sqf_p(f, p, ZZ) is True
g = (1, [([1, 22730, 68144], 1),
([1, 81553, 77449, 86810, 4724], 1),
([1, 86276, 56779, 14859, 31575], 1),
([1, 15347, 95022, 84569, 94508, 92335], 1)])
config.setup('GF_FACTOR_METHOD', 'zassenhaus')
assert gf_factor(f, p, ZZ) == g
config.setup('GF_FACTOR_METHOD', 'shoup')
assert gf_factor(f, p, ZZ) == g
g = (1, [[1, 22730, 68144],
[1, 81553, 77449, 86810, 4724],
[1, 86276, 56779, 14859, 31575],
[1, 15347, 95022, 84569, 94508, 92335]])
config.setup('GF_FACTOR_METHOD', 'zassenhaus')
assert gf_factor_sqf(f, p, ZZ) == g
config.setup('GF_FACTOR_METHOD', 'shoup')
assert gf_factor_sqf(f, p, ZZ) == g
# Shoup polynomials: f = a_0 x**n + a_1 x**(n-1) + ... + a_n
# (mod p > 2**(n-2) * pi), where a_n = a_{n-1}**2 + 1, a_0 = 1
p = ZZ(nextprime(int((2**4 * pi).evalf())))
f = ZZ.map([1, 2, 5, 26, 41, 39, 38])
assert gf_sqf_p(f, p, ZZ) is True
g = (1, [([1, 44, 26], 1),
([1, 11, 25, 18, 30], 1)])
config.setup('GF_FACTOR_METHOD', 'zassenhaus')
assert gf_factor(f, p, ZZ) == g
config.setup('GF_FACTOR_METHOD', 'shoup')
assert gf_factor(f, p, ZZ) == g
g = (1, [[1, 44, 26],
[1, 11, 25, 18, 30]])
config.setup('GF_FACTOR_METHOD', 'zassenhaus')
assert gf_factor_sqf(f, p, ZZ) == g
config.setup('GF_FACTOR_METHOD', 'shoup')
assert gf_factor_sqf(f, p, ZZ) == g
config.setup('GF_FACTOR_METHOD', 'other')
raises(KeyError, lambda: gf_factor([1, 1], 11, ZZ))
config.setup('GF_FACTOR_METHOD')
def test_gf_csolve():
assert gf_value([1, 7, 2, 4], 11) == 2204
assert linear_congruence(4, 3, 5) == [2]
assert linear_congruence(0, 3, 5) == []
assert linear_congruence(6, 1, 4) == []
assert linear_congruence(0, 5, 5) == [0, 1, 2, 3, 4]
assert linear_congruence(3, 12, 15) == [4, 9, 14]
assert linear_congruence(6, 0, 18) == [0, 3, 6, 9, 12, 15]
# with power = 1
assert csolve_prime([1, 3, 2, 17], 7) == [3]
assert csolve_prime([1, 3, 1, 5], 5) == [0, 1]
assert csolve_prime([3, 6, 9, 3], 3) == [0, 1, 2]
# with power > 1
assert csolve_prime(
[1, 1, 223], 3, 4) == [4, 13, 22, 31, 40, 49, 58, 67, 76]
assert csolve_prime([3, 5, 2, 25], 5, 3) == [16, 50, 99]
assert csolve_prime([3, 2, 2, 49], 7, 3) == [147, 190, 234]
assert gf_csolve([1, 1, 7], 189) == [13, 49, 76, 112, 139, 175]
assert gf_csolve([1, 3, 4, 1, 30], 60) == [10, 30]
assert gf_csolve([1, 1, 7], 15) == []
| 27,879 | 31.343387 | 93 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/domains/algebraicfield.py
|
"""Implementation of :class:`AlgebraicField` class. """
from __future__ import print_function, division
from sympy.polys.domains.field import Field
from sympy.polys.domains.simpledomain import SimpleDomain
from sympy.polys.domains.characteristiczero import CharacteristicZero
from sympy.polys.polyclasses import ANP
from sympy.polys.polyerrors import CoercionFailed, DomainError, NotAlgebraic, IsomorphismFailed
from sympy.utilities import public
@public
class AlgebraicField(Field, CharacteristicZero, SimpleDomain):
"""A class for representing algebraic number fields. """
dtype = ANP
is_AlgebraicField = is_Algebraic = True
is_Numerical = True
has_assoc_Ring = False
has_assoc_Field = True
def __init__(self, dom, *ext):
if not dom.is_QQ:
raise DomainError("ground domain must be a rational field")
from sympy.polys.numberfields import to_number_field
self.orig_ext = ext
self.ext = to_number_field(ext)
self.mod = self.ext.minpoly.rep
self.domain = self.dom = dom
self.ngens = 1
self.symbols = self.gens = (self.ext,)
self.unit = self([dom(1), dom(0)])
self.zero = self.dtype.zero(self.mod.rep, dom)
self.one = self.dtype.one(self.mod.rep, dom)
def new(self, element):
return self.dtype(element, self.mod.rep, self.dom)
def __str__(self):
return str(self.dom) + '<' + str(self.ext) + '>'
def __hash__(self):
return hash((self.__class__.__name__, self.dtype, self.dom, self.ext))
def __eq__(self, other):
"""Returns ``True`` if two domains are equivalent. """
return isinstance(other, AlgebraicField) and \
self.dtype == other.dtype and self.ext == other.ext
def algebraic_field(self, *extension):
r"""Returns an algebraic field, i.e. `\mathbb{Q}(\alpha, \ldots)`. """
return AlgebraicField(self.dom, *((self.ext,) + extension))
def to_sympy(self, a):
"""Convert ``a`` to a SymPy object. """
from sympy.polys.numberfields import AlgebraicNumber
return AlgebraicNumber(self.ext, a).as_expr()
def from_sympy(self, a):
"""Convert SymPy's expression to ``dtype``. """
try:
return self([self.dom.from_sympy(a)])
except CoercionFailed:
pass
from sympy.polys.numberfields import to_number_field
try:
return self(to_number_field(a, self.ext).native_coeffs())
except (NotAlgebraic, IsomorphismFailed):
raise CoercionFailed(
"%s is not a valid algebraic number in %s" % (a, self))
def from_ZZ_python(K1, a, K0):
"""Convert a Python ``int`` object to ``dtype``. """
return K1(K1.dom.convert(a, K0))
def from_QQ_python(K1, a, K0):
"""Convert a Python ``Fraction`` object to ``dtype``. """
return K1(K1.dom.convert(a, K0))
def from_ZZ_gmpy(K1, a, K0):
"""Convert a GMPY ``mpz`` object to ``dtype``. """
return K1(K1.dom.convert(a, K0))
def from_QQ_gmpy(K1, a, K0):
"""Convert a GMPY ``mpq`` object to ``dtype``. """
return K1(K1.dom.convert(a, K0))
def from_RealField(K1, a, K0):
"""Convert a mpmath ``mpf`` object to ``dtype``. """
return K1(K1.dom.convert(a, K0))
def get_ring(self):
"""Returns a ring associated with ``self``. """
raise DomainError('there is no ring associated with %s' % self)
def is_positive(self, a):
"""Returns True if ``a`` is positive. """
return self.dom.is_positive(a.LC())
def is_negative(self, a):
"""Returns True if ``a`` is negative. """
return self.dom.is_negative(a.LC())
def is_nonpositive(self, a):
"""Returns True if ``a`` is non-positive. """
return self.dom.is_nonpositive(a.LC())
def is_nonnegative(self, a):
"""Returns True if ``a`` is non-negative. """
return self.dom.is_nonnegative(a.LC())
def numer(self, a):
"""Returns numerator of ``a``. """
return a
def denom(self, a):
"""Returns denominator of ``a``. """
return self.one
| 4,195 | 31.527132 | 95 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/domains/old_fractionfield.py
|
"""Implementation of :class:`FractionField` class. """
from __future__ import print_function, division
from sympy.polys.domains.field import Field
from sympy.polys.domains.compositedomain import CompositeDomain
from sympy.polys.domains.characteristiczero import CharacteristicZero
from sympy.polys.polyclasses import DMF
from sympy.polys.polyerrors import GeneratorsNeeded
from sympy.polys.polyutils import dict_from_basic, basic_from_dict, _dict_reorder
from sympy.utilities import public
@public
class FractionField(Field, CharacteristicZero, CompositeDomain):
"""A class for representing rational function fields. """
dtype = DMF
is_FractionField = is_Frac = True
has_assoc_Ring = True
has_assoc_Field = True
def __init__(self, dom, *gens):
if not gens:
raise GeneratorsNeeded("generators not specified")
lev = len(gens) - 1
self.ngens = len(gens)
self.zero = self.dtype.zero(lev, dom, ring=self)
self.one = self.dtype.one(lev, dom, ring=self)
self.domain = self.dom = dom
self.symbols = self.gens = gens
def new(self, element):
return self.dtype(element, self.dom, len(self.gens) - 1, ring=self)
def __str__(self):
return str(self.dom) + '(' + ','.join(map(str, self.gens)) + ')'
def __hash__(self):
return hash((self.__class__.__name__, self.dtype, self.dom, self.gens))
def __eq__(self, other):
"""Returns ``True`` if two domains are equivalent. """
return isinstance(other, FractionField) and \
self.dtype == other.dtype and self.dom == other.dom and self.gens == other.gens
def to_sympy(self, a):
"""Convert ``a`` to a SymPy object. """
return (basic_from_dict(a.numer().to_sympy_dict(), *self.gens) /
basic_from_dict(a.denom().to_sympy_dict(), *self.gens))
def from_sympy(self, a):
"""Convert SymPy's expression to ``dtype``. """
p, q = a.as_numer_denom()
num, _ = dict_from_basic(p, gens=self.gens)
den, _ = dict_from_basic(q, gens=self.gens)
for k, v in num.items():
num[k] = self.dom.from_sympy(v)
for k, v in den.items():
den[k] = self.dom.from_sympy(v)
return self((num, den)).cancel()
def from_ZZ_python(K1, a, K0):
"""Convert a Python ``int`` object to ``dtype``. """
return K1(K1.dom.convert(a, K0))
def from_QQ_python(K1, a, K0):
"""Convert a Python ``Fraction`` object to ``dtype``. """
return K1(K1.dom.convert(a, K0))
def from_ZZ_gmpy(K1, a, K0):
"""Convert a GMPY ``mpz`` object to ``dtype``. """
return K1(K1.dom.convert(a, K0))
def from_QQ_gmpy(K1, a, K0):
"""Convert a GMPY ``mpq`` object to ``dtype``. """
return K1(K1.dom.convert(a, K0))
def from_RealField(K1, a, K0):
"""Convert a mpmath ``mpf`` object to ``dtype``. """
return K1(K1.dom.convert(a, K0))
def from_GlobalPolynomialRing(K1, a, K0):
"""Convert a ``DMF`` object to ``dtype``. """
if K1.gens == K0.gens:
if K1.dom == K0.dom:
return K1(a.rep)
else:
return K1(a.convert(K1.dom).rep)
else:
monoms, coeffs = _dict_reorder(a.to_dict(), K0.gens, K1.gens)
if K1.dom != K0.dom:
coeffs = [ K1.dom.convert(c, K0.dom) for c in coeffs ]
return K1(dict(zip(monoms, coeffs)))
def from_FractionField(K1, a, K0):
"""
Convert a fraction field element to another fraction field.
Examples
========
>>> from sympy.polys.polyclasses import DMF
>>> from sympy.polys.domains import ZZ, QQ
>>> from sympy.abc import x
>>> f = DMF(([ZZ(1), ZZ(2)], [ZZ(1), ZZ(1)]), ZZ)
>>> QQx = QQ.old_frac_field(x)
>>> ZZx = ZZ.old_frac_field(x)
>>> QQx.from_FractionField(f, ZZx)
(x + 2)/(x + 1)
"""
if K1.gens == K0.gens:
if K1.dom == K0.dom:
return a
else:
return K1((a.numer().convert(K1.dom).rep,
a.denom().convert(K1.dom).rep))
elif set(K0.gens).issubset(K1.gens):
nmonoms, ncoeffs = _dict_reorder(
a.numer().to_dict(), K0.gens, K1.gens)
dmonoms, dcoeffs = _dict_reorder(
a.denom().to_dict(), K0.gens, K1.gens)
if K1.dom != K0.dom:
ncoeffs = [ K1.dom.convert(c, K0.dom) for c in ncoeffs ]
dcoeffs = [ K1.dom.convert(c, K0.dom) for c in dcoeffs ]
return K1((dict(zip(nmonoms, ncoeffs)), dict(zip(dmonoms, dcoeffs))))
def get_ring(self):
"""Returns a ring associated with ``self``. """
from sympy.polys.domains import PolynomialRing
return PolynomialRing(self.dom, *self.gens)
def poly_ring(self, *gens):
"""Returns a polynomial ring, i.e. `K[X]`. """
raise NotImplementedError('nested domains not allowed')
def frac_field(self, *gens):
"""Returns a fraction field, i.e. `K(X)`. """
raise NotImplementedError('nested domains not allowed')
def is_positive(self, a):
"""Returns True if ``a`` is positive. """
return self.dom.is_positive(a.numer().LC())
def is_negative(self, a):
"""Returns True if ``a`` is negative. """
return self.dom.is_negative(a.numer().LC())
def is_nonpositive(self, a):
"""Returns True if ``a`` is non-positive. """
return self.dom.is_nonpositive(a.numer().LC())
def is_nonnegative(self, a):
"""Returns True if ``a`` is non-negative. """
return self.dom.is_nonnegative(a.numer().LC())
def numer(self, a):
"""Returns numerator of ``a``. """
return a.numer()
def denom(self, a):
"""Returns denominator of ``a``. """
return a.denom()
def factorial(self, a):
"""Returns factorial of ``a``. """
return self.dtype(self.dom.factorial(a))
| 6,097 | 31.962162 | 91 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/domains/compositedomain.py
|
"""Implementation of :class:`CompositeDomain` class. """
from __future__ import print_function, division
from sympy.polys.domains.domain import Domain
from sympy.polys.polyerrors import GeneratorsError
from sympy.utilities import public
@public
class CompositeDomain(Domain):
"""Base class for composite domains, e.g. ZZ[x], ZZ(X). """
is_Composite = True
gens, ngens, symbols, domain = [None]*4
def inject(self, *symbols):
"""Inject generators into this domain. """
if not (set(self.symbols) & set(symbols)):
return self.__class__(self.domain, self.symbols + symbols, self.order)
else:
raise GeneratorsError("common generators in %s and %s" % (self.symbols, symbols))
| 740 | 29.875 | 93 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/domains/fractionfield.py
|
"""Implementation of :class:`FractionField` class. """
from __future__ import print_function, division
from sympy.polys.domains.field import Field
from sympy.polys.domains.compositedomain import CompositeDomain
from sympy.polys.polyerrors import CoercionFailed, GeneratorsError
from sympy.utilities import public
@public
class FractionField(Field, CompositeDomain):
"""A class for representing multivariate rational function fields. """
is_FractionField = is_Frac = True
has_assoc_Ring = True
has_assoc_Field = True
def __init__(self, domain_or_field, symbols=None, order=None):
from sympy.polys.fields import FracField
if isinstance(domain_or_field, FracField) and symbols is None and order is None:
field = domain_or_field
else:
field = FracField(symbols, domain_or_field, order)
self.field = field
self.dtype = field.dtype
self.gens = field.gens
self.ngens = field.ngens
self.symbols = field.symbols
self.domain = field.domain
# TODO: remove this
self.dom = self.domain
def new(self, element):
return self.field.field_new(element)
@property
def zero(self):
return self.field.zero
@property
def one(self):
return self.field.one
@property
def order(self):
return self.field.order
def __str__(self):
return str(self.domain) + '(' + ','.join(map(str, self.symbols)) + ')'
def __hash__(self):
return hash((self.__class__.__name__, self.dtype.field, self.domain, self.symbols))
def __eq__(self, other):
"""Returns `True` if two domains are equivalent. """
return isinstance(other, FractionField) and \
(self.dtype.field, self.domain, self.symbols) ==\
(other.dtype.field, other.domain, other.symbols)
def to_sympy(self, a):
"""Convert `a` to a SymPy object. """
return a.as_expr()
def from_sympy(self, a):
"""Convert SymPy's expression to `dtype`. """
return self.field.from_expr(a)
def from_ZZ_python(K1, a, K0):
"""Convert a Python `int` object to `dtype`. """
return K1(K1.domain.convert(a, K0))
def from_QQ_python(K1, a, K0):
"""Convert a Python `Fraction` object to `dtype`. """
return K1(K1.domain.convert(a, K0))
def from_ZZ_gmpy(K1, a, K0):
"""Convert a GMPY `mpz` object to `dtype`. """
return K1(K1.domain.convert(a, K0))
def from_QQ_gmpy(K1, a, K0):
"""Convert a GMPY `mpq` object to `dtype`. """
return K1(K1.domain.convert(a, K0))
def from_RealField(K1, a, K0):
"""Convert a mpmath `mpf` object to `dtype`. """
return K1(K1.domain.convert(a, K0))
def from_AlgebraicField(K1, a, K0):
"""Convert an algebraic number to ``dtype``. """
if K1.domain == K0:
return K1.new(a)
def from_PolynomialRing(K1, a, K0):
"""Convert a polynomial to ``dtype``. """
try:
return K1.new(a)
except (CoercionFailed, GeneratorsError):
return None
def from_FractionField(K1, a, K0):
"""Convert a rational function to ``dtype``. """
try:
return a.set_field(K1.field)
except (CoercionFailed, GeneratorsError):
return None
def get_ring(self):
"""Returns a field associated with `self`. """
return self.field.to_ring().to_domain()
def is_positive(self, a):
"""Returns True if `LC(a)` is positive. """
return self.domain.is_positive(a.numer.LC)
def is_negative(self, a):
"""Returns True if `LC(a)` is negative. """
return self.domain.is_negative(a.numer.LC)
def is_nonpositive(self, a):
"""Returns True if `LC(a)` is non-positive. """
return self.domain.is_nonpositive(a.numer.LC)
def is_nonnegative(self, a):
"""Returns True if `LC(a)` is non-negative. """
return self.domain.is_nonnegative(a.numer.LC)
def numer(self, a):
"""Returns numerator of ``a``. """
return a.numer
def denom(self, a):
"""Returns denominator of ``a``. """
return a.denom
def factorial(self, a):
"""Returns factorial of `a`. """
return self.dtype(self.domain.factorial(a))
| 4,359 | 29.277778 | 91 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/domains/simpledomain.py
|
"""Implementation of :class:`SimpleDomain` class. """
from __future__ import print_function, division
from sympy.polys.domains.domain import Domain
from sympy.utilities import public
@public
class SimpleDomain(Domain):
"""Base class for simple domains, e.g. ZZ, QQ. """
is_Simple = True
def inject(self, *gens):
"""Inject generators into this domain. """
return self.poly_ring(*gens)
| 417 | 23.588235 | 54 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/domains/pythonintegerring.py
|
"""Implementaton of :class:`PythonIntegerRing` class. """
from __future__ import print_function, division
from sympy.polys.domains.integerring import IntegerRing
from sympy.polys.domains.groundtypes import (
PythonInteger, SymPyInteger, python_sqrt,
python_factorial, python_gcdex, python_gcd, python_lcm,
)
from sympy.polys.polyerrors import CoercionFailed
from sympy.utilities import public
@public
class PythonIntegerRing(IntegerRing):
"""Integer ring based on Python's ``int`` type. """
dtype = PythonInteger
zero = dtype(0)
one = dtype(1)
alias = 'ZZ_python'
def __init__(self):
"""Allow instantiation of this domain. """
def to_sympy(self, a):
"""Convert ``a`` to a SymPy object. """
return SymPyInteger(a)
def from_sympy(self, a):
"""Convert SymPy's Integer to ``dtype``. """
if a.is_Integer:
return PythonInteger(a.p)
elif a.is_Float and int(a) == a:
return PythonInteger(int(a))
else:
raise CoercionFailed("expected an integer, got %s" % a)
def from_FF_python(K1, a, K0):
"""Convert ``ModularInteger(int)`` to Python's ``int``. """
return a.to_int()
def from_ZZ_python(K1, a, K0):
"""Convert Python's ``int`` to Python's ``int``. """
return a
def from_QQ_python(K1, a, K0):
"""Convert Python's ``Fraction`` to Python's ``int``. """
if a.denominator == 1:
return a.numerator
def from_FF_gmpy(K1, a, K0):
"""Convert ``ModularInteger(mpz)`` to Python's ``int``. """
return PythonInteger(a.to_int())
def from_ZZ_gmpy(K1, a, K0):
"""Convert GMPY's ``mpz`` to Python's ``int``. """
return PythonInteger(a)
def from_QQ_gmpy(K1, a, K0):
"""Convert GMPY's ``mpq`` to Python's ``int``. """
if a.denom() == 1:
return PythonInteger(a.numer())
def from_RealField(K1, a, K0):
"""Convert mpmath's ``mpf`` to Python's ``int``. """
p, q = K0.to_rational(a)
if q == 1:
return PythonInteger(p)
def gcdex(self, a, b):
"""Compute extended GCD of ``a`` and ``b``. """
return python_gcdex(a, b)
def gcd(self, a, b):
"""Compute GCD of ``a`` and ``b``. """
return python_gcd(a, b)
def lcm(self, a, b):
"""Compute LCM of ``a`` and ``b``. """
return python_lcm(a, b)
def sqrt(self, a):
"""Compute square root of ``a``. """
return python_sqrt(a)
def factorial(self, a):
"""Compute factorial of ``a``. """
return python_factorial(a)
| 2,650 | 28.131868 | 67 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/domains/mpelements.py
|
"""Real and complex elements. """
from __future__ import print_function, division
from sympy.polys.domains.domainelement import DomainElement
from mpmath.ctx_mp_python import PythonMPContext, _mpf, _mpc, _constant
from mpmath.libmp import (MPZ_ONE, fzero, fone, finf, fninf, fnan,
round_nearest, mpf_mul, mpf_abs, mpf_lt, mpc_abs, repr_dps, int_types,
from_int, from_float, from_str, to_rational)
from mpmath.rational import mpq
from sympy.utilities import public
@public
class RealElement(_mpf, DomainElement):
"""An element of a real domain. """
__slots__ = ['__mpf__']
def _set_mpf(self, val):
self.__mpf__ = val
_mpf_ = property(lambda self: self.__mpf__, _set_mpf)
def parent(self):
return self.context._parent
@public
class ComplexElement(_mpc, DomainElement):
"""An element of a complex domain. """
__slots__ = ['__mpc__']
def _set_mpc(self, val):
self.__mpc__ = val
_mpc_ = property(lambda self: self.__mpc__, _set_mpc)
def parent(self):
return self.context._parent
new = object.__new__
@public
class MPContext(PythonMPContext):
def __init__(ctx, prec=53, dps=None, tol=None):
ctx._prec_rounding = [prec, round_nearest]
if dps is None:
ctx._set_prec(prec)
else:
ctx._set_dps(dps)
ctx.mpf = RealElement
ctx.mpc = ComplexElement
ctx.mpf._ctxdata = [ctx.mpf, new, ctx._prec_rounding]
ctx.mpc._ctxdata = [ctx.mpc, new, ctx._prec_rounding]
ctx.mpf.context = ctx
ctx.mpc.context = ctx
ctx.constant = _constant
ctx.constant._ctxdata = [ctx.mpf, new, ctx._prec_rounding]
ctx.constant.context = ctx
ctx.types = [ctx.mpf, ctx.mpc, ctx.constant]
ctx.trap_complex = True
ctx.pretty = True
if tol is None:
ctx.tol = ctx._make_tol()
elif tol is False:
ctx.tol = fzero
else:
ctx.tol = ctx._convert_tol(tol)
ctx.tolerance = ctx.make_mpf(ctx.tol)
if not ctx.tolerance:
ctx.max_denom = 1000000
else:
ctx.max_denom = int(1/ctx.tolerance)
ctx.zero = ctx.make_mpf(fzero)
ctx.one = ctx.make_mpf(fone)
ctx.j = ctx.make_mpc((fzero, fone))
ctx.inf = ctx.make_mpf(finf)
ctx.ninf = ctx.make_mpf(fninf)
ctx.nan = ctx.make_mpf(fnan)
def _make_tol(ctx):
hundred = (0, 25, 2, 5)
eps = (0, MPZ_ONE, 1-ctx.prec, 1)
return mpf_mul(hundred, eps)
def make_tol(ctx):
return ctx.make_mpf(ctx._make_tol())
def _convert_tol(ctx, tol):
if isinstance(tol, int_types):
return from_int(tol)
if isinstance(tol, float):
return from_float(tol)
if hasattr(tol, "_mpf_"):
return tol._mpf_
prec, rounding = ctx._prec_rounding
if isinstance(tol, basestring):
return from_str(tol, prec, rounding)
raise ValueError("expected a real number, got %s" % tol)
def _convert_fallback(ctx, x, strings):
raise TypeError("cannot create mpf from " + repr(x))
@property
def _repr_digits(ctx):
return repr_dps(ctx._prec)
@property
def _str_digits(ctx):
return ctx._dps
def to_rational(ctx, s, limit=True):
p, q = to_rational(s._mpf_)
if not limit or q <= ctx.max_denom:
return p, q
p0, q0, p1, q1 = 0, 1, 1, 0
n, d = p, q
while True:
a = n//d
q2 = q0 + a*q1
if q2 > ctx.max_denom:
break
p0, q0, p1, q1 = p1, q1, p0 + a*p1, q2
n, d = d, n - a*d
k = (ctx.max_denom - q0)//q1
number = mpq(p, q)
bound1 = mpq(p0 + k*p1, q0 + k*q1)
bound2 = mpq(p1, q1)
if not bound2 or not bound1:
return p, q
elif abs(bound2 - number) <= abs(bound1 - number):
return bound2._mpq_
else:
return bound1._mpq_
def almosteq(ctx, s, t, rel_eps=None, abs_eps=None):
t = ctx.convert(t)
if abs_eps is None and rel_eps is None:
rel_eps = abs_eps = ctx.tolerance or ctx.make_tol()
if abs_eps is None:
abs_eps = ctx.convert(rel_eps)
elif rel_eps is None:
rel_eps = ctx.convert(abs_eps)
diff = abs(s-t)
if diff <= abs_eps:
return True
abss = abs(s)
abst = abs(t)
if abss < abst:
err = diff/abst
else:
err = diff/abss
return err <= rel_eps
| 4,642 | 26.311765 | 74 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/domains/field.py
|
"""Implementation of :class:`Field` class. """
from __future__ import print_function, division
from sympy.polys.domains.ring import Ring
from sympy.polys.polyerrors import NotReversible, DomainError
from sympy.utilities import public
@public
class Field(Ring):
"""Represents a field domain. """
is_Field = True
is_PID = True
def get_ring(self):
"""Returns a ring associated with ``self``. """
raise DomainError('there is no ring associated with %s' % self)
def get_field(self):
"""Returns a field associated with ``self``. """
return self
def exquo(self, a, b):
"""Exact quotient of ``a`` and ``b``, implies ``__div__``. """
return a / b
def quo(self, a, b):
"""Quotient of ``a`` and ``b``, implies ``__div__``. """
return a / b
def rem(self, a, b):
"""Remainder of ``a`` and ``b``, implies nothing. """
return self.zero
def div(self, a, b):
"""Division of ``a`` and ``b``, implies ``__div__``. """
return a / b, self.zero
def gcd(self, a, b):
"""
Returns GCD of ``a`` and ``b``.
This definition of GCD over fields allows to clear denominators
in `primitive()`.
>>> from sympy.polys.domains import QQ
>>> from sympy import S, gcd, primitive
>>> from sympy.abc import x
>>> QQ.gcd(QQ(2, 3), QQ(4, 9))
2/9
>>> gcd(S(2)/3, S(4)/9)
2/9
>>> primitive(2*x/3 + S(4)/9)
(2/9, 3*x + 2)
"""
try:
ring = self.get_ring()
except DomainError:
return self.one
p = ring.gcd(self.numer(a), self.numer(b))
q = ring.lcm(self.denom(a), self.denom(b))
return self.convert(p, ring)/q
def lcm(self, a, b):
"""
Returns LCM of ``a`` and ``b``.
>>> from sympy.polys.domains import QQ
>>> from sympy import S, lcm
>>> QQ.lcm(QQ(2, 3), QQ(4, 9))
4/3
>>> lcm(S(2)/3, S(4)/9)
4/3
"""
try:
ring = self.get_ring()
except DomainError:
return a*b
p = ring.lcm(self.numer(a), self.numer(b))
q = ring.gcd(self.denom(a), self.denom(b))
return self.convert(p, ring)/q
def revert(self, a):
"""Returns ``a**(-1)`` if possible. """
if a:
return 1/a
else:
raise NotReversible('zero is not reversible')
| 2,491 | 24.171717 | 71 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/domains/complexfield.py
|
"""Implementation of :class:`ComplexField` class. """
from __future__ import print_function, division
from sympy.core.numbers import Float, I
from sympy.utilities import public
from sympy.polys.domains.field import Field
from sympy.polys.domains.simpledomain import SimpleDomain
from sympy.polys.domains.characteristiczero import CharacteristicZero
from sympy.polys.domains.mpelements import MPContext
from sympy.polys.polyerrors import DomainError, CoercionFailed
@public
class ComplexField(Field, CharacteristicZero, SimpleDomain):
"""Complex numbers up to the given precision. """
rep = 'CC'
is_ComplexField = is_CC = True
is_Exact = False
is_Numerical = True
has_assoc_Ring = False
has_assoc_Field = True
_default_precision = 53
@property
def has_default_precision(self):
return self.precision == self._default_precision
@property
def precision(self):
return self._context.prec
@property
def dps(self):
return self._context.dps
@property
def tolerance(self):
return self._context.tolerance
def __init__(self, prec=_default_precision, dps=None, tol=None):
context = MPContext(prec, dps, tol)
context._parent = self
self._context = context
self.dtype = context.mpc
self.zero = self.dtype(0)
self.one = self.dtype(1)
def __eq__(self, other):
return (isinstance(other, ComplexField)
and self.precision == other.precision
and self.tolerance == other.tolerance)
def __hash__(self):
return hash((self.__class__.__name__, self.dtype, self.precision, self.tolerance))
def to_sympy(self, element):
"""Convert ``element`` to SymPy number. """
return Float(element.real, self.dps) + I*Float(element.imag, self.dps)
def from_sympy(self, expr):
"""Convert SymPy's number to ``dtype``. """
number = expr.evalf(n=self.dps)
real, imag = number.as_real_imag()
if real.is_Number and imag.is_Number:
return self.dtype(real, imag)
else:
raise CoercionFailed("expected complex number, got %s" % expr)
def from_ZZ_python(self, element, base):
return self.dtype(element)
def from_QQ_python(self, element, base):
return self.dtype(element.numerator) / element.denominator
def from_ZZ_gmpy(self, element, base):
return self.dtype(int(element))
def from_QQ_gmpy(self, element, base):
return self.dtype(int(element.numerator)) / int(element.denominator)
def from_RealField(self, element, base):
return self.dtype(element)
def from_ComplexField(self, element, base):
if self == base:
return element
else:
return self.dtype(element)
def get_ring(self):
"""Returns a ring associated with ``self``. """
raise DomainError("there is no ring associated with %s" % self)
def get_exact(self):
"""Returns an exact domain associated with ``self``. """
raise DomainError("there is no exact domain associated with %s" % self)
def gcd(self, a, b):
"""Returns GCD of ``a`` and ``b``. """
return self.one
def lcm(self, a, b):
"""Returns LCM of ``a`` and ``b``. """
return a*b
def almosteq(self, a, b, tolerance=None):
"""Check if ``a`` and ``b`` are almost equal. """
return self._context.almosteq(a, b, tolerance)
| 3,492 | 28.854701 | 90 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/domains/pythonrationalfield.py
|
"""Implementation of :class:`PythonRationalField` class. """
from __future__ import print_function, division
from sympy.polys.domains.rationalfield import RationalField
from sympy.polys.domains.groundtypes import PythonInteger, PythonRational, SymPyRational
from sympy.polys.polyerrors import CoercionFailed
from sympy.utilities import public
@public
class PythonRationalField(RationalField):
"""Rational field based on Python rational number type. """
dtype = PythonRational
zero = dtype(0)
one = dtype(1)
alias = 'QQ_python'
def __init__(self):
pass
def get_ring(self):
"""Returns ring associated with ``self``. """
from sympy.polys.domains import PythonIntegerRing
return PythonIntegerRing()
def to_sympy(self, a):
"""Convert `a` to a SymPy object. """
return SymPyRational(a.numerator, a.denominator)
def from_sympy(self, a):
"""Convert SymPy's Rational to `dtype`. """
if a.is_Rational:
return PythonRational(a.p, a.q)
elif a.is_Float:
from sympy.polys.domains import RR
p, q = RR.to_rational(a)
return PythonRational(int(p), int(q))
else:
raise CoercionFailed("expected `Rational` object, got %s" % a)
def from_ZZ_python(K1, a, K0):
"""Convert a Python `int` object to `dtype`. """
return PythonRational(a)
def from_QQ_python(K1, a, K0):
"""Convert a Python `Fraction` object to `dtype`. """
return a
def from_ZZ_gmpy(K1, a, K0):
"""Convert a GMPY `mpz` object to `dtype`. """
return PythonRational(PythonInteger(a))
def from_QQ_gmpy(K1, a, K0):
"""Convert a GMPY `mpq` object to `dtype`. """
return PythonRational(PythonInteger(a.numer()),
PythonInteger(a.denom()))
def from_RealField(K1, a, K0):
"""Convert a mpmath `mpf` object to `dtype`. """
p, q = K0.to_rational(a)
return PythonRational(int(p), int(q))
def numer(self, a):
"""Returns numerator of `a`. """
return a.numerator
def denom(self, a):
"""Returns denominator of `a`. """
return a.denominator
| 2,234 | 30.041667 | 88 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/domains/groundtypes.py
|
"""Ground types for various mathematical domains in SymPy. """
from __future__ import print_function, division
__all__ = []
from sympy.core.compatibility import builtins, HAS_GMPY
PythonInteger = builtins.int
PythonReal = builtins.float
PythonComplex = builtins.complex
from .pythonrational import PythonRational
from sympy.core.numbers import (
igcdex as python_gcdex,
igcd2 as python_gcd,
ilcm as python_lcm,
)
from sympy import (
Float as SymPyReal,
Integer as SymPyInteger,
Rational as SymPyRational,
)
if HAS_GMPY == 1:
from gmpy import (
mpz as GMPYInteger,
mpq as GMPYRational,
fac as gmpy_factorial,
numer as gmpy_numer,
denom as gmpy_denom,
gcdext as gmpy_gcdex,
gcd as gmpy_gcd,
lcm as gmpy_lcm,
sqrt as gmpy_sqrt,
qdiv as gmpy_qdiv,
)
elif HAS_GMPY == 2:
from gmpy2 import (
mpz as GMPYInteger,
mpq as GMPYRational,
fac as gmpy_factorial,
numer as gmpy_numer,
denom as gmpy_denom,
gcdext as gmpy_gcdex,
gcd as gmpy_gcd,
lcm as gmpy_lcm,
isqrt as gmpy_sqrt,
qdiv as gmpy_qdiv,
)
else:
class GMPYInteger(object):
def __init__(self, obj):
pass
class GMPYRational(object):
def __init__(self, obj):
pass
gmpy_factorial = None
gmpy_numer = None
gmpy_denom = None
gmpy_gcdex = None
gmpy_gcd = None
gmpy_lcm = None
gmpy_sqrt = None
gmpy_qdiv = None
import mpmath.libmp as mlib
def python_sqrt(n):
return int(mlib.isqrt(n))
def python_factorial(n):
return int(mlib.ifac(n))
| 1,680 | 19.753086 | 62 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/domains/ring.py
|
"""Implementation of :class:`Ring` class. """
from __future__ import print_function, division
from sympy.polys.domains.domain import Domain
from sympy.polys.polyerrors import ExactQuotientFailed, NotInvertible, NotReversible
from sympy.utilities import public
@public
class Ring(Domain):
"""Represents a ring domain. """
is_Ring = True
def get_ring(self):
"""Returns a ring associated with ``self``. """
return self
def exquo(self, a, b):
"""Exact quotient of ``a`` and ``b``, implies ``__floordiv__``. """
if a % b:
raise ExactQuotientFailed(a, b, self)
else:
return a // b
def quo(self, a, b):
"""Quotient of ``a`` and ``b``, implies ``__floordiv__``. """
return a // b
def rem(self, a, b):
"""Remainder of ``a`` and ``b``, implies ``__mod__``. """
return a % b
def div(self, a, b):
"""Division of ``a`` and ``b``, implies ``__divmod__``. """
return divmod(a, b)
def invert(self, a, b):
"""Returns inversion of ``a mod b``. """
s, t, h = self.gcdex(a, b)
if self.is_one(h):
return s % b
else:
raise NotInvertible("zero divisor")
def revert(self, a):
"""Returns ``a**(-1)`` if possible. """
if self.is_one(a):
return a
else:
raise NotReversible('only unity is reversible in a ring')
def is_unit(self, a):
try:
self.revert(a)
return True
except NotReversible:
return False
def numer(self, a):
"""Returns numerator of ``a``. """
return a
def denom(self, a):
"""Returns denominator of `a`. """
return self.one
def free_module(self, rank):
"""
Generate a free module of rank ``rank`` over self.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> QQ.old_poly_ring(x).free_module(2)
QQ[x]**2
"""
raise NotImplementedError
def ideal(self, *gens):
"""
Generate an ideal of ``self``.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> QQ.old_poly_ring(x).ideal(x**2)
<x**2>
"""
from sympy.polys.agca.ideals import ModuleImplementedIdeal
return ModuleImplementedIdeal(self, self.free_module(1).submodule(
*[[x] for x in gens]))
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 __div__(self, e):
return self.quotient_ring(e)
__truediv__ = __div__
| 3,287 | 25.95082 | 84 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/domains/gmpyfinitefield.py
|
"""Implementation of :class:`GMPYFiniteField` class. """
from __future__ import print_function, division
from sympy.polys.domains.finitefield import FiniteField
from sympy.polys.domains.gmpyintegerring import GMPYIntegerRing
from sympy.utilities import public
@public
class GMPYFiniteField(FiniteField):
"""Finite field based on GMPY integers. """
alias = 'FF_gmpy'
def __init__(self, mod, symmetric=True):
return super(GMPYFiniteField, self).__init__(mod, GMPYIntegerRing(), symmetric)
| 513 | 27.555556 | 87 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/domains/rationalfield.py
|
"""Implementation of :class:`RationalField` class. """
from __future__ import print_function, division
from sympy.polys.domains.field import Field
from sympy.polys.domains.simpledomain import SimpleDomain
from sympy.polys.domains.characteristiczero import CharacteristicZero
from sympy.utilities import public
@public
class RationalField(Field, CharacteristicZero, SimpleDomain):
"""General class for rational fields. """
rep = 'QQ'
is_RationalField = is_QQ = True
is_Numerical = True
has_assoc_Ring = True
has_assoc_Field = True
def algebraic_field(self, *extension):
r"""Returns an algebraic field, i.e. `\mathbb{Q}(\alpha, \ldots)`. """
from sympy.polys.domains import AlgebraicField
return AlgebraicField(self, *extension)
def from_AlgebraicField(K1, a, K0):
"""Convert a ``ANP`` object to ``dtype``. """
if a.is_ground:
return K1.convert(a.LC(), K0.dom)
| 952 | 28.78125 | 78 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/domains/characteristiczero.py
|
"""Implementaton of :class:`CharacteristicZero` class. """
from __future__ import print_function, division
from sympy.polys.domains.domain import Domain
from sympy.utilities import public
@public
class CharacteristicZero(Domain):
"""Domain that has infinite number of elements. """
has_CharacteristicZero = True
def characteristic(self):
"""Return the characteristic of this domain. """
return 0
| 429 | 24.294118 | 58 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/domains/quotientring.py
|
"""Implementation of :class:`QuotientRing` class."""
from __future__ import print_function, division
from sympy.polys.domains.ring import Ring
from sympy.polys.polyerrors import NotReversible, CoercionFailed
from sympy.polys.agca.modules import FreeModuleQuotientRing
from sympy.utilities import public
# TODO
# - successive quotients (when quotient ideals are implemented)
# - poly rings over quotients?
# - division by non-units in integral domains?
@public
class QuotientRingElement(object):
"""
Class representing elements of (commutative) quotient rings.
Attributes:
- ring - containing ring
- data - element of ring.ring (i.e. base ring) representing self
"""
def __init__(self, ring, data):
self.ring = ring
self.data = data
def __str__(self):
from sympy import sstr
return sstr(self.data) + " + " + str(self.ring.base_ideal)
def __add__(self, om):
if not isinstance(om, self.__class__) or om.ring != self.ring:
try:
om = self.ring.convert(om)
except (NotImplementedError, CoercionFailed):
return NotImplemented
return self.ring(self.data + om.data)
__radd__ = __add__
def __neg__(self):
return self.ring(self.data*self.ring.ring.convert(-1))
def __sub__(self, om):
return self.__add__(-om)
def __rsub__(self, om):
return (-self).__add__(om)
def __mul__(self, o):
if not isinstance(o, self.__class__):
try:
o = self.ring.convert(o)
except (NotImplementedError, CoercionFailed):
return NotImplemented
return self.ring(self.data*o.data)
__rmul__ = __mul__
def __rdiv__(self, o):
return self.ring.revert(self)*o
__rtruediv__ = __rdiv__
def __div__(self, o):
if not isinstance(o, self.__class__):
try:
o = self.ring.convert(o)
except (NotImplementedError, CoercionFailed):
return NotImplemented
return self.ring.revert(o)*self
__truediv__ = __div__
def __pow__(self, oth):
return self.ring(self.data**oth)
def __eq__(self, om):
if not isinstance(om, self.__class__) or om.ring != self.ring:
return False
return self.ring.is_zero(self - om)
def __ne__(self, om):
return not self.__eq__(om)
class QuotientRing(Ring):
"""
Class representing (commutative) quotient rings.
You should not usually instantiate this by hand, instead use the constructor
from the base ring in the construction.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> I = QQ.old_poly_ring(x).ideal(x**3 + 1)
>>> QQ.old_poly_ring(x).quotient_ring(I)
QQ[x]/<x**3 + 1>
Shorter versions are possible:
>>> QQ.old_poly_ring(x)/I
QQ[x]/<x**3 + 1>
>>> QQ.old_poly_ring(x)/[x**3 + 1]
QQ[x]/<x**3 + 1>
Attributes:
- ring - the base ring
- base_ideal - the ideal used to form the quotient
"""
has_assoc_Ring = True
has_assoc_Field = False
dtype = QuotientRingElement
def __init__(self, ring, ideal):
if not ideal.ring == ring:
raise ValueError('Ideal must belong to %s, got %s' % (ring, ideal))
self.ring = ring
self.base_ideal = ideal
self.zero = self(self.ring.zero)
self.one = self(self.ring.one)
def __str__(self):
return str(self.ring) + "/" + str(self.base_ideal)
def __hash__(self):
return hash((self.__class__.__name__, self.dtype, self.ring, self.base_ideal))
def new(self, a):
"""Construct an element of `self` domain from `a`. """
if not isinstance(a, self.ring.dtype):
a = self.ring(a)
# TODO optionally disable reduction?
return self.dtype(self, self.base_ideal.reduce_element(a))
def __eq__(self, other):
"""Returns `True` if two domains are equivalent. """
return isinstance(other, QuotientRing) and \
self.ring == other.ring and self.base_ideal == other.base_ideal
def from_ZZ_python(K1, a, K0):
"""Convert a Python `int` object to `dtype`. """
return K1(K1.ring.convert(a, K0))
from_QQ_python = from_ZZ_python
from_ZZ_gmpy = from_ZZ_python
from_QQ_gmpy = from_ZZ_python
from_RealField = from_ZZ_python
from_GlobalPolynomialRing = from_ZZ_python
from_FractionField = from_ZZ_python
def from_sympy(self, a):
return self(self.ring.from_sympy(a))
def to_sympy(self, a):
return self.ring.to_sympy(a.data)
def from_QuotientRing(self, a, K0):
if K0 == self:
return a
def poly_ring(self, *gens):
"""Returns a polynomial ring, i.e. `K[X]`. """
raise NotImplementedError('nested domains not allowed')
def frac_field(self, *gens):
"""Returns a fraction field, i.e. `K(X)`. """
raise NotImplementedError('nested domains not allowed')
def revert(self, a):
"""
Compute a**(-1), if possible.
"""
I = self.ring.ideal(a.data) + self.base_ideal
try:
return self(I.in_terms_of_generators(1)[0])
except ValueError: # 1 not in I
raise NotReversible('%s not a unit in %r' % (a, self))
def is_zero(self, a):
return self.base_ideal.contains(a.data)
def free_module(self, rank):
"""
Generate a free module of rank ``rank`` over ``self``.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> (QQ.old_poly_ring(x)/[x**2 + 1]).free_module(2)
(QQ[x]/<x**2 + 1>)**2
"""
return FreeModuleQuotientRing(self, rank)
| 5,763 | 27.82 | 86 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/domains/polynomialring.py
|
"""Implementation of :class:`PolynomialRing` class. """
from __future__ import print_function, division
from sympy.polys.domains.ring import Ring
from sympy.polys.domains.compositedomain import CompositeDomain
from sympy.polys.polyerrors import CoercionFailed, GeneratorsError
from sympy.utilities import public
@public
class PolynomialRing(Ring, CompositeDomain):
"""A class for representing multivariate polynomial rings. """
is_PolynomialRing = is_Poly = True
has_assoc_Ring = True
has_assoc_Field = True
def __init__(self, domain_or_ring, symbols=None, order=None):
from sympy.polys.rings import PolyRing
if isinstance(domain_or_ring, PolyRing) and symbols is None and order is None:
ring = domain_or_ring
else:
ring = PolyRing(symbols, domain_or_ring, order)
self.ring = ring
self.dtype = ring.dtype
self.gens = ring.gens
self.ngens = ring.ngens
self.symbols = ring.symbols
self.domain = ring.domain
if symbols:
if ring.domain.is_Field and ring.domain.is_Exact and len(symbols)==1:
self.is_PID = True
# TODO: remove this
self.dom = self.domain
def new(self, element):
return self.ring.ring_new(element)
@property
def zero(self):
return self.ring.zero
@property
def one(self):
return self.ring.one
@property
def order(self):
return self.ring.order
def __str__(self):
return str(self.domain) + '[' + ','.join(map(str, self.symbols)) + ']'
def __hash__(self):
return hash((self.__class__.__name__, self.dtype.ring, self.domain, self.symbols))
def __eq__(self, other):
"""Returns `True` if two domains are equivalent. """
return isinstance(other, PolynomialRing) and \
(self.dtype.ring, self.domain, self.symbols) == \
(other.dtype.ring, other.domain, other.symbols)
def to_sympy(self, a):
"""Convert `a` to a SymPy object. """
return a.as_expr()
def from_sympy(self, a):
"""Convert SymPy's expression to `dtype`. """
return self.ring.from_expr(a)
def from_ZZ_python(K1, a, K0):
"""Convert a Python `int` object to `dtype`. """
return K1(K1.domain.convert(a, K0))
def from_QQ_python(K1, a, K0):
"""Convert a Python `Fraction` object to `dtype`. """
return K1(K1.domain.convert(a, K0))
def from_ZZ_gmpy(K1, a, K0):
"""Convert a GMPY `mpz` object to `dtype`. """
return K1(K1.domain.convert(a, K0))
def from_QQ_gmpy(K1, a, K0):
"""Convert a GMPY `mpq` object to `dtype`. """
return K1(K1.domain.convert(a, K0))
def from_RealField(K1, a, K0):
"""Convert a mpmath `mpf` object to `dtype`. """
return K1(K1.domain.convert(a, K0))
def from_AlgebraicField(K1, a, K0):
"""Convert an algebraic number to ``dtype``. """
if K1.domain == K0:
return K1.new(a)
def from_PolynomialRing(K1, a, K0):
"""Convert a polynomial to ``dtype``. """
try:
return a.set_ring(K1.ring)
except (CoercionFailed, GeneratorsError):
return None
def from_FractionField(K1, a, K0):
"""Convert a rational function to ``dtype``. """
q, r = K0.numer(a).div(K0.denom(a))
if r.is_zero:
return K1.from_PolynomialRing(q, K0.field.ring.to_domain())
else:
return None
def get_field(self):
"""Returns a field associated with `self`. """
return self.ring.to_field().to_domain()
def is_positive(self, a):
"""Returns True if `LC(a)` is positive. """
return self.domain.is_positive(a.LC)
def is_negative(self, a):
"""Returns True if `LC(a)` is negative. """
return self.domain.is_negative(a.LC)
def is_nonpositive(self, a):
"""Returns True if `LC(a)` is non-positive. """
return self.domain.is_nonpositive(a.LC)
def is_nonnegative(self, a):
"""Returns True if `LC(a)` is non-negative. """
return self.domain.is_nonnegative(a.LC)
def gcdex(self, a, b):
"""Extended GCD of `a` and `b`. """
return a.gcdex(b)
def gcd(self, a, b):
"""Returns GCD of `a` and `b`. """
return a.gcd(b)
def lcm(self, a, b):
"""Returns LCM of `a` and `b`. """
return a.lcm(b)
def factorial(self, a):
"""Returns factorial of `a`. """
return self.dtype(self.domain.factorial(a))
| 4,603 | 28.703226 | 90 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/domains/pythonrational.py
|
"""Rational number type based on Python integers. """
from __future__ import print_function, division
import operator
from sympy.polys.polyutils import PicklableWithSlots
from sympy.polys.domains.domainelement import DomainElement
from sympy.core.compatibility import integer_types
from sympy.core.sympify import converter
from sympy.core.numbers import Rational, Integer
from sympy.printing.defaults import DefaultPrinting
from sympy.utilities import public
@public
class PythonRational(DefaultPrinting, PicklableWithSlots, DomainElement):
"""
Rational number type based on Python integers.
This was supposed to be needed for compatibility with older Python
versions which don't support Fraction. However, Fraction is very
slow so we don't use it anyway.
Examples
========
>>> from sympy.polys.domains import PythonRational
>>> PythonRational(1)
1
>>> PythonRational(2, 3)
2/3
>>> PythonRational(14, 10)
7/5
"""
__slots__ = ['p', 'q']
def parent(self):
from sympy.polys.domains import PythonRationalField
return PythonRationalField()
def __init__(self, p, q=1, _gcd=True):
from sympy.polys.domains.groundtypes import python_gcd as gcd
if isinstance(p, Integer):
p = p.p
elif isinstance(p, Rational):
p, q = p.p, p.q
if not q:
raise ZeroDivisionError('rational number')
elif q < 0:
p, q = -p, -q
if not p:
self.p = 0
self.q = 1
elif p == 1 or q == 1:
self.p = p
self.q = q
else:
if _gcd:
x = gcd(p, q)
if x != 1:
p //= x
q //= x
self.p = p
self.q = q
@classmethod
def new(cls, p, q):
obj = object.__new__(cls)
obj.p = p
obj.q = q
return obj
def __hash__(self):
if self.q == 1:
return hash(self.p)
else:
return hash((self.p, self.q))
def __int__(self):
p, q = self.p, self.q
if p < 0:
return -(-p//q)
return p//q
def __float__(self):
return float(self.p)/self.q
def __abs__(self):
return self.new(abs(self.p), self.q)
def __pos__(self):
return self.new(+self.p, self.q)
def __neg__(self):
return self.new(-self.p, self.q)
def __add__(self, other):
from sympy.polys.domains.groundtypes import python_gcd as gcd
if isinstance(other, PythonRational):
ap, aq, bp, bq = self.p, self.q, other.p, other.q
g = gcd(aq, bq)
if g == 1:
p = ap*bq + aq*bp
q = bq*aq
else:
q1, q2 = aq//g, bq//g
p, q = ap*q2 + bp*q1, q1*q2
g2 = gcd(p, g)
p, q = (p // g2), q * (g // g2)
elif isinstance(other, integer_types):
p = self.p + self.q*other
q = self.q
else:
return NotImplemented
return self.__class__(p, q, _gcd=False)
def __radd__(self, other):
if not isinstance(other, integer_types):
return NotImplemented
p = self.p + self.q*other
q = self.q
return self.__class__(p, q, _gcd=False)
def __sub__(self, other):
from sympy.polys.domains.groundtypes import python_gcd as gcd
if isinstance(other, PythonRational):
ap, aq, bp, bq = self.p, self.q, other.p, other.q
g = gcd(aq, bq)
if g == 1:
p = ap*bq - aq*bp
q = bq*aq
else:
q1, q2 = aq//g, bq//g
p, q = ap*q2 - bp*q1, q1*q2
g2 = gcd(p, g)
p, q = (p // g2), q * (g // g2)
elif isinstance(other, integer_types):
p = self.p - self.q*other
q = self.q
else:
return NotImplemented
return self.__class__(p, q, _gcd=False)
def __rsub__(self, other):
if not isinstance(other, integer_types):
return NotImplemented
p = self.q*other - self.p
q = self.q
return self.__class__(p, q, _gcd=False)
def __mul__(self, other):
from sympy.polys.domains.groundtypes import python_gcd as gcd
if isinstance(other, PythonRational):
ap, aq, bp, bq = self.p, self.q, other.p, other.q
x1 = gcd(ap, bq)
x2 = gcd(bp, aq)
p, q = ((ap//x1)*(bp//x2), (aq//x2)*(bq//x1))
elif isinstance(other, integer_types):
x = gcd(other, self.q)
p = self.p*(other//x)
q = self.q//x
else:
return NotImplemented
return self.__class__(p, q, _gcd=False)
def __rmul__(self, other):
from sympy.polys.domains.groundtypes import python_gcd as gcd
if not isinstance(other, integer_types):
return NotImplemented
x = gcd(self.q, other)
p = self.p*(other//x)
q = self.q//x
return self.__class__(p, q, _gcd=False)
def __div__(self, other):
from sympy.polys.domains.groundtypes import python_gcd as gcd
if isinstance(other, PythonRational):
ap, aq, bp, bq = self.p, self.q, other.p, other.q
x1 = gcd(ap, bp)
x2 = gcd(bq, aq)
p, q = ((ap//x1)*(bq//x2), (aq//x2)*(bp//x1))
elif isinstance(other, integer_types):
x = gcd(other, self.p)
p = self.p//x
q = self.q*(other//x)
else:
return NotImplemented
return self.__class__(p, q, _gcd=False)
__truediv__ = __div__
def __rdiv__(self, other):
from sympy.polys.domains.groundtypes import python_gcd as gcd
if not isinstance(other, integer_types):
return NotImplemented
x = gcd(self.p, other)
p = self.q*(other//x)
q = self.p//x
return self.__class__(p, q)
__rtruediv__ = __rdiv__
def __mod__(self, other):
return self.__class__(0)
def __divmod__(self, other):
return (self//other, self % other)
def __pow__(self, exp):
p, q = self.p, self.q
if exp < 0:
p, q, exp = q, p, -exp
return self.__class__(p**exp, q**exp, _gcd=False)
def __nonzero__(self):
return self.p != 0
__bool__ = __nonzero__
def __eq__(self, other):
if isinstance(other, PythonRational):
return self.q == other.q and self.p == other.p
elif isinstance(other, integer_types):
return self.q == 1 and self.p == other
else:
return False
def __ne__(self, other):
return not self.__eq__(other)
def _cmp(self, other, op):
try:
diff = self - other
except TypeError:
return NotImplemented
else:
return op(diff.p, 0)
def __lt__(self, other):
return self._cmp(other, operator.lt)
def __le__(self, other):
return self._cmp(other, operator.le)
def __gt__(self, other):
return self._cmp(other, operator.gt)
def __ge__(self, other):
return self._cmp(other, operator.ge)
@property
def numer(self):
return self.p
@property
def denom(self):
return self.q
numerator = numer
denominator = denom
def sympify_pythonrational(arg):
return Rational(arg.p, arg.q)
converter[PythonRational] = sympify_pythonrational
| 7,630 | 25.496528 | 73 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/domains/integerring.py
|
"""Implementation of :class:`IntegerRing` class. """
from __future__ import print_function, division
from sympy.polys.domains.ring import Ring
from sympy.polys.domains.simpledomain import SimpleDomain
from sympy.polys.domains.characteristiczero import CharacteristicZero
from sympy.utilities import public
import math
@public
class IntegerRing(Ring, CharacteristicZero, SimpleDomain):
"""General class for integer rings. """
rep = 'ZZ'
is_IntegerRing = is_ZZ = True
is_Numerical = True
is_PID = True
has_assoc_Ring = True
has_assoc_Field = True
def get_field(self):
"""Returns a field associated with ``self``. """
from sympy.polys.domains import QQ
return QQ
def algebraic_field(self, *extension):
r"""Returns an algebraic field, i.e. `\mathbb{Q}(\alpha, \ldots)`. """
return self.get_field().algebraic_field(*extension)
def from_AlgebraicField(K1, a, K0):
"""Convert a ``ANP`` object to ``dtype``. """
if a.is_ground:
return K1.convert(a.LC(), K0.dom)
def log(self, a, b):
"""Returns b-base logarithm of ``a``. """
return self.dtype(math.log(int(a), b))
| 1,196 | 26.837209 | 78 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/domains/finitefield.py
|
"""Implementation of :class:`FiniteField` class. """
from __future__ import print_function, division
from sympy.polys.domains.field import Field
from sympy.polys.domains.simpledomain import SimpleDomain
from sympy.polys.domains.groundtypes import SymPyInteger
from sympy.polys.domains.modularinteger import ModularIntegerFactory
from sympy.polys.polyerrors import CoercionFailed
from sympy.utilities import public
@public
class FiniteField(Field, SimpleDomain):
"""General class for finite fields. """
rep = 'FF'
is_FiniteField = is_FF = True
is_Numerical = True
has_assoc_Ring = False
has_assoc_Field = True
dom = None
mod = None
def __init__(self, mod, dom=None, symmetric=True):
if mod <= 0:
raise ValueError('modulus must be a positive integer, got %s' % mod)
if dom is None:
from sympy.polys.domains import ZZ
dom = ZZ
self.dtype = ModularIntegerFactory(mod, dom, symmetric, self)
self.zero = self.dtype(0)
self.one = self.dtype(1)
self.dom = dom
self.mod = mod
def __str__(self):
return 'GF(%s)' % self.mod
def __hash__(self):
return hash((self.__class__.__name__, self.dtype, self.mod, self.dom))
def __eq__(self, other):
"""Returns ``True`` if two domains are equivalent. """
return isinstance(other, FiniteField) and \
self.mod == other.mod and self.dom == other.dom
def characteristic(self):
"""Return the characteristic of this domain. """
return self.mod
def get_field(self):
"""Returns a field associated with ``self``. """
return self
def to_sympy(self, a):
"""Convert ``a`` to a SymPy object. """
return SymPyInteger(int(a))
def from_sympy(self, a):
"""Convert SymPy's Integer to SymPy's ``Integer``. """
if a.is_Integer:
return self.dtype(self.dom.dtype(int(a)))
elif a.is_Float and int(a) == a:
return self.dtype(self.dom.dtype(int(a)))
else:
raise CoercionFailed("expected an integer, got %s" % a)
def from_FF_python(K1, a, K0=None):
"""Convert ``ModularInteger(int)`` to ``dtype``. """
return K1.dtype(K1.dom.from_ZZ_python(a.val, K0.dom))
def from_ZZ_python(K1, a, K0=None):
"""Convert Python's ``int`` to ``dtype``. """
return K1.dtype(K1.dom.from_ZZ_python(a, K0))
def from_QQ_python(K1, a, K0=None):
"""Convert Python's ``Fraction`` to ``dtype``. """
if a.denominator == 1:
return K1.from_ZZ_python(a.numerator)
def from_FF_gmpy(K1, a, K0=None):
"""Convert ``ModularInteger(mpz)`` to ``dtype``. """
return K1.dtype(K1.dom.from_ZZ_gmpy(a.val, K0.dom))
def from_ZZ_gmpy(K1, a, K0=None):
"""Convert GMPY's ``mpz`` to ``dtype``. """
return K1.dtype(K1.dom.from_ZZ_gmpy(a, K0))
def from_QQ_gmpy(K1, a, K0=None):
"""Convert GMPY's ``mpq`` to ``dtype``. """
if a.denominator == 1:
return K1.from_ZZ_gmpy(a.numerator)
def from_RealField(K1, a, K0):
"""Convert mpmath's ``mpf`` to ``dtype``. """
p, q = K0.to_rational(a)
if q == 1:
return K1.dtype(self.dom.dtype(p))
| 3,306 | 30.495238 | 80 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/domains/pythonfinitefield.py
|
"""Implementation of :class:`PythonFiniteField` class. """
from __future__ import print_function, division
from sympy.polys.domains.finitefield import FiniteField
from sympy.polys.domains.pythonintegerring import PythonIntegerRing
from sympy.utilities import public
@public
class PythonFiniteField(FiniteField):
"""Finite field based on Python's integers. """
alias = 'FF_python'
def __init__(self, mod, symmetric=True):
return super(PythonFiniteField, self).__init__(mod, PythonIntegerRing(), symmetric)
| 531 | 28.555556 | 91 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/domains/realfield.py
|
"""Implementation of :class:`RealField` class. """
from __future__ import print_function, division
from sympy.polys.domains.field import Field
from sympy.polys.domains.simpledomain import SimpleDomain
from sympy.polys.domains.characteristiczero import CharacteristicZero
from sympy.polys.domains.mpelements import MPContext
from sympy.polys.polyerrors import DomainError, CoercionFailed
from sympy.core.numbers import Float
from sympy.utilities import public
@public
class RealField(Field, CharacteristicZero, SimpleDomain):
"""Real numbers up to the given precision. """
rep = 'RR'
is_RealField = is_RR = True
is_Exact = False
is_Numerical = True
is_PID = False
has_assoc_Ring = False
has_assoc_Field = True
_default_precision = 53
@property
def has_default_precision(self):
return self.precision == self._default_precision
@property
def precision(self):
return self._context.prec
@property
def dps(self):
return self._context.dps
@property
def tolerance(self):
return self._context.tolerance
def __init__(self, prec=_default_precision, dps=None, tol=None):
context = MPContext(prec, dps, tol)
context._parent = self
self._context = context
self.dtype = context.mpf
self.zero = self.dtype(0)
self.one = self.dtype(1)
def __eq__(self, other):
return (isinstance(other, RealField)
and self.precision == other.precision
and self.tolerance == other.tolerance)
def __hash__(self):
return hash((self.__class__.__name__, self.dtype, self.precision, self.tolerance))
def to_sympy(self, element):
"""Convert ``element`` to SymPy number. """
return Float(element, self.dps)
def from_sympy(self, expr):
"""Convert SymPy's number to ``dtype``. """
number = expr.evalf(n=self.dps)
if number.is_Number:
return self.dtype(number)
else:
raise CoercionFailed("expected real number, got %s" % expr)
def from_ZZ_python(self, element, base):
return self.dtype(element)
def from_QQ_python(self, element, base):
return self.dtype(element.numerator) / element.denominator
def from_ZZ_gmpy(self, element, base):
return self.dtype(int(element))
def from_QQ_gmpy(self, element, base):
return self.dtype(int(element.numerator)) / int(element.denominator)
def from_RealField(self, element, base):
if self == base:
return element
else:
return self.dtype(element)
def from_ComplexField(self, element, base):
if not element.imag:
return self.dtype(element.real)
def to_rational(self, element, limit=True):
"""Convert a real number to rational number. """
return self._context.to_rational(element, limit)
def get_ring(self):
"""Returns a ring associated with ``self``. """
return self
def get_exact(self):
"""Returns an exact domain associated with ``self``. """
from sympy.polys.domains import QQ
return QQ
def gcd(self, a, b):
"""Returns GCD of ``a`` and ``b``. """
return self.one
def lcm(self, a, b):
"""Returns LCM of ``a`` and ``b``. """
return a*b
def almosteq(self, a, b, tolerance=None):
"""Check if ``a`` and ``b`` are almost equal. """
return self._context.almosteq(a, b, tolerance)
| 3,517 | 27.601626 | 90 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/domains/domain.py
|
"""Implementation of :class:`Domain` class. """
from __future__ import print_function, division
from sympy.polys.domains.domainelement import DomainElement
from sympy.core import Basic, sympify
from sympy.core.compatibility import HAS_GMPY, integer_types, is_sequence
from sympy.polys.polyerrors import UnificationFailed, CoercionFailed, DomainError
from sympy.polys.orderings import lex
from sympy.polys.polyutils import _unify_gens
from sympy.utilities import default_sort_key, public
from sympy.core.decorators import deprecated
@public
class Domain(object):
"""Represents an abstract domain. """
dtype = None
zero = None
one = None
is_Ring = False
is_Field = False
has_assoc_Ring = False
has_assoc_Field = False
is_FiniteField = is_FF = False
is_IntegerRing = is_ZZ = False
is_RationalField = is_QQ = False
is_RealField = is_RR = False
is_ComplexField = is_CC = False
is_AlgebraicField = is_Algebraic = False
is_PolynomialRing = is_Poly = False
is_FractionField = is_Frac = False
is_SymbolicDomain = is_EX = False
is_Exact = True
is_Numerical = False
is_Simple = False
is_Composite = False
is_PID = False
has_CharacteristicZero = False
rep = None
alias = None
@property
@deprecated(useinstead="is_Field", issue=12723, deprecated_since_version="1.1")
def has_Field(self):
return self.is_Field
@property
@deprecated(useinstead="is_Ring", issue=12723, deprecated_since_version="1.1")
def has_Ring(self):
return self.is_Ring
def __init__(self):
raise NotImplementedError
def __str__(self):
return self.rep
def __repr__(self):
return str(self)
def __hash__(self):
return hash((self.__class__.__name__, self.dtype))
def new(self, *args):
return self.dtype(*args)
@property
def tp(self):
return self.dtype
def __call__(self, *args):
"""Construct an element of ``self`` domain from ``args``. """
return self.new(*args)
def normal(self, *args):
return self.dtype(*args)
def convert_from(self, element, base):
"""Convert ``element`` to ``self.dtype`` given the base domain. """
if base.alias is not None:
method = "from_" + base.alias
else:
method = "from_" + base.__class__.__name__
_convert = getattr(self, method)
if _convert is not None:
result = _convert(element, base)
if result is not None:
return result
raise CoercionFailed("can't convert %s of type %s from %s to %s" % (element, type(element), base, self))
def convert(self, element, base=None):
"""Convert ``element`` to ``self.dtype``. """
if base is not None:
return self.convert_from(element, base)
if self.of_type(element):
return element
from sympy.polys.domains import PythonIntegerRing, GMPYIntegerRing, GMPYRationalField, RealField, ComplexField
if isinstance(element, integer_types):
return self.convert_from(element, PythonIntegerRing())
if HAS_GMPY:
integers = GMPYIntegerRing()
if isinstance(element, integers.tp):
return self.convert_from(element, integers)
rationals = GMPYRationalField()
if isinstance(element, rationals.tp):
return self.convert_from(element, rationals)
if isinstance(element, float):
parent = RealField(tol=False)
return self.convert_from(parent(element), parent)
if isinstance(element, complex):
parent = ComplexField(tol=False)
return self.convert_from(parent(element), parent)
if isinstance(element, DomainElement):
return self.convert_from(element, element.parent())
# TODO: implement this in from_ methods
if self.is_Numerical and getattr(element, 'is_ground', False):
return self.convert(element.LC())
if isinstance(element, Basic):
try:
return self.from_sympy(element)
except (TypeError, ValueError):
pass
else: # TODO: remove this branch
if not is_sequence(element):
try:
element = sympify(element)
if isinstance(element, Basic):
return self.from_sympy(element)
except (TypeError, ValueError):
pass
raise CoercionFailed("can't convert %s of type %s to %s" % (element, type(element), self))
def of_type(self, element):
"""Check if ``a`` is of type ``dtype``. """
return isinstance(element, self.tp) # XXX: this isn't correct, e.g. PolyElement
def __contains__(self, a):
"""Check if ``a`` belongs to this domain. """
try:
self.convert(a)
except CoercionFailed:
return False
return True
def to_sympy(self, a):
"""Convert ``a`` to a SymPy object. """
raise NotImplementedError
def from_sympy(self, a):
"""Convert a SymPy object to ``dtype``. """
raise NotImplementedError
def from_FF_python(K1, a, K0):
"""Convert ``ModularInteger(int)`` to ``dtype``. """
return None
def from_ZZ_python(K1, a, K0):
"""Convert a Python ``int`` object to ``dtype``. """
return None
def from_QQ_python(K1, a, K0):
"""Convert a Python ``Fraction`` object to ``dtype``. """
return None
def from_FF_gmpy(K1, a, K0):
"""Convert ``ModularInteger(mpz)`` to ``dtype``. """
return None
def from_ZZ_gmpy(K1, a, K0):
"""Convert a GMPY ``mpz`` object to ``dtype``. """
return None
def from_QQ_gmpy(K1, a, K0):
"""Convert a GMPY ``mpq`` object to ``dtype``. """
return None
def from_RealField(K1, a, K0):
"""Convert a real element object to ``dtype``. """
return None
def from_ComplexField(K1, a, K0):
"""Convert a complex element to ``dtype``. """
return None
def from_AlgebraicField(K1, a, K0):
"""Convert an algebraic number to ``dtype``. """
return None
def from_PolynomialRing(K1, a, K0):
"""Convert a polynomial to ``dtype``. """
if a.is_ground:
return K1.convert(a.LC, K0.dom)
def from_FractionField(K1, a, K0):
"""Convert a rational function to ``dtype``. """
return None
def from_ExpressionDomain(K1, a, K0):
"""Convert a ``EX`` object to ``dtype``. """
return K1.from_sympy(a.ex)
def from_GlobalPolynomialRing(K1, a, K0):
"""Convert a polynomial to ``dtype``. """
if a.degree() <= 0:
return K1.convert(a.LC(), K0.dom)
def from_GeneralizedPolynomialRing(K1, a, K0):
return K1.from_FractionField(a, K0)
def unify_with_symbols(K0, K1, symbols):
if (K0.is_Composite and (set(K0.symbols) & set(symbols))) or (K1.is_Composite and (set(K1.symbols) & set(symbols))):
raise UnificationFailed("can't unify %s with %s, given %s generators" % (K0, K1, tuple(symbols)))
return K0.unify(K1)
def unify(K0, K1, symbols=None):
"""
Construct a minimal domain that contains elements of ``K0`` and ``K1``.
Known domains (from smallest to largest):
- ``GF(p)``
- ``ZZ``
- ``QQ``
- ``RR(prec, tol)``
- ``CC(prec, tol)``
- ``ALG(a, b, c)``
- ``K[x, y, z]``
- ``K(x, y, z)``
- ``EX``
"""
if symbols is not None:
return K0.unify_with_symbols(K1, symbols)
if K0 == K1:
return K0
if K0.is_EX:
return K0
if K1.is_EX:
return K1
if K0.is_Composite or K1.is_Composite:
K0_ground = K0.dom if K0.is_Composite else K0
K1_ground = K1.dom if K1.is_Composite else K1
K0_symbols = K0.symbols if K0.is_Composite else ()
K1_symbols = K1.symbols if K1.is_Composite else ()
domain = K0_ground.unify(K1_ground)
symbols = _unify_gens(K0_symbols, K1_symbols)
order = K0.order if K0.is_Composite else K1.order
if ((K0.is_FractionField and K1.is_PolynomialRing or
K1.is_FractionField and K0.is_PolynomialRing) and
(not K0_ground.is_Field or not K1_ground.is_Field) and domain.is_Field):
domain = domain.get_ring()
if K0.is_Composite and (not K1.is_Composite or K0.is_FractionField or K1.is_PolynomialRing):
cls = K0.__class__
else:
cls = K1.__class__
from sympy.polys.domains.old_polynomialring import GlobalPolynomialRing
if cls == GlobalPolynomialRing:
return cls(domain, symbols)
return cls(domain, symbols, order)
def mkinexact(cls, K0, K1):
prec = max(K0.precision, K1.precision)
tol = max(K0.tolerance, K1.tolerance)
return cls(prec=prec, tol=tol)
if K0.is_ComplexField and K1.is_ComplexField:
return mkinexact(K0.__class__, K0, K1)
if K0.is_ComplexField and K1.is_RealField:
return mkinexact(K0.__class__, K0, K1)
if K0.is_RealField and K1.is_ComplexField:
return mkinexact(K1.__class__, K1, K0)
if K0.is_RealField and K1.is_RealField:
return mkinexact(K0.__class__, K0, K1)
if K0.is_ComplexField or K0.is_RealField:
return K0
if K1.is_ComplexField or K1.is_RealField:
return K1
if K0.is_AlgebraicField and K1.is_AlgebraicField:
return K0.__class__(K0.dom.unify(K1.dom), *_unify_gens(K0.orig_ext, K1.orig_ext))
elif K0.is_AlgebraicField:
return K0
elif K1.is_AlgebraicField:
return K1
if K0.is_RationalField:
return K0
if K1.is_RationalField:
return K1
if K0.is_IntegerRing:
return K0
if K1.is_IntegerRing:
return K1
if K0.is_FiniteField and K1.is_FiniteField:
return K0.__class__(max(K0.mod, K1.mod, key=default_sort_key))
from sympy.polys.domains import EX
return EX
def __eq__(self, other):
"""Returns ``True`` if two domains are equivalent. """
return isinstance(other, Domain) and self.dtype == other.dtype
def __ne__(self, other):
"""Returns ``False`` if two domains are equivalent. """
return not self.__eq__(other)
def map(self, seq):
"""Rersively apply ``self`` to all elements of ``seq``. """
result = []
for elt in seq:
if isinstance(elt, list):
result.append(self.map(elt))
else:
result.append(self(elt))
return result
def get_ring(self):
"""Returns a ring associated with ``self``. """
raise DomainError('there is no ring associated with %s' % self)
def get_field(self):
"""Returns a field associated with ``self``. """
raise DomainError('there is no field associated with %s' % self)
def get_exact(self):
"""Returns an exact domain associated with ``self``. """
return self
def __getitem__(self, symbols):
"""The mathematical way to make a polynomial ring. """
if hasattr(symbols, '__iter__'):
return self.poly_ring(*symbols)
else:
return self.poly_ring(symbols)
def poly_ring(self, *symbols, **kwargs):
"""Returns a polynomial ring, i.e. `K[X]`. """
from sympy.polys.domains.polynomialring import PolynomialRing
return PolynomialRing(self, symbols, kwargs.get("order", lex))
def frac_field(self, *symbols, **kwargs):
"""Returns a fraction field, i.e. `K(X)`. """
from sympy.polys.domains.fractionfield import FractionField
return FractionField(self, symbols, kwargs.get("order", lex))
def old_poly_ring(self, *symbols, **kwargs):
"""Returns a polynomial ring, i.e. `K[X]`. """
from sympy.polys.domains.old_polynomialring import PolynomialRing
return PolynomialRing(self, *symbols, **kwargs)
def old_frac_field(self, *symbols, **kwargs):
"""Returns a fraction field, i.e. `K(X)`. """
from sympy.polys.domains.old_fractionfield import FractionField
return FractionField(self, *symbols, **kwargs)
def algebraic_field(self, *extension):
r"""Returns an algebraic field, i.e. `K(\alpha, \ldots)`. """
raise DomainError("can't create algebraic field over %s" % self)
def inject(self, *symbols):
"""Inject generators into this domain. """
raise NotImplementedError
def is_zero(self, a):
"""Returns True if ``a`` is zero. """
return not a
def is_one(self, a):
"""Returns True if ``a`` is one. """
return a == self.one
def is_positive(self, a):
"""Returns True if ``a`` is positive. """
return a > 0
def is_negative(self, a):
"""Returns True if ``a`` is negative. """
return a < 0
def is_nonpositive(self, a):
"""Returns True if ``a`` is non-positive. """
return a <= 0
def is_nonnegative(self, a):
"""Returns True if ``a`` is non-negative. """
return a >= 0
def abs(self, a):
"""Absolute value of ``a``, implies ``__abs__``. """
return abs(a)
def neg(self, a):
"""Returns ``a`` negated, implies ``__neg__``. """
return -a
def pos(self, a):
"""Returns ``a`` positive, implies ``__pos__``. """
return +a
def add(self, a, b):
"""Sum of ``a`` and ``b``, implies ``__add__``. """
return a + b
def sub(self, a, b):
"""Difference of ``a`` and ``b``, implies ``__sub__``. """
return a - b
def mul(self, a, b):
"""Product of ``a`` and ``b``, implies ``__mul__``. """
return a * b
def pow(self, a, b):
"""Raise ``a`` to power ``b``, implies ``__pow__``. """
return a ** b
def exquo(self, a, b):
"""Exact quotient of ``a`` and ``b``, implies something. """
raise NotImplementedError
def quo(self, a, b):
"""Quotient of ``a`` and ``b``, implies something. """
raise NotImplementedError
def rem(self, a, b):
"""Remainder of ``a`` and ``b``, implies ``__mod__``. """
raise NotImplementedError
def div(self, a, b):
"""Division of ``a`` and ``b``, implies something. """
raise NotImplementedError
def invert(self, a, b):
"""Returns inversion of ``a mod b``, implies something. """
raise NotImplementedError
def revert(self, a):
"""Returns ``a**(-1)`` if possible. """
raise NotImplementedError
def numer(self, a):
"""Returns numerator of ``a``. """
raise NotImplementedError
def denom(self, a):
"""Returns denominator of ``a``. """
raise NotImplementedError
def half_gcdex(self, a, b):
"""Half extended GCD of ``a`` and ``b``. """
s, t, h = self.gcdex(a, b)
return s, h
def gcdex(self, a, b):
"""Extended GCD of ``a`` and ``b``. """
raise NotImplementedError
def cofactors(self, a, b):
"""Returns GCD and cofactors of ``a`` and ``b``. """
gcd = self.gcd(a, b)
cfa = self.quo(a, gcd)
cfb = self.quo(b, gcd)
return gcd, cfa, cfb
def gcd(self, a, b):
"""Returns GCD of ``a`` and ``b``. """
raise NotImplementedError
def lcm(self, a, b):
"""Returns LCM of ``a`` and ``b``. """
raise NotImplementedError
def log(self, a, b):
"""Returns b-base logarithm of ``a``. """
raise NotImplementedError
def sqrt(self, a):
"""Returns square root of ``a``. """
raise NotImplementedError
def evalf(self, a, prec=None, **options):
"""Returns numerical approximation of ``a``. """
return self.to_sympy(a).evalf(prec, **options)
n = evalf
def real(self, a):
return a
def imag(self, a):
return self.zero
def almosteq(self, a, b, tolerance=None):
"""Check if ``a`` and ``b`` are almost equal. """
return a == b
def characteristic(self):
"""Return the characteristic of this domain. """
raise NotImplementedError('characteristic()')
| 16,734 | 29.876384 | 124 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/domains/__init__.py
|
"""Implementation of mathematical domains. """
__all__ = []
from . import domain
__all__.extend(domain.__all__)
from .domain import *
from . import finitefield
__all__.extend(finitefield.__all__)
from .finitefield import *
from . import integerring
__all__.extend(integerring.__all__)
from .integerring import *
from . import rationalfield
__all__.extend(rationalfield.__all__)
from .rationalfield import *
from . import realfield
__all__.extend(realfield.__all__)
from .realfield import *
from . import complexfield
__all__.extend(complexfield.__all__)
from .complexfield import *
from . import pythonfinitefield
__all__.extend(pythonfinitefield.__all__)
from .pythonfinitefield import *
from . import gmpyfinitefield
__all__.extend(gmpyfinitefield.__all__)
from .gmpyfinitefield import *
from . import pythonintegerring
__all__.extend(pythonintegerring.__all__)
from .pythonintegerring import *
from . import gmpyintegerring
__all__.extend(gmpyintegerring.__all__)
from .gmpyintegerring import *
from . import pythonrationalfield
__all__.extend(pythonrationalfield.__all__)
from .pythonrationalfield import *
from . import gmpyrationalfield
__all__.extend(gmpyrationalfield.__all__)
from .gmpyrationalfield import *
from . import algebraicfield
__all__.extend(algebraicfield.__all__)
from .algebraicfield import *
from . import polynomialring
__all__.extend(polynomialring.__all__)
from .polynomialring import *
from . import fractionfield
__all__.extend(fractionfield.__all__)
from .fractionfield import *
from . import expressiondomain
__all__.extend(expressiondomain.__all__)
from .expressiondomain import *
FF_python = PythonFiniteField
FF_gmpy = GMPYFiniteField
ZZ_python = PythonIntegerRing
ZZ_gmpy = GMPYIntegerRing
QQ_python = PythonRationalField
QQ_gmpy = GMPYRationalField
RR = RealField()
CC = ComplexField()
from .pythonrational import PythonRational
from sympy.core.compatibility import GROUND_TYPES
_GROUND_TYPES_MAP = {
'gmpy': (FF_gmpy, ZZ_gmpy(), QQ_gmpy()),
'python': (FF_python, ZZ_python(), QQ_python()),
}
try:
FF, ZZ, QQ = _GROUND_TYPES_MAP[GROUND_TYPES]
except KeyError:
raise ValueError("invalid ground types: %s" % GROUND_TYPES)
GF = FF
EX = ExpressionDomain()
__all__.extend([
"FF_python", "FF_gmpy",
"ZZ_python", "ZZ_gmpy",
"QQ_python", "QQ_gmpy",
"GF", "FF", "ZZ", "QQ", "RR", "CC", "EX",
])
| 2,382 | 21.695238 | 63 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/domains/gmpyrationalfield.py
|
"""Implementaton of :class:`GMPYRationalField` class. """
from __future__ import print_function, division
from sympy.polys.domains.rationalfield import RationalField
from sympy.polys.domains.groundtypes import (
GMPYRational, SymPyRational,
gmpy_numer, gmpy_denom, gmpy_factorial, gmpy_qdiv,
)
from sympy.polys.polyerrors import CoercionFailed
from sympy.utilities import public
@public
class GMPYRationalField(RationalField):
"""Rational field based on GMPY mpq class. """
dtype = GMPYRational
zero = dtype(0)
one = dtype(1)
tp = type(one)
alias = 'QQ_gmpy'
def __init__(self):
pass
def get_ring(self):
"""Returns ring associated with ``self``. """
from sympy.polys.domains import GMPYIntegerRing
return GMPYIntegerRing()
def to_sympy(self, a):
"""Convert `a` to a SymPy object. """
return SymPyRational(int(gmpy_numer(a)),
int(gmpy_denom(a)))
def from_sympy(self, a):
"""Convert SymPy's Integer to `dtype`. """
if a.is_Rational:
return GMPYRational(a.p, a.q)
elif a.is_Float:
from sympy.polys.domains import RR
return GMPYRational(*RR.to_rational(a))
else:
raise CoercionFailed("expected `Rational` object, got %s" % a)
def from_ZZ_python(K1, a, K0):
"""Convert a Python `int` object to `dtype`. """
return GMPYRational(a)
def from_QQ_python(K1, a, K0):
"""Convert a Python `Fraction` object to `dtype`. """
return GMPYRational(a.numerator, a.denominator)
def from_ZZ_gmpy(K1, a, K0):
"""Convert a GMPY `mpz` object to `dtype`. """
return GMPYRational(a)
def from_QQ_gmpy(K1, a, K0):
"""Convert a GMPY `mpq` object to `dtype`. """
return a
def from_RealField(K1, a, K0):
"""Convert a mpmath `mpf` object to `dtype`. """
return GMPYRational(*K0.to_rational(a))
def exquo(self, a, b):
"""Exact quotient of `a` and `b`, implies `__div__`. """
return GMPYRational(a) / GMPYRational(b)
def quo(self, a, b):
"""Quotient of `a` and `b`, implies `__div__`. """
return GMPYRational(a) / GMPYRational(b)
def rem(self, a, b):
"""Remainder of `a` and `b`, implies nothing. """
return self.zero
def div(self, a, b):
"""Division of `a` and `b`, implies `__div__`. """
return GMPYRational(a) / GMPYRational(b), self.zero
def numer(self, a):
"""Returns numerator of `a`. """
return a.numerator
def denom(self, a):
"""Returns denominator of `a`. """
return a.denominator
def factorial(self, a):
"""Returns factorial of `a`. """
return GMPYRational(gmpy_factorial(int(a)))
| 2,825 | 29.06383 | 74 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/domains/domainelement.py
|
"""Trait for implementing domain elements. """
from __future__ import print_function, division
from sympy.utilities import public
@public
class DomainElement(object):
"""
Represents an element of a domain.
Mix in this trait into a class which instances should be recognized as
elements of a domain. Method ``parent()`` gives that domain.
"""
def parent(self):
raise NotImplementedError("abstract method")
| 443 | 22.368421 | 74 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/domains/expressiondomain.py
|
"""Implementation of :class:`ExpressionDomain` class. """
from __future__ import print_function, division
from sympy.polys.domains.field import Field
from sympy.polys.domains.simpledomain import SimpleDomain
from sympy.polys.domains.characteristiczero import CharacteristicZero
from sympy.core import sympify, SympifyError
from sympy.utilities import public
from sympy.polys.polyutils import PicklableWithSlots
@public
class ExpressionDomain(Field, CharacteristicZero, SimpleDomain):
"""A class for arbitrary expressions. """
is_SymbolicDomain = is_EX = True
class Expression(PicklableWithSlots):
"""An arbitrary expression. """
__slots__ = ['ex']
def __init__(self, ex):
if not isinstance(ex, self.__class__):
self.ex = sympify(ex)
else:
self.ex = ex.ex
def __repr__(f):
return 'EX(%s)' % repr(f.ex)
def __str__(f):
return 'EX(%s)' % str(f.ex)
def __hash__(self):
return hash((self.__class__.__name__, self.ex))
def as_expr(f):
return f.ex
def numer(f):
return f.__class__(f.ex.as_numer_denom()[0])
def denom(f):
return f.__class__(f.ex.as_numer_denom()[1])
def simplify(f, ex):
return f.__class__(ex.cancel())
def __abs__(f):
return f.__class__(abs(f.ex))
def __neg__(f):
return f.__class__(-f.ex)
def _to_ex(f, g):
try:
return f.__class__(g)
except SympifyError:
return None
def __add__(f, g):
g = f._to_ex(g)
if g is not None:
return f.simplify(f.ex + g.ex)
else:
return NotImplemented
def __radd__(f, g):
return f.simplify(f.__class__(g).ex + f.ex)
def __sub__(f, g):
g = f._to_ex(g)
if g is not None:
return f.simplify(f.ex - g.ex)
else:
return NotImplemented
def __rsub__(f, g):
return f.simplify(f.__class__(g).ex - f.ex)
def __mul__(f, g):
g = f._to_ex(g)
if g is not None:
return f.simplify(f.ex*g.ex)
else:
return NotImplemented
def __rmul__(f, g):
return f.simplify(f.__class__(g).ex*f.ex)
def __pow__(f, n):
n = f._to_ex(n)
if n is not None:
return f.simplify(f.ex**n.ex)
else:
return NotImplemented
def __truediv__(f, g):
g = f._to_ex(g)
if g is not None:
return f.simplify(f.ex/g.ex)
else:
return NotImplemented
def __rtruediv__(f, g):
return f.simplify(f.__class__(g).ex/f.ex)
__div__ = __truediv__
__rdiv__ = __rtruediv__
def __eq__(f, g):
return f.ex == f.__class__(g).ex
def __ne__(f, g):
return not f.__eq__(g)
def __nonzero__(f):
return f.ex != 0
__bool__ = __nonzero__
def gcd(f, g):
from sympy.polys import gcd
return f.__class__(gcd(f.ex, f.__class__(g).ex))
def lcm(f, g):
from sympy.polys import lcm
return f.__class__(lcm(f.ex, f.__class__(g).ex))
dtype = Expression
zero = Expression(0)
one = Expression(1)
rep = 'EX'
has_assoc_Ring = False
has_assoc_Field = True
def __init__(self):
pass
def to_sympy(self, a):
"""Convert ``a`` to a SymPy object. """
return a.as_expr()
def from_sympy(self, a):
"""Convert SymPy's expression to ``dtype``. """
return self.dtype(a)
def from_ZZ_python(K1, a, K0):
"""Convert a Python ``int`` object to ``dtype``. """
return K1(K0.to_sympy(a))
def from_QQ_python(K1, a, K0):
"""Convert a Python ``Fraction`` object to ``dtype``. """
return K1(K0.to_sympy(a))
def from_ZZ_gmpy(K1, a, K0):
"""Convert a GMPY ``mpz`` object to ``dtype``. """
return K1(K0.to_sympy(a))
def from_QQ_gmpy(K1, a, K0):
"""Convert a GMPY ``mpq`` object to ``dtype``. """
return K1(K0.to_sympy(a))
def from_RealField(K1, a, K0):
"""Convert a mpmath ``mpf`` object to ``dtype``. """
return K1(K0.to_sympy(a))
def from_PolynomialRing(K1, a, K0):
"""Convert a ``DMP`` object to ``dtype``. """
return K1(K0.to_sympy(a))
def from_FractionField(K1, a, K0):
"""Convert a ``DMF`` object to ``dtype``. """
return K1(K0.to_sympy(a))
def from_ExpressionDomain(K1, a, K0):
"""Convert a ``EX`` object to ``dtype``. """
return a
def get_ring(self):
"""Returns a ring associated with ``self``. """
return self # XXX: EX is not a ring but we don't have much choice here.
def get_field(self):
"""Returns a field associated with ``self``. """
return self
def is_positive(self, a):
"""Returns True if ``a`` is positive. """
return a.ex.as_coeff_mul()[0].is_positive
def is_negative(self, a):
"""Returns True if ``a`` is negative. """
return a.ex.as_coeff_mul()[0].is_negative
def is_nonpositive(self, a):
"""Returns True if ``a`` is non-positive. """
return a.ex.as_coeff_mul()[0].is_nonpositive
def is_nonnegative(self, a):
"""Returns True if ``a`` is non-negative. """
return a.ex.as_coeff_mul()[0].is_nonnegative
def numer(self, a):
"""Returns numerator of ``a``. """
return a.numer()
def denom(self, a):
"""Returns denominator of ``a``. """
return a.denom()
def gcd(self, a, b):
return a.gcd(b)
def lcm(self, a, b):
return a.lcm(b)
| 5,978 | 25.339207 | 80 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/domains/old_polynomialring.py
|
"""Implementation of :class:`PolynomialRing` class. """
from __future__ import print_function, division
from sympy.polys.domains.ring import Ring
from sympy.polys.domains.compositedomain import CompositeDomain
from sympy.polys.domains.characteristiczero import CharacteristicZero
from sympy.polys.domains.old_fractionfield import FractionField
from sympy.polys.polyclasses import DMP, DMF
from sympy.polys.polyerrors import (GeneratorsNeeded, PolynomialError,
CoercionFailed, ExactQuotientFailed, NotReversible)
from sympy.polys.polyutils import dict_from_basic, basic_from_dict, _dict_reorder
from sympy.polys.orderings import monomial_key, build_product_order
from sympy.polys.agca.modules import FreeModulePolyRing
from sympy.core.compatibility import iterable, range
from sympy.utilities import public
# XXX why does this derive from CharacteristicZero???
@public
class PolynomialRingBase(Ring, CharacteristicZero, CompositeDomain):
"""
Base class for generalized polynomial rings.
This base class should be used for uniform access to generalized polynomial
rings. Subclasses only supply information about the element storage etc.
Do not instantiate.
"""
has_assoc_Ring = True
has_assoc_Field = True
default_order = "grevlex"
def __init__(self, dom, *gens, **opts):
if not gens:
raise GeneratorsNeeded("generators not specified")
lev = len(gens) - 1
self.ngens = len(gens)
self.zero = self.dtype.zero(lev, dom, ring=self)
self.one = self.dtype.one(lev, dom, ring=self)
self.domain = self.dom = dom
self.symbols = self.gens = gens
# NOTE 'order' may not be set if inject was called through CompositeDomain
self.order = opts.get('order', monomial_key(self.default_order))
def new(self, element):
return self.dtype(element, self.dom, len(self.gens) - 1, ring=self)
def __str__(self):
s_order = str(self.order)
orderstr = (
" order=" + s_order) if s_order != self.default_order else ""
return str(self.dom) + '[' + ','.join(map(str, self.gens)) + orderstr + ']'
def __hash__(self):
return hash((self.__class__.__name__, self.dtype, self.dom,
self.gens, self.order))
def __eq__(self, other):
"""Returns `True` if two domains are equivalent. """
return isinstance(other, PolynomialRingBase) and \
self.dtype == other.dtype and self.dom == other.dom and \
self.gens == other.gens and self.order == other.order
def from_ZZ_python(K1, a, K0):
"""Convert a Python `int` object to `dtype`. """
return K1(K1.dom.convert(a, K0))
def from_QQ_python(K1, a, K0):
"""Convert a Python `Fraction` object to `dtype`. """
return K1(K1.dom.convert(a, K0))
def from_ZZ_gmpy(K1, a, K0):
"""Convert a GMPY `mpz` object to `dtype`. """
return K1(K1.dom.convert(a, K0))
def from_QQ_gmpy(K1, a, K0):
"""Convert a GMPY `mpq` object to `dtype`. """
return K1(K1.dom.convert(a, K0))
def from_RealField(K1, a, K0):
"""Convert a mpmath `mpf` object to `dtype`. """
return K1(K1.dom.convert(a, K0))
def from_AlgebraicField(K1, a, K0):
"""Convert a `ANP` object to `dtype`. """
if K1.dom == K0:
return K1(a)
def from_GlobalPolynomialRing(K1, a, K0):
"""Convert a `DMP` object to `dtype`. """
if K1.gens == K0.gens:
if K1.dom == K0.dom:
return K1(a.rep) # set the correct ring
else:
return K1(a.convert(K1.dom).rep)
else:
monoms, coeffs = _dict_reorder(a.to_dict(), K0.gens, K1.gens)
if K1.dom != K0.dom:
coeffs = [ K1.dom.convert(c, K0.dom) for c in coeffs ]
return K1(dict(zip(monoms, coeffs)))
def get_field(self):
"""Returns a field associated with `self`. """
return FractionField(self.dom, *self.gens)
def poly_ring(self, *gens):
"""Returns a polynomial ring, i.e. `K[X]`. """
raise NotImplementedError('nested domains not allowed')
def frac_field(self, *gens):
"""Returns a fraction field, i.e. `K(X)`. """
raise NotImplementedError('nested domains not allowed')
def revert(self, a):
try:
return 1/a
except (ExactQuotientFailed, ZeroDivisionError):
raise NotReversible('%s is not a unit' % a)
def gcdex(self, a, b):
"""Extended GCD of `a` and `b`. """
return a.gcdex(b)
def gcd(self, a, b):
"""Returns GCD of `a` and `b`. """
return a.gcd(b)
def lcm(self, a, b):
"""Returns LCM of `a` and `b`. """
return a.lcm(b)
def factorial(self, a):
"""Returns factorial of `a`. """
return self.dtype(self.dom.factorial(a))
def _vector_to_sdm(self, v, order):
"""
For internal use by the modules class.
Convert an iterable of elements of this ring into a sparse distributed
module element.
"""
raise NotImplementedError
def _sdm_to_dics(self, s, n):
"""Helper for _sdm_to_vector."""
from sympy.polys.distributedmodules import sdm_to_dict
dic = sdm_to_dict(s)
res = [{} for _ in range(n)]
for k, v in dic.items():
res[k[0]][k[1:]] = v
return res
def _sdm_to_vector(self, s, n):
"""
For internal use by the modules class.
Convert a sparse distributed module into a list of length ``n``.
>>> from sympy import QQ, ilex
>>> from sympy.abc import x, y
>>> R = QQ.old_poly_ring(x, y, order=ilex)
>>> L = [((1, 1, 1), QQ(1)), ((0, 1, 0), QQ(1)), ((0, 0, 1), QQ(2))]
>>> R._sdm_to_vector(L, 2)
[x + 2*y, x*y]
"""
dics = self._sdm_to_dics(s, n)
# NOTE this works for global and local rings!
return [self(x) for x in dics]
def free_module(self, rank):
"""
Generate a free module of rank ``rank`` over ``self``.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> QQ.old_poly_ring(x).free_module(2)
QQ[x]**2
"""
return FreeModulePolyRing(self, rank)
def _vector_to_sdm_helper(v, order):
"""Helper method for common code in Global and Local poly rings."""
from sympy.polys.distributedmodules import sdm_from_dict
d = {}
for i, e in enumerate(v):
for key, value in e.to_dict().items():
d[(i,) + key] = value
return sdm_from_dict(d, order)
@public
class GlobalPolynomialRing(PolynomialRingBase):
"""A true polynomial ring, with objects DMP. """
is_PolynomialRing = is_Poly = True
dtype = DMP
def from_FractionField(K1, a, K0):
"""
Convert a ``DMF`` object to ``DMP``.
Examples
========
>>> from sympy.polys.polyclasses import DMP, DMF
>>> from sympy.polys.domains import ZZ
>>> from sympy.abc import x
>>> f = DMF(([ZZ(1), ZZ(1)], [ZZ(1)]), ZZ)
>>> K = ZZ.old_frac_field(x)
>>> F = ZZ.old_poly_ring(x).from_FractionField(f, K)
>>> F == DMP([ZZ(1), ZZ(1)], ZZ)
True
>>> type(F)
<class 'sympy.polys.polyclasses.DMP'>
"""
if a.denom().is_one:
return K1.from_GlobalPolynomialRing(a.numer(), K0)
def to_sympy(self, a):
"""Convert `a` to a SymPy object. """
return basic_from_dict(a.to_sympy_dict(), *self.gens)
def from_sympy(self, a):
"""Convert SymPy's expression to `dtype`. """
try:
rep, _ = dict_from_basic(a, gens=self.gens)
except PolynomialError:
raise CoercionFailed("can't convert %s to type %s" % (a, self))
for k, v in rep.items():
rep[k] = self.dom.from_sympy(v)
return self(rep)
def is_positive(self, a):
"""Returns True if `LC(a)` is positive. """
return self.dom.is_positive(a.LC())
def is_negative(self, a):
"""Returns True if `LC(a)` is negative. """
return self.dom.is_negative(a.LC())
def is_nonpositive(self, a):
"""Returns True if `LC(a)` is non-positive. """
return self.dom.is_nonpositive(a.LC())
def is_nonnegative(self, a):
"""Returns True if `LC(a)` is non-negative. """
return self.dom.is_nonnegative(a.LC())
def _vector_to_sdm(self, v, order):
"""
>>> from sympy import lex, QQ
>>> from sympy.abc import x, y
>>> R = QQ.old_poly_ring(x, y)
>>> f = R.convert(x + 2*y)
>>> g = R.convert(x * y)
>>> R._vector_to_sdm([f, g], lex)
[((1, 1, 1), 1), ((0, 1, 0), 1), ((0, 0, 1), 2)]
"""
return _vector_to_sdm_helper(v, order)
class GeneralizedPolynomialRing(PolynomialRingBase):
"""A generalized polynomial ring, with objects DMF. """
dtype = DMF
def new(self, a):
"""Construct an element of `self` domain from `a`. """
res = self.dtype(a, self.dom, len(self.gens) - 1, ring=self)
# make sure res is actually in our ring
if res.denom().terms(order=self.order)[0][0] != (0,)*len(self.gens):
from sympy.printing.str import sstr
raise CoercionFailed("denominator %s not allowed in %s"
% (sstr(res), self))
return res
def __contains__(self, a):
try:
a = self.convert(a)
except CoercionFailed:
return False
return a.denom().terms(order=self.order)[0][0] == (0,)*len(self.gens)
def from_FractionField(K1, a, K0):
dmf = K1.get_field().from_FractionField(a, K0)
return K1((dmf.num, dmf.den))
def to_sympy(self, a):
"""Convert `a` to a SymPy object. """
return (basic_from_dict(a.numer().to_sympy_dict(), *self.gens) /
basic_from_dict(a.denom().to_sympy_dict(), *self.gens))
def from_sympy(self, a):
"""Convert SymPy's expression to `dtype`. """
p, q = a.as_numer_denom()
num, _ = dict_from_basic(p, gens=self.gens)
den, _ = dict_from_basic(q, gens=self.gens)
for k, v in num.items():
num[k] = self.dom.from_sympy(v)
for k, v in den.items():
den[k] = self.dom.from_sympy(v)
return self((num, den)).cancel()
def _vector_to_sdm(self, v, order):
"""
Turn an iterable into a sparse distributed module.
Note that the vector is multiplied by a unit first to make all entries
polynomials.
>>> from sympy import ilex, QQ
>>> from sympy.abc import x, y
>>> R = QQ.old_poly_ring(x, y, order=ilex)
>>> f = R.convert((x + 2*y) / (1 + x))
>>> g = R.convert(x * y)
>>> R._vector_to_sdm([f, g], ilex)
[((0, 0, 1), 2), ((0, 1, 0), 1), ((1, 1, 1), 1), ((1,
2, 1), 1)]
"""
# NOTE this is quite inefficient...
u = self.one.numer()
for x in v:
u *= x.denom()
return _vector_to_sdm_helper([x.numer()*u/x.denom() for x in v], order)
@public
def PolynomialRing(dom, *gens, **opts):
r"""
Create a generalized multivariate polynomial ring.
A generalized polynomial ring is defined by a ground field `K`, a set
of generators (typically `x_1, \ldots, x_n`) and a monomial order `<`.
The monomial order can be global, local or mixed. In any case it induces
a total ordering on the monomials, and there exists for every (non-zero)
polynomial `f \in K[x_1, \ldots, x_n]` a well-defined "leading monomial"
`LM(f) = LM(f, >)`. One can then define a multiplicative subset
`S = S_> = \{f \in K[x_1, \ldots, x_n] | LM(f) = 1\}`. The generalized
polynomial ring corresponding to the monomial order is
`R = S^{-1}K[x_1, \ldots, x_n]`.
If `>` is a so-called global order, that is `1` is the smallest monomial,
then we just have `S = K` and `R = K[x_1, \ldots, x_n]`.
Examples
========
A few examples may make this clearer.
>>> from sympy.abc import x, y
>>> from sympy import QQ
Our first ring uses global lexicographic order.
>>> R1 = QQ.old_poly_ring(x, y, order=(("lex", x, y),))
The second ring uses local lexicographic order. Note that when using a
single (non-product) order, you can just specify the name and omit the
variables:
>>> R2 = QQ.old_poly_ring(x, y, order="ilex")
The third and fourth rings use a mixed orders:
>>> o1 = (("ilex", x), ("lex", y))
>>> o2 = (("lex", x), ("ilex", y))
>>> R3 = QQ.old_poly_ring(x, y, order=o1)
>>> R4 = QQ.old_poly_ring(x, y, order=o2)
We will investigate what elements of `K(x, y)` are contained in the various
rings.
>>> L = [x, 1/x, y/(1 + x), 1/(1 + y), 1/(1 + x*y)]
>>> test = lambda R: [f in R for f in L]
The first ring is just `K[x, y]`:
>>> test(R1)
[True, False, False, False, False]
The second ring is R1 localised at the maximal ideal (x, y):
>>> test(R2)
[True, False, True, True, True]
The third ring is R1 localised at the prime ideal (x):
>>> test(R3)
[True, False, True, False, True]
Finally the fourth ring is R1 localised at `S = K[x, y] \setminus yK[y]`:
>>> test(R4)
[True, False, False, True, False]
"""
order = opts.get("order", GeneralizedPolynomialRing.default_order)
if iterable(order):
order = build_product_order(order, gens)
order = monomial_key(order)
opts['order'] = order
if order.is_global:
return GlobalPolynomialRing(dom, *gens, **opts)
else:
return GeneralizedPolynomialRing(dom, *gens, **opts)
| 13,861 | 31.087963 | 83 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/domains/modularinteger.py
|
"""Implementation of :class:`ModularInteger` class. """
from __future__ import print_function, division
import operator
from sympy.polys.polyutils import PicklableWithSlots
from sympy.polys.polyerrors import CoercionFailed
from sympy.polys.domains.domainelement import DomainElement
from sympy.utilities import public
@public
class ModularInteger(PicklableWithSlots, DomainElement):
"""A class representing a modular integer. """
mod, dom, sym, _parent = None, None, None, None
__slots__ = ['val']
def parent(self):
return self._parent
def __init__(self, val):
if isinstance(val, self.__class__):
self.val = val.val % self.mod
else:
self.val = self.dom.convert(val) % self.mod
def __hash__(self):
return hash((self.val, self.mod))
def __repr__(self):
return "%s(%s)" % (self.__class__.__name__, self.val)
def __str__(self):
return "%s mod %s" % (self.val, self.mod)
def __int__(self):
return int(self.to_int())
def to_int(self):
if self.sym:
if self.val <= self.mod // 2:
return self.val
else:
return self.val - self.mod
else:
return self.val
def __pos__(self):
return self
def __neg__(self):
return self.__class__(-self.val)
@classmethod
def _get_val(cls, other):
if isinstance(other, cls):
return other.val
else:
try:
return cls.dom.convert(other)
except CoercionFailed:
return None
def __add__(self, other):
val = self._get_val(other)
if val is not None:
return self.__class__(self.val + val)
else:
return NotImplemented
def __radd__(self, other):
return self.__add__(other)
def __sub__(self, other):
val = self._get_val(other)
if val is not None:
return self.__class__(self.val - val)
else:
return NotImplemented
def __rsub__(self, other):
return (-self).__add__(other)
def __mul__(self, other):
val = self._get_val(other)
if val is not None:
return self.__class__(self.val * val)
else:
return NotImplemented
def __rmul__(self, other):
return self.__mul__(other)
def __div__(self, other):
val = self._get_val(other)
if val is not None:
return self.__class__(self.val * self._invert(val))
else:
return NotImplemented
def __rdiv__(self, other):
return self.invert().__mul__(other)
__truediv__ = __div__
__rtruediv__ = __rdiv__
def __mod__(self, other):
val = self._get_val(other)
if val is not None:
return self.__class__(self.val % val)
else:
return NotImplemented
def __rmod__(self, other):
val = self._get_val(other)
if val is not None:
return self.__class__(val % self.val)
else:
return NotImplemented
def __pow__(self, exp):
if not exp:
return self.__class__(self.dom.one)
if exp < 0:
val, exp = self.invert(), -exp
else:
val = self.val
return self.__class__(val**exp)
def _compare(self, other, op):
val = self._get_val(other)
if val is not None:
return op(self.val, val % self.mod)
else:
return NotImplemented
def __eq__(self, other):
return self._compare(other, operator.eq)
def __ne__(self, other):
return self._compare(other, operator.ne)
def __lt__(self, other):
return self._compare(other, operator.lt)
def __le__(self, other):
return self._compare(other, operator.le)
def __gt__(self, other):
return self._compare(other, operator.gt)
def __ge__(self, other):
return self._compare(other, operator.ge)
def __nonzero__(self):
return bool(self.val)
__bool__ = __nonzero__
@classmethod
def _invert(cls, value):
return cls.dom.invert(value, cls.mod)
def invert(self):
return self.__class__(self._invert(self.val))
_modular_integer_cache = {}
def ModularIntegerFactory(_mod, _dom, _sym, parent):
"""Create custom class for specific integer modulus."""
try:
_mod = _dom.convert(_mod)
except CoercionFailed:
ok = False
else:
ok = True
if not ok or _mod < 1:
raise ValueError("modulus must be a positive integer, got %s" % _mod)
key = _mod, _dom, _sym
try:
cls = _modular_integer_cache[key]
except KeyError:
class cls(ModularInteger):
mod, dom, sym = _mod, _dom, _sym
_parent = parent
if _sym:
cls.__name__ = "SymmetricModularIntegerMod%s" % _mod
else:
cls.__name__ = "ModularIntegerMod%s" % _mod
_modular_integer_cache[key] = cls
return cls
| 5,087 | 23.228571 | 77 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/domains/gmpyintegerring.py
|
"""Implementaton of :class:`GMPYIntegerRing` class. """
from __future__ import print_function, division
from sympy.polys.domains.integerring import IntegerRing
from sympy.polys.domains.groundtypes import (
GMPYInteger, SymPyInteger,
gmpy_factorial,
gmpy_gcdex, gmpy_gcd, gmpy_lcm, gmpy_sqrt,
)
from sympy.polys.polyerrors import CoercionFailed
from sympy.utilities import public
@public
class GMPYIntegerRing(IntegerRing):
"""Integer ring based on GMPY's ``mpz`` type. """
dtype = GMPYInteger
zero = dtype(0)
one = dtype(1)
tp = type(one)
alias = 'ZZ_gmpy'
def __init__(self):
"""Allow instantiation of this domain. """
def to_sympy(self, a):
"""Convert ``a`` to a SymPy object. """
return SymPyInteger(int(a))
def from_sympy(self, a):
"""Convert SymPy's Integer to ``dtype``. """
if a.is_Integer:
return GMPYInteger(a.p)
elif a.is_Float and int(a) == a:
return GMPYInteger(int(a))
else:
raise CoercionFailed("expected an integer, got %s" % a)
def from_FF_python(K1, a, K0):
"""Convert ``ModularInteger(int)`` to GMPY's ``mpz``. """
return GMPYInteger(a.to_int())
def from_ZZ_python(K1, a, K0):
"""Convert Python's ``int`` to GMPY's ``mpz``. """
return GMPYInteger(a)
def from_QQ_python(K1, a, K0):
"""Convert Python's ``Fraction`` to GMPY's ``mpz``. """
if a.denominator == 1:
return GMPYInteger(a.numerator)
def from_FF_gmpy(K1, a, K0):
"""Convert ``ModularInteger(mpz)`` to GMPY's ``mpz``. """
return a.to_int()
def from_ZZ_gmpy(K1, a, K0):
"""Convert GMPY's ``mpz`` to GMPY's ``mpz``. """
return a
def from_QQ_gmpy(K1, a, K0):
"""Convert GMPY ``mpq`` to GMPY's ``mpz``. """
if a.denominator == 1:
return a.numerator
def from_RealField(K1, a, K0):
"""Convert mpmath's ``mpf`` to GMPY's ``mpz``. """
p, q = K0.to_rational(a)
if q == 1:
return GMPYInteger(p)
def gcdex(self, a, b):
"""Compute extended GCD of ``a`` and ``b``. """
h, s, t = gmpy_gcdex(a, b)
return s, t, h
def gcd(self, a, b):
"""Compute GCD of ``a`` and ``b``. """
return gmpy_gcd(a, b)
def lcm(self, a, b):
"""Compute LCM of ``a`` and ``b``. """
return gmpy_lcm(a, b)
def sqrt(self, a):
"""Compute square root of ``a``. """
return gmpy_sqrt(a)
def factorial(self, a):
"""Compute factorial of ``a``. """
return gmpy_factorial(a)
| 2,650 | 27.202128 | 67 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/domains/tests/test_polynomialring.py
|
"""Tests for the PolynomialRing classes. """
from sympy.polys.domains import QQ, ZZ
from sympy.polys.polyerrors import ExactQuotientFailed, CoercionFailed, NotReversible
from sympy.abc import x, y
from sympy.utilities.pytest import raises
def test_build_order():
R = QQ.old_poly_ring(x, y, order=(("lex", x), ("ilex", y)))
assert R.order((1, 5)) == ((1,), (-5,))
def test_globalring():
Qxy = QQ.old_frac_field(x, y)
R = QQ.old_poly_ring(x, y)
X = R.convert(x)
Y = R.convert(y)
assert x in R
assert 1/x not in R
assert 1/(1 + x) not in R
assert Y in R
assert X.ring == R
assert X * (Y**2 + 1) == R.convert(x * (y**2 + 1))
assert X * y == X * Y == R.convert(x * y) == x * Y
assert X + y == X + Y == R.convert(x + y) == x + Y
assert X - y == X - Y == R.convert(x - y) == x - Y
assert X + 1 == R.convert(x + 1)
raises(ExactQuotientFailed, lambda: X/Y)
raises(ExactQuotientFailed, lambda: x/Y)
raises(ExactQuotientFailed, lambda: X/y)
assert X**2 / X == X
assert R.from_GlobalPolynomialRing(ZZ.old_poly_ring(x, y).convert(x), ZZ.old_poly_ring(x, y)) == X
assert R.from_FractionField(Qxy.convert(x), Qxy) == X
assert R.from_FractionField(Qxy.convert(x)/y, Qxy) is None
assert R._sdm_to_vector(R._vector_to_sdm([X, Y], R.order), 2) == [X, Y]
def test_localring():
Qxy = QQ.old_frac_field(x, y)
R = QQ.old_poly_ring(x, y, order="ilex")
X = R.convert(x)
Y = R.convert(y)
assert x in R
assert 1/x not in R
assert 1/(1 + x) in R
assert Y in R
assert X.ring == R
assert X*(Y**2 + 1)/(1 + X) == R.convert(x*(y**2 + 1)/(1 + x))
assert X*y == X*Y
raises(ExactQuotientFailed, lambda: X/Y)
raises(ExactQuotientFailed, lambda: x/Y)
raises(ExactQuotientFailed, lambda: X/y)
assert X + y == X + Y == R.convert(x + y) == x + Y
assert X - y == X - Y == R.convert(x - y) == x - Y
assert X + 1 == R.convert(x + 1)
assert X**2 / X == X
assert R.from_GlobalPolynomialRing(ZZ.old_poly_ring(x, y).convert(x), ZZ.old_poly_ring(x, y)) == X
assert R.from_FractionField(Qxy.convert(x), Qxy) == X
raises(CoercionFailed, lambda: R.from_FractionField(Qxy.convert(x)/y, Qxy))
raises(ExactQuotientFailed, lambda: X/Y)
raises(NotReversible, lambda: X.invert())
assert R._sdm_to_vector(
R._vector_to_sdm([X/(X + 1), Y/(1 + X*Y)], R.order), 2) == \
[X*(1 + X*Y), Y*(1 + X)]
def test_conversion():
L = QQ.old_poly_ring(x, y, order="ilex")
G = QQ.old_poly_ring(x, y)
assert L.convert(x) == L.convert(G.convert(x), G)
assert G.convert(x) == G.convert(L.convert(x), L)
raises(CoercionFailed, lambda: G.convert(L.convert(1/(1 + x)), L))
def test_units():
R = QQ.old_poly_ring(x)
assert R.is_unit(R.convert(1))
assert R.is_unit(R.convert(2))
assert not R.is_unit(R.convert(x))
assert not R.is_unit(R.convert(1 + x))
R = QQ.old_poly_ring(x, order='ilex')
assert R.is_unit(R.convert(1))
assert R.is_unit(R.convert(2))
assert not R.is_unit(R.convert(x))
assert R.is_unit(R.convert(1 + x))
R = ZZ.old_poly_ring(x)
assert R.is_unit(R.convert(1))
assert not R.is_unit(R.convert(2))
assert not R.is_unit(R.convert(x))
assert not R.is_unit(R.convert(1 + x))
| 3,314 | 31.184466 | 102 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/domains/tests/__init__.py
| 0 | 0 | 0 |
py
|
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/domains/tests/test_domains.py
|
"""Tests for classes defining properties of ground domains, e.g. ZZ, QQ, ZZ[x] ... """
from sympy import S, sqrt, sin, oo, Poly, Float
from sympy.abc import x, y, z
from sympy.polys.domains import ZZ, QQ, RR, CC, FF, GF, EX
from sympy.polys.domains.realfield import RealField
from sympy.polys.rings import ring
from sympy.polys.fields import field
from sympy.polys.polyerrors import (
UnificationFailed,
GeneratorsError,
CoercionFailed,
NotInvertible,
DomainError)
from sympy.utilities.pytest import raises
ALG = QQ.algebraic_field(sqrt(2), sqrt(3))
def unify(K0, K1):
return K0.unify(K1)
def test_Domain_unify():
F3 = GF(3)
assert unify(F3, F3) == F3
assert unify(F3, ZZ) == ZZ
assert unify(F3, QQ) == QQ
assert unify(F3, ALG) == ALG
assert unify(F3, RR) == RR
assert unify(F3, CC) == CC
assert unify(F3, ZZ[x]) == ZZ[x]
assert unify(F3, ZZ.frac_field(x)) == ZZ.frac_field(x)
assert unify(F3, EX) == EX
assert unify(ZZ, F3) == ZZ
assert unify(ZZ, ZZ) == ZZ
assert unify(ZZ, QQ) == QQ
assert unify(ZZ, ALG) == ALG
assert unify(ZZ, RR) == RR
assert unify(ZZ, CC) == CC
assert unify(ZZ, ZZ[x]) == ZZ[x]
assert unify(ZZ, ZZ.frac_field(x)) == ZZ.frac_field(x)
assert unify(ZZ, EX) == EX
assert unify(QQ, F3) == QQ
assert unify(QQ, ZZ) == QQ
assert unify(QQ, QQ) == QQ
assert unify(QQ, ALG) == ALG
assert unify(QQ, RR) == RR
assert unify(QQ, CC) == CC
assert unify(QQ, ZZ[x]) == QQ[x]
assert unify(QQ, ZZ.frac_field(x)) == QQ.frac_field(x)
assert unify(QQ, EX) == EX
assert unify(RR, F3) == RR
assert unify(RR, ZZ) == RR
assert unify(RR, QQ) == RR
assert unify(RR, ALG) == RR
assert unify(RR, RR) == RR
assert unify(RR, CC) == CC
assert unify(RR, ZZ[x]) == RR[x]
assert unify(RR, ZZ.frac_field(x)) == RR.frac_field(x)
assert unify(RR, EX) == EX
assert RR[x].unify(ZZ.frac_field(y)) == RR.frac_field(x, y)
assert unify(CC, F3) == CC
assert unify(CC, ZZ) == CC
assert unify(CC, QQ) == CC
assert unify(CC, ALG) == CC
assert unify(CC, RR) == CC
assert unify(CC, CC) == CC
assert unify(CC, ZZ[x]) == CC[x]
assert unify(CC, ZZ.frac_field(x)) == CC.frac_field(x)
assert unify(CC, EX) == EX
assert unify(ZZ[x], F3) == ZZ[x]
assert unify(ZZ[x], ZZ) == ZZ[x]
assert unify(ZZ[x], QQ) == QQ[x]
assert unify(ZZ[x], ALG) == ALG[x]
assert unify(ZZ[x], RR) == RR[x]
assert unify(ZZ[x], CC) == CC[x]
assert unify(ZZ[x], ZZ[x]) == ZZ[x]
assert unify(ZZ[x], ZZ.frac_field(x)) == ZZ.frac_field(x)
assert unify(ZZ[x], EX) == EX
assert unify(ZZ.frac_field(x), F3) == ZZ.frac_field(x)
assert unify(ZZ.frac_field(x), ZZ) == ZZ.frac_field(x)
assert unify(ZZ.frac_field(x), QQ) == QQ.frac_field(x)
assert unify(ZZ.frac_field(x), ALG) == ALG.frac_field(x)
assert unify(ZZ.frac_field(x), RR) == RR.frac_field(x)
assert unify(ZZ.frac_field(x), CC) == CC.frac_field(x)
assert unify(ZZ.frac_field(x), ZZ[x]) == ZZ.frac_field(x)
assert unify(ZZ.frac_field(x), ZZ.frac_field(x)) == ZZ.frac_field(x)
assert unify(ZZ.frac_field(x), EX) == EX
assert unify(EX, F3) == EX
assert unify(EX, ZZ) == EX
assert unify(EX, QQ) == EX
assert unify(EX, ALG) == EX
assert unify(EX, RR) == EX
assert unify(EX, CC) == EX
assert unify(EX, ZZ[x]) == EX
assert unify(EX, ZZ.frac_field(x)) == EX
assert unify(EX, EX) == EX
def test_Domain_unify_composite():
assert unify(ZZ.poly_ring(x), ZZ) == ZZ.poly_ring(x)
assert unify(ZZ.poly_ring(x), QQ) == QQ.poly_ring(x)
assert unify(QQ.poly_ring(x), ZZ) == QQ.poly_ring(x)
assert unify(QQ.poly_ring(x), QQ) == QQ.poly_ring(x)
assert unify(ZZ, ZZ.poly_ring(x)) == ZZ.poly_ring(x)
assert unify(QQ, ZZ.poly_ring(x)) == QQ.poly_ring(x)
assert unify(ZZ, QQ.poly_ring(x)) == QQ.poly_ring(x)
assert unify(QQ, QQ.poly_ring(x)) == QQ.poly_ring(x)
assert unify(ZZ.poly_ring(x, y), ZZ) == ZZ.poly_ring(x, y)
assert unify(ZZ.poly_ring(x, y), QQ) == QQ.poly_ring(x, y)
assert unify(QQ.poly_ring(x, y), ZZ) == QQ.poly_ring(x, y)
assert unify(QQ.poly_ring(x, y), QQ) == QQ.poly_ring(x, y)
assert unify(ZZ, ZZ.poly_ring(x, y)) == ZZ.poly_ring(x, y)
assert unify(QQ, ZZ.poly_ring(x, y)) == QQ.poly_ring(x, y)
assert unify(ZZ, QQ.poly_ring(x, y)) == QQ.poly_ring(x, y)
assert unify(QQ, QQ.poly_ring(x, y)) == QQ.poly_ring(x, y)
assert unify(ZZ.frac_field(x), ZZ) == ZZ.frac_field(x)
assert unify(ZZ.frac_field(x), QQ) == QQ.frac_field(x)
assert unify(QQ.frac_field(x), ZZ) == QQ.frac_field(x)
assert unify(QQ.frac_field(x), QQ) == QQ.frac_field(x)
assert unify(ZZ, ZZ.frac_field(x)) == ZZ.frac_field(x)
assert unify(QQ, ZZ.frac_field(x)) == QQ.frac_field(x)
assert unify(ZZ, QQ.frac_field(x)) == QQ.frac_field(x)
assert unify(QQ, QQ.frac_field(x)) == QQ.frac_field(x)
assert unify(ZZ.frac_field(x, y), ZZ) == ZZ.frac_field(x, y)
assert unify(ZZ.frac_field(x, y), QQ) == QQ.frac_field(x, y)
assert unify(QQ.frac_field(x, y), ZZ) == QQ.frac_field(x, y)
assert unify(QQ.frac_field(x, y), QQ) == QQ.frac_field(x, y)
assert unify(ZZ, ZZ.frac_field(x, y)) == ZZ.frac_field(x, y)
assert unify(QQ, ZZ.frac_field(x, y)) == QQ.frac_field(x, y)
assert unify(ZZ, QQ.frac_field(x, y)) == QQ.frac_field(x, y)
assert unify(QQ, QQ.frac_field(x, y)) == QQ.frac_field(x, y)
assert unify(ZZ.poly_ring(x), ZZ.poly_ring(x)) == ZZ.poly_ring(x)
assert unify(ZZ.poly_ring(x), QQ.poly_ring(x)) == QQ.poly_ring(x)
assert unify(QQ.poly_ring(x), ZZ.poly_ring(x)) == QQ.poly_ring(x)
assert unify(QQ.poly_ring(x), QQ.poly_ring(x)) == QQ.poly_ring(x)
assert unify(ZZ.poly_ring(x, y), ZZ.poly_ring(x)) == ZZ.poly_ring(x, y)
assert unify(ZZ.poly_ring(x, y), QQ.poly_ring(x)) == QQ.poly_ring(x, y)
assert unify(QQ.poly_ring(x, y), ZZ.poly_ring(x)) == QQ.poly_ring(x, y)
assert unify(QQ.poly_ring(x, y), QQ.poly_ring(x)) == QQ.poly_ring(x, y)
assert unify(ZZ.poly_ring(x), ZZ.poly_ring(x, y)) == ZZ.poly_ring(x, y)
assert unify(ZZ.poly_ring(x), QQ.poly_ring(x, y)) == QQ.poly_ring(x, y)
assert unify(QQ.poly_ring(x), ZZ.poly_ring(x, y)) == QQ.poly_ring(x, y)
assert unify(QQ.poly_ring(x), QQ.poly_ring(x, y)) == QQ.poly_ring(x, y)
assert unify(ZZ.poly_ring(x, y), ZZ.poly_ring(x, z)) == ZZ.poly_ring(x, y, z)
assert unify(ZZ.poly_ring(x, y), QQ.poly_ring(x, z)) == QQ.poly_ring(x, y, z)
assert unify(QQ.poly_ring(x, y), ZZ.poly_ring(x, z)) == QQ.poly_ring(x, y, z)
assert unify(QQ.poly_ring(x, y), QQ.poly_ring(x, z)) == QQ.poly_ring(x, y, z)
assert unify(ZZ.frac_field(x), ZZ.frac_field(x)) == ZZ.frac_field(x)
assert unify(ZZ.frac_field(x), QQ.frac_field(x)) == QQ.frac_field(x)
assert unify(QQ.frac_field(x), ZZ.frac_field(x)) == QQ.frac_field(x)
assert unify(QQ.frac_field(x), QQ.frac_field(x)) == QQ.frac_field(x)
assert unify(ZZ.frac_field(x, y), ZZ.frac_field(x)) == ZZ.frac_field(x, y)
assert unify(ZZ.frac_field(x, y), QQ.frac_field(x)) == QQ.frac_field(x, y)
assert unify(QQ.frac_field(x, y), ZZ.frac_field(x)) == QQ.frac_field(x, y)
assert unify(QQ.frac_field(x, y), QQ.frac_field(x)) == QQ.frac_field(x, y)
assert unify(ZZ.frac_field(x), ZZ.frac_field(x, y)) == ZZ.frac_field(x, y)
assert unify(ZZ.frac_field(x), QQ.frac_field(x, y)) == QQ.frac_field(x, y)
assert unify(QQ.frac_field(x), ZZ.frac_field(x, y)) == QQ.frac_field(x, y)
assert unify(QQ.frac_field(x), QQ.frac_field(x, y)) == QQ.frac_field(x, y)
assert unify(ZZ.frac_field(x, y), ZZ.frac_field(x, z)) == ZZ.frac_field(x, y, z)
assert unify(ZZ.frac_field(x, y), QQ.frac_field(x, z)) == QQ.frac_field(x, y, z)
assert unify(QQ.frac_field(x, y), ZZ.frac_field(x, z)) == QQ.frac_field(x, y, z)
assert unify(QQ.frac_field(x, y), QQ.frac_field(x, z)) == QQ.frac_field(x, y, z)
assert unify(ZZ.poly_ring(x), ZZ.frac_field(x)) == ZZ.frac_field(x)
assert unify(ZZ.poly_ring(x), QQ.frac_field(x)) == ZZ.frac_field(x)
assert unify(QQ.poly_ring(x), ZZ.frac_field(x)) == ZZ.frac_field(x)
assert unify(QQ.poly_ring(x), QQ.frac_field(x)) == QQ.frac_field(x)
assert unify(ZZ.poly_ring(x, y), ZZ.frac_field(x)) == ZZ.frac_field(x, y)
assert unify(ZZ.poly_ring(x, y), QQ.frac_field(x)) == ZZ.frac_field(x, y)
assert unify(QQ.poly_ring(x, y), ZZ.frac_field(x)) == ZZ.frac_field(x, y)
assert unify(QQ.poly_ring(x, y), QQ.frac_field(x)) == QQ.frac_field(x, y)
assert unify(ZZ.poly_ring(x), ZZ.frac_field(x, y)) == ZZ.frac_field(x, y)
assert unify(ZZ.poly_ring(x), QQ.frac_field(x, y)) == ZZ.frac_field(x, y)
assert unify(QQ.poly_ring(x), ZZ.frac_field(x, y)) == ZZ.frac_field(x, y)
assert unify(QQ.poly_ring(x), QQ.frac_field(x, y)) == QQ.frac_field(x, y)
assert unify(ZZ.poly_ring(x, y), ZZ.frac_field(x, z)) == ZZ.frac_field(x, y, z)
assert unify(ZZ.poly_ring(x, y), QQ.frac_field(x, z)) == ZZ.frac_field(x, y, z)
assert unify(QQ.poly_ring(x, y), ZZ.frac_field(x, z)) == ZZ.frac_field(x, y, z)
assert unify(QQ.poly_ring(x, y), QQ.frac_field(x, z)) == QQ.frac_field(x, y, z)
assert unify(ZZ.frac_field(x), ZZ.poly_ring(x)) == ZZ.frac_field(x)
assert unify(ZZ.frac_field(x), QQ.poly_ring(x)) == ZZ.frac_field(x)
assert unify(QQ.frac_field(x), ZZ.poly_ring(x)) == ZZ.frac_field(x)
assert unify(QQ.frac_field(x), QQ.poly_ring(x)) == QQ.frac_field(x)
assert unify(ZZ.frac_field(x, y), ZZ.poly_ring(x)) == ZZ.frac_field(x, y)
assert unify(ZZ.frac_field(x, y), QQ.poly_ring(x)) == ZZ.frac_field(x, y)
assert unify(QQ.frac_field(x, y), ZZ.poly_ring(x)) == ZZ.frac_field(x, y)
assert unify(QQ.frac_field(x, y), QQ.poly_ring(x)) == QQ.frac_field(x, y)
assert unify(ZZ.frac_field(x), ZZ.poly_ring(x, y)) == ZZ.frac_field(x, y)
assert unify(ZZ.frac_field(x), QQ.poly_ring(x, y)) == ZZ.frac_field(x, y)
assert unify(QQ.frac_field(x), ZZ.poly_ring(x, y)) == ZZ.frac_field(x, y)
assert unify(QQ.frac_field(x), QQ.poly_ring(x, y)) == QQ.frac_field(x, y)
assert unify(ZZ.frac_field(x, y), ZZ.poly_ring(x, z)) == ZZ.frac_field(x, y, z)
assert unify(ZZ.frac_field(x, y), QQ.poly_ring(x, z)) == ZZ.frac_field(x, y, z)
assert unify(QQ.frac_field(x, y), ZZ.poly_ring(x, z)) == ZZ.frac_field(x, y, z)
assert unify(QQ.frac_field(x, y), QQ.poly_ring(x, z)) == QQ.frac_field(x, y, z)
def test_Domain_unify_algebraic():
sqrt5 = QQ.algebraic_field(sqrt(5))
sqrt7 = QQ.algebraic_field(sqrt(7))
sqrt57 = QQ.algebraic_field(sqrt(5), sqrt(7))
assert sqrt5.unify(sqrt7) == sqrt57
assert sqrt5.unify(sqrt5[x, y]) == sqrt5[x, y]
assert sqrt5[x, y].unify(sqrt5) == sqrt5[x, y]
assert sqrt5.unify(sqrt5.frac_field(x, y)) == sqrt5.frac_field(x, y)
assert sqrt5.frac_field(x, y).unify(sqrt5) == sqrt5.frac_field(x, y)
assert sqrt5.unify(sqrt7[x, y]) == sqrt57[x, y]
assert sqrt5[x, y].unify(sqrt7) == sqrt57[x, y]
assert sqrt5.unify(sqrt7.frac_field(x, y)) == sqrt57.frac_field(x, y)
assert sqrt5.frac_field(x, y).unify(sqrt7) == sqrt57.frac_field(x, y)
def test_Domain_unify_with_symbols():
raises(UnificationFailed, lambda: ZZ[x, y].unify_with_symbols(ZZ, (y, z)))
raises(UnificationFailed, lambda: ZZ.unify_with_symbols(ZZ[x, y], (y, z)))
def test_Domain__contains__():
assert (0 in EX) is True
assert (0 in ZZ) is True
assert (0 in QQ) is True
assert (0 in RR) is True
assert (0 in CC) is True
assert (0 in ALG) is True
assert (0 in ZZ[x, y]) is True
assert (0 in QQ[x, y]) is True
assert (0 in RR[x, y]) is True
assert (-7 in EX) is True
assert (-7 in ZZ) is True
assert (-7 in QQ) is True
assert (-7 in RR) is True
assert (-7 in CC) is True
assert (-7 in ALG) is True
assert (-7 in ZZ[x, y]) is True
assert (-7 in QQ[x, y]) is True
assert (-7 in RR[x, y]) is True
assert (17 in EX) is True
assert (17 in ZZ) is True
assert (17 in QQ) is True
assert (17 in RR) is True
assert (17 in CC) is True
assert (17 in ALG) is True
assert (17 in ZZ[x, y]) is True
assert (17 in QQ[x, y]) is True
assert (17 in RR[x, y]) is True
assert (-S(1)/7 in EX) is True
assert (-S(1)/7 in ZZ) is False
assert (-S(1)/7 in QQ) is True
assert (-S(1)/7 in RR) is True
assert (-S(1)/7 in CC) is True
assert (-S(1)/7 in ALG) is True
assert (-S(1)/7 in ZZ[x, y]) is False
assert (-S(1)/7 in QQ[x, y]) is True
assert (-S(1)/7 in RR[x, y]) is True
assert (S(3)/5 in EX) is True
assert (S(3)/5 in ZZ) is False
assert (S(3)/5 in QQ) is True
assert (S(3)/5 in RR) is True
assert (S(3)/5 in CC) is True
assert (S(3)/5 in ALG) is True
assert (S(3)/5 in ZZ[x, y]) is False
assert (S(3)/5 in QQ[x, y]) is True
assert (S(3)/5 in RR[x, y]) is True
assert (3.0 in EX) is True
assert (3.0 in ZZ) is True
assert (3.0 in QQ) is True
assert (3.0 in RR) is True
assert (3.0 in CC) is True
assert (3.0 in ALG) is True
assert (3.0 in ZZ[x, y]) is True
assert (3.0 in QQ[x, y]) is True
assert (3.0 in RR[x, y]) is True
assert (3.14 in EX) is True
assert (3.14 in ZZ) is False
assert (3.14 in QQ) is True
assert (3.14 in RR) is True
assert (3.14 in CC) is True
assert (3.14 in ALG) is True
assert (3.14 in ZZ[x, y]) is False
assert (3.14 in QQ[x, y]) is True
assert (3.14 in RR[x, y]) is True
assert (oo in EX) is True
assert (oo in ZZ) is False
assert (oo in QQ) is False
assert (oo in RR) is True
assert (oo in CC) is True
assert (oo in ALG) is False
assert (oo in ZZ[x, y]) is False
assert (oo in QQ[x, y]) is False
assert (oo in RR[x, y]) is True
assert (-oo in EX) is True
assert (-oo in ZZ) is False
assert (-oo in QQ) is False
assert (-oo in RR) is True
assert (-oo in CC) is True
assert (-oo in ALG) is False
assert (-oo in ZZ[x, y]) is False
assert (-oo in QQ[x, y]) is False
assert (-oo in RR[x, y]) is True
assert (sqrt(7) in EX) is True
assert (sqrt(7) in ZZ) is False
assert (sqrt(7) in QQ) is False
assert (sqrt(7) in RR) is True
assert (sqrt(7) in CC) is True
assert (sqrt(7) in ALG) is False
assert (sqrt(7) in ZZ[x, y]) is False
assert (sqrt(7) in QQ[x, y]) is False
assert (sqrt(7) in RR[x, y]) is True
assert (2*sqrt(3) + 1 in EX) is True
assert (2*sqrt(3) + 1 in ZZ) is False
assert (2*sqrt(3) + 1 in QQ) is False
assert (2*sqrt(3) + 1 in RR) is True
assert (2*sqrt(3) + 1 in CC) is True
assert (2*sqrt(3) + 1 in ALG) is True
assert (2*sqrt(3) + 1 in ZZ[x, y]) is False
assert (2*sqrt(3) + 1 in QQ[x, y]) is False
assert (2*sqrt(3) + 1 in RR[x, y]) is True
assert (sin(1) in EX) is True
assert (sin(1) in ZZ) is False
assert (sin(1) in QQ) is False
assert (sin(1) in RR) is True
assert (sin(1) in CC) is True
assert (sin(1) in ALG) is False
assert (sin(1) in ZZ[x, y]) is False
assert (sin(1) in QQ[x, y]) is False
assert (sin(1) in RR[x, y]) is True
assert (x**2 + 1 in EX) is True
assert (x**2 + 1 in ZZ) is False
assert (x**2 + 1 in QQ) is False
assert (x**2 + 1 in RR) is False
assert (x**2 + 1 in CC) is False
assert (x**2 + 1 in ALG) is False
assert (x**2 + 1 in ZZ[x]) is True
assert (x**2 + 1 in QQ[x]) is True
assert (x**2 + 1 in RR[x]) is True
assert (x**2 + 1 in ZZ[x, y]) is True
assert (x**2 + 1 in QQ[x, y]) is True
assert (x**2 + 1 in RR[x, y]) is True
assert (x**2 + y**2 in EX) is True
assert (x**2 + y**2 in ZZ) is False
assert (x**2 + y**2 in QQ) is False
assert (x**2 + y**2 in RR) is False
assert (x**2 + y**2 in CC) is False
assert (x**2 + y**2 in ALG) is False
assert (x**2 + y**2 in ZZ[x]) is False
assert (x**2 + y**2 in QQ[x]) is False
assert (x**2 + y**2 in RR[x]) is False
assert (x**2 + y**2 in ZZ[x, y]) is True
assert (x**2 + y**2 in QQ[x, y]) is True
assert (x**2 + y**2 in RR[x, y]) is True
assert (S(3)/2*x/(y + 1) - z in QQ[x, y, z]) is False
def test_Domain_get_ring():
assert ZZ.has_assoc_Ring is True
assert QQ.has_assoc_Ring is True
assert ZZ[x].has_assoc_Ring is True
assert QQ[x].has_assoc_Ring is True
assert ZZ[x, y].has_assoc_Ring is True
assert QQ[x, y].has_assoc_Ring is True
assert ZZ.frac_field(x).has_assoc_Ring is True
assert QQ.frac_field(x).has_assoc_Ring is True
assert ZZ.frac_field(x, y).has_assoc_Ring is True
assert QQ.frac_field(x, y).has_assoc_Ring is True
assert EX.has_assoc_Ring is False
assert RR.has_assoc_Ring is False
assert ALG.has_assoc_Ring is False
assert ZZ.get_ring() == ZZ
assert QQ.get_ring() == ZZ
assert ZZ[x].get_ring() == ZZ[x]
assert QQ[x].get_ring() == QQ[x]
assert ZZ[x, y].get_ring() == ZZ[x, y]
assert QQ[x, y].get_ring() == QQ[x, y]
assert ZZ.frac_field(x).get_ring() == ZZ[x]
assert QQ.frac_field(x).get_ring() == QQ[x]
assert ZZ.frac_field(x, y).get_ring() == ZZ[x, y]
assert QQ.frac_field(x, y).get_ring() == QQ[x, y]
assert EX.get_ring() == EX
assert RR.get_ring() == RR
# XXX: This should also be like RR
raises(DomainError, lambda: ALG.get_ring())
def test_Domain_get_field():
assert EX.has_assoc_Field is True
assert ZZ.has_assoc_Field is True
assert QQ.has_assoc_Field is True
assert RR.has_assoc_Field is True
assert ALG.has_assoc_Field is True
assert ZZ[x].has_assoc_Field is True
assert QQ[x].has_assoc_Field is True
assert ZZ[x, y].has_assoc_Field is True
assert QQ[x, y].has_assoc_Field is True
assert EX.get_field() == EX
assert ZZ.get_field() == QQ
assert QQ.get_field() == QQ
assert RR.get_field() == RR
assert ALG.get_field() == ALG
assert ZZ[x].get_field() == ZZ.frac_field(x)
assert QQ[x].get_field() == QQ.frac_field(x)
assert ZZ[x, y].get_field() == ZZ.frac_field(x, y)
assert QQ[x, y].get_field() == QQ.frac_field(x, y)
def test_Domain_get_exact():
assert EX.get_exact() == EX
assert ZZ.get_exact() == ZZ
assert QQ.get_exact() == QQ
assert RR.get_exact() == QQ
assert ALG.get_exact() == ALG
assert ZZ[x].get_exact() == ZZ[x]
assert QQ[x].get_exact() == QQ[x]
assert ZZ[x, y].get_exact() == ZZ[x, y]
assert QQ[x, y].get_exact() == QQ[x, y]
assert ZZ.frac_field(x).get_exact() == ZZ.frac_field(x)
assert QQ.frac_field(x).get_exact() == QQ.frac_field(x)
assert ZZ.frac_field(x, y).get_exact() == ZZ.frac_field(x, y)
assert QQ.frac_field(x, y).get_exact() == QQ.frac_field(x, y)
def test_Domain_convert():
assert QQ.convert(10e-52) == QQ(1684996666696915, 1684996666696914987166688442938726917102321526408785780068975640576)
R, x = ring("x", ZZ)
assert ZZ.convert(x - x) == 0
assert ZZ.convert(x - x, R.to_domain()) == 0
def test_PolynomialRing__init():
R, = ring("", ZZ)
assert ZZ.poly_ring() == R.to_domain()
def test_FractionField__init():
F, = field("", ZZ)
assert ZZ.frac_field() == F.to_domain()
def test_inject():
assert ZZ.inject(x, y, z) == ZZ[x, y, z]
assert ZZ[x].inject(y, z) == ZZ[x, y, z]
assert ZZ.frac_field(x).inject(y, z) == ZZ.frac_field(x, y, z)
raises(GeneratorsError, lambda: ZZ[x].inject(x))
def test_Domain_map():
seq = ZZ.map([1, 2, 3, 4])
assert all(ZZ.of_type(elt) for elt in seq)
seq = ZZ.map([[1, 2, 3, 4]])
assert all(ZZ.of_type(elt) for elt in seq[0]) and len(seq) == 1
def test_Domain___eq__():
assert (ZZ[x, y] == ZZ[x, y]) is True
assert (QQ[x, y] == QQ[x, y]) is True
assert (ZZ[x, y] == QQ[x, y]) is False
assert (QQ[x, y] == ZZ[x, y]) is False
assert (ZZ.frac_field(x, y) == ZZ.frac_field(x, y)) is True
assert (QQ.frac_field(x, y) == QQ.frac_field(x, y)) is True
assert (ZZ.frac_field(x, y) == QQ.frac_field(x, y)) is False
assert (QQ.frac_field(x, y) == ZZ.frac_field(x, y)) is False
assert RealField()[x] == RR[x]
def test_Domain__algebraic_field():
alg = ZZ.algebraic_field(sqrt(2))
assert alg.ext.minpoly == Poly(x**2 - 2)
assert alg.dom == QQ
alg = QQ.algebraic_field(sqrt(2))
assert alg.ext.minpoly == Poly(x**2 - 2)
assert alg.dom == QQ
alg = alg.algebraic_field(sqrt(3))
assert alg.ext.minpoly == Poly(x**4 - 10*x**2 + 1)
assert alg.dom == QQ
def test_PolynomialRing_from_FractionField():
F, x,y = field("x,y", ZZ)
R, X,Y = ring("x,y", ZZ)
f = (x**2 + y**2)/(x + 1)
g = (x**2 + y**2)/4
h = x**2 + y**2
assert R.to_domain().from_FractionField(f, F.to_domain()) is None
assert R.to_domain().from_FractionField(g, F.to_domain()) == X**2/4 + Y**2/4
assert R.to_domain().from_FractionField(h, F.to_domain()) == X**2 + Y**2
F, x,y = field("x,y", QQ)
R, X,Y = ring("x,y", QQ)
f = (x**2 + y**2)/(x + 1)
g = (x**2 + y**2)/4
h = x**2 + y**2
assert R.to_domain().from_FractionField(f, F.to_domain()) is None
assert R.to_domain().from_FractionField(g, F.to_domain()) == X**2/4 + Y**2/4
assert R.to_domain().from_FractionField(h, F.to_domain()) == X**2 + Y**2
def test_FractionField_from_PolynomialRing():
R, x,y = ring("x,y", QQ)
F, X,Y = field("x,y", ZZ)
f = 3*x**2 + 5*y**2
g = x**2/3 + y**2/5
assert F.to_domain().from_PolynomialRing(f, R.to_domain()) == 3*X**2 + 5*Y**2
assert F.to_domain().from_PolynomialRing(g, R.to_domain()) == (5*X**2 + 3*Y**2)/15
def test_FF_of_type():
assert FF(3).of_type(FF(3)(1)) is True
assert FF(5).of_type(FF(5)(3)) is True
assert FF(5).of_type(FF(7)(3)) is False
def test___eq__():
assert not QQ[x] == ZZ[x]
assert not QQ.frac_field(x) == ZZ.frac_field(x)
def test_RealField_from_sympy():
assert RR.convert(S(0)) == RR.dtype(0)
assert RR.convert(S(0.0)) == RR.dtype(0.0)
assert RR.convert(S(1)) == RR.dtype(1)
assert RR.convert(S(1.0)) == RR.dtype(1.0)
assert RR.convert(sin(1)) == RR.dtype(sin(1).evalf())
assert RR.convert(oo) == RR("+inf")
assert RR.convert(-oo) == RR("-inf")
raises(CoercionFailed, lambda: RR.convert(x))
def test_ModularInteger():
F3 = FF(3)
a = F3(0)
assert isinstance(a, F3.dtype) and a == 0
a = F3(1)
assert isinstance(a, F3.dtype) and a == 1
a = F3(2)
assert isinstance(a, F3.dtype) and a == 2
a = F3(3)
assert isinstance(a, F3.dtype) and a == 0
a = F3(4)
assert isinstance(a, F3.dtype) and a == 1
a = F3(F3(0))
assert isinstance(a, F3.dtype) and a == 0
a = F3(F3(1))
assert isinstance(a, F3.dtype) and a == 1
a = F3(F3(2))
assert isinstance(a, F3.dtype) and a == 2
a = F3(F3(3))
assert isinstance(a, F3.dtype) and a == 0
a = F3(F3(4))
assert isinstance(a, F3.dtype) and a == 1
a = -F3(1)
assert isinstance(a, F3.dtype) and a == 2
a = -F3(2)
assert isinstance(a, F3.dtype) and a == 1
a = 2 + F3(2)
assert isinstance(a, F3.dtype) and a == 1
a = F3(2) + 2
assert isinstance(a, F3.dtype) and a == 1
a = F3(2) + F3(2)
assert isinstance(a, F3.dtype) and a == 1
a = F3(2) + F3(2)
assert isinstance(a, F3.dtype) and a == 1
a = 3 - F3(2)
assert isinstance(a, F3.dtype) and a == 1
a = F3(3) - 2
assert isinstance(a, F3.dtype) and a == 1
a = F3(3) - F3(2)
assert isinstance(a, F3.dtype) and a == 1
a = F3(3) - F3(2)
assert isinstance(a, F3.dtype) and a == 1
a = 2*F3(2)
assert isinstance(a, F3.dtype) and a == 1
a = F3(2)*2
assert isinstance(a, F3.dtype) and a == 1
a = F3(2)*F3(2)
assert isinstance(a, F3.dtype) and a == 1
a = F3(2)*F3(2)
assert isinstance(a, F3.dtype) and a == 1
a = 2/F3(2)
assert isinstance(a, F3.dtype) and a == 1
a = F3(2)/2
assert isinstance(a, F3.dtype) and a == 1
a = F3(2)/F3(2)
assert isinstance(a, F3.dtype) and a == 1
a = F3(2)/F3(2)
assert isinstance(a, F3.dtype) and a == 1
a = 1 % F3(2)
assert isinstance(a, F3.dtype) and a == 1
a = F3(1) % 2
assert isinstance(a, F3.dtype) and a == 1
a = F3(1) % F3(2)
assert isinstance(a, F3.dtype) and a == 1
a = F3(1) % F3(2)
assert isinstance(a, F3.dtype) and a == 1
a = F3(2)**0
assert isinstance(a, F3.dtype) and a == 1
a = F3(2)**1
assert isinstance(a, F3.dtype) and a == 2
a = F3(2)**2
assert isinstance(a, F3.dtype) and a == 1
assert bool(F3(3)) is False
assert bool(F3(4)) is True
F5 = FF(5)
a = F5(1)**(-1)
assert isinstance(a, F5.dtype) and a == 1
a = F5(2)**(-1)
assert isinstance(a, F5.dtype) and a == 3
a = F5(3)**(-1)
assert isinstance(a, F5.dtype) and a == 2
a = F5(4)**(-1)
assert isinstance(a, F5.dtype) and a == 4
assert (F5(1) < F5(2)) is True
assert (F5(1) <= F5(2)) is True
assert (F5(1) > F5(2)) is False
assert (F5(1) >= F5(2)) is False
assert (F5(3) < F5(2)) is False
assert (F5(3) <= F5(2)) is False
assert (F5(3) > F5(2)) is True
assert (F5(3) >= F5(2)) is True
assert (F5(1) < F5(7)) is True
assert (F5(1) <= F5(7)) is True
assert (F5(1) > F5(7)) is False
assert (F5(1) >= F5(7)) is False
assert (F5(3) < F5(7)) is False
assert (F5(3) <= F5(7)) is False
assert (F5(3) > F5(7)) is True
assert (F5(3) >= F5(7)) is True
assert (F5(1) < 2) is True
assert (F5(1) <= 2) is True
assert (F5(1) > 2) is False
assert (F5(1) >= 2) is False
assert (F5(3) < 2) is False
assert (F5(3) <= 2) is False
assert (F5(3) > 2) is True
assert (F5(3) >= 2) is True
assert (F5(1) < 7) is True
assert (F5(1) <= 7) is True
assert (F5(1) > 7) is False
assert (F5(1) >= 7) is False
assert (F5(3) < 7) is False
assert (F5(3) <= 7) is False
assert (F5(3) > 7) is True
assert (F5(3) >= 7) is True
raises(NotInvertible, lambda: F5(0)**(-1))
raises(NotInvertible, lambda: F5(5)**(-1))
raises(ValueError, lambda: FF(0))
raises(ValueError, lambda: FF(2.1))
def test_QQ_int():
assert int(QQ(2**2000, 3**1250)) == 455431
assert int(QQ(2**100, 3)) == 422550200076076467165567735125
def test_RR_double():
assert RR(3.14) > 1e-50
assert RR(1e-13) > 1e-50
assert RR(1e-14) > 1e-50
assert RR(1e-15) > 1e-50
assert RR(1e-20) > 1e-50
assert RR(1e-40) > 1e-50
def test_RR_Float():
f1 = Float("1.01")
f2 = Float("1.0000000000000000000001")
assert f1._prec == 53
assert f2._prec == 80
assert RR(f1)-1 > 1e-50
assert RR(f2)-1 < 1e-50 # RR's precision is lower than f2's
RR2 = RealField(prec=f2._prec)
assert RR2(f1)-1 > 1e-50
assert RR2(f2)-1 > 1e-50 # RR's precision is equal to f2's
def test_CC_double():
assert CC(3.14).real > 1e-50
assert CC(1e-13).real > 1e-50
assert CC(1e-14).real > 1e-50
assert CC(1e-15).real > 1e-50
assert CC(1e-20).real > 1e-50
assert CC(1e-40).real > 1e-50
assert CC(3.14j).imag > 1e-50
assert CC(1e-13j).imag > 1e-50
assert CC(1e-14j).imag > 1e-50
assert CC(1e-15j).imag > 1e-50
assert CC(1e-20j).imag > 1e-50
assert CC(1e-40j).imag > 1e-50
| 27,358 | 34.256443 | 122 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/domains/tests/test_quotientring.py
|
"""Tests for quotient rings."""
from sympy import QQ, ZZ
from sympy.abc import x, y
from sympy.polys.polyerrors import NotReversible
from sympy.utilities.pytest import raises
from sympy.core.compatibility import range
def test_QuotientRingElement():
R = QQ.old_poly_ring(x)/[x**10]
X = R.convert(x)
assert X*(X + 1) == R.convert(x**2 + x)
assert X*x == R.convert(x**2)
assert x*X == R.convert(x**2)
assert X + x == R.convert(2*x)
assert x + X == 2*X
assert X**2 == R.convert(x**2)
assert 1/(1 - X) == R.convert(sum(x**i for i in range(10)))
assert X**10 == R.zero
assert X != x
raises(NotReversible, lambda: 1/X)
def test_QuotientRing():
I = QQ.old_poly_ring(x).ideal(x**2 + 1)
R = QQ.old_poly_ring(x)/I
assert R == QQ.old_poly_ring(x)/[x**2 + 1]
assert R == QQ.old_poly_ring(x)/QQ.old_poly_ring(x).ideal(x**2 + 1)
assert R != QQ.old_poly_ring(x)
assert R.convert(1)/x == -x + I
assert -1 + I == x**2 + I
assert R.convert(ZZ(1), ZZ) == 1 + I
assert R.convert(R.convert(x), R) == R.convert(x)
X = R.convert(x)
Y = QQ.old_poly_ring(x).convert(x)
assert -1 + I == X**2 + I
assert -1 + I == Y**2 + I
assert R.to_sympy(X) == x
raises(ValueError, lambda: QQ.old_poly_ring(x)/QQ.old_poly_ring(x, y).ideal(x))
R = QQ.old_poly_ring(x, order="ilex")
I = R.ideal(x)
assert R.convert(1) + I == (R/I).convert(1)
| 1,433 | 26.056604 | 83 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/agca/ideals.py
|
"""Computations with ideals of polynomial rings."""
from __future__ import print_function, division
from sympy.polys.polyerrors import CoercionFailed
from sympy.core.compatibility import reduce
class Ideal(object):
"""
Abstract base class for ideals.
Do not instantiate - use explicit constructors in the ring class instead:
>>> from sympy import QQ
>>> from sympy.abc import x
>>> QQ.old_poly_ring(x).ideal(x+1)
<x + 1>
Attributes
- ring - the ring this ideal belongs to
Non-implemented methods:
- _contains_elem
- _contains_ideal
- _quotient
- _intersect
- _union
- _product
- is_whole_ring
- is_zero
- is_prime, is_maximal, is_primary, is_radical
- is_principal
- height, depth
- radical
Methods that likely should be overridden in subclasses:
- reduce_element
"""
def _contains_elem(self, x):
"""Implementation of element containment."""
raise NotImplementedError
def _contains_ideal(self, I):
"""Implementation of ideal containment."""
raise NotImplementedError
def _quotient(self, J):
"""Implementation of ideal quotient."""
raise NotImplementedError
def _intersect(self, J):
"""Implementation of ideal intersection."""
raise NotImplementedError
def is_whole_ring(self):
"""Return True if ``self`` is the whole ring."""
raise NotImplementedError
def is_zero(self):
"""Return True if ``self`` is the zero ideal."""
raise NotImplementedError
def _equals(self, J):
"""Implementation of ideal equality."""
return self._contains_ideal(J) and J._contains_ideal(self)
def is_prime(self):
"""Return True if ``self`` is a prime ideal."""
raise NotImplementedError
def is_maximal(self):
"""Return True if ``self`` is a maximal ideal."""
raise NotImplementedError
def is_radical(self):
"""Return True if ``self`` is a radical ideal."""
raise NotImplementedError
def is_primary(self):
"""Return True if ``self`` is a primary ideal."""
raise NotImplementedError
def is_principal(self):
"""Return True if ``self`` is a principal ideal."""
raise NotImplementedError
def radical(self):
"""Compute the radical of ``self``."""
raise NotImplementedError
def depth(self):
"""Compute the depth of ``self``."""
raise NotImplementedError
def height(self):
"""Compute the height of ``self``."""
raise NotImplementedError
# TODO more
# non-implemented methods end here
def __init__(self, ring):
self.ring = ring
def _check_ideal(self, J):
"""Helper to check ``J`` is an ideal of our ring."""
if not isinstance(J, Ideal) or J.ring != self.ring:
raise ValueError(
'J must be an ideal of %s, got %s' % (self.ring, J))
def contains(self, elem):
"""
Return True if ``elem`` is an element of this ideal.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> QQ.old_poly_ring(x).ideal(x+1, x-1).contains(3)
True
>>> QQ.old_poly_ring(x).ideal(x**2, x**3).contains(x)
False
"""
return self._contains_elem(self.ring.convert(elem))
def subset(self, other):
"""
Returns True if ``other`` is is a subset of ``self``.
Here ``other`` may be an ideal.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> I = QQ.old_poly_ring(x).ideal(x+1)
>>> I.subset([x**2 - 1, x**2 + 2*x + 1])
True
>>> I.subset([x**2 + 1, x + 1])
False
>>> I.subset(QQ.old_poly_ring(x).ideal(x**2 - 1))
True
"""
if isinstance(other, Ideal):
return self._contains_ideal(other)
return all(self._contains_elem(x) for x in other)
def quotient(self, J, **opts):
r"""
Compute the ideal quotient of ``self`` by ``J``.
That is, if ``self`` is the ideal `I`, compute the set
`I : J = \{x \in R | xJ \subset I \}`.
>>> from sympy.abc import x, y
>>> from sympy import QQ
>>> R = QQ.old_poly_ring(x, y)
>>> R.ideal(x*y).quotient(R.ideal(x))
<y>
"""
self._check_ideal(J)
return self._quotient(J, **opts)
def intersect(self, J):
"""
Compute the intersection of self with ideal J.
>>> from sympy.abc import x, y
>>> from sympy import QQ
>>> R = QQ.old_poly_ring(x, y)
>>> R.ideal(x).intersect(R.ideal(y))
<x*y>
"""
self._check_ideal(J)
return self._intersect(J)
def saturate(self, J):
r"""
Compute the ideal saturation of ``self`` by ``J``.
That is, if ``self`` is the ideal `I`, compute the set
`I : J^\infty = \{x \in R | xJ^n \subset I \text{ for some } n\}`.
"""
raise NotImplementedError
# Note this can be implemented using repeated quotient
def union(self, J):
"""
Compute the ideal generated by the union of ``self`` and ``J``.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> QQ.old_poly_ring(x).ideal(x**2 - 1).union(QQ.old_poly_ring(x).ideal((x+1)**2)) == QQ.old_poly_ring(x).ideal(x+1)
True
"""
self._check_ideal(J)
return self._union(J)
def product(self, J):
"""
Compute the ideal product of ``self`` and ``J``.
That is, compute the ideal generated by products `xy`, for `x` an element
of ``self`` and `y \in J`.
>>> from sympy.abc import x, y
>>> from sympy import QQ
>>> QQ.old_poly_ring(x, y).ideal(x).product(QQ.old_poly_ring(x, y).ideal(y))
<x*y>
"""
self._check_ideal(J)
return self._product(J)
def reduce_element(self, x):
"""
Reduce the element ``x`` of our ring modulo the ideal ``self``.
Here "reduce" has no specific meaning: it could return a unique normal
form, simplify the expression a bit, or just do nothing.
"""
return x
def __add__(self, e):
if not isinstance(e, Ideal):
R = self.ring.quotient_ring(self)
if isinstance(e, R.dtype):
return e
if isinstance(e, R.ring.dtype):
return R(e)
return R.convert(e)
self._check_ideal(e)
return self.union(e)
__radd__ = __add__
def __mul__(self, e):
if not isinstance(e, Ideal):
try:
e = self.ring.ideal(e)
except CoercionFailed:
return NotImplemented
self._check_ideal(e)
return self.product(e)
__rmul__ = __mul__
def __pow__(self, exp):
if exp < 0:
raise NotImplementedError
# TODO exponentiate by squaring
return reduce(lambda x, y: x*y, [self]*exp, self.ring.ideal(1))
def __eq__(self, e):
if not isinstance(e, Ideal) or e.ring != self.ring:
return False
return self._equals(e)
def __ne__(self, e):
return not (self == e)
class ModuleImplementedIdeal(Ideal):
"""
Ideal implementation relying on the modules code.
Attributes:
- _module - the underlying module
"""
def __init__(self, ring, module):
Ideal.__init__(self, ring)
self._module = module
def _contains_elem(self, x):
return self._module.contains([x])
def _contains_ideal(self, J):
if not isinstance(J, ModuleImplementedIdeal):
raise NotImplementedError
return self._module.is_submodule(J._module)
def _intersect(self, J):
if not isinstance(J, ModuleImplementedIdeal):
raise NotImplementedError
return self.__class__(self.ring, self._module.intersect(J._module))
def _quotient(self, J, **opts):
if not isinstance(J, ModuleImplementedIdeal):
raise NotImplementedError
return self._module.module_quotient(J._module, **opts)
def _union(self, J):
if not isinstance(J, ModuleImplementedIdeal):
raise NotImplementedError
return self.__class__(self.ring, self._module.union(J._module))
@property
def gens(self):
"""
Return generators for ``self``.
>>> from sympy import QQ
>>> from sympy.abc import x, y
>>> list(QQ.old_poly_ring(x, y).ideal(x, y, x**2 + y).gens)
[x, y, x**2 + y]
"""
return (x[0] for x in self._module.gens)
def is_zero(self):
"""
Return True if ``self`` is the zero ideal.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> QQ.old_poly_ring(x).ideal(x).is_zero()
False
>>> QQ.old_poly_ring(x).ideal().is_zero()
True
"""
return self._module.is_zero()
def is_whole_ring(self):
"""
Return True if ``self`` is the whole ring, i.e. one generator is a unit.
>>> from sympy.abc import x
>>> from sympy import QQ, ilex
>>> QQ.old_poly_ring(x).ideal(x).is_whole_ring()
False
>>> QQ.old_poly_ring(x).ideal(3).is_whole_ring()
True
>>> QQ.old_poly_ring(x, order=ilex).ideal(2 + x).is_whole_ring()
True
"""
return self._module.is_full_module()
def __repr__(self):
from sympy import sstr
return '<' + ','.join(sstr(x) for [x] in self._module.gens) + '>'
# NOTE this is the only method using the fact that the module is a SubModule
def _product(self, J):
if not isinstance(J, ModuleImplementedIdeal):
raise NotImplementedError
return self.__class__(self.ring, self._module.submodule(
*[[x*y] for [x] in self._module.gens for [y] in J._module.gens]))
def in_terms_of_generators(self, e):
"""
Express ``e`` in terms of the generators of ``self``.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> I = QQ.old_poly_ring(x).ideal(x**2 + 1, x)
>>> I.in_terms_of_generators(1)
[1, -x]
"""
return self._module.in_terms_of_generators([e])
def reduce_element(self, x, **options):
return self._module.reduce_element([x], **options)[0]
| 10,509 | 27.715847 | 124 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/agca/modules.py
|
"""
Computations with modules over polynomial rings.
This module implements various classes that encapsulate groebner basis
computations for modules. Most of them should not be instantiated by hand.
Instead, use the constructing routines on objects you already have.
For example, to construct a free module over ``QQ[x, y]``, call
``QQ[x, y].free_module(rank)`` instead of the ``FreeModule`` constructor.
In fact ``FreeModule`` is an abstract base class that should not be
instantiated, the ``free_module`` method instead returns the implementing class
``FreeModulePolyRing``.
In general, the abstract base classes implement most functionality in terms of
a few non-implemented methods. The concrete base classes supply only these
non-implemented methods. They may also supply new implementations of the
convenience methods, for example if there are faster algorithms available.
"""
from __future__ import print_function, division
from copy import copy
from sympy.polys.polyerrors import CoercionFailed
from sympy.polys.orderings import ProductOrder, monomial_key
from sympy.polys.domains.field import Field
from sympy.polys.agca.ideals import Ideal
from sympy.core.compatibility import iterable, reduce, range
# TODO
# - module saturation
# - module quotient/intersection for quotient rings
# - free resoltutions / syzygies
# - finding small/minimal generating sets
# - ...
##########################################################################
## Abstract base classes #################################################
##########################################################################
class Module(object):
"""
Abstract base class for modules.
Do not instantiate - use ring explicit constructors instead:
>>> from sympy import QQ
>>> from sympy.abc import x
>>> QQ.old_poly_ring(x).free_module(2)
QQ[x]**2
Attributes:
- dtype - type of elements
- ring - containing ring
Non-implemented methods:
- submodule
- quotient_module
- is_zero
- is_submodule
- multiply_ideal
The method convert likely needs to be changed in subclasses.
"""
def __init__(self, ring):
self.ring = ring
def convert(self, elem, M=None):
"""
Convert ``elem`` into internal representation of this module.
If ``M`` is not None, it should be a module containing it.
"""
if not isinstance(elem, self.dtype):
raise CoercionFailed
return elem
def submodule(self, *gens):
"""Generate a submodule."""
raise NotImplementedError
def quotient_module(self, other):
"""Generate a quotient module."""
raise NotImplementedError
def __div__(self, e):
if not isinstance(e, Module):
e = self.submodule(*e)
return self.quotient_module(e)
__truediv__ = __div__
def contains(self, elem):
"""Return True if ``elem`` is an element of this module."""
try:
self.convert(elem)
return True
except CoercionFailed:
return False
def __contains__(self, elem):
return self.contains(elem)
def subset(self, other):
"""
Returns True if ``other`` is is a subset of ``self``.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> F.subset([(1, x), (x, 2)])
True
>>> F.subset([(1/x, x), (x, 2)])
False
"""
return all(self.contains(x) for x in other)
def __eq__(self, other):
return self.is_submodule(other) and other.is_submodule(self)
def __ne__(self, other):
return not (self == other)
def is_zero(self):
"""Returns True if ``self`` is a zero module."""
raise NotImplementedError
def is_submodule(self, other):
"""Returns True if ``other`` is a submodule of ``self``."""
raise NotImplementedError
def multiply_ideal(self, other):
"""
Multiply ``self`` by the ideal ``other``.
"""
raise NotImplementedError
def __mul__(self, e):
if not isinstance(e, Ideal):
try:
e = self.ring.ideal(e)
except (CoercionFailed, NotImplementedError):
return NotImplemented
return self.multiply_ideal(e)
__rmul__ = __mul__
def identity_hom(self):
"""Return the identity homomorphism on ``self``."""
raise NotImplementedError
class ModuleElement(object):
"""
Base class for module element wrappers.
Use this class to wrap primitive data types as module elements. It stores
a reference to the containing module, and implements all the arithmetic
operators.
Attributes:
- module - containing module
- data - internal data
Methods that likely need change in subclasses:
- add
- mul
- div
- eq
"""
def __init__(self, module, data):
self.module = module
self.data = data
def add(self, d1, d2):
"""Add data ``d1`` and ``d2``."""
return d1 + d2
def mul(self, m, d):
"""Multiply module data ``m`` by coefficient d."""
return m * d
def div(self, m, d):
"""Divide module data ``m`` by coefficient d."""
return m / d
def eq(self, d1, d2):
"""Return true if d1 and d2 represent the same element."""
return d1 == d2
def __add__(self, om):
if not isinstance(om, self.__class__) or om.module != self.module:
try:
om = self.module.convert(om)
except CoercionFailed:
return NotImplemented
return self.__class__(self.module, self.add(self.data, om.data))
__radd__ = __add__
def __neg__(self):
return self.__class__(self.module, self.mul(self.data,
self.module.ring.convert(-1)))
def __sub__(self, om):
if not isinstance(om, self.__class__) or om.module != self.module:
try:
om = self.module.convert(om)
except CoercionFailed:
return NotImplemented
return self.__add__(-om)
def __rsub__(self, om):
return (-self).__add__(om)
def __mul__(self, o):
if not isinstance(o, self.module.ring.dtype):
try:
o = self.module.ring.convert(o)
except CoercionFailed:
return NotImplemented
return self.__class__(self.module, self.mul(self.data, o))
__rmul__ = __mul__
def __div__(self, o):
if not isinstance(o, self.module.ring.dtype):
try:
o = self.module.ring.convert(o)
except CoercionFailed:
return NotImplemented
return self.__class__(self.module, self.div(self.data, o))
__truediv__ = __div__
def __eq__(self, om):
if not isinstance(om, self.__class__) or om.module != self.module:
try:
om = self.module.convert(om)
except CoercionFailed:
return False
return self.eq(self.data, om.data)
def __ne__(self, om):
return not self.__eq__(om)
##########################################################################
## Free Modules ##########################################################
##########################################################################
class FreeModuleElement(ModuleElement):
"""Element of a free module. Data stored as a tuple."""
def add(self, d1, d2):
return tuple(x + y for x, y in zip(d1, d2))
def mul(self, d, p):
return tuple(x * p for x in d)
def div(self, d, p):
return tuple(x / p for x in d)
def __repr__(self):
from sympy import sstr
return '[' + ', '.join(sstr(x) for x in self.data) + ']'
def __iter__(self):
return self.data.__iter__()
def __getitem__(self, idx):
return self.data[idx]
class FreeModule(Module):
"""
Abstract base class for free modules.
Additional attributes:
- rank - rank of the free module
Non-implemented methods:
- submodule
"""
dtype = FreeModuleElement
def __init__(self, ring, rank):
Module.__init__(self, ring)
self.rank = rank
def __repr__(self):
return repr(self.ring) + "**" + repr(self.rank)
def is_submodule(self, other):
"""
Returns True if ``other`` is a submodule of ``self``.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> M = F.submodule([2, x])
>>> F.is_submodule(F)
True
>>> F.is_submodule(M)
True
>>> M.is_submodule(F)
False
"""
if isinstance(other, SubModule):
return other.container == self
if isinstance(other, FreeModule):
return other.ring == self.ring and other.rank == self.rank
return False
def convert(self, elem, M=None):
"""
Convert ``elem`` into the internal representation.
This method is called implicitly whenever computations involve elements
not in the internal representation.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> F.convert([1, 0])
[1, 0]
"""
if isinstance(elem, FreeModuleElement):
if elem.module is self:
return elem
if elem.module.rank != self.rank:
raise CoercionFailed
return FreeModuleElement(self,
tuple(self.ring.convert(x, elem.module.ring) for x in elem.data))
elif iterable(elem):
tpl = tuple(self.ring.convert(x) for x in elem)
if len(tpl) != self.rank:
raise CoercionFailed
return FreeModuleElement(self, tpl)
elif elem is 0:
return FreeModuleElement(self, (self.ring.convert(0),)*self.rank)
else:
raise CoercionFailed
def is_zero(self):
"""
Returns True if ``self`` is a zero module.
(If, as this implementation assumes, the coefficient ring is not the
zero ring, then this is equivalent to the rank being zero.)
>>> from sympy.abc import x
>>> from sympy import QQ
>>> QQ.old_poly_ring(x).free_module(0).is_zero()
True
>>> QQ.old_poly_ring(x).free_module(1).is_zero()
False
"""
return self.rank == 0
def basis(self):
"""
Return a set of basis elements.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> QQ.old_poly_ring(x).free_module(3).basis()
([1, 0, 0], [0, 1, 0], [0, 0, 1])
"""
from sympy.matrices import eye
M = eye(self.rank)
return tuple(self.convert(M.row(i)) for i in range(self.rank))
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 multiply_ideal(self, other):
"""
Multiply ``self`` by the ideal ``other``.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> I = QQ.old_poly_ring(x).ideal(x)
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> F.multiply_ideal(I)
<[x, 0], [0, x]>
"""
return self.submodule(*self.basis()).multiply_ideal(other)
def identity_hom(self):
"""
Return the identity homomorphism on ``self``.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> QQ.old_poly_ring(x).free_module(2).identity_hom()
Matrix([
[1, 0], : QQ[x]**2 -> QQ[x]**2
[0, 1]])
"""
from sympy.polys.agca.homomorphisms import homomorphism
return homomorphism(self, self, self.basis())
class FreeModulePolyRing(FreeModule):
"""
Free module over a generalized polynomial ring.
Do not instantiate this, use the constructor method of the ring instead:
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(3)
>>> F
QQ[x]**3
>>> F.contains([x, 1, 0])
True
>>> F.contains([1/x, 0, 1])
False
"""
def __init__(self, ring, rank):
from sympy.polys.domains.old_polynomialring import PolynomialRingBase
FreeModule.__init__(self, ring, rank)
if not isinstance(ring, PolynomialRingBase):
raise NotImplementedError('This implementation only works over '
+ 'polynomial rings, got %s' % ring)
if not isinstance(ring.dom, Field):
raise NotImplementedError('Ground domain must be a field, '
+ 'got %s' % ring.dom)
def submodule(self, *gens, **opts):
"""
Generate a submodule.
>>> from sympy.abc import x, y
>>> from sympy import QQ
>>> M = QQ.old_poly_ring(x, y).free_module(2).submodule([x, x + y])
>>> M
<[x, x + y]>
>>> M.contains([2*x, 2*x + 2*y])
True
>>> M.contains([x, y])
False
"""
return SubModulePolyRing(gens, self, **opts)
class FreeModuleQuotientRing(FreeModule):
"""
Free module over a quotient ring.
Do not instantiate this, use the constructor method of the ring instead:
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = (QQ.old_poly_ring(x)/[x**2 + 1]).free_module(3)
>>> F
(QQ[x]/<x**2 + 1>)**3
Attributes
- quot - the quotient module `R^n / IR^n`, where `R/I` is our ring
"""
def __init__(self, ring, rank):
from sympy.polys.domains.quotientring import QuotientRing
FreeModule.__init__(self, ring, rank)
if not isinstance(ring, QuotientRing):
raise NotImplementedError('This implementation only works over '
+ 'quotient rings, got %s' % ring)
F = self.ring.ring.free_module(self.rank)
self.quot = F / (self.ring.base_ideal*F)
def __repr__(self):
return "(" + repr(self.ring) + ")" + "**" + repr(self.rank)
def submodule(self, *gens, **opts):
"""
Generate a submodule.
>>> from sympy.abc import x, y
>>> from sympy import QQ
>>> M = (QQ.old_poly_ring(x, y)/[x**2 - y**2]).free_module(2).submodule([x, x + y])
>>> M
<[x + <x**2 - y**2>, x + y + <x**2 - y**2>]>
>>> M.contains([y**2, x**2 + x*y])
True
>>> M.contains([x, y])
False
"""
return SubModuleQuotientRing(gens, self, **opts)
def lift(self, elem):
"""
Lift the element ``elem`` of self to the module self.quot.
Note that self.quot is the same set as self, just as an R-module
and not as an R/I-module, so this makes sense.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = (QQ.old_poly_ring(x)/[x**2 + 1]).free_module(2)
>>> e = F.convert([1, 0])
>>> e
[1 + <x**2 + 1>, 0 + <x**2 + 1>]
>>> L = F.quot
>>> l = F.lift(e)
>>> l
[1, 0] + <[x**2 + 1, 0], [0, x**2 + 1]>
>>> L.contains(l)
True
"""
return self.quot.convert([x.data for x in elem])
def unlift(self, elem):
"""
Push down an element of self.quot to self.
This undoes ``lift``.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = (QQ.old_poly_ring(x)/[x**2 + 1]).free_module(2)
>>> e = F.convert([1, 0])
>>> l = F.lift(e)
>>> e == l
False
>>> e == F.unlift(l)
True
"""
return self.convert(elem.data)
##########################################################################
## Submodules and subquotients ###########################################
##########################################################################
class SubModule(Module):
"""
Base class for submodules.
Attributes:
- container - containing module
- gens - generators (subset of containing module)
- rank - rank of containing module
Non-implemented methods:
- _contains
- _syzygies
- _in_terms_of_generators
- _intersect
- _module_quotient
Methods that likely need change in subclasses:
- reduce_element
"""
def __init__(self, gens, container):
Module.__init__(self, container.ring)
self.gens = tuple(container.convert(x) for x in gens)
self.container = container
self.rank = container.rank
self.ring = container.ring
self.dtype = container.dtype
def __repr__(self):
return "<" + ", ".join(repr(x) for x in self.gens) + ">"
def _contains(self, other):
"""Implementation of containment.
Other is guaranteed to be FreeModuleElement."""
raise NotImplementedError
def _syzygies(self):
"""Implementation of syzygy computation wrt self generators."""
raise NotImplementedError
def _in_terms_of_generators(self, e):
"""Implementation of expression in terms of generators."""
raise NotImplementedError
def convert(self, elem, M=None):
"""
Convert ``elem`` into the internal represantition.
Mostly called implicitly.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> M = QQ.old_poly_ring(x).free_module(2).submodule([1, x])
>>> M.convert([2, 2*x])
[2, 2*x]
"""
if isinstance(elem, self.container.dtype) and elem.module is self:
return elem
r = copy(self.container.convert(elem, M))
r.module = self
if not self._contains(r):
raise CoercionFailed
return r
def _intersect(self, other):
"""Implementation of intersection.
Other is guaranteed to be a submodule of same free module."""
raise NotImplementedError
def _module_quotient(self, other):
"""Implementation of quotient.
Other is guaranteed to be a submodule of same free module."""
raise NotImplementedError
def intersect(self, other, **options):
"""
Returns the intersection of ``self`` with submodule ``other``.
>>> from sympy.abc import x, y
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x, y).free_module(2)
>>> F.submodule([x, x]).intersect(F.submodule([y, y]))
<[x*y, x*y]>
Some implementation allow further options to be passed. Currently, to
only one implemented is ``relations=True``, in which case the function
will return a triple ``(res, rela, relb)``, where ``res`` is the
intersection module, and ``rela`` and ``relb`` are lists of coefficient
vectors, expressing the generators of ``res`` in terms of the
generators of ``self`` (``rela``) and ``other`` (``relb``).
>>> F.submodule([x, x]).intersect(F.submodule([y, y]), relations=True)
(<[x*y, x*y]>, [(y,)], [(x,)])
The above result says: the intersection module is generated by the
single element `(-xy, -xy) = -y (x, x) = -x (y, y)`, where
`(x, x)` and `(y, y)` respectively are the unique generators of
the two modules being intersected.
"""
if not isinstance(other, SubModule):
raise TypeError('%s is not a SubModule' % other)
if other.container != self.container:
raise ValueError(
'%s is contained in a different free module' % other)
return self._intersect(other, **options)
def module_quotient(self, other, **options):
r"""
Returns the module quotient of ``self`` by submodule ``other``.
That is, if ``self`` is the module `M` and ``other`` is `N`, then
return the ideal `\{f \in R | fN \subset M\}`.
>>> from sympy import QQ
>>> from sympy.abc import x, y
>>> F = QQ.old_poly_ring(x, y).free_module(2)
>>> S = F.submodule([x*y, x*y])
>>> T = F.submodule([x, x])
>>> S.module_quotient(T)
<y>
Some implementations allow further options to be passed. Currently, the
only one implemented is ``relations=True``, which may only be passed
if ``other`` is prinicipal. In this case the function
will return a pair ``(res, rel)`` where ``res`` is the ideal, and
``rel`` is a list of coefficient vectors, expressing the generators of
the ideal, multiplied by the generator of ``other`` in terms of
generators of ``self``.
>>> S.module_quotient(T, relations=True)
(<y>, [[1]])
This means that the quotient ideal is generated by the single element
`y`, and that `y (x, x) = 1 (xy, xy)`, `(x, x)` and `(xy, xy)` being
the generators of `T` and `S`, respectively.
"""
if not isinstance(other, SubModule):
raise TypeError('%s is not a SubModule' % other)
if other.container != self.container:
raise ValueError(
'%s is contained in a different free module' % other)
return self._module_quotient(other, **options)
def union(self, other):
"""
Returns the module generated by the union of ``self`` and ``other``.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(1)
>>> M = F.submodule([x**2 + x]) # <x(x+1)>
>>> N = F.submodule([x**2 - 1]) # <(x-1)(x+1)>
>>> M.union(N) == F.submodule([x+1])
True
"""
if not isinstance(other, SubModule):
raise TypeError('%s is not a SubModule' % other)
if other.container != self.container:
raise ValueError(
'%s is contained in a different free module' % other)
return self.__class__(self.gens + other.gens, self.container)
def is_zero(self):
"""
Return True if ``self`` is a zero module.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> F.submodule([x, 1]).is_zero()
False
>>> F.submodule([0, 0]).is_zero()
True
"""
return all(x == 0 for x in self.gens)
def submodule(self, *gens):
"""
Generate a submodule.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> M = QQ.old_poly_ring(x).free_module(2).submodule([x, 1])
>>> M.submodule([x**2, x])
<[x**2, x]>
"""
if not self.subset(gens):
raise ValueError('%s not a subset of %s' % (gens, self))
return self.__class__(gens, self.container)
def is_full_module(self):
"""
Return True if ``self`` is the entire free module.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> F.submodule([x, 1]).is_full_module()
False
>>> F.submodule([1, 1], [1, 2]).is_full_module()
True
"""
return all(self.contains(x) for x in self.container.basis())
def is_submodule(self, other):
"""
Returns True if ``other`` is a submodule of ``self``.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> M = F.submodule([2, x])
>>> N = M.submodule([2*x, x**2])
>>> M.is_submodule(M)
True
>>> M.is_submodule(N)
True
>>> N.is_submodule(M)
False
"""
if isinstance(other, SubModule):
return self.container == other.container and \
all(self.contains(x) for x in other.gens)
if isinstance(other, (FreeModule, QuotientModule)):
return self.container == other and self.is_full_module()
return False
def syzygy_module(self, **opts):
r"""
Compute the syzygy module of the generators of ``self``.
Suppose `M` is generated by `f_1, \ldots, f_n` over the ring
`R`. Consider the homomorphism `\phi: R^n \to M`, given by
sending `(r_1, \ldots, r_n) \to r_1 f_1 + \cdots + r_n f_n`.
The syzygy module is defined to be the kernel of `\phi`.
The syzygy module is zero iff the generators generate freely a free
submodule:
>>> from sympy.abc import x, y
>>> from sympy import QQ
>>> QQ.old_poly_ring(x).free_module(2).submodule([1, 0], [1, 1]).syzygy_module().is_zero()
True
A slightly more interesting example:
>>> M = QQ.old_poly_ring(x, y).free_module(2).submodule([x, 2*x], [y, 2*y])
>>> S = QQ.old_poly_ring(x, y).free_module(2).submodule([y, -x])
>>> M.syzygy_module() == S
True
"""
F = self.ring.free_module(len(self.gens))
# NOTE we filter out zero syzygies. This is for convenience of the
# _syzygies function and not meant to replace any real "generating set
# reduction" algorithm
return F.submodule(*[x for x in self._syzygies() if F.convert(x) != 0],
**opts)
def in_terms_of_generators(self, e):
"""
Express element ``e`` of ``self`` in terms of the generators.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> M = F.submodule([1, 0], [1, 1])
>>> M.in_terms_of_generators([x, x**2])
[-x**2 + x, x**2]
"""
try:
e = self.convert(e)
except CoercionFailed:
raise ValueError('%s is not an element of %s' % (e, self))
return self._in_terms_of_generators(e)
def reduce_element(self, x):
"""
Reduce the element ``x`` of our ring modulo the ideal ``self``.
Here "reduce" has no specific meaning, it could return a unique normal
form, simplify the expression a bit, or just do nothing.
"""
return x
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 __add__(self, oth):
return self.container.quotient_module(self).convert(oth)
__radd__ = __add__
def multiply_ideal(self, I):
"""
Multiply ``self`` by the ideal ``I``.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> I = QQ.old_poly_ring(x).ideal(x**2)
>>> M = QQ.old_poly_ring(x).free_module(2).submodule([1, 1])
>>> I*M
<[x**2, x**2]>
"""
return self.submodule(*[x*g for [x] in I._module.gens for g in self.gens])
def inclusion_hom(self):
"""
Return a homomorphism representing the inclusion map of ``self``.
That is, the natural map from ``self`` to ``self.container``.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> QQ.old_poly_ring(x).free_module(2).submodule([x, x]).inclusion_hom()
Matrix([
[1, 0], : <[x, x]> -> QQ[x]**2
[0, 1]])
"""
return self.container.identity_hom().restrict_domain(self)
def identity_hom(self):
"""
Return the identity homomorphism on ``self``.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> QQ.old_poly_ring(x).free_module(2).submodule([x, x]).identity_hom()
Matrix([
[1, 0], : <[x, x]> -> <[x, x]>
[0, 1]])
"""
return self.container.identity_hom().restrict_domain(
self).restrict_codomain(self)
class SubQuotientModule(SubModule):
"""
Submodule of a quotient module.
Equivalently, quotient module of a submodule.
Do not instantiate this, instead use the submodule or quotient_module
constructing methods:
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> S = F.submodule([1, 0], [1, x])
>>> Q = F/[(1, 0)]
>>> S/[(1, 0)] == Q.submodule([5, x])
True
Attributes:
- base - base module we are quotient of
- killed_module - submodule used to form the quotient
"""
def __init__(self, gens, container, **opts):
SubModule.__init__(self, gens, container)
self.killed_module = self.container.killed_module
# XXX it is important for some code below that the generators of base
# are in this particular order!
self.base = self.container.base.submodule(
*[x.data for x in self.gens], **opts).union(self.killed_module)
def _contains(self, elem):
return self.base.contains(elem.data)
def _syzygies(self):
# let N = self.killed_module be generated by e_1, ..., e_r
# let F = self.base be generated by f_1, ..., f_s and e_1, ..., e_r
# Then self = F/N.
# Let phi: R**s --> self be the evident surjection.
# Similarly psi: R**(s + r) --> F.
# We need to find generators for ker(phi). Let chi: R**s --> F be the
# evident lift of phi. For X in R**s, phi(X) = 0 iff chi(X) is
# contained in N, iff there exists Y in R**r such that
# psi(X, Y) = 0.
# Hence if alpha: R**(s + r) --> R**s is the projection map, then
# ker(phi) = alpha ker(psi).
return [X[:len(self.gens)] for X in self.base._syzygies()]
def _in_terms_of_generators(self, e):
return self.base._in_terms_of_generators(e.data)[:len(self.gens)]
def is_full_module(self):
"""
Return True if ``self`` is the entire free module.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> F.submodule([x, 1]).is_full_module()
False
>>> F.submodule([1, 1], [1, 2]).is_full_module()
True
"""
return self.base.is_full_module()
def quotient_hom(self):
"""
Return the quotient homomorphism to self.
That is, return the natural map from ``self.base`` to ``self``.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> M = (QQ.old_poly_ring(x).free_module(2) / [(1, x)]).submodule([1, 0])
>>> M.quotient_hom()
Matrix([
[1, 0], : <[1, 0], [1, x]> -> <[1, 0] + <[1, x]>, [1, x] + <[1, x]>>
[0, 1]])
"""
return self.base.identity_hom().quotient_codomain(self.killed_module)
_subs0 = lambda x: x[0]
_subs1 = lambda x: x[1:]
class ModuleOrder(ProductOrder):
"""A product monomial order with a zeroth term as module index."""
def __init__(self, o1, o2, TOP):
if TOP:
ProductOrder.__init__(self, (o2, _subs1), (o1, _subs0))
else:
ProductOrder.__init__(self, (o1, _subs0), (o2, _subs1))
class SubModulePolyRing(SubModule):
"""
Submodule of a free module over a generalized polynomial ring.
Do not instantiate this, use the constructor method of FreeModule instead:
>>> from sympy.abc import x, y
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x, y).free_module(2)
>>> F.submodule([x, y], [1, 0])
<[x, y], [1, 0]>
Attributes:
- order - monomial order used
"""
#self._gb - cached groebner basis
#self._gbe - cached groebner basis relations
def __init__(self, gens, container, order="lex", TOP=True):
SubModule.__init__(self, gens, container)
if not isinstance(container, FreeModulePolyRing):
raise NotImplementedError('This implementation is for submodules of '
+ 'FreeModulePolyRing, got %s' % container)
self.order = ModuleOrder(monomial_key(order), self.ring.order, TOP)
self._gb = None
self._gbe = None
def __eq__(self, other):
if isinstance(other, SubModulePolyRing) and self.order != other.order:
return False
return SubModule.__eq__(self, other)
def _groebner(self, extended=False):
"""Returns a standard basis in sdm form."""
from sympy.polys.distributedmodules import sdm_groebner, sdm_nf_mora
if self._gbe is None and extended:
gb, gbe = sdm_groebner(
[self.ring._vector_to_sdm(x, self.order) for x in self.gens],
sdm_nf_mora, self.order, self.ring.dom, extended=True)
self._gb, self._gbe = tuple(gb), tuple(gbe)
if self._gb is None:
self._gb = tuple(sdm_groebner(
[self.ring._vector_to_sdm(x, self.order) for x in self.gens],
sdm_nf_mora, self.order, self.ring.dom))
if extended:
return self._gb, self._gbe
else:
return self._gb
def _groebner_vec(self, extended=False):
"""Returns a standard basis in element form."""
if not extended:
return [self.convert(self.ring._sdm_to_vector(x, self.rank))
for x in self._groebner()]
gb, gbe = self._groebner(extended=True)
return ([self.convert(self.ring._sdm_to_vector(x, self.rank))
for x in gb],
[self.ring._sdm_to_vector(x, len(self.gens)) for x in gbe])
def _contains(self, x):
from sympy.polys.distributedmodules import sdm_zero, sdm_nf_mora
return sdm_nf_mora(self.ring._vector_to_sdm(x, self.order),
self._groebner(), self.order, self.ring.dom) == \
sdm_zero()
def _syzygies(self):
"""Compute syzygies. See [SCA, algorithm 2.5.4]."""
# NOTE if self.gens is a standard basis, this can be done more
# efficiently using Schreyer's theorem
from sympy.matrices import eye
# First bullet point
k = len(self.gens)
r = self.rank
im = eye(k)
Rkr = self.ring.free_module(r + k)
newgens = []
for j, f in enumerate(self.gens):
m = [0]*(r + k)
for i, v in enumerate(f):
m[i] = f[i]
for i in range(k):
m[r + i] = im[j, i]
newgens.append(Rkr.convert(m))
# Note: we need *descending* order on module index, and TOP=False to
# get an eliminetaion order
F = Rkr.submodule(*newgens, order='ilex', TOP=False)
# Second bullet point: standard basis of F
G = F._groebner_vec()
# Third bullet point: G0 = G intersect the new k components
G0 = [x[r:] for x in G if all(y == self.ring.convert(0)
for y in x[:r])]
# Fourth and fifth bullet points: we are done
return G0
def _in_terms_of_generators(self, e):
"""Expression in terms of generators. See [SCA, 2.8.1]."""
# NOTE: if gens is a standard basis, this can be done more efficiently
M = self.ring.free_module(self.rank).submodule(*((e,) + self.gens))
S = M.syzygy_module(
order="ilex", TOP=False) # We want decreasing order!
G = S._groebner_vec()
# This list cannot not be empty since e is an element
e = [x for x in G if self.ring.is_unit(x[0])][0]
return [-x/e[0] for x in e[1:]]
def reduce_element(self, x, NF=None):
"""
Reduce the element ``x`` of our container modulo ``self``.
This applies the normal form ``NF`` to ``x``. If ``NF`` is passed
as none, the default Mora normal form is used (which is not unique!).
"""
from sympy.polys.distributedmodules import sdm_nf_mora
if NF is None:
NF = sdm_nf_mora
return self.container.convert(self.ring._sdm_to_vector(NF(
self.ring._vector_to_sdm(x, self.order), self._groebner(),
self.order, self.ring.dom),
self.rank))
def _intersect(self, other, relations=False):
# See: [SCA, section 2.8.2]
fi = self.gens
hi = other.gens
r = self.rank
ci = [[0]*(2*r) for _ in range(r)]
for k in range(r):
ci[k][k] = 1
ci[k][r + k] = 1
di = [list(f) + [0]*r for f in fi]
ei = [[0]*r + list(h) for h in hi]
syz = self.ring.free_module(2*r).submodule(*(ci + di + ei))._syzygies()
nonzero = [x for x in syz if any(y != self.ring.zero for y in x[:r])]
res = self.container.submodule(*([-y for y in x[:r]] for x in nonzero))
reln1 = [x[r:r + len(fi)] for x in nonzero]
reln2 = [x[r + len(fi):] for x in nonzero]
if relations:
return res, reln1, reln2
return res
def _module_quotient(self, other, relations=False):
# See: [SCA, section 2.8.4]
if relations and len(other.gens) != 1:
raise NotImplementedError
if len(other.gens) == 0:
return self.ring.ideal(1)
elif len(other.gens) == 1:
# We do some trickery. Let f be the (vector!) generating ``other``
# and f1, .., fn be the (vectors) generating self.
# Consider the submodule of R^{r+1} generated by (f, 1) and
# {(fi, 0) | i}. Then the intersection with the last module
# component yields the quotient.
g1 = list(other.gens[0]) + [1]
gi = [list(x) + [0] for x in self.gens]
# NOTE: We *need* to use an elimination order
M = self.ring.free_module(self.rank + 1).submodule(*([g1] + gi),
order='ilex', TOP=False)
if not relations:
return self.ring.ideal(*[x[-1] for x in M._groebner_vec() if
all(y == self.ring.zero for y in x[:-1])])
else:
G, R = M._groebner_vec(extended=True)
indices = [i for i, x in enumerate(G) if
all(y == self.ring.zero for y in x[:-1])]
return (self.ring.ideal(*[G[i][-1] for i in indices]),
[[-x for x in R[i][1:]] for i in indices])
# For more generators, we use I : <h1, .., hn> = intersection of
# {I : <hi> | i}
# TODO this can be done more efficiently
return reduce(lambda x, y: x.intersect(y),
(self._module_quotient(self.container.submodule(x)) for x in other.gens))
class SubModuleQuotientRing(SubModule):
"""
Class for submodules of free modules over quotient rings.
Do not instantiate this. Instead use the submodule methods.
>>> from sympy.abc import x, y
>>> from sympy import QQ
>>> M = (QQ.old_poly_ring(x, y)/[x**2 - y**2]).free_module(2).submodule([x, x + y])
>>> M
<[x + <x**2 - y**2>, x + y + <x**2 - y**2>]>
>>> M.contains([y**2, x**2 + x*y])
True
>>> M.contains([x, y])
False
Attributes:
- quot - the subquotient of `R^n/IR^n` generated by lifts of our generators
"""
def __init__(self, gens, container):
SubModule.__init__(self, gens, container)
self.quot = self.container.quot.submodule(
*[self.container.lift(x) for x in self.gens])
def _contains(self, elem):
return self.quot._contains(self.container.lift(elem))
def _syzygies(self):
return [tuple(self.ring.convert(y, self.quot.ring) for y in x)
for x in self.quot._syzygies()]
def _in_terms_of_generators(self, elem):
return [self.ring.convert(x, self.quot.ring) for x in
self.quot._in_terms_of_generators(self.container.lift(elem))]
##########################################################################
## Quotient Modules ######################################################
##########################################################################
class QuotientModuleElement(ModuleElement):
"""Element of a quotient module."""
def eq(self, d1, d2):
"""Equality comparison."""
return self.module.killed_module.contains(d1 - d2)
def __repr__(self):
return repr(self.data) + " + " + repr(self.module.killed_module)
class QuotientModule(Module):
"""
Class for quotient modules.
Do not instantiate this directly. For subquotients, see the
SubQuotientModule class.
Attributes:
- base - the base module we are a quotient of
- killed_module - the submodule used to form the quotient
- rank of the base
"""
dtype = QuotientModuleElement
def __init__(self, ring, base, submodule):
Module.__init__(self, ring)
if not base.is_submodule(submodule):
raise ValueError('%s is not a submodule of %s' % (submodule, base))
self.base = base
self.killed_module = submodule
self.rank = base.rank
def __repr__(self):
return repr(self.base) + "/" + repr(self.killed_module)
def is_zero(self):
"""
Return True if ``self`` is a zero module.
This happens if and only if the base module is the same as the
submodule being killed.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> (F/[(1, 0)]).is_zero()
False
>>> (F/[(1, 0), (0, 1)]).is_zero()
True
"""
return self.base == self.killed_module
def is_submodule(self, other):
"""
Return True if ``other`` is a submodule of ``self``.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> Q = QQ.old_poly_ring(x).free_module(2) / [(x, x)]
>>> S = Q.submodule([1, 0])
>>> Q.is_submodule(S)
True
>>> S.is_submodule(Q)
False
"""
if isinstance(other, QuotientModule):
return self.killed_module == other.killed_module and \
self.base.is_submodule(other.base)
if isinstance(other, SubQuotientModule):
return other.container == self
return False
def submodule(self, *gens, **opts):
"""
Generate a submodule.
This is the same as taking a quotient of a submodule of the base
module.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> Q = QQ.old_poly_ring(x).free_module(2) / [(x, x)]
>>> Q.submodule([x, 0])
<[x, 0] + <[x, x]>>
"""
return SubQuotientModule(gens, self, **opts)
def convert(self, elem, M=None):
"""
Convert ``elem`` into the internal representation.
This method is called implicitly whenever computations involve elements
not in the internal representation.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(2) / [(1, 2), (1, x)]
>>> F.convert([1, 0])
[1, 0] + <[1, 2], [1, x]>
"""
if isinstance(elem, QuotientModuleElement):
if elem.module is self:
return elem
if self.killed_module.is_submodule(elem.module.killed_module):
return QuotientModuleElement(self, self.base.convert(elem.data))
raise CoercionFailed
return QuotientModuleElement(self, self.base.convert(elem))
def identity_hom(self):
"""
Return the identity homomorphism on ``self``.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> M = QQ.old_poly_ring(x).free_module(2) / [(1, 2), (1, x)]
>>> M.identity_hom()
Matrix([
[1, 0], : QQ[x]**2/<[1, 2], [1, x]> -> QQ[x]**2/<[1, 2], [1, x]>
[0, 1]])
"""
return self.base.identity_hom().quotient_codomain(
self.killed_module).quotient_domain(self.killed_module)
def quotient_hom(self):
"""
Return the quotient homomorphism to ``self``.
That is, return a homomorphism representing the natural map from
``self.base`` to ``self``.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> M = QQ.old_poly_ring(x).free_module(2) / [(1, 2), (1, x)]
>>> M.quotient_hom()
Matrix([
[1, 0], : QQ[x]**2 -> QQ[x]**2/<[1, 2], [1, x]>
[0, 1]])
"""
return self.base.identity_hom().quotient_codomain(
self.killed_module)
| 45,730 | 32.066522 | 98 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/agca/__init__.py
|
"""Module for algebraic geometry and commutative algebra."""
from .homomorphisms import homomorphism
| 102 | 24.75 | 60 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/agca/homomorphisms.py
|
"""
Computations with homomorphisms of modules and rings.
This module implements classes for representing homomorphisms of rings and
their modules. Instead of instantiating the classes directly, you should use
the function ``homomorphism(from, to, matrix)`` to create homomorphism objects.
"""
from __future__ import print_function, division
from sympy.polys.agca.modules import (Module, FreeModule, QuotientModule,
SubModule, SubQuotientModule)
from sympy.polys.polyerrors import CoercionFailed
from sympy.core.compatibility import range
# The main computational task for module homomorphisms is kernels.
# For this reason, the concrete classes are organised by domain module type.
class ModuleHomomorphism(object):
"""
Abstract base class for module homomoprhisms. Do not instantiate.
Instead, use the ``homomorphism`` function:
>>> from sympy import QQ
>>> from sympy.abc import x
>>> from sympy.polys.agca import homomorphism
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> homomorphism(F, F, [[1, 0], [0, 1]])
Matrix([
[1, 0], : QQ[x]**2 -> QQ[x]**2
[0, 1]])
Attributes:
- ring - the ring over which we are considering modules
- domain - the domain module
- codomain - the codomain module
- _ker - cached kernel
- _img - cached image
Non-implemented methods:
- _kernel
- _image
- _restrict_domain
- _restrict_codomain
- _quotient_domain
- _quotient_codomain
- _apply
- _mul_scalar
- _compose
- _add
"""
def __init__(self, domain, codomain):
if not isinstance(domain, Module):
raise TypeError('Source must be a module, got %s' % domain)
if not isinstance(codomain, Module):
raise TypeError('Target must be a module, got %s' % codomain)
if domain.ring != codomain.ring:
raise ValueError('Source and codomain must be over same ring, '
'got %s != %s' % (domain, codomain))
self.domain = domain
self.codomain = codomain
self.ring = domain.ring
self._ker = None
self._img = None
def kernel(self):
r"""
Compute the kernel of ``self``.
That is, if ``self`` is the homomorphism `\phi: M \to N`, then compute
`ker(\phi) = \{x \in M | \phi(x) = 0\}`. This is a submodule of `M`.
>>> from sympy import QQ
>>> from sympy.abc import x
>>> from sympy.polys.agca import homomorphism
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> homomorphism(F, F, [[1, 0], [x, 0]]).kernel()
<[x, -1]>
"""
if self._ker is None:
self._ker = self._kernel()
return self._ker
def image(self):
r"""
Compute the image of ``self``.
That is, if ``self`` is the homomorphism `\phi: M \to N`, then compute
`im(\phi) = \{\phi(x) | x \in M \}`. This is a submodule of `N`.
>>> from sympy import QQ
>>> from sympy.abc import x
>>> from sympy.polys.agca import homomorphism
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> homomorphism(F, F, [[1, 0], [x, 0]]).image() == F.submodule([1, 0])
True
"""
if self._img is None:
self._img = self._image()
return self._img
def _kernel(self):
"""Compute the kernel of ``self``."""
raise NotImplementedError
def _image(self):
"""Compute the image of ``self``."""
raise NotImplementedError
def _restrict_domain(self, sm):
"""Implementation of domain restriction."""
raise NotImplementedError
def _restrict_codomain(self, sm):
"""Implementation of codomain restriction."""
raise NotImplementedError
def _quotient_domain(self, sm):
"""Implementation of domain quotient."""
raise NotImplementedError
def _quotient_codomain(self, sm):
"""Implementation of codomain quotient."""
raise NotImplementedError
def restrict_domain(self, sm):
"""
Return ``self``, with the domain restricted to ``sm``.
Here ``sm`` has to be a submodule of ``self.domain``.
>>> from sympy import QQ
>>> from sympy.abc import x
>>> from sympy.polys.agca import homomorphism
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> h = homomorphism(F, F, [[1, 0], [x, 0]])
>>> h
Matrix([
[1, x], : QQ[x]**2 -> QQ[x]**2
[0, 0]])
>>> h.restrict_domain(F.submodule([1, 0]))
Matrix([
[1, x], : <[1, 0]> -> QQ[x]**2
[0, 0]])
This is the same as just composing on the right with the submodule
inclusion:
>>> h * F.submodule([1, 0]).inclusion_hom()
Matrix([
[1, x], : <[1, 0]> -> QQ[x]**2
[0, 0]])
"""
if not self.domain.is_submodule(sm):
raise ValueError('sm must be a submodule of %s, got %s'
% (self.domain, sm))
if sm == self.domain:
return self
return self._restrict_domain(sm)
def restrict_codomain(self, sm):
"""
Return ``self``, with codomain restricted to to ``sm``.
Here ``sm`` has to be a submodule of ``self.codomain`` containing the
image.
>>> from sympy import QQ
>>> from sympy.abc import x
>>> from sympy.polys.agca import homomorphism
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> h = homomorphism(F, F, [[1, 0], [x, 0]])
>>> h
Matrix([
[1, x], : QQ[x]**2 -> QQ[x]**2
[0, 0]])
>>> h.restrict_codomain(F.submodule([1, 0]))
Matrix([
[1, x], : QQ[x]**2 -> <[1, 0]>
[0, 0]])
"""
if not sm.is_submodule(self.image()):
raise ValueError('the image %s must contain sm, got %s'
% (self.image(), sm))
if sm == self.codomain:
return self
return self._restrict_codomain(sm)
def quotient_domain(self, sm):
"""
Return ``self`` with domain replaced by ``domain/sm``.
Here ``sm`` must be a submodule of ``self.kernel()``.
>>> from sympy import QQ
>>> from sympy.abc import x
>>> from sympy.polys.agca import homomorphism
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> h = homomorphism(F, F, [[1, 0], [x, 0]])
>>> h
Matrix([
[1, x], : QQ[x]**2 -> QQ[x]**2
[0, 0]])
>>> h.quotient_domain(F.submodule([-x, 1]))
Matrix([
[1, x], : QQ[x]**2/<[-x, 1]> -> QQ[x]**2
[0, 0]])
"""
if not self.kernel().is_submodule(sm):
raise ValueError('kernel %s must contain sm, got %s' %
(self.kernel(), sm))
if sm.is_zero():
return self
return self._quotient_domain(sm)
def quotient_codomain(self, sm):
"""
Return ``self`` with codomain replaced by ``codomain/sm``.
Here ``sm`` must be a submodule of ``self.codomain``.
>>> from sympy import QQ
>>> from sympy.abc import x
>>> from sympy.polys.agca import homomorphism
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> h = homomorphism(F, F, [[1, 0], [x, 0]])
>>> h
Matrix([
[1, x], : QQ[x]**2 -> QQ[x]**2
[0, 0]])
>>> h.quotient_codomain(F.submodule([1, 1]))
Matrix([
[1, x], : QQ[x]**2 -> QQ[x]**2/<[1, 1]>
[0, 0]])
This is the same as composing with the quotient map on the left:
>>> (F/[(1, 1)]).quotient_hom() * h
Matrix([
[1, x], : QQ[x]**2 -> QQ[x]**2/<[1, 1]>
[0, 0]])
"""
if not self.codomain.is_submodule(sm):
raise ValueError('sm must be a submodule of codomain %s, got %s'
% (self.codomain, sm))
if sm.is_zero():
return self
return self._quotient_codomain(sm)
def _apply(self, elem):
"""Apply ``self`` to ``elem``."""
raise NotImplementedError
def __call__(self, elem):
return self.codomain.convert(self._apply(self.domain.convert(elem)))
def _compose(self, oth):
"""
Compose ``self`` with ``oth``, that is, return the homomorphism
obtained by first applying then ``self``, then ``oth``.
(This method is private since in this syntax, it is non-obvious which
homomorphism is executed first.)
"""
raise NotImplementedError
def _mul_scalar(self, c):
"""Scalar multiplication. ``c`` is guaranteed in self.ring."""
raise NotImplementedError
def _add(self, oth):
"""
Homomorphism addition.
``oth`` is guaranteed to be a homomorphism with same domain/codomain.
"""
raise NotImplementedError
def _check_hom(self, oth):
"""Helper to check that oth is a homomorphism with same domain/codomain."""
if not isinstance(oth, ModuleHomomorphism):
return False
return oth.domain == self.domain and oth.codomain == self.codomain
def __mul__(self, oth):
if isinstance(oth, ModuleHomomorphism) and self.domain == oth.codomain:
return oth._compose(self)
try:
return self._mul_scalar(self.ring.convert(oth))
except CoercionFailed:
return NotImplemented
# NOTE: _compose will never be called from rmul
__rmul__ = __mul__
def __div__(self, oth):
try:
return self._mul_scalar(1/self.ring.convert(oth))
except CoercionFailed:
return NotImplemented
__truediv__ = __div__
def __add__(self, oth):
if self._check_hom(oth):
return self._add(oth)
return NotImplemented
def __sub__(self, oth):
if self._check_hom(oth):
return self._add(oth._mul_scalar(self.ring.convert(-1)))
return NotImplemented
def is_injective(self):
"""
Return True if ``self`` is injective.
That is, check if the elements of the domain are mapped to the same
codomain element.
>>> from sympy import QQ
>>> from sympy.abc import x
>>> from sympy.polys.agca import homomorphism
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> h = homomorphism(F, F, [[1, 0], [x, 0]])
>>> h.is_injective()
False
>>> h.quotient_domain(h.kernel()).is_injective()
True
"""
return self.kernel().is_zero()
def is_surjective(self):
"""
Return True if ``self`` is surjective.
That is, check if every element of the codomain has at least one
preimage.
>>> from sympy import QQ
>>> from sympy.abc import x
>>> from sympy.polys.agca import homomorphism
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> h = homomorphism(F, F, [[1, 0], [x, 0]])
>>> h.is_surjective()
False
>>> h.restrict_codomain(h.image()).is_surjective()
True
"""
return self.image() == self.codomain
def is_isomorphism(self):
"""
Return True if ``self`` is an isomorphism.
That is, check if every element of the codomain has precisely one
preimage. Equivalently, ``self`` is both injective and surjective.
>>> from sympy import QQ
>>> from sympy.abc import x
>>> from sympy.polys.agca import homomorphism
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> h = homomorphism(F, F, [[1, 0], [x, 0]])
>>> h = h.restrict_codomain(h.image())
>>> h.is_isomorphism()
False
>>> h.quotient_domain(h.kernel()).is_isomorphism()
True
"""
return self.is_injective() and self.is_surjective()
def is_zero(self):
"""
Return True if ``self`` is a zero morphism.
That is, check if every element of the domain is mapped to zero
under self.
>>> from sympy import QQ
>>> from sympy.abc import x
>>> from sympy.polys.agca import homomorphism
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> h = homomorphism(F, F, [[1, 0], [x, 0]])
>>> h.is_zero()
False
>>> h.restrict_domain(F.submodule()).is_zero()
True
>>> h.quotient_codomain(h.image()).is_zero()
True
"""
return self.image().is_zero()
def __eq__(self, oth):
try:
return (self - oth).is_zero()
except TypeError:
return False
def __ne__(self, oth):
return not (self == oth)
class MatrixHomomorphism(ModuleHomomorphism):
"""
Helper class for all homomoprhisms which are expressed via a matrix.
That is, for such homomorphisms ``domain`` is contained in a module
generated by finitely many elements `e_1, \ldots, e_n`, so that the
homomorphism is determined uniquely by its action on the `e_i`. It
can thus be represented as a vector of elements of the codomain module,
or potentially a supermodule of the codomain module
(and hence conventionally as a matrix, if there is a similar interpretation
for elements of the codomain module).
Note that this class does *not* assume that the `e_i` freely generate a
submodule, nor that ``domain`` is even all of this submodule. It exists
only to unify the interface.
Do not instantiate.
Attributes:
- matrix - the list of images determining the homomorphism.
NOTE: the elements of matrix belong to either self.codomain or
self.codomain.container
Still non-implemented methods:
- kernel
- _apply
"""
def __init__(self, domain, codomain, matrix):
ModuleHomomorphism.__init__(self, domain, codomain)
if len(matrix) != domain.rank:
raise ValueError('Need to provide %s elements, got %s'
% (domain.rank, len(matrix)))
converter = self.codomain.convert
if isinstance(self.codomain, (SubModule, SubQuotientModule)):
converter = self.codomain.container.convert
self.matrix = tuple(converter(x) for x in matrix)
def _sympy_matrix(self):
"""Helper function which returns a sympy matrix ``self.matrix``."""
from sympy.matrices import Matrix
c = lambda x: x
if isinstance(self.codomain, (QuotientModule, SubQuotientModule)):
c = lambda x: x.data
return Matrix([[self.ring.to_sympy(y) for y in c(x)] for x in self.matrix]).T
def __repr__(self):
lines = repr(self._sympy_matrix()).split('\n')
t = " : %s -> %s" % (self.domain, self.codomain)
s = ' '*len(t)
n = len(lines)
for i in range(n // 2):
lines[i] += s
lines[n // 2] += t
for i in range(n//2 + 1, n):
lines[i] += s
return '\n'.join(lines)
def _restrict_domain(self, sm):
"""Implementation of domain restriction."""
return SubModuleHomomorphism(sm, self.codomain, self.matrix)
def _restrict_codomain(self, sm):
"""Implementation of codomain restriction."""
return self.__class__(self.domain, sm, self.matrix)
def _quotient_domain(self, sm):
"""Implementation of domain quotient."""
return self.__class__(self.domain/sm, self.codomain, self.matrix)
def _quotient_codomain(self, sm):
"""Implementation of codomain quotient."""
Q = self.codomain/sm
converter = Q.convert
if isinstance(self.codomain, SubModule):
converter = Q.container.convert
return self.__class__(self.domain, self.codomain/sm,
[converter(x) for x in self.matrix])
def _add(self, oth):
return self.__class__(self.domain, self.codomain,
[x + y for x, y in zip(self.matrix, oth.matrix)])
def _mul_scalar(self, c):
return self.__class__(self.domain, self.codomain, [c*x for x in self.matrix])
def _compose(self, oth):
return self.__class__(self.domain, oth.codomain, [oth(x) for x in self.matrix])
class FreeModuleHomomorphism(MatrixHomomorphism):
"""
Concrete class for homomorphisms with domain a free module or a quotient
thereof.
Do not instantiate; the constructor does not check that your data is well
defined. Use the ``homomorphism`` function instead:
>>> from sympy import QQ
>>> from sympy.abc import x
>>> from sympy.polys.agca import homomorphism
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> homomorphism(F, F, [[1, 0], [0, 1]])
Matrix([
[1, 0], : QQ[x]**2 -> QQ[x]**2
[0, 1]])
"""
def _apply(self, elem):
if isinstance(self.domain, QuotientModule):
elem = elem.data
return sum(x * e for x, e in zip(elem, self.matrix))
def _image(self):
return self.codomain.submodule(*self.matrix)
def _kernel(self):
# The domain is either a free module or a quotient thereof.
# It does not matter if it is a quotient, because that won't increase
# the kernel.
# Our generators {e_i} are sent to the matrix entries {b_i}.
# The kernel is essentially the syzygy module of these {b_i}.
syz = self.image().syzygy_module()
return self.domain.submodule(*syz.gens)
class SubModuleHomomorphism(MatrixHomomorphism):
"""
Concrete class for homomorphism with domain a submodule of a free module
or a quotient thereof.
Do not instantiate; the constructor does not check that your data is well
defined. Use the ``homomorphism`` function instead:
>>> from sympy import QQ
>>> from sympy.abc import x
>>> from sympy.polys.agca import homomorphism
>>> M = QQ.old_poly_ring(x).free_module(2)*x
>>> homomorphism(M, M, [[1, 0], [0, 1]])
Matrix([
[1, 0], : <[x, 0], [0, x]> -> <[x, 0], [0, x]>
[0, 1]])
"""
def _apply(self, elem):
if isinstance(self.domain, SubQuotientModule):
elem = elem.data
return sum(x * e for x, e in zip(elem, self.matrix))
def _image(self):
return self.codomain.submodule(*[self(x) for x in self.domain.gens])
def _kernel(self):
syz = self.image().syzygy_module()
return self.domain.submodule(
*[sum(xi*gi for xi, gi in zip(s, self.domain.gens))
for s in syz.gens])
def homomorphism(domain, codomain, matrix):
r"""
Create a homomorphism object.
This function tries to build a homomorphism from ``domain`` to ``codomain``
via the matrix ``matrix``.
Examples
========
>>> from sympy import QQ
>>> from sympy.abc import x
>>> from sympy.polys.agca import homomorphism
>>> R = QQ.old_poly_ring(x)
>>> T = R.free_module(2)
If ``domain`` is a free module generated by `e_1, \ldots, e_n`, then
``matrix`` should be an n-element iterable `(b_1, \ldots, b_n)` where
the `b_i` are elements of ``codomain``. The constructed homomorphism is the
unique homomorphism sending `e_i` to `b_i`.
>>> F = R.free_module(2)
>>> h = homomorphism(F, T, [[1, x], [x**2, 0]])
>>> h
Matrix([
[1, x**2], : QQ[x]**2 -> QQ[x]**2
[x, 0]])
>>> h([1, 0])
[1, x]
>>> h([0, 1])
[x**2, 0]
>>> h([1, 1])
[x**2 + 1, x]
If ``domain`` is a submodule of a free module, them ``matrix`` determines
a homomoprhism from the containing free module to ``codomain``, and the
homomorphism returned is obtained by restriction to ``domain``.
>>> S = F.submodule([1, 0], [0, x])
>>> homomorphism(S, T, [[1, x], [x**2, 0]])
Matrix([
[1, x**2], : <[1, 0], [0, x]> -> QQ[x]**2
[x, 0]])
If ``domain`` is a (sub)quotient `N/K`, then ``matrix`` determines a
homomorphism from `N` to ``codomain``. If the kernel contains `K`, this
homomorphism descends to ``domain`` and is returned; otherwise an exception
is raised.
>>> homomorphism(S/[(1, 0)], T, [0, [x**2, 0]])
Matrix([
[0, x**2], : <[1, 0] + <[1, 0]>, [0, x] + <[1, 0]>, [1, 0] + <[1, 0]>> -> QQ[x]**2
[0, 0]])
>>> homomorphism(S/[(0, x)], T, [0, [x**2, 0]])
Traceback (most recent call last):
...
ValueError: kernel <[1, 0], [0, 0]> must contain sm, got <[0,x]>
"""
def freepres(module):
"""
Return a tuple ``(F, S, Q, c)`` where ``F`` is a free module, ``S`` is a
submodule of ``F``, and ``Q`` a submodule of ``S``, such that
``module = S/Q``, and ``c`` is a conversion function.
"""
if isinstance(module, FreeModule):
return module, module, module.submodule(), lambda x: module.convert(x)
if isinstance(module, QuotientModule):
return (module.base, module.base, module.killed_module,
lambda x: module.convert(x).data)
if isinstance(module, SubQuotientModule):
return (module.base.container, module.base, module.killed_module,
lambda x: module.container.convert(x).data)
# an ordinary submodule
return (module.container, module, module.submodule(),
lambda x: module.container.convert(x))
SF, SS, SQ, _ = freepres(domain)
TF, TS, TQ, c = freepres(codomain)
# NOTE this is probably a bit inefficient (redundant checks)
return FreeModuleHomomorphism(SF, TF, [c(x) for x in matrix]
).restrict_domain(SS).restrict_codomain(TS
).quotient_codomain(TQ).quotient_domain(SQ)
| 21,708 | 31.596096 | 87 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/agca/tests/test_ideals.py
|
"""Test ideals.py code."""
from sympy.polys import QQ, ilex
from sympy.abc import x, y, z
from sympy.utilities.pytest import raises
def test_ideal_operations():
R = QQ.old_poly_ring(x, y)
I = R.ideal(x)
J = R.ideal(y)
S = R.ideal(x*y)
T = R.ideal(x, y)
assert not (I == J)
assert I == I
assert I.union(J) == T
assert I + J == T
assert I + T == T
assert not I.subset(T)
assert T.subset(I)
assert I.product(J) == S
assert I*J == S
assert x*J == S
assert I*y == S
assert R.convert(x)*J == S
assert I*R.convert(y) == S
assert not I.is_zero()
assert not J.is_whole_ring()
assert R.ideal(x**2 + 1, x).is_whole_ring()
assert R.ideal() == R.ideal(0)
assert R.ideal().is_zero()
assert T.contains(x*y)
assert T.subset([x, y])
assert T.in_terms_of_generators(x) == [R(1), R(0)]
assert T**0 == R.ideal(1)
assert T**1 == T
assert T**2 == R.ideal(x**2, y**2, x*y)
assert I**5 == R.ideal(x**5)
def test_exceptions():
I = QQ.old_poly_ring(x).ideal(x)
J = QQ.old_poly_ring(y).ideal(1)
raises(ValueError, lambda: I.union(x))
raises(ValueError, lambda: I + J)
raises(ValueError, lambda: I * J)
raises(ValueError, lambda: I.union(J))
assert (I == J) is False
assert I != J
def test_nontriv_global():
R = QQ.old_poly_ring(x, y, z)
def contains(I, f):
return R.ideal(*I).contains(f)
assert contains([x, y], x)
assert contains([x, y], x + y)
assert not contains([x, y], 1)
assert not contains([x, y], z)
assert contains([x**2 + y, x**2 + x], x - y)
assert not contains([x + y + z, x*y + x*z + y*z, x*y*z], x**2)
assert contains([x + y + z, x*y + x*z + y*z, x*y*z], x**3)
assert contains([x + y + z, x*y + x*z + y*z, x*y*z], x**4)
assert not contains([x + y + z, x*y + x*z + y*z, x*y*z], x*y**2)
assert contains([x + y + z, x*y + x*z + y*z, x*y*z], x**4 + y**3 + 2*z*y*x)
assert contains([x + y + z, x*y + x*z + y*z, x*y*z], x*y*z)
assert contains([x, 1 + x + y, 5 - 7*y], 1)
assert contains(
[x**3 + y**3, y**3 + z**3, z**3 + x**3, x**2*y + x**2*z + y**2*z],
x**3)
assert not contains(
[x**3 + y**3, y**3 + z**3, z**3 + x**3, x**2*y + x**2*z + y**2*z],
x**2 + y**2)
# compare local order
assert not contains([x*(1 + x + y), y*(1 + z)], x)
assert not contains([x*(1 + x + y), y*(1 + z)], x + y)
def test_nontriv_local():
R = QQ.old_poly_ring(x, y, z, order=ilex)
def contains(I, f):
return R.ideal(*I).contains(f)
assert contains([x, y], x)
assert contains([x, y], x + y)
assert not contains([x, y], 1)
assert not contains([x, y], z)
assert contains([x**2 + y, x**2 + x], x - y)
assert not contains([x + y + z, x*y + x*z + y*z, x*y*z], x**2)
assert contains([x*(1 + x + y), y*(1 + z)], x)
assert contains([x*(1 + x + y), y*(1 + z)], x + y)
def test_intersection():
R = QQ.old_poly_ring(x, y, z)
# SCA, example 1.8.11
assert R.ideal(x, y).intersect(R.ideal(y**2, z)) == R.ideal(y**2, y*z, x*z)
assert R.ideal(x, y).intersect(R.ideal()).is_zero()
R = QQ.old_poly_ring(x, y, z, order="ilex")
assert R.ideal(x, y).intersect(R.ideal(y**2 + y**2*z, z + z*x**3*y)) == \
R.ideal(y**2, y*z, x*z)
def test_quotient():
# SCA, example 1.8.13
R = QQ.old_poly_ring(x, y, z)
assert R.ideal(x, y).quotient(R.ideal(y**2, z)) == R.ideal(x, y)
def test_reduction():
from sympy.polys.distributedmodules import sdm_nf_buchberger_reduced
R = QQ.old_poly_ring(x, y)
I = R.ideal(x**5, y)
e = R.convert(x**3 + y**2)
assert I.reduce_element(e) == e
assert I.reduce_element(e, NF=sdm_nf_buchberger_reduced) == R.convert(x**3)
| 3,790 | 27.719697 | 79 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/agca/tests/test_modules.py
|
"""Test modules.py code."""
from sympy.polys.agca.modules import FreeModule, ModuleOrder, FreeModulePolyRing
from sympy.polys import CoercionFailed, QQ, lex, grlex, ilex, ZZ
from sympy.abc import x, y, z
from sympy.utilities.pytest import raises
from sympy import S
def test_FreeModuleElement():
M = QQ.old_poly_ring(x).free_module(3)
e = M.convert([1, x, x**2])
f = [QQ.old_poly_ring(x).convert(1), QQ.old_poly_ring(x).convert(x), QQ.old_poly_ring(x).convert(x**2)]
assert list(e) == f
assert f[0] == e[0]
assert f[1] == e[1]
assert f[2] == e[2]
raises(IndexError, lambda: e[3])
g = M.convert([x, 0, 0])
assert e + g == M.convert([x + 1, x, x**2])
assert f + g == M.convert([x + 1, x, x**2])
assert -e == M.convert([-1, -x, -x**2])
assert e - g == M.convert([1 - x, x, x**2])
assert e != g
assert M.convert([x, x, x]) / QQ.old_poly_ring(x).convert(x) == [1, 1, 1]
R = QQ.old_poly_ring(x, order="ilex")
assert R.free_module(1).convert([x]) / R.convert(x) == [1]
def test_FreeModule():
M1 = FreeModule(QQ.old_poly_ring(x), 2)
assert M1 == FreeModule(QQ.old_poly_ring(x), 2)
assert M1 != FreeModule(QQ.old_poly_ring(y), 2)
assert M1 != FreeModule(QQ.old_poly_ring(x), 3)
M2 = FreeModule(QQ.old_poly_ring(x, order="ilex"), 2)
assert [x, 1] in M1
assert [x] not in M1
assert [2, y] not in M1
assert [1/(x + 1), 2] not in M1
e = M1.convert([x, x**2 + 1])
X = QQ.old_poly_ring(x).convert(x)
assert e == [X, X**2 + 1]
assert e == [x, x**2 + 1]
assert 2*e == [2*x, 2*x**2 + 2]
assert e*2 == [2*x, 2*x**2 + 2]
assert e/2 == [x/2, (x**2 + 1)/2]
assert x*e == [x**2, x**3 + x]
assert e*x == [x**2, x**3 + x]
assert X*e == [x**2, x**3 + x]
assert e*X == [x**2, x**3 + x]
assert [x, 1] in M2
assert [x] not in M2
assert [2, y] not in M2
assert [1/(x + 1), 2] in M2
e = M2.convert([x, x**2 + 1])
X = QQ.old_poly_ring(x, order="ilex").convert(x)
assert e == [X, X**2 + 1]
assert e == [x, x**2 + 1]
assert 2*e == [2*x, 2*x**2 + 2]
assert e*2 == [2*x, 2*x**2 + 2]
assert e/2 == [x/2, (x**2 + 1)/2]
assert x*e == [x**2, x**3 + x]
assert e*x == [x**2, x**3 + x]
assert e/(1 + x) == [x/(1 + x), (x**2 + 1)/(1 + x)]
assert X*e == [x**2, x**3 + x]
assert e*X == [x**2, x**3 + x]
M3 = FreeModule(QQ.old_poly_ring(x, y), 2)
assert M3.convert(e) == M3.convert([x, x**2 + 1])
assert not M3.is_submodule(0)
assert not M3.is_zero()
raises(NotImplementedError, lambda: ZZ.old_poly_ring(x).free_module(2))
raises(NotImplementedError, lambda: FreeModulePolyRing(ZZ, 2))
raises(CoercionFailed, lambda: M1.convert(QQ.old_poly_ring(x).free_module(3)
.convert([1, 2, 3])))
raises(CoercionFailed, lambda: M3.convert(1))
def test_ModuleOrder():
o1 = ModuleOrder(lex, grlex, False)
o2 = ModuleOrder(ilex, lex, False)
assert o1 == ModuleOrder(lex, grlex, False)
assert (o1 != ModuleOrder(lex, grlex, False)) is False
assert o1 != o2
assert o1((1, 2, 3)) == (1, (5, (2, 3)))
assert o2((1, 2, 3)) == (-1, (2, 3))
def test_SubModulePolyRing_global():
R = QQ.old_poly_ring(x, y)
F = R.free_module(3)
Fd = F.submodule([1, 0, 0], [1, 2, 0], [1, 2, 3])
M = F.submodule([x**2 + y**2, 1, 0], [x, y, 1])
assert F == Fd
assert Fd == F
assert F != M
assert M != F
assert Fd != M
assert M != Fd
assert Fd == F.submodule(*F.basis())
assert Fd.is_full_module()
assert not M.is_full_module()
assert not Fd.is_zero()
assert not M.is_zero()
assert Fd.submodule().is_zero()
assert M.contains([x**2 + y**2 + x, 1 + y, 1])
assert not M.contains([x**2 + y**2 + x, 1 + y, 2])
assert M.contains([y**2, 1 - x*y, -x])
assert not F.submodule([1 + x, 0, 0]) == F.submodule([1, 0, 0])
assert F.submodule([1, 0, 0], [0, 1, 0]).union(F.submodule([0, 0, 1])) == F
assert not M.is_submodule(0)
m = F.convert([x**2 + y**2, 1, 0])
n = M.convert(m)
assert m.module is F
assert n.module is M
raises(ValueError, lambda: M.submodule([1, 0, 0]))
raises(TypeError, lambda: M.union(1))
raises(ValueError, lambda: M.union(R.free_module(1).submodule([x])))
assert F.submodule([x, x, x]) != F.submodule([x, x, x], order="ilex")
def test_SubModulePolyRing_local():
R = QQ.old_poly_ring(x, y, order=ilex)
F = R.free_module(3)
Fd = F.submodule([1 + x, 0, 0], [1 + y, 2 + 2*y, 0], [1, 2, 3])
M = F.submodule([x**2 + y**2, 1, 0], [x, y, 1])
assert F == Fd
assert Fd == F
assert F != M
assert M != F
assert Fd != M
assert M != Fd
assert Fd == F.submodule(*F.basis())
assert Fd.is_full_module()
assert not M.is_full_module()
assert not Fd.is_zero()
assert not M.is_zero()
assert Fd.submodule().is_zero()
assert M.contains([x**2 + y**2 + x, 1 + y, 1])
assert not M.contains([x**2 + y**2 + x, 1 + y, 2])
assert M.contains([y**2, 1 - x*y, -x])
assert F.submodule([1 + x, 0, 0]) == F.submodule([1, 0, 0])
assert F.submodule(
[1, 0, 0], [0, 1, 0]).union(F.submodule([0, 0, 1 + x*y])) == F
raises(ValueError, lambda: M.submodule([1, 0, 0]))
def test_SubModulePolyRing_nontriv_global():
R = QQ.old_poly_ring(x, y, z)
F = R.free_module(1)
def contains(I, f):
return F.submodule(*[[g] for g in I]).contains([f])
assert contains([x, y], x)
assert contains([x, y], x + y)
assert not contains([x, y], 1)
assert not contains([x, y], z)
assert contains([x**2 + y, x**2 + x], x - y)
assert not contains([x + y + z, x*y + x*z + y*z, x*y*z], x**2)
assert contains([x + y + z, x*y + x*z + y*z, x*y*z], x**3)
assert contains([x + y + z, x*y + x*z + y*z, x*y*z], x**4)
assert not contains([x + y + z, x*y + x*z + y*z, x*y*z], x*y**2)
assert contains([x + y + z, x*y + x*z + y*z, x*y*z], x**4 + y**3 + 2*z*y*x)
assert contains([x + y + z, x*y + x*z + y*z, x*y*z], x*y*z)
assert contains([x, 1 + x + y, 5 - 7*y], 1)
assert contains(
[x**3 + y**3, y**3 + z**3, z**3 + x**3, x**2*y + x**2*z + y**2*z],
x**3)
assert not contains(
[x**3 + y**3, y**3 + z**3, z**3 + x**3, x**2*y + x**2*z + y**2*z],
x**2 + y**2)
# compare local order
assert not contains([x*(1 + x + y), y*(1 + z)], x)
assert not contains([x*(1 + x + y), y*(1 + z)], x + y)
def test_SubModulePolyRing_nontriv_local():
R = QQ.old_poly_ring(x, y, z, order=ilex)
F = R.free_module(1)
def contains(I, f):
return F.submodule(*[[g] for g in I]).contains([f])
assert contains([x, y], x)
assert contains([x, y], x + y)
assert not contains([x, y], 1)
assert not contains([x, y], z)
assert contains([x**2 + y, x**2 + x], x - y)
assert not contains([x + y + z, x*y + x*z + y*z, x*y*z], x**2)
assert contains([x*(1 + x + y), y*(1 + z)], x)
assert contains([x*(1 + x + y), y*(1 + z)], x + y)
def test_syzygy():
R = QQ.old_poly_ring(x, y, z)
M = R.free_module(1).submodule([x*y], [y*z], [x*z])
S = R.free_module(3).submodule([0, x, -y], [z, -x, 0])
assert M.syzygy_module() == S
M2 = M / ([x*y*z],)
S2 = R.free_module(3).submodule([z, 0, 0], [0, x, 0], [0, 0, y])
assert M2.syzygy_module() == S2
F = R.free_module(3)
assert F.submodule(*F.basis()).syzygy_module() == F.submodule()
R2 = QQ.old_poly_ring(x, y, z) / [x*y*z]
M3 = R2.free_module(1).submodule([x*y], [y*z], [x*z])
S3 = R2.free_module(3).submodule([z, 0, 0], [0, x, 0], [0, 0, y])
assert M3.syzygy_module() == S3
def test_in_terms_of_generators():
R = QQ.old_poly_ring(x, order="ilex")
M = R.free_module(2).submodule([2*x, 0], [1, 2])
assert M.in_terms_of_generators(
[x, x]) == [R.convert(S(1)/4), R.convert(x/2)]
raises(ValueError, lambda: M.in_terms_of_generators([1, 0]))
M = R.free_module(2) / ([x, 0], [1, 1])
SM = M.submodule([1, x])
assert SM.in_terms_of_generators([2, 0]) == [R.convert(-2/(x - 1))]
R = QQ.old_poly_ring(x, y) / [x**2 - y**2]
M = R.free_module(2)
SM = M.submodule([x, 0], [0, y])
assert SM.in_terms_of_generators(
[x**2, x**2]) == [R.convert(x), R.convert(y)]
def test_QuotientModuleElement():
R = QQ.old_poly_ring(x)
F = R.free_module(3)
N = F.submodule([1, x, x**2])
M = F/N
e = M.convert([x**2, 2, 0])
assert M.convert([x + 1, x**2 + x, x**3 + x**2]) == 0
assert e == [x**2, 2, 0] + N == F.convert([x**2, 2, 0]) + N == \
M.convert(F.convert([x**2, 2, 0]))
assert M.convert([x**2 + 1, 2*x + 2, x**2]) == e + [0, x, 0] == \
e + M.convert([0, x, 0]) == e + F.convert([0, x, 0])
assert M.convert([x**2 + 1, 2, x**2]) == e - [0, x, 0] == \
e - M.convert([0, x, 0]) == e - F.convert([0, x, 0])
assert M.convert([0, 2, 0]) == M.convert([x**2, 4, 0]) - e == \
[x**2, 4, 0] - e == F.convert([x**2, 4, 0]) - e
assert M.convert([x**3 + x**2, 2*x + 2, 0]) == (1 + x)*e == \
R.convert(1 + x)*e == e*(1 + x) == e*R.convert(1 + x)
assert -e == [-x**2, -2, 0]
f = [x, x, 0] + N
assert M.convert([1, 1, 0]) == f / x == f / R.convert(x)
M2 = F/[(2, 2*x, 2*x**2), (0, 0, 1)]
G = R.free_module(2)
M3 = G/[[1, x]]
M4 = F.submodule([1, x, x**2], [1, 0, 0]) / N
raises(CoercionFailed, lambda: M.convert(G.convert([1, x])))
raises(CoercionFailed, lambda: M.convert(M3.convert([1, x])))
raises(CoercionFailed, lambda: M.convert(M2.convert([1, x, x])))
assert M2.convert(M.convert([2, x, x**2])) == [2, x, 0]
assert M.convert(M4.convert([2, 0, 0])) == [2, 0, 0]
def test_QuotientModule():
R = QQ.old_poly_ring(x)
F = R.free_module(3)
N = F.submodule([1, x, x**2])
M = F/N
assert M != F
assert M != N
assert M == F / [(1, x, x**2)]
assert not M.is_zero()
assert (F / F.basis()).is_zero()
SQ = F.submodule([1, x, x**2], [2, 0, 0]) / N
assert SQ == M.submodule([2, x, x**2])
assert SQ != M.submodule([2, 1, 0])
assert SQ != M
assert M.is_submodule(SQ)
assert not SQ.is_full_module()
raises(ValueError, lambda: N/F)
raises(ValueError, lambda: F.submodule([2, 0, 0]) / N)
raises(ValueError, lambda: R.free_module(2)/F)
raises(CoercionFailed, lambda: F.convert(M.convert([1, x, x**2])))
M1 = F / [[1, 1, 1]]
M2 = M1.submodule([1, 0, 0], [0, 1, 0])
assert M1 == M2
def test_ModulesQuotientRing():
R = QQ.old_poly_ring(x, y, order=(("lex", x), ("ilex", y))) / [x**2 + 1]
M1 = R.free_module(2)
assert M1 == R.free_module(2)
assert M1 != QQ.old_poly_ring(x).free_module(2)
assert M1 != R.free_module(3)
assert [x, 1] in M1
assert [x] not in M1
assert [1/(R.convert(x) + 1), 2] in M1
assert [1, 2/(1 + y)] in M1
assert [1, 2/y] not in M1
assert M1.convert([x**2, y]) == [-1, y]
F = R.free_module(3)
Fd = F.submodule([x**2, 0, 0], [1, 2, 0], [1, 2, 3])
M = F.submodule([x**2 + y**2, 1, 0], [x, y, 1])
assert F == Fd
assert Fd == F
assert F != M
assert M != F
assert Fd != M
assert M != Fd
assert Fd == F.submodule(*F.basis())
assert Fd.is_full_module()
assert not M.is_full_module()
assert not Fd.is_zero()
assert not M.is_zero()
assert Fd.submodule().is_zero()
assert M.contains([x**2 + y**2 + x, -x**2 + y, 1])
assert not M.contains([x**2 + y**2 + x, 1 + y, 2])
assert M.contains([y**2, 1 - x*y, -x])
assert F.submodule([x, 0, 0]) == F.submodule([1, 0, 0])
assert not F.submodule([y, 0, 0]) == F.submodule([1, 0, 0])
assert F.submodule([1, 0, 0], [0, 1, 0]).union(F.submodule([0, 0, 1])) == F
assert not M.is_submodule(0)
def test_module_mul():
R = QQ.old_poly_ring(x)
M = R.free_module(2)
S1 = M.submodule([x, 0], [0, x])
S2 = M.submodule([x**2, 0], [0, x**2])
I = R.ideal(x)
assert I*M == M*I == S1 == x*M == M*x
assert I*S1 == S2 == x*S1
def test_intersection():
# SCA, example 2.8.5
F = QQ.old_poly_ring(x, y).free_module(2)
M1 = F.submodule([x, y], [y, 1])
M2 = F.submodule([0, y - 1], [x, 1], [y, x])
I = F.submodule([x, y], [y**2 - y, y - 1], [x*y + y, x + 1])
I1, rel1, rel2 = M1.intersect(M2, relations=True)
assert I1 == M2.intersect(M1) == I
for i, g in enumerate(I1.gens):
assert g == sum(c*x for c, x in zip(rel1[i], M1.gens)) \
== sum(d*y for d, y in zip(rel2[i], M2.gens))
assert F.submodule([x, y]).intersect(F.submodule([y, x])).is_zero()
def test_quotient():
# SCA, example 2.8.6
R = QQ.old_poly_ring(x, y, z)
F = R.free_module(2)
assert F.submodule([x*y, x*z], [y*z, x*y]).module_quotient(
F.submodule([y, z], [z, y])) == QQ.old_poly_ring(x, y, z).ideal(x**2*y**2 - x*y*z**2)
assert F.submodule([x, y]).module_quotient(F.submodule()).is_whole_ring()
M = F.submodule([x**2, x**2], [y**2, y**2])
N = F.submodule([x + y, x + y])
q, rel = M.module_quotient(N, relations=True)
assert q == R.ideal(y**2, x - y)
for i, g in enumerate(q.gens):
assert g*N.gens[0] == sum(c*x for c, x in zip(rel[i], M.gens))
def test_groebner_extendend():
M = QQ.old_poly_ring(x, y, z).free_module(3).submodule([x + 1, y, 1], [x*y, z, z**2])
G, R = M._groebner_vec(extended=True)
for i, g in enumerate(G):
assert g == sum(c*gen for c, gen in zip(R[i], M.gens))
| 13,526 | 32.07335 | 107 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/agca/tests/__init__.py
| 0 | 0 | 0 |
py
|
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/polys/agca/tests/test_homomorphisms.py
|
"""Tests for homomorphisms."""
from sympy import QQ, S
from sympy.abc import x, y
from sympy.polys.agca import homomorphism
from sympy.utilities.pytest import raises
def test_printing():
R = QQ.old_poly_ring(x)
assert str(homomorphism(R.free_module(1), R.free_module(1), [0])) == \
'Matrix([[0]]) : QQ[x]**1 -> QQ[x]**1'
assert str(homomorphism(R.free_module(2), R.free_module(2), [0, 0])) == \
'Matrix([ \n[0, 0], : QQ[x]**2 -> QQ[x]**2\n[0, 0]]) '
assert str(homomorphism(R.free_module(1), R.free_module(1) / [[x]], [0])) == \
'Matrix([[0]]) : QQ[x]**1 -> QQ[x]**1/<[x]>'
assert str(R.free_module(0).identity_hom()) == 'Matrix(0, 0, []) : QQ[x]**0 -> QQ[x]**0'
def test_operations():
F = QQ.old_poly_ring(x).free_module(2)
G = QQ.old_poly_ring(x).free_module(3)
f = F.identity_hom()
g = homomorphism(F, F, [0, [1, x]])
h = homomorphism(F, F, [[1, 0], 0])
i = homomorphism(F, G, [[1, 0, 0], [0, 1, 0]])
assert f == f
assert f != g
assert f != i
assert (f != F.identity_hom()) is False
assert 2*f == f*2 == homomorphism(F, F, [[2, 0], [0, 2]])
assert f/2 == homomorphism(F, F, [[S(1)/2, 0], [0, S(1)/2]])
assert f + g == homomorphism(F, F, [[1, 0], [1, x + 1]])
assert f - g == homomorphism(F, F, [[1, 0], [-1, 1 - x]])
assert f*g == g == g*f
assert h*g == homomorphism(F, F, [0, [1, 0]])
assert g*h == homomorphism(F, F, [0, 0])
assert i*f == i
assert f([1, 2]) == [1, 2]
assert g([1, 2]) == [2, 2*x]
assert i.restrict_domain(F.submodule([x, x]))([x, x]) == i([x, x])
h1 = h.quotient_domain(F.submodule([0, 1]))
assert h1([1, 0]) == h([1, 0])
assert h1.restrict_domain(h1.domain.submodule([x, 0]))([x, 0]) == h([x, 0])
raises(TypeError, lambda: f/g)
raises(TypeError, lambda: f + 1)
raises(TypeError, lambda: f + i)
raises(TypeError, lambda: f - 1)
raises(TypeError, lambda: f*i)
def test_creation():
F = QQ.old_poly_ring(x).free_module(3)
G = QQ.old_poly_ring(x).free_module(2)
SM = F.submodule([1, 1, 1])
Q = F / SM
SQ = Q.submodule([1, 0, 0])
matrix = [[1, 0], [0, 1], [-1, -1]]
h = homomorphism(F, G, matrix)
h2 = homomorphism(Q, G, matrix)
assert h.quotient_domain(SM) == h2
raises(ValueError, lambda: h.quotient_domain(F.submodule([1, 0, 0])))
assert h2.restrict_domain(SQ) == homomorphism(SQ, G, matrix)
raises(ValueError, lambda: h.restrict_domain(G))
raises(ValueError, lambda: h.restrict_codomain(G.submodule([1, 0])))
raises(ValueError, lambda: h.quotient_codomain(F))
im = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
for M in [F, SM, Q, SQ]:
assert M.identity_hom() == homomorphism(M, M, im)
assert SM.inclusion_hom() == homomorphism(SM, F, im)
assert SQ.inclusion_hom() == homomorphism(SQ, Q, im)
assert Q.quotient_hom() == homomorphism(F, Q, im)
assert SQ.quotient_hom() == homomorphism(SQ.base, SQ, im)
class conv(object):
def convert(x, y=None):
return x
class dummy(object):
container = conv()
def submodule(*args):
return None
raises(TypeError, lambda: homomorphism(dummy(), G, matrix))
raises(TypeError, lambda: homomorphism(F, dummy(), matrix))
raises(
ValueError, lambda: homomorphism(QQ.old_poly_ring(x, y).free_module(3), G, matrix))
raises(ValueError, lambda: homomorphism(F, G, [0, 0]))
def test_properties():
R = QQ.old_poly_ring(x, y)
F = R.free_module(2)
h = homomorphism(F, F, [[x, 0], [y, 0]])
assert h.kernel() == F.submodule([-y, x])
assert h.image() == F.submodule([x, 0], [y, 0])
assert not h.is_injective()
assert not h.is_surjective()
assert h.restrict_codomain(h.image()).is_surjective()
assert h.restrict_domain(F.submodule([1, 0])).is_injective()
assert h.quotient_domain(
h.kernel()).restrict_codomain(h.image()).is_isomorphism()
R2 = QQ.old_poly_ring(x, y, order=(("lex", x), ("ilex", y))) / [x**2 + 1]
F = R2.free_module(2)
h = homomorphism(F, F, [[x, 0], [y, y + 1]])
assert h.is_isomorphism()
| 4,182 | 36.017699 | 106 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/ntheory/egyptian_fraction.py
|
from __future__ import print_function, division
import sympy.polys
from sympy import Integer
from sympy.core.compatibility import range
import sys
if sys.version_info < (3,5):
from fractions import gcd
else:
from math import gcd
def egyptian_fraction(r, algorithm="Greedy"):
"""
Return the list of denominators of an Egyptian fraction
expansion [1]_ of the said rational `r`.
Parameters
==========
r : Rational
a positive rational number.
algorithm : { "Greedy", "Graham Jewett", "Takenouchi", "Golomb" }, optional
Denotes the algorithm to be used (the default is "Greedy").
Examples
========
>>> from sympy import Rational
>>> from sympy.ntheory.egyptian_fraction import egyptian_fraction
>>> egyptian_fraction(Rational(3, 7))
[3, 11, 231]
>>> egyptian_fraction(Rational(3, 7), "Graham Jewett")
[7, 8, 9, 56, 57, 72, 3192]
>>> egyptian_fraction(Rational(3, 7), "Takenouchi")
[4, 7, 28]
>>> egyptian_fraction(Rational(3, 7), "Golomb")
[3, 15, 35]
>>> egyptian_fraction(Rational(11, 5), "Golomb")
[1, 2, 3, 4, 9, 234, 1118, 2580]
See Also
========
sympy.core.numbers.Rational
Notes
=====
Currently the following algorithms are supported:
1) Greedy Algorithm
Also called the Fibonacci-Sylvester algorithm [2]_.
At each step, extract the largest unit fraction less
than the target and replace the target with the remainder.
It has some distinct properties:
a) Given `p/q` in lowest terms, generates an expansion of maximum
length `p`. Even as the numerators get large, the number of
terms is seldom more than a handful.
b) Uses minimal memory.
c) The terms can blow up (standard examples of this are 5/121 and
31/311). The denominator is at most squared at each step
(doubly-exponential growth) and typically exhibits
singly-exponential growth.
2) Graham Jewett Algorithm
The algorithm suggested by the result of Graham and Jewett.
Note that this has a tendency to blow up: the length of the
resulting expansion is always ``2**(x/gcd(x, y)) - 1``. See [3]_.
3) Takenouchi Algorithm
The algorithm suggested by Takenouchi (1921).
Differs from the Graham-Jewett algorithm only in the handling
of duplicates. See [3]_.
4) Golomb's Algorithm
A method given by Golumb (1962), using modular arithmetic and
inverses. It yields the same results as a method using continued
fractions proposed by Bleicher (1972). See [4]_.
If the given rational is greater than or equal to 1, a greedy algorithm
of summing the harmonic sequence 1/1 + 1/2 + 1/3 + ... is used, taking
all the unit fractions of this sequence until adding one more would be
greater than the given number. This list of denominators is prefixed
to the result from the requested algorithm used on the remainder. For
example, if r is 8/3, using the Greedy algorithm, we get [1, 2, 3, 4,
5, 6, 7, 14, 420], where the beginning of the sequence, [1, 2, 3, 4, 5,
6, 7] is part of the harmonic sequence summing to 363/140, leaving a
remainder of 31/420, which yields [14, 420] by the Greedy algorithm.
The result of egyptian_fraction(Rational(8, 3), "Golomb") is [1, 2, 3,
4, 5, 6, 7, 14, 574, 2788, 6460, 11590, 33062, 113820], and so on.
References
==========
.. [1] http://en.wikipedia.org/wiki/Egyptian_fraction
.. [2] https://en.wikipedia.org/wiki/Greedy_algorithm_for_Egyptian_fractions
.. [3] http://www.ics.uci.edu/~eppstein/numth/egypt/conflict.html
.. [4] http://ami.ektf.hu/uploads/papers/finalpdf/AMI_42_from129to134.pdf
"""
if r <= 0:
raise ValueError("Value must be positive")
prefix, rem = egypt_harmonic(r)
if rem == 0:
return prefix
x, y = rem.as_numer_denom()
if algorithm == "Greedy":
return prefix + egypt_greedy(x, y)
elif algorithm == "Graham Jewett":
return prefix + egypt_graham_jewett(x, y)
elif algorithm == "Takenouchi":
return prefix + egypt_takenouchi(x, y)
elif algorithm == "Golomb":
return prefix + egypt_golomb(x, y)
else:
raise ValueError("Entered invalid algorithm")
def egypt_greedy(x, y):
if x == 1:
return [y]
else:
a = (-y) % (x)
b = y*(y//x + 1)
c = gcd(a, b)
if c > 1:
num, denom = a//c, b//c
else:
num, denom = a, b
return [y//x + 1] + egypt_greedy(num, denom)
def egypt_graham_jewett(x, y):
l = [y] * x
# l is now a list of integers whose reciprocals sum to x/y.
# we shall now proceed to manipulate the elements of l without
# changing the reciprocated sum until all elements are unique.
while len(l) != len(set(l)):
l.sort() # so the list has duplicates. find a smallest pair
for i in range(len(l) - 1):
if l[i] == l[i + 1]:
break
# we have now identified a pair of identical
# elements: l[i] and l[i + 1].
# now comes the application of the result of graham and jewett:
l[i + 1] = l[i] + 1
# and we just iterate that until the list has no duplicates.
l.append(l[i]*(l[i] + 1))
return sorted(l)
def egypt_takenouchi(x, y):
l = [y] * x
while len(l) != len(set(l)):
l.sort()
for i in range(len(l) - 1):
if l[i] == l[i + 1]:
break
k = l[i]
if k % 2 == 0:
l[i] = l[i] // 2
del l[i + 1]
else:
l[i], l[i + 1] = (k + 1)//2, k*(k + 1)//2
return sorted(l)
def egypt_golomb(x, y):
if x == 1:
return [y]
xp = sympy.polys.ZZ.invert(int(x), int(y))
rv = [Integer(xp*y)]
rv.extend(egypt_golomb((x*xp - 1)//y, xp))
return sorted(rv)
def egypt_harmonic(r):
rv = []
d = Integer(1)
acc = Integer(0)
while acc + 1/d <= r:
acc += 1/d
rv.append(d)
d += 1
return (rv, r - acc)
| 6,157 | 29.79 | 80 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/ntheory/modular.py
|
from __future__ import print_function, division
from sympy.core.numbers import igcdex, igcd
from sympy.core.mul import prod
from sympy.core.compatibility import as_int, reduce
from sympy.ntheory.primetest import isprime
from sympy.polys.domains import ZZ
from sympy.polys.galoistools import gf_crt, gf_crt1, gf_crt2
def symmetric_residue(a, m):
"""Return the residual mod m such that it is within half of the modulus.
>>> from sympy.ntheory.modular import symmetric_residue
>>> symmetric_residue(1, 6)
1
>>> symmetric_residue(4, 6)
-2
"""
if a <= m // 2:
return a
return a - m
def crt(m, v, symmetric=False, check=True):
r"""Chinese Remainder Theorem.
The moduli in m are assumed to be pairwise coprime. The output
is then an integer f, such that f = v_i mod m_i for each pair out
of v and m. If ``symmetric`` is False a positive integer will be
returned, else \|f\| will be less than or equal to the LCM of the
moduli, and thus f may be negative.
If the moduli are not co-prime the correct result will be returned
if/when the test of the result is found to be incorrect. This result
will be None if there is no solution.
The keyword ``check`` can be set to False if it is known that the moduli
are coprime.
As an example consider a set of residues ``U = [49, 76, 65]``
and a set of moduli ``M = [99, 97, 95]``. Then we have::
>>> from sympy.ntheory.modular import crt, solve_congruence
>>> crt([99, 97, 95], [49, 76, 65])
(639985, 912285)
This is the correct result because::
>>> [639985 % m for m in [99, 97, 95]]
[49, 76, 65]
If the moduli are not co-prime, you may receive an incorrect result
if you use ``check=False``:
>>> crt([12, 6, 17], [3, 4, 2], check=False)
(954, 1224)
>>> [954 % m for m in [12, 6, 17]]
[6, 0, 2]
>>> crt([12, 6, 17], [3, 4, 2]) is None
True
>>> crt([3, 6], [2, 5])
(5, 6)
Note: the order of gf_crt's arguments is reversed relative to crt,
and that solve_congruence takes residue, modulus pairs.
Programmer's note: rather than checking that all pairs of moduli share
no GCD (an O(n**2) test) and rather than factoring all moduli and seeing
that there is no factor in common, a check that the result gives the
indicated residuals is performed -- an O(n) operation.
See Also
========
solve_congruence
sympy.polys.galoistools.gf_crt : low level crt routine used by this routine
"""
if check:
m = list(map(as_int, m))
v = list(map(as_int, v))
result = gf_crt(v, m, ZZ)
mm = prod(m)
if check:
if not all(v % m == result % m for v, m in zip(v, m)):
result = solve_congruence(*list(zip(v, m)),
check=False, symmetric=symmetric)
if result is None:
return result
result, mm = result
if symmetric:
return symmetric_residue(result, mm), mm
return result, mm
def crt1(m):
"""First part of Chinese Remainder Theorem, for multiple application.
Examples
========
>>> from sympy.ntheory.modular import crt1
>>> crt1([18, 42, 6])
(4536, [252, 108, 756], [0, 2, 0])
"""
return gf_crt1(m, ZZ)
def crt2(m, v, mm, e, s, symmetric=False):
"""Second part of Chinese Remainder Theorem, for multiple application.
Examples
========
>>> from sympy.ntheory.modular import crt1, crt2
>>> mm, e, s = crt1([18, 42, 6])
>>> crt2([18, 42, 6], [0, 0, 0], mm, e, s)
(0, 4536)
"""
result = gf_crt2(v, m, mm, e, s, ZZ)
if symmetric:
return symmetric_residue(result, mm), mm
return result, mm
def solve_congruence(*remainder_modulus_pairs, **hint):
"""Compute the integer ``n`` that has the residual ``ai`` when it is
divided by ``mi`` where the ``ai`` and ``mi`` are given as pairs to
this function: ((a1, m1), (a2, m2), ...). If there is no solution,
return None. Otherwise return ``n`` and its modulus.
The ``mi`` values need not be co-prime. If it is known that the moduli are
not co-prime then the hint ``check`` can be set to False (default=True) and
the check for a quicker solution via crt() (valid when the moduli are
co-prime) will be skipped.
If the hint ``symmetric`` is True (default is False), the value of ``n``
will be within 1/2 of the modulus, possibly negative.
Examples
========
>>> from sympy.ntheory.modular import solve_congruence
What number is 2 mod 3, 3 mod 5 and 2 mod 7?
>>> solve_congruence((2, 3), (3, 5), (2, 7))
(23, 105)
>>> [23 % m for m in [3, 5, 7]]
[2, 3, 2]
If you prefer to work with all remainder in one list and
all moduli in another, send the arguments like this:
>>> solve_congruence(*zip((2, 3, 2), (3, 5, 7)))
(23, 105)
The moduli need not be co-prime; in this case there may or
may not be a solution:
>>> solve_congruence((2, 3), (4, 6)) is None
True
>>> solve_congruence((2, 3), (5, 6))
(5, 6)
The symmetric flag will make the result be within 1/2 of the modulus:
>>> solve_congruence((2, 3), (5, 6), symmetric=True)
(-1, 6)
See Also
========
crt : high level routine implementing the Chinese Remainder Theorem
"""
def combine(c1, c2):
"""Return the tuple (a, m) which satisfies the requirement
that n = a + i*m satisfy n = a1 + j*m1 and n = a2 = k*m2.
References
==========
- http://en.wikipedia.org/wiki/Method_of_successive_substitution
"""
a1, m1 = c1
a2, m2 = c2
a, b, c = m1, a2 - a1, m2
g = reduce(igcd, [a, b, c])
a, b, c = [i//g for i in [a, b, c]]
if a != 1:
inv_a, _, g = igcdex(a, c)
if g != 1:
return None
b *= inv_a
a, m = a1 + m1*b, m1*c
return a, m
rm = remainder_modulus_pairs
symmetric = hint.get('symmetric', False)
if hint.get('check', True):
rm = [(as_int(r), as_int(m)) for r, m in rm]
# ignore redundant pairs but raise an error otherwise; also
# make sure that a unique set of bases is sent to gf_crt if
# they are all prime.
#
# The routine will work out less-trivial violations and
# return None, e.g. for the pairs (1,3) and (14,42) there
# is no answer because 14 mod 42 (having a gcd of 14) implies
# (14/2) mod (42/2), (14/7) mod (42/7) and (14/14) mod (42/14)
# which, being 0 mod 3, is inconsistent with 1 mod 3. But to
# preprocess the input beyond checking of another pair with 42
# or 3 as the modulus (for this example) is not necessary.
uniq = {}
for r, m in rm:
r %= m
if m in uniq:
if r != uniq[m]:
return None
continue
uniq[m] = r
rm = [(r, m) for m, r in uniq.items()]
del uniq
# if the moduli are co-prime, the crt will be significantly faster;
# checking all pairs for being co-prime gets to be slow but a prime
# test is a good trade-off
if all(isprime(m) for r, m in rm):
r, m = list(zip(*rm))
return crt(m, r, symmetric=symmetric, check=False)
rv = (0, 1)
for rmi in rm:
rv = combine(rv, rmi)
if rv is None:
break
n, m = rv
n = n % m
else:
if symmetric:
return symmetric_residue(n, m), m
return n, m
| 7,676 | 29.343874 | 79 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/ntheory/factor_.py
|
"""
Integer factorization
"""
from __future__ import print_function, division
import random
import math
from .primetest import isprime
from .generate import sieve, primerange, nextprime
from sympy.core import sympify
from sympy.core.evalf import bitcount
from sympy.core.logic import fuzzy_and
from sympy.core.numbers import igcd, ilcm, Rational
from sympy.core.power import integer_nthroot, Pow
from sympy.core.mul import Mul
from sympy.core.compatibility import as_int, SYMPY_INTS, range
from sympy.core.singleton import S
from sympy.core.function import Function
small_trailing = [i and max(int(not i % 2**j) and j for j in range(1, 8))
for i in range(256)]
def smoothness(n):
"""
Return the B-smooth and B-power smooth values of n.
The smoothness of n is the largest prime factor of n; the power-
smoothness is the largest divisor raised to its multiplicity.
>>> from sympy.ntheory.factor_ import smoothness
>>> smoothness(2**7*3**2)
(3, 128)
>>> smoothness(2**4*13)
(13, 16)
>>> smoothness(2)
(2, 2)
See Also
========
factorint, smoothness_p
"""
if n == 1:
return (1, 1) # not prime, but otherwise this causes headaches
facs = factorint(n)
return max(facs), max(m**facs[m] for m in facs)
def smoothness_p(n, m=-1, power=0, visual=None):
"""
Return a list of [m, (p, (M, sm(p + m), psm(p + m)))...]
where:
1. p**M is the base-p divisor of n
2. sm(p + m) is the smoothness of p + m (m = -1 by default)
3. psm(p + m) is the power smoothness of p + m
The list is sorted according to smoothness (default) or by power smoothness
if power=1.
The smoothness of the numbers to the left (m = -1) or right (m = 1) of a
factor govern the results that are obtained from the p +/- 1 type factoring
methods.
>>> from sympy.ntheory.factor_ import smoothness_p, factorint
>>> smoothness_p(10431, m=1)
(1, [(3, (2, 2, 4)), (19, (1, 5, 5)), (61, (1, 31, 31))])
>>> smoothness_p(10431)
(-1, [(3, (2, 2, 2)), (19, (1, 3, 9)), (61, (1, 5, 5))])
>>> smoothness_p(10431, power=1)
(-1, [(3, (2, 2, 2)), (61, (1, 5, 5)), (19, (1, 3, 9))])
If visual=True then an annotated string will be returned:
>>> print(smoothness_p(21477639576571, visual=1))
p**i=4410317**1 has p-1 B=1787, B-pow=1787
p**i=4869863**1 has p-1 B=2434931, B-pow=2434931
This string can also be generated directly from a factorization dictionary
and vice versa:
>>> factorint(17*9)
{3: 2, 17: 1}
>>> smoothness_p(_)
'p**i=3**2 has p-1 B=2, B-pow=2\\np**i=17**1 has p-1 B=2, B-pow=16'
>>> smoothness_p(_)
{3: 2, 17: 1}
The table of the output logic is:
====== ====== ======= =======
| Visual
------ ----------------------
Input True False other
====== ====== ======= =======
dict str tuple str
str str tuple dict
tuple str tuple str
n str tuple tuple
mul str tuple tuple
====== ====== ======= =======
See Also
========
factorint, smoothness
"""
from sympy.utilities import flatten
# visual must be True, False or other (stored as None)
if visual in (1, 0):
visual = bool(visual)
elif visual not in (True, False):
visual = None
if type(n) is str:
if visual:
return n
d = {}
for li in n.splitlines():
k, v = [int(i) for i in
li.split('has')[0].split('=')[1].split('**')]
d[k] = v
if visual is not True and visual is not False:
return d
return smoothness_p(d, visual=False)
elif type(n) is not tuple:
facs = factorint(n, visual=False)
if power:
k = -1
else:
k = 1
if type(n) is not tuple:
rv = (m, sorted([(f,
tuple([M] + list(smoothness(f + m))))
for f, M in [i for i in facs.items()]],
key=lambda x: (x[1][k], x[0])))
else:
rv = n
if visual is False or (visual is not True) and (type(n) in [int, Mul]):
return rv
lines = []
for dat in rv[1]:
dat = flatten(dat)
dat.insert(2, m)
lines.append('p**i=%i**%i has p%+i B=%i, B-pow=%i' % tuple(dat))
return '\n'.join(lines)
def trailing(n):
"""Count the number of trailing zero digits in the binary
representation of n, i.e. determine the largest power of 2
that divides n.
Examples
========
>>> from sympy import trailing
>>> trailing(128)
7
>>> trailing(63)
0
"""
n = int(n)
if not n:
return 0
low_byte = n & 0xff
if low_byte:
return small_trailing[low_byte]
# 2**m is quick for z up through 2**30
z = bitcount(n) - 1
if isinstance(z, SYMPY_INTS):
if n == 1 << z:
return z
t = 0
p = 8
while not n & 1:
while not n & ((1 << p) - 1):
n >>= p
t += p
p *= 2
p //= 2
return t
def multiplicity(p, n):
"""
Find the greatest integer m such that p**m divides n.
Examples
========
>>> from sympy.ntheory import multiplicity
>>> from sympy.core.numbers import Rational as R
>>> [multiplicity(5, n) for n in [8, 5, 25, 125, 250]]
[0, 1, 2, 3, 3]
>>> multiplicity(3, R(1, 9))
-2
"""
try:
p, n = as_int(p), as_int(n)
except ValueError:
if all(isinstance(i, (SYMPY_INTS, Rational)) for i in (p, n)):
try:
p = Rational(p)
n = Rational(n)
if p.q == 1:
if n.p == 1:
return -multiplicity(p.p, n.q)
return S.Zero
elif p.p == 1:
return multiplicity(p.q, n.q)
else:
like = min(
multiplicity(p.p, n.p),
multiplicity(p.q, n.q))
cross = min(
multiplicity(p.q, n.p),
multiplicity(p.p, n.q))
return like - cross
except AttributeError:
pass
raise ValueError('expecting ints or fractions, got %s and %s' % (p, n))
if n == 0:
raise ValueError('no such integer exists: multiplicity of %s is not-defined' %(n))
if p == 2:
return trailing(n)
if p < 2:
raise ValueError('p must be an integer, 2 or larger, but got %s' % p)
if p == n:
return 1
m = 0
n, rem = divmod(n, p)
while not rem:
m += 1
if m > 5:
# The multiplicity could be very large. Better
# to increment in powers of two
e = 2
while 1:
ppow = p**e
if ppow < n:
nnew, rem = divmod(n, ppow)
if not rem:
m += e
e *= 2
n = nnew
continue
return m + multiplicity(p, n)
n, rem = divmod(n, p)
return m
def perfect_power(n, candidates=None, big=True, factor=True):
"""
Return ``(b, e)`` such that ``n`` == ``b**e`` if ``n`` is a
perfect power; otherwise return ``False``.
By default, the base is recursively decomposed and the exponents
collected so the largest possible ``e`` is sought. If ``big=False``
then the smallest possible ``e`` (thus prime) will be chosen.
If ``candidates`` for exponents are given, they are assumed to be sorted
and the first one that is larger than the computed maximum will signal
failure for the routine.
If ``factor=True`` then simultaneous factorization of n is attempted
since finding a factor indicates the only possible root for n. This
is True by default since only a few small factors will be tested in
the course of searching for the perfect power.
Examples
========
>>> from sympy import perfect_power
>>> perfect_power(16)
(2, 4)
>>> perfect_power(16, big = False)
(4, 2)
"""
n = int(n)
if n < 3:
return False
logn = math.log(n, 2)
max_possible = int(logn) + 2 # only check values less than this
not_square = n % 10 in [2, 3, 7, 8] # squares cannot end in 2, 3, 7, 8
if not candidates:
candidates = primerange(2 + not_square, max_possible)
afactor = 2 + n % 2
for e in candidates:
if e < 3:
if e == 1 or e == 2 and not_square:
continue
if e > max_possible:
return False
# see if there is a factor present
if factor:
if n % afactor == 0:
# find what the potential power is
if afactor == 2:
e = trailing(n)
else:
e = multiplicity(afactor, n)
# if it's a trivial power we are done
if e == 1:
return False
# maybe the bth root of n is exact
r, exact = integer_nthroot(n, e)
if not exact:
# then remove this factor and check to see if
# any of e's factors are a common exponent; if
# not then it's not a perfect power
n //= afactor**e
m = perfect_power(n, candidates=primefactors(e), big=big)
if m is False:
return False
else:
r, m = m
# adjust the two exponents so the bases can
# be combined
g = igcd(m, e)
if g == 1:
return False
m //= g
e //= g
r, e = r**m*afactor**e, g
if not big:
e0 = primefactors(e)
if len(e0) > 1 or e0[0] != e:
e0 = e0[0]
r, e = r**(e//e0), e0
return r, e
else:
# get the next factor ready for the next pass through the loop
afactor = nextprime(afactor)
# Weed out downright impossible candidates
if logn/e < 40:
b = 2.0**(logn/e)
if abs(int(b + 0.5) - b) > 0.01:
continue
# now see if the plausible e makes a perfect power
r, exact = integer_nthroot(n, e)
if exact:
if big:
m = perfect_power(r, big=big, factor=factor)
if m is not False:
r, e = m[0], e*m[1]
return int(r), e
else:
return False
def pollard_rho(n, s=2, a=1, retries=5, seed=1234, max_steps=None, F=None):
r"""
Use Pollard's rho method to try to extract a nontrivial factor
of ``n``. The returned factor may be a composite number. If no
factor is found, ``None`` is returned.
The algorithm generates pseudo-random values of x with a generator
function, replacing x with F(x). If F is not supplied then the
function x**2 + ``a`` is used. The first value supplied to F(x) is ``s``.
Upon failure (if ``retries`` is > 0) a new ``a`` and ``s`` will be
supplied; the ``a`` will be ignored if F was supplied.
The sequence of numbers generated by such functions generally have a
a lead-up to some number and then loop around back to that number and
begin to repeat the sequence, e.g. 1, 2, 3, 4, 5, 3, 4, 5 -- this leader
and loop look a bit like the Greek letter rho, and thus the name, 'rho'.
For a given function, very different leader-loop values can be obtained
so it is a good idea to allow for retries:
>>> from sympy.ntheory.generate import cycle_length
>>> n = 16843009
>>> F = lambda x:(2048*pow(x, 2, n) + 32767) % n
>>> for s in range(5):
... print('loop length = %4i; leader length = %3i' % next(cycle_length(F, s)))
...
loop length = 2489; leader length = 42
loop length = 78; leader length = 120
loop length = 1482; leader length = 99
loop length = 1482; leader length = 285
loop length = 1482; leader length = 100
Here is an explicit example where there is a two element leadup to
a sequence of 3 numbers (11, 14, 4) that then repeat:
>>> x=2
>>> for i in range(9):
... x=(x**2+12)%17
... print(x)
...
16
13
11
14
4
11
14
4
11
>>> next(cycle_length(lambda x: (x**2+12)%17, 2))
(3, 2)
>>> list(cycle_length(lambda x: (x**2+12)%17, 2, values=True))
[16, 13, 11, 14, 4]
Instead of checking the differences of all generated values for a gcd
with n, only the kth and 2*kth numbers are checked, e.g. 1st and 2nd,
2nd and 4th, 3rd and 6th until it has been detected that the loop has been
traversed. Loops may be many thousands of steps long before rho finds a
factor or reports failure. If ``max_steps`` is specified, the iteration
is cancelled with a failure after the specified number of steps.
Examples
========
>>> from sympy import pollard_rho
>>> n=16843009
>>> F=lambda x:(2048*pow(x,2,n) + 32767) % n
>>> pollard_rho(n, F=F)
257
Use the default setting with a bad value of ``a`` and no retries:
>>> pollard_rho(n, a=n-2, retries=0)
If retries is > 0 then perhaps the problem will correct itself when
new values are generated for a:
>>> pollard_rho(n, a=n-2, retries=1)
257
References
==========
- Richard Crandall & Carl Pomerance (2005), "Prime Numbers:
A Computational Perspective", Springer, 2nd edition, 229-231
"""
n = int(n)
if n < 5:
raise ValueError('pollard_rho should receive n > 4')
prng = random.Random(seed + retries)
V = s
for i in range(retries + 1):
U = V
if not F:
F = lambda x: (pow(x, 2, n) + a) % n
j = 0
while 1:
if max_steps and (j > max_steps):
break
j += 1
U = F(U)
V = F(F(V)) # V is 2x further along than U
g = igcd(U - V, n)
if g == 1:
continue
if g == n:
break
return int(g)
V = prng.randint(0, n - 1)
a = prng.randint(1, n - 3) # for x**2 + a, a%n should not be 0 or -2
F = None
return None
def pollard_pm1(n, B=10, a=2, retries=0, seed=1234):
"""
Use Pollard's p-1 method to try to extract a nontrivial factor
of ``n``. Either a divisor (perhaps composite) or ``None`` is returned.
The value of ``a`` is the base that is used in the test gcd(a**M - 1, n).
The default is 2. If ``retries`` > 0 then if no factor is found after the
first attempt, a new ``a`` will be generated randomly (using the ``seed``)
and the process repeated.
Note: the value of M is lcm(1..B) = reduce(ilcm, range(2, B + 1)).
A search is made for factors next to even numbers having a power smoothness
less than ``B``. Choosing a larger B increases the likelihood of finding a
larger factor but takes longer. Whether a factor of n is found or not
depends on ``a`` and the power smoothness of the even mumber just less than
the factor p (hence the name p - 1).
Although some discussion of what constitutes a good ``a`` some
descriptions are hard to interpret. At the modular.math site referenced
below it is stated that if gcd(a**M - 1, n) = N then a**M % q**r is 1
for every prime power divisor of N. But consider the following:
>>> from sympy.ntheory.factor_ import smoothness_p, pollard_pm1
>>> n=257*1009
>>> smoothness_p(n)
(-1, [(257, (1, 2, 256)), (1009, (1, 7, 16))])
So we should (and can) find a root with B=16:
>>> pollard_pm1(n, B=16, a=3)
1009
If we attempt to increase B to 256 we find that it doesn't work:
>>> pollard_pm1(n, B=256)
>>>
But if the value of ``a`` is changed we find that only multiples of
257 work, e.g.:
>>> pollard_pm1(n, B=256, a=257)
1009
Checking different ``a`` values shows that all the ones that didn't
work had a gcd value not equal to ``n`` but equal to one of the
factors:
>>> from sympy.core.numbers import ilcm, igcd
>>> from sympy import factorint, Pow
>>> M = 1
>>> for i in range(2, 256):
... M = ilcm(M, i)
...
>>> set([igcd(pow(a, M, n) - 1, n) for a in range(2, 256) if
... igcd(pow(a, M, n) - 1, n) != n])
{1009}
But does aM % d for every divisor of n give 1?
>>> aM = pow(255, M, n)
>>> [(d, aM%Pow(*d.args)) for d in factorint(n, visual=True).args]
[(257**1, 1), (1009**1, 1)]
No, only one of them. So perhaps the principle is that a root will
be found for a given value of B provided that:
1) the power smoothness of the p - 1 value next to the root
does not exceed B
2) a**M % p != 1 for any of the divisors of n.
By trying more than one ``a`` it is possible that one of them
will yield a factor.
Examples
========
With the default smoothness bound, this number can't be cracked:
>>> from sympy.ntheory import pollard_pm1, primefactors
>>> pollard_pm1(21477639576571)
Increasing the smoothness bound helps:
>>> pollard_pm1(21477639576571, B=2000)
4410317
Looking at the smoothness of the factors of this number we find:
>>> from sympy.utilities import flatten
>>> from sympy.ntheory.factor_ import smoothness_p, factorint
>>> print(smoothness_p(21477639576571, visual=1))
p**i=4410317**1 has p-1 B=1787, B-pow=1787
p**i=4869863**1 has p-1 B=2434931, B-pow=2434931
The B and B-pow are the same for the p - 1 factorizations of the divisors
because those factorizations had a very large prime factor:
>>> factorint(4410317 - 1)
{2: 2, 617: 1, 1787: 1}
>>> factorint(4869863-1)
{2: 1, 2434931: 1}
Note that until B reaches the B-pow value of 1787, the number is not cracked;
>>> pollard_pm1(21477639576571, B=1786)
>>> pollard_pm1(21477639576571, B=1787)
4410317
The B value has to do with the factors of the number next to the divisor,
not the divisors themselves. A worst case scenario is that the number next
to the factor p has a large prime divisisor or is a perfect power. If these
conditions apply then the power-smoothness will be about p/2 or p. The more
realistic is that there will be a large prime factor next to p requiring
a B value on the order of p/2. Although primes may have been searched for
up to this level, the p/2 is a factor of p - 1, something that we don't
know. The modular.math reference below states that 15% of numbers in the
range of 10**15 to 15**15 + 10**4 are 10**6 power smooth so a B of 10**6
will fail 85% of the time in that range. From 10**8 to 10**8 + 10**3 the
percentages are nearly reversed...but in that range the simple trial
division is quite fast.
References
==========
- Richard Crandall & Carl Pomerance (2005), "Prime Numbers:
A Computational Perspective", Springer, 2nd edition, 236-238
- http://modular.math.washington.edu/edu/2007/spring/ent/ent-html/node81.html
- http://www.cs.toronto.edu/~yuvalf/Factorization.pdf
"""
n = int(n)
if n < 4 or B < 3:
raise ValueError('pollard_pm1 should receive n > 3 and B > 2')
prng = random.Random(seed + B)
# computing a**lcm(1,2,3,..B) % n for B > 2
# it looks weird, but it's right: primes run [2, B]
# and the answer's not right until the loop is done.
for i in range(retries + 1):
aM = a
for p in sieve.primerange(2, B + 1):
e = int(math.log(B, p))
aM = pow(aM, pow(p, e), n)
g = igcd(aM - 1, n)
if 1 < g < n:
return int(g)
# get a new a:
# since the exponent, lcm(1..B), is even, if we allow 'a' to be 'n-1'
# then (n - 1)**even % n will be 1 which will give a g of 0 and 1 will
# give a zero, too, so we set the range as [2, n-2]. Some references
# say 'a' should be coprime to n, but either will detect factors.
a = prng.randint(2, n - 2)
def _trial(factors, n, candidates, verbose=False):
"""
Helper function for integer factorization. Trial factors ``n`
against all integers given in the sequence ``candidates``
and updates the dict ``factors`` in-place. Returns the reduced
value of ``n`` and a flag indicating whether any factors were found.
"""
if verbose:
factors0 = list(factors.keys())
nfactors = len(factors)
for d in candidates:
if n % d == 0:
m = multiplicity(d, n)
n //= d**m
factors[d] = m
if verbose:
for k in sorted(set(factors).difference(set(factors0))):
print(factor_msg % (k, factors[k]))
return int(n), len(factors) != nfactors
def _check_termination(factors, n, limitp1, use_trial, use_rho, use_pm1,
verbose):
"""
Helper function for integer factorization. Checks if ``n``
is a prime or a perfect power, and in those cases updates
the factorization and raises ``StopIteration``.
"""
if verbose:
print('Check for termination')
# since we've already been factoring there is no need to do
# simultaneous factoring with the power check
p = perfect_power(n, factor=False)
if p is not False:
base, exp = p
if limitp1:
limit = limitp1 - 1
else:
limit = limitp1
facs = factorint(base, limit, use_trial, use_rho, use_pm1,
verbose=False)
for b, e in facs.items():
if verbose:
print(factor_msg % (b, e))
factors[b] = exp*e
raise StopIteration
if isprime(n):
factors[int(n)] = 1
raise StopIteration
if n == 1:
raise StopIteration
trial_int_msg = "Trial division with ints [%i ... %i] and fail_max=%i"
trial_msg = "Trial division with primes [%i ... %i]"
rho_msg = "Pollard's rho with retries %i, max_steps %i and seed %i"
pm1_msg = "Pollard's p-1 with smoothness bound %i and seed %i"
factor_msg = '\t%i ** %i'
fermat_msg = 'Close factors satisying Fermat condition found.'
complete_msg = 'Factorization is complete.'
def _factorint_small(factors, n, limit, fail_max):
"""
Return the value of n and either a 0 (indicating that factorization up
to the limit was complete) or else the next near-prime that would have
been tested.
Factoring stops if there are fail_max unsuccessful tests in a row.
If factors of n were found they will be in the factors dictionary as
{factor: multiplicity} and the returned value of n will have had those
factors removed. The factors dictionary is modified in-place.
"""
def done(n, d):
"""return n, d if the sqrt(n) wasn't reached yet, else
n, 0 indicating that factoring is done.
"""
if d*d <= n:
return n, d
return n, 0
d = 2
m = trailing(n)
if m:
factors[d] = m
n >>= m
d = 3
if limit < d:
if n > 1:
factors[n] = 1
return done(n, d)
# reduce
m = 0
while n % d == 0:
n //= d
m += 1
if m == 20:
mm = multiplicity(d, n)
m += mm
n //= d**mm
break
if m:
factors[d] = m
# when d*d exceeds maxx or n we are done; if limit**2 is greater
# than n then maxx is set to zero so the value of n will flag the finish
if limit*limit > n:
maxx = 0
else:
maxx = limit*limit
dd = maxx or n
d = 5
fails = 0
while fails < fail_max:
if d*d > dd:
break
# d = 6*i - 1
# reduce
m = 0
while n % d == 0:
n //= d
m += 1
if m == 20:
mm = multiplicity(d, n)
m += mm
n //= d**mm
break
if m:
factors[d] = m
dd = maxx or n
fails = 0
else:
fails += 1
d += 2
if d*d > dd:
break
# d = 6*i - 1
# reduce
m = 0
while n % d == 0:
n //= d
m += 1
if m == 20:
mm = multiplicity(d, n)
m += mm
n //= d**mm
break
if m:
factors[d] = m
dd = maxx or n
fails = 0
else:
fails += 1
# d = 6*(i+1) - 1
d += 4
return done(n, d)
def factorint(n, limit=None, use_trial=True, use_rho=True, use_pm1=True,
verbose=False, visual=None, multiple=False):
r"""
Given a positive integer ``n``, ``factorint(n)`` returns a dict containing
the prime factors of ``n`` as keys and their respective multiplicities
as values. For example:
>>> from sympy.ntheory import factorint
>>> factorint(2000) # 2000 = (2**4) * (5**3)
{2: 4, 5: 3}
>>> factorint(65537) # This number is prime
{65537: 1}
For input less than 2, factorint behaves as follows:
- ``factorint(1)`` returns the empty factorization, ``{}``
- ``factorint(0)`` returns ``{0:1}``
- ``factorint(-n)`` adds ``-1:1`` to the factors and then factors ``n``
Partial Factorization:
If ``limit`` (> 3) is specified, the search is stopped after performing
trial division up to (and including) the limit (or taking a
corresponding number of rho/p-1 steps). This is useful if one has
a large number and only is interested in finding small factors (if
any). Note that setting a limit does not prevent larger factors
from being found early; it simply means that the largest factor may
be composite. Since checking for perfect power is relatively cheap, it is
done regardless of the limit setting.
This number, for example, has two small factors and a huge
semi-prime factor that cannot be reduced easily:
>>> from sympy.ntheory import isprime
>>> from sympy.core.compatibility import long
>>> a = 1407633717262338957430697921446883
>>> f = factorint(a, limit=10000)
>>> f == {991: 1, long(202916782076162456022877024859): 1, 7: 1}
True
>>> isprime(max(f))
False
This number has a small factor and a residual perfect power whose
base is greater than the limit:
>>> factorint(3*101**7, limit=5)
{3: 1, 101: 7}
List of Factors:
If ``multiple`` is set to ``True`` then a list containing the
prime factors including multiplicities is returned.
>>> factorint(24, multiple=True)
[2, 2, 2, 3]
Visual Factorization:
If ``visual`` is set to ``True``, then it will return a visual
factorization of the integer. For example:
>>> from sympy import pprint
>>> pprint(factorint(4200, visual=True))
3 1 2 1
2 *3 *5 *7
Note that this is achieved by using the evaluate=False flag in Mul
and Pow. If you do other manipulations with an expression where
evaluate=False, it may evaluate. Therefore, you should use the
visual option only for visualization, and use the normal dictionary
returned by visual=False if you want to perform operations on the
factors.
You can easily switch between the two forms by sending them back to
factorint:
>>> from sympy import Mul, Pow
>>> regular = factorint(1764); regular
{2: 2, 3: 2, 7: 2}
>>> pprint(factorint(regular))
2 2 2
2 *3 *7
>>> visual = factorint(1764, visual=True); pprint(visual)
2 2 2
2 *3 *7
>>> print(factorint(visual))
{2: 2, 3: 2, 7: 2}
If you want to send a number to be factored in a partially factored form
you can do so with a dictionary or unevaluated expression:
>>> factorint(factorint({4: 2, 12: 3})) # twice to toggle to dict form
{2: 10, 3: 3}
>>> factorint(Mul(4, 12, evaluate=False))
{2: 4, 3: 1}
The table of the output logic is:
====== ====== ======= =======
Visual
------ ----------------------
Input True False other
====== ====== ======= =======
dict mul dict mul
n mul dict dict
mul mul dict dict
====== ====== ======= =======
Notes
=====
Algorithm:
The function switches between multiple algorithms. Trial division
quickly finds small factors (of the order 1-5 digits), and finds
all large factors if given enough time. The Pollard rho and p-1
algorithms are used to find large factors ahead of time; they
will often find factors of the order of 10 digits within a few
seconds:
>>> factors = factorint(12345678910111213141516)
>>> for base, exp in sorted(factors.items()):
... print('%s %s' % (base, exp))
...
2 2
2507191691 1
1231026625769 1
Any of these methods can optionally be disabled with the following
boolean parameters:
- ``use_trial``: Toggle use of trial division
- ``use_rho``: Toggle use of Pollard's rho method
- ``use_pm1``: Toggle use of Pollard's p-1 method
``factorint`` also periodically checks if the remaining part is
a prime number or a perfect power, and in those cases stops.
If ``verbose`` is set to ``True``, detailed progress is printed.
See Also
========
smoothness, smoothness_p, divisors
"""
if multiple:
fac = factorint(n, limit=limit, use_trial=use_trial,
use_rho=use_rho, use_pm1=use_pm1,
verbose=verbose, visual=False, multiple=False)
factorlist = sum(([p] * fac[p] if fac[p] > 0 else [S(1)/p]*(-1*fac[p])
for p in sorted(fac)), [])
return factorlist
factordict = {}
if visual and not isinstance(n, Mul) and not isinstance(n, dict):
factordict = factorint(n, limit=limit, use_trial=use_trial,
use_rho=use_rho, use_pm1=use_pm1,
verbose=verbose, visual=False)
elif isinstance(n, Mul):
factordict = dict([(int(k), int(v)) for k, v in
list(n.as_powers_dict().items())])
elif isinstance(n, dict):
factordict = n
if factordict and (isinstance(n, Mul) or isinstance(n, dict)):
# check it
for k in list(factordict.keys()):
if isprime(k):
continue
e = factordict.pop(k)
d = factorint(k, limit=limit, use_trial=use_trial, use_rho=use_rho,
use_pm1=use_pm1, verbose=verbose, visual=False)
for k, v in d.items():
if k in factordict:
factordict[k] += v*e
else:
factordict[k] = v*e
if visual or (type(n) is dict and
visual is not True and
visual is not False):
if factordict == {}:
return S.One
if -1 in factordict:
factordict.pop(-1)
args = [S.NegativeOne]
else:
args = []
args.extend([Pow(*i, evaluate=False)
for i in sorted(factordict.items())])
return Mul(*args, evaluate=False)
elif isinstance(n, dict) or isinstance(n, Mul):
return factordict
assert use_trial or use_rho or use_pm1
n = as_int(n)
if limit:
limit = int(limit)
# special cases
if n < 0:
factors = factorint(
-n, limit=limit, use_trial=use_trial, use_rho=use_rho,
use_pm1=use_pm1, verbose=verbose, visual=False)
factors[-1] = 1
return factors
if limit and limit < 2:
if n == 1:
return {}
return {n: 1}
elif n < 10:
# doing this we are assured of getting a limit > 2
# when we have to compute it later
return [{0: 1}, {}, {2: 1}, {3: 1}, {2: 2}, {5: 1},
{2: 1, 3: 1}, {7: 1}, {2: 3}, {3: 2}][n]
factors = {}
# do simplistic factorization
if verbose:
sn = str(n)
if len(sn) > 50:
print('Factoring %s' % sn[:5] + \
'..(%i other digits)..' % (len(sn) - 10) + sn[-5:])
else:
print('Factoring', n)
if use_trial:
# this is the preliminary factorization for small factors
small = 2**15
fail_max = 600
small = min(small, limit or small)
if verbose:
print(trial_int_msg % (2, small, fail_max))
n, next_p = _factorint_small(factors, n, small, fail_max)
else:
next_p = 2
if factors and verbose:
for k in sorted(factors):
print(factor_msg % (k, factors[k]))
if next_p == 0:
if n > 1:
factors[int(n)] = 1
if verbose:
print(complete_msg)
return factors
# continue with more advanced factorization methods
# first check if the simplistic run didn't finish
# because of the limit and check for a perfect
# power before exiting
try:
if limit and next_p > limit:
if verbose:
print('Exceeded limit:', limit)
_check_termination(factors, n, limit, use_trial, use_rho, use_pm1,
verbose)
if n > 1:
factors[int(n)] = 1
return factors
else:
# Before quitting (or continuing on)...
# ...do a Fermat test since it's so easy and we need the
# square root anyway. Finding 2 factors is easy if they are
# "close enough." This is the big root equivalent of dividing by
# 2, 3, 5.
sqrt_n = integer_nthroot(n, 2)[0]
a = sqrt_n + 1
a2 = a**2
b2 = a2 - n
for i in range(3):
b, fermat = integer_nthroot(b2, 2)
if fermat:
break
b2 += 2*a + 1 # equiv to (a+1)**2 - n
a += 1
if fermat:
if verbose:
print(fermat_msg)
if limit:
limit -= 1
for r in [a - b, a + b]:
facs = factorint(r, limit=limit, use_trial=use_trial,
use_rho=use_rho, use_pm1=use_pm1,
verbose=verbose)
factors.update(facs)
raise StopIteration
# ...see if factorization can be terminated
_check_termination(factors, n, limit, use_trial, use_rho, use_pm1,
verbose)
except StopIteration:
if verbose:
print(complete_msg)
return factors
# these are the limits for trial division which will
# be attempted in parallel with pollard methods
low, high = next_p, 2*next_p
limit = limit or sqrt_n
# add 1 to make sure limit is reached in primerange calls
limit += 1
while 1:
try:
high_ = high
if limit < high_:
high_ = limit
# Trial division
if use_trial:
if verbose:
print(trial_msg % (low, high_))
ps = sieve.primerange(low, high_)
n, found_trial = _trial(factors, n, ps, verbose)
if found_trial:
_check_termination(factors, n, limit, use_trial, use_rho,
use_pm1, verbose)
else:
found_trial = False
if high > limit:
if verbose:
print('Exceeded limit:', limit)
if n > 1:
factors[int(n)] = 1
raise StopIteration
# Only used advanced methods when no small factors were found
if not found_trial:
if (use_pm1 or use_rho):
high_root = max(int(math.log(high_**0.7)), low, 3)
# Pollard p-1
if use_pm1:
if verbose:
print(pm1_msg % (high_root, high_))
c = pollard_pm1(n, B=high_root, seed=high_)
if c:
# factor it and let _trial do the update
ps = factorint(c, limit=limit - 1,
use_trial=use_trial,
use_rho=use_rho,
use_pm1=use_pm1,
verbose=verbose)
n, _ = _trial(factors, n, ps, verbose=False)
_check_termination(factors, n, limit, use_trial,
use_rho, use_pm1, verbose)
# Pollard rho
if use_rho:
max_steps = high_root
if verbose:
print(rho_msg % (1, max_steps, high_))
c = pollard_rho(n, retries=1, max_steps=max_steps,
seed=high_)
if c:
# factor it and let _trial do the update
ps = factorint(c, limit=limit - 1,
use_trial=use_trial,
use_rho=use_rho,
use_pm1=use_pm1,
verbose=verbose)
n, _ = _trial(factors, n, ps, verbose=False)
_check_termination(factors, n, limit, use_trial,
use_rho, use_pm1, verbose)
except StopIteration:
if verbose:
print(complete_msg)
return factors
low, high = high, high*2
def factorrat(rat, limit=None, use_trial=True, use_rho=True, use_pm1=True,
verbose=False, visual=None, multiple=False):
r"""
Given a Rational ``r``, ``factorrat(r)`` returns a dict containing
the prime factors of ``r`` as keys and their respective multiplicities
as values. For example:
>>> from sympy.ntheory import factorrat
>>> from sympy.core.symbol import S
>>> factorrat(S(8)/9) # 8/9 = (2**3) * (3**-2)
{2: 3, 3: -2}
>>> factorrat(S(-1)/987) # -1/789 = -1 * (3**-1) * (7**-1) * (47**-1)
{-1: 1, 3: -1, 7: -1, 47: -1}
Please see the docstring for ``factorint`` for detailed explanations
and examples of the following keywords:
- ``limit``: Integer limit up to which trial division is done
- ``use_trial``: Toggle use of trial division
- ``use_rho``: Toggle use of Pollard's rho method
- ``use_pm1``: Toggle use of Pollard's p-1 method
- ``verbose``: Toggle detailed printing of progress
- ``multiple``: Toggle returning a list of factors or dict
- ``visual``: Toggle product form of output
"""
from collections import defaultdict
if multiple:
fac = factorrat(rat, limit=limit, use_trial=use_trial,
use_rho=use_rho, use_pm1=use_pm1,
verbose=verbose, visual=False,multiple=False)
factorlist = sum(([p] * fac[p] if fac[p] > 0 else [S(1)/p]*(-1*fac[p])
for p, _ in sorted(fac.items(),
key=lambda elem: elem[0]
if elem[1] > 0
else 1/elem[0])), [])
return factorlist
f = factorint(rat.p, limit=limit, use_trial=use_trial,
use_rho=use_rho, use_pm1=use_pm1,
verbose=verbose).copy()
f = defaultdict(int, f)
for p, e in factorint(rat.q, limit=limit,
use_trial=use_trial,
use_rho=use_rho,
use_pm1=use_pm1,
verbose=verbose).items():
f[p] += -e
if len(f) > 1 and 1 in f:
del f[1]
if not visual:
return dict(f)
else:
if -1 in f:
f.pop(-1)
args = [S.NegativeOne]
else:
args = []
args.extend([Pow(*i, evaluate=False)
for i in sorted(f.items())])
return Mul(*args, evaluate=False)
def primefactors(n, limit=None, verbose=False):
"""Return a sorted list of n's prime factors, ignoring multiplicity
and any composite factor that remains if the limit was set too low
for complete factorization. Unlike factorint(), primefactors() does
not return -1 or 0.
Examples
========
>>> from sympy.ntheory import primefactors, factorint, isprime
>>> primefactors(6)
[2, 3]
>>> primefactors(-5)
[5]
>>> sorted(factorint(123456).items())
[(2, 6), (3, 1), (643, 1)]
>>> primefactors(123456)
[2, 3, 643]
>>> sorted(factorint(10000000001, limit=200).items())
[(101, 1), (99009901, 1)]
>>> isprime(99009901)
False
>>> primefactors(10000000001, limit=300)
[101]
See Also
========
divisors
"""
n = int(n)
factors = sorted(factorint(n, limit=limit, verbose=verbose).keys())
s = [f for f in factors[:-1:] if f not in [-1, 0, 1]]
if factors and isprime(factors[-1]):
s += [factors[-1]]
return s
def _divisors(n):
"""Helper function for divisors which generates the divisors."""
factordict = factorint(n)
ps = sorted(factordict.keys())
def rec_gen(n=0):
if n == len(ps):
yield 1
else:
pows = [1]
for j in range(factordict[ps[n]]):
pows.append(pows[-1] * ps[n])
for q in rec_gen(n + 1):
for p in pows:
yield p * q
for p in rec_gen():
yield p
def divisors(n, generator=False):
r"""
Return all divisors of n sorted from 1..n by default.
If generator is ``True`` an unordered generator is returned.
The number of divisors of n can be quite large if there are many
prime factors (counting repeated factors). If only the number of
factors is desired use divisor_count(n).
Examples
========
>>> from sympy import divisors, divisor_count
>>> divisors(24)
[1, 2, 3, 4, 6, 8, 12, 24]
>>> divisor_count(24)
8
>>> list(divisors(120, generator=True))
[1, 2, 4, 8, 3, 6, 12, 24, 5, 10, 20, 40, 15, 30, 60, 120]
This is a slightly modified version of Tim Peters referenced at:
http://stackoverflow.com/questions/1010381/python-factorization
See Also
========
primefactors, factorint, divisor_count
"""
n = as_int(abs(n))
if isprime(n):
return [1, n]
if n == 1:
return [1]
if n == 0:
return []
rv = _divisors(n)
if not generator:
return sorted(rv)
return rv
def divisor_count(n, modulus=1):
"""
Return the number of divisors of ``n``. If ``modulus`` is not 1 then only
those that are divisible by ``modulus`` are counted.
References
==========
- http://www.mayer.dial.pipex.com/maths/formulae.htm
>>> from sympy import divisor_count
>>> divisor_count(6)
4
See Also
========
factorint, divisors, totient
"""
if not modulus:
return 0
elif modulus != 1:
n, r = divmod(n, modulus)
if r:
return 0
if n == 0:
return 0
return Mul(*[v + 1 for k, v in factorint(n).items() if k > 1])
def _udivisors(n):
"""Helper function for udivisors which generates the unitary divisors."""
factorpows = [p**e for p, e in factorint(n).items()]
for i in range(2**len(factorpows)):
d, j, k = 1, i, 0
while j:
if (j & 1):
d *= factorpows[k]
j >>= 1
k += 1
yield d
def udivisors(n, generator=False):
r"""
Return all unitary divisors of n sorted from 1..n by default.
If generator is ``True`` an unordered generator is returned.
The number of unitary divisors of n can be quite large if there are many
prime factors. If only the number of unitary divisors is desired use
udivisor_count(n).
References
==========
- http://en.wikipedia.org/wiki/Unitary_divisor
- http://mathworld.wolfram.com/UnitaryDivisor.html
Examples
========
>>> from sympy.ntheory.factor_ import udivisors, udivisor_count
>>> udivisors(15)
[1, 3, 5, 15]
>>> udivisor_count(15)
4
>>> sorted(udivisors(120, generator=True))
[1, 3, 5, 8, 15, 24, 40, 120]
See Also
========
primefactors, factorint, divisors, divisor_count, udivisor_count
"""
n = as_int(abs(n))
if isprime(n):
return [1, n]
if n == 1:
return [1]
if n == 0:
return []
rv = _udivisors(n)
if not generator:
return sorted(rv)
return rv
def udivisor_count(n):
"""
Return the number of unitary divisors of ``n``.
References
==========
- http://mathworld.wolfram.com/UnitaryDivisorFunction.html
>>> from sympy.ntheory.factor_ import udivisor_count
>>> udivisor_count(120)
8
See Also
========
factorint, divisors, udivisors, divisor_count, totient
"""
if n == 0:
return 0
return 2**len([p for p in factorint(n) if p > 1])
def _antidivisors(n):
"""Helper function for antidivisors which generates the antidivisors."""
for d in _divisors(n):
y = 2*d
if n > y and n % y:
yield y
for d in _divisors(2*n-1):
if n > d >= 2 and n % d:
yield d
for d in _divisors(2*n+1):
if n > d >= 2 and n % d:
yield d
def antidivisors(n, generator=False):
r"""
Return all antidivisors of n sorted from 1..n by default.
Antidivisors [1]_ of n are numbers that do not divide n by the largest
possible margin. If generator is True an unordered generator is returned.
References
==========
.. [1] definition is described in http://oeis.org/A066272/a066272a.html
Examples
========
>>> from sympy.ntheory.factor_ import antidivisors
>>> antidivisors(24)
[7, 16]
>>> sorted(antidivisors(128, generator=True))
[3, 5, 15, 17, 51, 85]
See Also
========
primefactors, factorint, divisors, divisor_count, antidivisor_count
"""
n = as_int(abs(n))
if n <= 2:
return []
rv = _antidivisors(n)
if not generator:
return sorted(rv)
return rv
def antidivisor_count(n):
"""
Return the number of antidivisors [1]_ of ``n``.
References
==========
.. [1] formula from https://oeis.org/A066272
Examples
========
>>> from sympy.ntheory.factor_ import antidivisor_count
>>> antidivisor_count(13)
4
>>> antidivisor_count(27)
5
See Also
========
factorint, divisors, antidivisors, divisor_count, totient
"""
n = as_int(abs(n))
if n <= 2:
return 0
return divisor_count(2*n-1) + divisor_count(2*n+1) + \
divisor_count(n) - divisor_count(n, 2) - 5
class totient(Function):
r"""
Calculate the Euler totient function phi(n)
``totient(n)`` or `\phi(n)` is the number of positive integers `\leq` n
that are relatively prime to n.
References
==========
.. [1] https://en.wikipedia.org/wiki/Euler%27s_totient_function
.. [2] http://mathworld.wolfram.com/TotientFunction.html
Examples
========
>>> from sympy.ntheory import totient
>>> totient(1)
1
>>> totient(25)
20
See Also
========
divisor_count
"""
@classmethod
def eval(cls, n):
n = sympify(n)
if n.is_Integer:
if n < 1:
raise ValueError("n must be a positive integer")
factors = factorint(n)
t = 1
for p, k in factors.items():
t *= (p - 1) * p**(k - 1)
return t
def _eval_is_integer(self):
return fuzzy_and([self.args[0].is_integer, self.args[0].is_positive])
class reduced_totient(Function):
r"""
Calculate the Carmichael reduced totient function lambda(n)
``reduced_totient(n)`` or `\lambda(n)` is the smallest m > 0 such that
`k^m \equiv 1 \mod n` for all k relatively prime to n.
References
==========
.. [1] https://en.wikipedia.org/wiki/Carmichael_function
.. [2] http://mathworld.wolfram.com/CarmichaelFunction.html
Examples
========
>>> from sympy.ntheory import reduced_totient
>>> reduced_totient(1)
1
>>> reduced_totient(8)
2
>>> reduced_totient(30)
4
See Also
========
totient
"""
@classmethod
def eval(cls, n):
n = sympify(n)
if n.is_Integer:
if n < 1:
raise ValueError("n must be a positive integer")
factors = factorint(n)
t = 1
for p, k in factors.items():
if p == 2 and k > 2:
t = ilcm(t, 2**(k - 2))
else:
t = ilcm(t, (p - 1) * p**(k - 1))
return t
def _eval_is_integer(self):
return fuzzy_and([self.args[0].is_integer, self.args[0].is_positive])
class divisor_sigma(Function):
r"""
Calculate the divisor function `\sigma_k(n)` for positive integer n
``divisor_sigma(n, k)`` is equal to ``sum([x**k for x in divisors(n)])``
If n's prime factorization is:
.. math ::
n = \prod_{i=1}^\omega p_i^{m_i},
then
.. math ::
\sigma_k(n) = \prod_{i=1}^\omega (1+p_i^k+p_i^{2k}+\cdots
+ p_i^{m_ik}).
Parameters
==========
k : power of divisors in the sum
for k = 0, 1:
``divisor_sigma(n, 0)`` is equal to ``divisor_count(n)``
``divisor_sigma(n, 1)`` is equal to ``sum(divisors(n))``
Default for k is 1.
References
==========
.. [1] http://en.wikipedia.org/wiki/Divisor_function
Examples
========
>>> from sympy.ntheory import divisor_sigma
>>> divisor_sigma(18, 0)
6
>>> divisor_sigma(39, 1)
56
>>> divisor_sigma(12, 2)
210
>>> divisor_sigma(37)
38
See Also
========
divisor_count, totient, divisors, factorint
"""
@classmethod
def eval(cls, n, k=1):
n = sympify(n)
k = sympify(k)
if n.is_prime:
return 1 + n**k
if n.is_Integer:
if n <= 0:
raise ValueError("n must be a positive integer")
else:
return Mul(*[(p**(k*(e + 1)) - 1)/(p**k - 1) if k != 0
else e + 1 for p, e in factorint(n).items()])
def core(n, t=2):
r"""
Calculate core(n,t) = `core_t(n)` of a positive integer n
``core_2(n)`` is equal to the squarefree part of n
If n's prime factorization is:
.. math ::
n = \prod_{i=1}^\omega p_i^{m_i},
then
.. math ::
core_t(n) = \prod_{i=1}^\omega p_i^{m_i \mod t}.
Parameters
==========
t : core(n,t) calculates the t-th power free part of n
``core(n, 2)`` is the squarefree part of ``n``
``core(n, 3)`` is the cubefree part of ``n``
Default for t is 2.
References
==========
.. [1] http://en.wikipedia.org/wiki/Square-free_integer#Squarefree_core
Examples
========
>>> from sympy.ntheory.factor_ import core
>>> core(24, 2)
6
>>> core(9424, 3)
1178
>>> core(379238)
379238
>>> core(15**11, 10)
15
See Also
========
factorint, sympy.solvers.diophantine.square_factor
"""
n = as_int(n)
t = as_int(t)
if n <= 0:
raise ValueError("n must be a positive integer")
elif t <= 1:
raise ValueError("t must be >= 2")
else:
y = 1
for p, e in factorint(n).items():
y *= p**(e % t)
return y
def digits(n, b=10):
"""
Return a list of the digits of n in base b. The first element in the list
is b (or -b if n is negative).
Examples
========
>>> from sympy.ntheory.factor_ import digits
>>> digits(35)
[10, 3, 5]
>>> digits(27, 2)
[2, 1, 1, 0, 1, 1]
>>> digits(65536, 256)
[256, 1, 0, 0]
>>> digits(-3958, 27)
[-27, 5, 11, 16]
"""
b = as_int(b)
n = as_int(n)
if b <= 1:
raise ValueError("b must be >= 2")
else:
x, y = abs(n), []
while x >= b:
x, r = divmod(x, b)
y.append(r)
y.append(x)
y.append(-b if n < 0 else b)
y.reverse()
return y
class udivisor_sigma(Function):
r"""
Calculate the unitary divisor function `\sigma_k^*(n)` for positive integer n
``udivisor_sigma(n, k)`` is equal to ``sum([x**k for x in udivisors(n)])``
If n's prime factorization is:
.. math ::
n = \prod_{i=1}^\omega p_i^{m_i},
then
.. math ::
\sigma_k^*(n) = \prod_{i=1}^\omega (1+ p_i^{m_ik}).
Parameters
==========
k : power of divisors in the sum
for k = 0, 1:
``udivisor_sigma(n, 0)`` is equal to ``udivisor_count(n)``
``udivisor_sigma(n, 1)`` is equal to ``sum(udivisors(n))``
Default for k is 1.
References
==========
.. [1] http://mathworld.wolfram.com/UnitaryDivisorFunction.html
Examples
========
>>> from sympy.ntheory.factor_ import udivisor_sigma
>>> udivisor_sigma(18, 0)
4
>>> udivisor_sigma(74, 1)
114
>>> udivisor_sigma(36, 3)
47450
>>> udivisor_sigma(111)
152
See Also
========
divisor_count, totient, divisors, udivisors, udivisor_count, divisor_sigma,
factorint
"""
@classmethod
def eval(cls, n, k=1):
n = sympify(n)
k = sympify(k)
if n.is_prime:
return 1 + n**k
if n.is_Integer:
if n <= 0:
raise ValueError("n must be a positive integer")
else:
return Mul(*[1+p**(k*e) for p, e in factorint(n).items()])
class primenu(Function):
r"""
Calculate the number of distinct prime factors for a positive integer n.
If n's prime factorization is:
.. math ::
n = \prod_{i=1}^k p_i^{m_i},
then ``primenu(n)`` or `\nu(n)` is:
.. math ::
\nu(n) = k.
References
==========
.. [1] http://mathworld.wolfram.com/PrimeFactor.html
Examples
========
>>> from sympy.ntheory.factor_ import primenu
>>> primenu(1)
0
>>> primenu(30)
3
See Also
========
factorint
"""
@classmethod
def eval(cls, n):
n = sympify(n)
if n.is_Integer:
if n <= 0:
raise ValueError("n must be a positive integer")
else:
return len(factorint(n).keys())
class primeomega(Function):
r"""
Calculate the number of prime factors counting multiplicities for a
positive integer n.
If n's prime factorization is:
.. math ::
n = \prod_{i=1}^k p_i^{m_i},
then ``primeomega(n)`` or `\Omega(n)` is:
.. math ::
\Omega(n) = \sum_{i=1}^k m_i.
References
==========
.. [1] http://mathworld.wolfram.com/PrimeFactor.html
Examples
========
>>> from sympy.ntheory.factor_ import primeomega
>>> primeomega(1)
0
>>> primeomega(20)
3
See Also
========
factorint
"""
@classmethod
def eval(cls, n):
n = sympify(n)
if n.is_Integer:
if n <= 0:
raise ValueError("n must be a positive integer")
else:
return sum(factorint(n).values())
| 56,915 | 28.009174 | 90 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/ntheory/generate.py
|
"""
Generating and counting primes.
"""
from __future__ import print_function, division
import random
from bisect import bisect
# Using arrays for sieving instead of lists greatly reduces
# memory consumption
from array import array as _array
from .primetest import isprime
from sympy.core.compatibility import as_int, range
def _arange(a, b):
ar = _array('l', [0]*(b - a))
for i, e in enumerate(range(a, b)):
ar[i] = e
return ar
class Sieve:
"""An infinite list of prime numbers, implemented as a dynamically
growing sieve of Eratosthenes. When a lookup is requested involving
an odd number that has not been sieved, the sieve is automatically
extended up to that number.
Examples
========
>>> from sympy import sieve
>>> sieve._reset() # this line for doctest only
>>> 25 in sieve
False
>>> sieve._list
array('l', [2, 3, 5, 7, 11, 13, 17, 19, 23])
"""
# data shared (and updated) by all Sieve instances
_list = _array('l', [2, 3, 5, 7, 11, 13])
def __repr__(self):
return "<Sieve with %i primes sieved: 2, 3, 5, ... %i, %i>" % \
(len(self._list), self._list[-2], self._list[-1])
def _reset(self):
"""Return sieve to its initial state for testing purposes.
"""
self._list = self._list[:6]
def extend(self, n):
"""Grow the sieve to cover all primes <= n (a real number).
Examples
========
>>> from sympy import sieve
>>> sieve._reset() # this line for doctest only
>>> sieve.extend(30)
>>> sieve[10] == 29
True
"""
n = int(n)
if n <= self._list[-1]:
return
# We need to sieve against all bases up to sqrt(n).
# This is a recursive call that will do nothing if there are enough
# known bases already.
maxbase = int(n**0.5) + 1
self.extend(maxbase)
# Create a new sieve starting from sqrt(n)
begin = self._list[-1] + 1
newsieve = _arange(begin, n + 1)
# Now eliminate all multiples of primes in [2, sqrt(n)]
for p in self.primerange(2, maxbase):
# Start counting at a multiple of p, offsetting
# the index to account for the new sieve's base index
startindex = (-begin) % p
for i in range(startindex, len(newsieve), p):
newsieve[i] = 0
# Merge the sieves
self._list += _array('l', [x for x in newsieve if x])
def extend_to_no(self, i):
"""Extend to include the ith prime number.
i must be an integer.
The list is extended by 50% if it is too short, so it is
likely that it will be longer than requested.
Examples
========
>>> from sympy import sieve
>>> sieve._reset() # this line for doctest only
>>> sieve.extend_to_no(9)
>>> sieve._list
array('l', [2, 3, 5, 7, 11, 13, 17, 19, 23])
"""
i = as_int(i)
while len(self._list) < i:
self.extend(int(self._list[-1] * 1.5))
def primerange(self, a, b):
"""Generate all prime numbers in the range [a, b).
Examples
========
>>> from sympy import sieve
>>> print([i for i in sieve.primerange(7, 18)])
[7, 11, 13, 17]
"""
from sympy.functions.elementary.integers import ceiling
# wrapping ceiling in int will raise an error if there was a problem
# determining whether the expression was exactly an integer or not
a = max(2, int(ceiling(a)))
b = int(ceiling(b))
if a >= b:
return
self.extend(b)
i = self.search(a)[1]
maxi = len(self._list) + 1
while i < maxi:
p = self._list[i - 1]
if p < b:
yield p
i += 1
else:
return
def search(self, n):
"""Return the indices i, j of the primes that bound n.
If n is prime then i == j.
Although n can be an expression, if ceiling cannot convert
it to an integer then an n error will be raised.
Examples
========
>>> from sympy import sieve
>>> sieve.search(25)
(9, 10)
>>> sieve.search(23)
(9, 9)
"""
from sympy.functions.elementary.integers import ceiling
# wrapping ceiling in int will raise an error if there was a problem
# determining whether the expression was exactly an integer or not
test = int(ceiling(n))
n = int(n)
if n < 2:
raise ValueError("n should be >= 2 but got: %s" % n)
if n > self._list[-1]:
self.extend(n)
b = bisect(self._list, n)
if self._list[b - 1] == test:
return b, b
else:
return b, b + 1
def __contains__(self, n):
try:
n = as_int(n)
assert n >= 2
except (ValueError, AssertionError):
return False
if n % 2 == 0:
return n == 2
a, b = self.search(n)
return a == b
def __getitem__(self, n):
"""Return the nth prime number"""
if isinstance(n, slice):
self.extend_to_no(n.stop)
return self._list[n.start - 1:n.stop - 1:n.step]
else:
n = as_int(n)
self.extend_to_no(n)
return self._list[n - 1]
# Generate a global object for repeated use in trial division etc
sieve = Sieve()
def prime(nth):
""" Return the nth prime, with the primes indexed as prime(1) = 2,
prime(2) = 3, etc.... The nth prime is approximately n*log(n).
Logarithmic integral of x is a pretty nice approximation for number of
primes <= x, i.e.
li(x) ~ pi(x)
In fact, for the numbers we are concerned about( x<1e11 ),
li(x) - pi(x) < 50000
Also,
li(x) > pi(x) can be safely assumed for the numbers which
can be evaluated by this function.
Here, we find the least integer m such that li(m) > n using binary search.
Now pi(m-1) < li(m-1) <= n,
We find pi(m - 1) using primepi function.
Starting from m, we have to find n - pi(m-1) more primes.
For the inputs this implementation can handle, we will have to test
primality for at max about 10**5 numbers, to get our answer.
References
==========
- https://en.wikipedia.org/wiki/Prime_number_theorem#Table_of_.CF.80.28x.29.2C_x_.2F_log_x.2C_and_li.28x.29
- https://en.wikipedia.org/wiki/Prime_number_theorem#Approximations_for_the_nth_prime_number
- https://en.wikipedia.org/wiki/Skewes%27_number
Examples
========
>>> from sympy import prime
>>> prime(10)
29
>>> prime(1)
2
>>> prime(100000)
1299709
See Also
========
sympy.ntheory.primetest.isprime : Test if n is prime
primerange : Generate all primes in a given range
primepi : Return the number of primes less than or equal to n
"""
n = as_int(nth)
if n < 1:
raise ValueError("nth must be a positive integer; prime(1) == 2")
if n <= len(sieve._list):
return sieve[n]
from sympy.functions.special.error_functions import li
from sympy.functions.elementary.exponential import log
a = 2 # Lower bound for binary search
b = int(n*(log(n) + log(log(n)))) # Upper bound for the search.
while a < b:
mid = (a + b) >> 1
if li(mid) > n:
b = mid
else:
a = mid + 1
n_primes = primepi(a - 1)
while n_primes < n:
if isprime(a):
n_primes += 1
a += 1
return a - 1
def primepi(n):
""" Return the value of the prime counting function pi(n) = the number
of prime numbers less than or equal to n.
Algorithm Description:
In sieve method, we remove all multiples of prime p
except p itself.
Let phi(i,j) be the number of integers 2 <= k <= i
which remain after sieving from primes less than
or equal to j.
Clearly, pi(n) = phi(n, sqrt(n))
If j is not a prime,
phi(i,j) = phi(i, j - 1)
if j is a prime,
We remove all numbers(except j) whose
smallest prime factor is j.
Let x= j*a be such a number, where 2 <= a<= i / j
Now, after sieving from primes <= j - 1,
a must remain
(because x, and hence a has no prime factor <= j - 1)
Clearly, there are phi(i / j, j - 1) such a
which remain on sieving from primes <= j - 1
Now, if a is a prime less than equal to j - 1,
x= j*a has smallest prime factor = a, and
has already been removed(by sieving from a).
So, we don't need to remove it again.
(Note: there will be pi(j - 1) such x)
Thus, number of x, that will be removed are:
phi(i / j, j - 1) - phi(j - 1, j - 1)
(Note that pi(j - 1) = phi(j - 1, j - 1))
=> phi(i,j) = phi(i, j - 1) - phi(i / j, j - 1) + phi(j - 1, j - 1)
So,following recursion is used and implemented as dp:
phi(a, b) = phi(a, b - 1), if b is not a prime
phi(a, b) = phi(a, b-1)-phi(a / b, b-1) + phi(b-1, b-1), if b is prime
Clearly a is always of the form floor(n / k),
which can take at most 2*sqrt(n) values.
Two arrays arr1,arr2 are maintained
arr1[i] = phi(i, j),
arr2[i] = phi(n // i, j)
Finally the answer is arr2[1]
Examples
========
>>> from sympy import primepi
>>> primepi(25)
9
See Also
========
sympy.ntheory.primetest.isprime : Test if n is prime
primerange : Generate all primes in a given range
prime : Return the nth prime
"""
n = int(n)
if n < 2:
return 0
if n <= sieve._list[-1]:
return sieve.search(n)[0]
lim = int(n ** 0.5)
lim -= 1
lim = max(lim,0)
while lim * lim <= n:
lim += 1
lim-=1
arr1 = [0] * (lim + 1)
arr2 = [0] * (lim + 1)
for i in range(1, lim + 1):
arr1[i] = i - 1
arr2[i] = n // i - 1
for i in range(2, lim + 1):
# Presently, arr1[k]=phi(k,i - 1),
# arr2[k] = phi(n // k,i - 1)
if arr1[i] == arr1[i - 1]:
continue
p = arr1[i - 1]
for j in range(1,min(n // (i * i), lim) + 1):
st = i * j
if st <= lim:
arr2[j] -= arr2[st] - p
else:
arr2[j] -= arr1[n // st] - p
lim2 = min(lim, i*i - 1)
for j in range(lim, lim2, -1):
arr1[j] -= arr1[j // i] - p
return arr2[1]
def nextprime(n, ith=1):
""" Return the ith prime greater than n.
i must be an integer.
Notes
=====
Potential primes are located at 6*j +/- 1. This
property is used during searching.
>>> from sympy import nextprime
>>> [(i, nextprime(i)) for i in range(10, 15)]
[(10, 11), (11, 13), (12, 13), (13, 17), (14, 17)]
>>> nextprime(2, ith=2) # the 2nd prime after 2
5
See Also
========
prevprime : Return the largest prime smaller than n
primerange : Generate all primes in a given range
"""
n = int(n)
i = as_int(ith)
if i > 1:
pr = n
j = 1
while 1:
pr = nextprime(pr)
j += 1
if j > i:
break
return pr
if n < 2:
return 2
if n < 7:
return {2: 3, 3: 5, 4: 5, 5: 7, 6: 7}[n]
if n <= sieve._list[-2]:
l, u = sieve.search(n)
if l == u:
return sieve[u + 1]
else:
return sieve[u]
nn = 6*(n//6)
if nn == n:
n += 1
if isprime(n):
return n
n += 4
elif n - nn == 5:
n += 2
if isprime(n):
return n
n += 4
else:
n = nn + 5
while 1:
if isprime(n):
return n
n += 2
if isprime(n):
return n
n += 4
def prevprime(n):
""" Return the largest prime smaller than n.
Notes
=====
Potential primes are located at 6*j +/- 1. This
property is used during searching.
>>> from sympy import prevprime
>>> [(i, prevprime(i)) for i in range(10, 15)]
[(10, 7), (11, 7), (12, 11), (13, 11), (14, 13)]
See Also
========
nextprime : Return the ith prime greater than n
primerange : Generates all primes in a given range
"""
from sympy.functions.elementary.integers import ceiling
# wrapping ceiling in int will raise an error if there was a problem
# determining whether the expression was exactly an integer or not
n = int(ceiling(n))
if n < 3:
raise ValueError("no preceding primes")
if n < 8:
return {3: 2, 4: 3, 5: 3, 6: 5, 7: 5}[n]
if n <= sieve._list[-1]:
l, u = sieve.search(n)
if l == u:
return sieve[l-1]
else:
return sieve[l]
nn = 6*(n//6)
if n - nn <= 1:
n = nn - 1
if isprime(n):
return n
n -= 4
else:
n = nn + 1
while 1:
if isprime(n):
return n
n -= 2
if isprime(n):
return n
n -= 4
def primerange(a, b):
""" Generate a list of all prime numbers in the range [a, b).
If the range exists in the default sieve, the values will
be returned from there; otherwise values will be returned
but will not modify the sieve.
Notes
=====
Some famous conjectures about the occurence of primes in a given
range are [1]:
- Twin primes: though often not, the following will give 2 primes
an infinite number of times:
primerange(6*n - 1, 6*n + 2)
- Legendre's: the following always yields at least one prime
primerange(n**2, (n+1)**2+1)
- Bertrand's (proven): there is always a prime in the range
primerange(n, 2*n)
- Brocard's: there are at least four primes in the range
primerange(prime(n)**2, prime(n+1)**2)
The average gap between primes is log(n) [2]; the gap between
primes can be arbitrarily large since sequences of composite
numbers are arbitrarily large, e.g. the numbers in the sequence
n! + 2, n! + 3 ... n! + n are all composite.
References
==========
1. http://en.wikipedia.org/wiki/Prime_number
2. http://primes.utm.edu/notes/gaps.html
Examples
========
>>> from sympy import primerange, sieve
>>> print([i for i in primerange(1, 30)])
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
The Sieve method, primerange, is generally faster but it will
occupy more memory as the sieve stores values. The default
instance of Sieve, named sieve, can be used:
>>> list(sieve.primerange(1, 30))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
See Also
========
nextprime : Return the ith prime greater than n
prevprime : Return the largest prime smaller than n
randprime : Returns a random prime in a given range
primorial : Returns the product of primes based on condition
Sieve.primerange : return range from already computed primes
or extend the sieve to contain the requested
range.
"""
from sympy.functions.elementary.integers import ceiling
if a >= b:
return
# if we already have the range, return it
if b <= sieve._list[-1]:
for i in sieve.primerange(a, b):
yield i
return
# otherwise compute, without storing, the desired range.
# wrapping ceiling in int will raise an error if there was a problem
# determining whether the expression was exactly an integer or not
a = int(ceiling(a)) - 1
b = int(ceiling(b))
while 1:
a = nextprime(a)
if a < b:
yield a
else:
return
def randprime(a, b):
""" Return a random prime number in the range [a, b).
Bertrand's postulate assures that
randprime(a, 2*a) will always succeed for a > 1.
References
==========
- http://en.wikipedia.org/wiki/Bertrand's_postulate
Examples
========
>>> from sympy import randprime, isprime
>>> randprime(1, 30) #doctest: +SKIP
13
>>> isprime(randprime(1, 30))
True
See Also
========
primerange : Generate all primes in a given range
"""
if a >= b:
return
a, b = map(int, (a, b))
n = random.randint(a - 1, b)
p = nextprime(n)
if p >= b:
p = prevprime(b)
if p < a:
raise ValueError("no primes exist in the specified range")
return p
def primorial(n, nth=True):
"""
Returns the product of the first n primes (default) or
the primes less than or equal to n (when ``nth=False``).
>>> from sympy.ntheory.generate import primorial, randprime, primerange
>>> from sympy import factorint, Mul, primefactors, sqrt
>>> primorial(4) # the first 4 primes are 2, 3, 5, 7
210
>>> primorial(4, nth=False) # primes <= 4 are 2 and 3
6
>>> primorial(1)
2
>>> primorial(1, nth=False)
1
>>> primorial(sqrt(101), nth=False)
210
One can argue that the primes are infinite since if you take
a set of primes and multiply them together (e.g. the primorial) and
then add or subtract 1, the result cannot be divided by any of the
original factors, hence either 1 or more new primes must divide this
product of primes.
In this case, the number itself is a new prime:
>>> factorint(primorial(4) + 1)
{211: 1}
In this case two new primes are the factors:
>>> factorint(primorial(4) - 1)
{11: 1, 19: 1}
Here, some primes smaller and larger than the primes multiplied together
are obtained:
>>> p = list(primerange(10, 20))
>>> sorted(set(primefactors(Mul(*p) + 1)).difference(set(p)))
[2, 5, 31, 149]
See Also
========
primerange : Generate all primes in a given range
"""
if nth:
n = as_int(n)
else:
n = int(n)
if n < 1:
raise ValueError("primorial argument must be >= 1")
p = 1
if nth:
for i in range(1, n + 1):
p *= prime(i)
else:
for i in primerange(2, n + 1):
p *= i
return p
def cycle_length(f, x0, nmax=None, values=False):
"""For a given iterated sequence, return a generator that gives
the length of the iterated cycle (lambda) and the length of terms
before the cycle begins (mu); if ``values`` is True then the
terms of the sequence will be returned instead. The sequence is
started with value ``x0``.
Note: more than the first lambda + mu terms may be returned and this
is the cost of cycle detection with Brent's method; there are, however,
generally less terms calculated than would have been calculated if the
proper ending point were determined, e.g. by using Floyd's method.
>>> from sympy.ntheory.generate import cycle_length
This will yield successive values of i <-- func(i):
>>> def iter(func, i):
... while 1:
... ii = func(i)
... yield ii
... i = ii
...
A function is defined:
>>> func = lambda i: (i**2 + 1) % 51
and given a seed of 4 and the mu and lambda terms calculated:
>>> next(cycle_length(func, 4))
(6, 2)
We can see what is meant by looking at the output:
>>> n = cycle_length(func, 4, values=True)
>>> list(ni for ni in n)
[17, 35, 2, 5, 26, 14, 44, 50, 2, 5, 26, 14]
There are 6 repeating values after the first 2.
If a sequence is suspected of being longer than you might wish, ``nmax``
can be used to exit early (and mu will be returned as None):
>>> next(cycle_length(func, 4, nmax = 4))
(4, None)
>>> [ni for ni in cycle_length(func, 4, nmax = 4, values=True)]
[17, 35, 2, 5]
Code modified from:
http://en.wikipedia.org/wiki/Cycle_detection.
"""
nmax = int(nmax or 0)
# main phase: search successive powers of two
power = lam = 1
tortoise, hare = x0, f(x0) # f(x0) is the element/node next to x0.
i = 0
while tortoise != hare and (not nmax or i < nmax):
i += 1
if power == lam: # time to start a new power of two?
tortoise = hare
power *= 2
lam = 0
if values:
yield hare
hare = f(hare)
lam += 1
if nmax and i == nmax:
if values:
return
else:
yield nmax, None
return
if not values:
# Find the position of the first repetition of length lambda
mu = 0
tortoise = hare = x0
for i in range(lam):
hare = f(hare)
while tortoise != hare:
tortoise = f(tortoise)
hare = f(hare)
mu += 1
if mu:
mu -= 1
yield lam, mu
def composite(nth):
""" Return the nth composite number, with the composite numbers indexed as
composite(1) = 4, composite(2) = 6, etc....
Examples
========
>>> from sympy import composite
>>> composite(36)
52
>>> composite(1)
4
>>> composite(17737)
20000
See Also
========
sympy.ntheory.primetest.isprime : Test if n is prime
primerange : Generate all primes in a given range
primepi : Return the number of primes less than or equal to n
prime : Return the nth prime
compositepi : Return the number of positive composite numbers less than or equal to n
"""
n = as_int(nth)
if n < 1:
raise ValueError("nth must be a positive integer; composite(1) == 4")
composite_arr = [4, 6, 8, 9, 10, 12, 14, 15, 16, 18]
if n <= 10:
return composite_arr[n - 1]
a, b = 4, sieve._list[-1]
if n <= b - primepi(b) - 1:
while a < b - 1:
mid = (a + b) >> 1
if mid - primepi(mid) - 1 > n:
b = mid
else:
a = mid
if isprime(a):
a -= 1
return a
from sympy.functions.special.error_functions import li
from sympy.functions.elementary.exponential import log
a = 4 # Lower bound for binary search
b = int(n*(log(n) + log(log(n)))) # Upper bound for the search.
while a < b:
mid = (a + b) >> 1
if mid - li(mid) - 1 > n:
b = mid
else:
a = mid + 1
n_composites = a - primepi(a) - 1
while n_composites > n:
if not isprime(a):
n_composites -= 1
a -= 1
if isprime(a):
a -= 1
return a
def compositepi(n):
""" Return the number of positive composite numbers less than or equal to n.
The first positive composite is 4, i.e. compositepi(4) = 1.
Examples
========
>>> from sympy import compositepi
>>> compositepi(25)
15
>>> compositepi(1000)
831
See Also
========
sympy.ntheory.primetest.isprime : Test if n is prime
primerange : Generate all primes in a given range
prime : Return the nth prime
primepi : Return the number of primes less than or equal to n
composite : Return the nth composite number
"""
n = int(n)
if n < 4:
return 0
return n - primepi(n) - 1
| 24,171 | 27.205368 | 115 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/ntheory/residue_ntheory.py
|
# -*- coding: utf-8 -*-
from __future__ import print_function, division
from sympy.core.singleton import S
from sympy.core.numbers import igcd, igcdex, mod_inverse
from sympy.core.power import isqrt
from sympy.core.compatibility import as_int, range
from sympy.core.function import Function
from .primetest import isprime
from .factor_ import factorint, trailing, totient, multiplicity
from random import randint, Random
def n_order(a, n):
"""Returns the order of ``a`` modulo ``n``.
The order of ``a`` modulo ``n`` is the smallest integer
``k`` such that ``a**k`` leaves a remainder of 1 with ``n``.
Examples
========
>>> from sympy.ntheory import n_order
>>> n_order(3, 7)
6
>>> n_order(4, 7)
3
"""
from collections import defaultdict
a, n = as_int(a), as_int(n)
if igcd(a, n) != 1:
raise ValueError("The two numbers should be relatively prime")
factors = defaultdict(int)
f = factorint(n)
for px, kx in f.items():
if kx > 1:
factors[px] += kx - 1
fpx = factorint(px - 1)
for py, ky in fpx.items():
factors[py] += ky
group_order = 1
for px, kx in factors.items():
group_order *= px**kx
order = 1
if a > n:
a = a % n
for p, e in factors.items():
exponent = group_order
for f in range(e + 1):
if pow(a, exponent, n) != 1:
order *= p ** (e - f + 1)
break
exponent = exponent // p
return order
def _primitive_root_prime_iter(p):
"""
Generates the primitive roots for a prime ``p``
References
==========
.. [1] W. Stein "Elementary Number Theory" (2011), page 44
Examples
========
>>> from sympy.ntheory.residue_ntheory import _primitive_root_prime_iter
>>> list(_primitive_root_prime_iter(19))
[2, 3, 10, 13, 14, 15]
"""
p = as_int(p)
v = [(p - 1) // i for i in factorint(p - 1).keys()]
a = 2
while a < p:
for pw in v:
if pow(a, pw, p) == 1:
break
else:
yield a
a += 1
def primitive_root(p):
"""
Returns the smallest primitive root or None
References
==========
.. [1] W. Stein "Elementary Number Theory" (2011), page 44
.. [2] P. Hackman "Elementary Number Theory" (2009), Chapter C
Parameters
==========
p : positive integer
Examples
========
>>> from sympy.ntheory.residue_ntheory import primitive_root
>>> primitive_root(19)
2
"""
p = as_int(p)
if p < 1:
raise ValueError('p is required to be positive')
if p <= 2:
return 1
f = factorint(p)
if len(f) > 2:
return None
if len(f) == 2:
if 2 not in f or f[2] > 1:
return None
# case p = 2*p1**k, p1 prime
for p1, e1 in f.items():
if p1 != 2:
break
i = 1
while i < p:
i += 2
if i % p1 == 0:
continue
if is_primitive_root(i, p):
return i
else:
if 2 in f:
if p == 4:
return 3
return None
p1, n = list(f.items())[0]
if n > 1:
# see Ref [2], page 81
g = primitive_root(p1)
if is_primitive_root(g, p1**2):
return g
else:
for i in range(2, g + p1 + 1):
if igcd(i, p) == 1 and is_primitive_root(i, p):
return i
return next(_primitive_root_prime_iter(p))
def is_primitive_root(a, p):
"""
Returns True if ``a`` is a primitive root of ``p``
``a`` is said to be the primitive root of ``p`` if gcd(a, p) == 1 and
totient(p) is the smallest positive number s.t.
a**totient(p) cong 1 mod(p)
Examples
========
>>> from sympy.ntheory import is_primitive_root, n_order, totient
>>> is_primitive_root(3, 10)
True
>>> is_primitive_root(9, 10)
False
>>> n_order(3, 10) == totient(10)
True
>>> n_order(9, 10) == totient(10)
False
"""
a, p = as_int(a), as_int(p)
if igcd(a, p) != 1:
raise ValueError("The two numbers should be relatively prime")
if a > p:
a = a % p
return n_order(a, p) == totient(p)
def _sqrt_mod_tonelli_shanks(a, p):
"""
Returns the square root in the case of ``p`` prime with ``p == 1 (mod 8)``
References
==========
.. [1] R. Crandall and C. Pomerance "Prime Numbers", 2nt Ed., page 101
"""
s = trailing(p - 1)
t = p >> s
# find a non-quadratic residue
while 1:
d = randint(2, p - 1)
r = legendre_symbol(d, p)
if r == -1:
break
#assert legendre_symbol(d, p) == -1
A = pow(a, t, p)
D = pow(d, t, p)
m = 0
for i in range(s):
adm = A*pow(D, m, p) % p
adm = pow(adm, 2**(s - 1 - i), p)
if adm % p == p - 1:
m += 2**i
#assert A*pow(D, m, p) % p == 1
x = pow(a, (t + 1)//2, p)*pow(D, m//2, p) % p
return x
def sqrt_mod(a, p, all_roots=False):
"""
Find a root of ``x**2 = a mod p``
Parameters
==========
a : integer
p : positive integer
all_roots : if True the list of roots is returned or None
Notes
=====
If there is no root it is returned None; else the returned root
is less or equal to ``p // 2``; in general is not the smallest one.
It is returned ``p // 2`` only if it is the only root.
Use ``all_roots`` only when it is expected that all the roots fit
in memory; otherwise use ``sqrt_mod_iter``.
Examples
========
>>> from sympy.ntheory import sqrt_mod
>>> sqrt_mod(11, 43)
21
>>> sqrt_mod(17, 32, True)
[7, 9, 23, 25]
"""
if all_roots:
return sorted(list(sqrt_mod_iter(a, p)))
try:
p = abs(as_int(p))
it = sqrt_mod_iter(a, p)
r = next(it)
if r > p // 2:
return p - r
elif r < p // 2:
return r
else:
try:
r = next(it)
if r > p // 2:
return p - r
except StopIteration:
pass
return r
except StopIteration:
return None
def _product(*iters):
"""
Cartesian product generator
Notes
=====
Unlike itertools.product, it works also with iterables which do not fit
in memory. See http://bugs.python.org/issue10109
Author: Fernando Sumudu
with small changes
"""
import itertools
inf_iters = tuple(itertools.cycle(enumerate(it)) for it in iters)
num_iters = len(inf_iters)
cur_val = [None]*num_iters
first_v = True
while True:
i, p = 0, num_iters
while p and not i:
p -= 1
i, cur_val[p] = next(inf_iters[p])
if not p and not i:
if first_v:
first_v = False
else:
break
yield cur_val
def sqrt_mod_iter(a, p, domain=int):
"""
Iterate over solutions to ``x**2 = a mod p``
Parameters
==========
a : integer
p : positive integer
domain : integer domain, ``int``, ``ZZ`` or ``Integer``
Examples
========
>>> from sympy.ntheory.residue_ntheory import sqrt_mod_iter
>>> list(sqrt_mod_iter(11, 43))
[21, 22]
"""
from sympy.polys.galoistools import gf_crt1, gf_crt2
from sympy.polys.domains import ZZ
a, p = as_int(a), abs(as_int(p))
if isprime(p):
a = a % p
if a == 0:
res = _sqrt_mod1(a, p, 1)
else:
res = _sqrt_mod_prime_power(a, p, 1)
if res:
if domain is ZZ:
for x in res:
yield x
else:
for x in res:
yield domain(x)
else:
f = factorint(p)
v = []
pv = []
for px, ex in f.items():
if a % px == 0:
rx = _sqrt_mod1(a, px, ex)
if not rx:
return
else:
rx = _sqrt_mod_prime_power(a, px, ex)
if not rx:
return
v.append(rx)
pv.append(px**ex)
mm, e, s = gf_crt1(pv, ZZ)
if domain is ZZ:
for vx in _product(*v):
r = gf_crt2(vx, pv, mm, e, s, ZZ)
yield r
else:
for vx in _product(*v):
r = gf_crt2(vx, pv, mm, e, s, ZZ)
yield domain(r)
def _sqrt_mod_prime_power(a, p, k):
"""
Find the solutions to ``x**2 = a mod p**k`` when ``a % p != 0``
Parameters
==========
a : integer
p : prime number
k : positive integer
References
==========
.. [1] P. Hackman "Elementary Number Theory" (2009), page 160
.. [2] http://www.numbertheory.org/php/squareroot.html
.. [3] [Gathen99]_
Examples
========
>>> from sympy.ntheory.residue_ntheory import _sqrt_mod_prime_power
>>> _sqrt_mod_prime_power(11, 43, 1)
[21, 22]
"""
from sympy.core.numbers import igcdex
from sympy.polys.domains import ZZ
pk = p**k
a = a % pk
if k == 1:
if p == 2:
return [ZZ(a)]
if not is_quad_residue(a, p):
return None
if p % 4 == 3:
res = pow(a, (p + 1) // 4, p)
elif p % 8 == 5:
sign = pow(a, (p - 1) // 4, p)
if sign == 1:
res = pow(a, (p + 3) // 8, p)
else:
b = pow(4*a, (p - 5) // 8, p)
x = (2*a*b) % p
if pow(x, 2, p) == a:
res = x
else:
res = _sqrt_mod_tonelli_shanks(a, p)
# ``_sqrt_mod_tonelli_shanks(a, p)`` is not deterministic;
# sort to get always the same result
return sorted([ZZ(res), ZZ(p - res)])
if k > 1:
# see Ref.[2]
if p == 2:
if a % 8 != 1:
return None
if k <= 3:
s = set()
for i in range(0, pk, 4):
s.add(1 + i)
s.add(-1 + i)
return list(s)
# according to Ref.[2] for k > 2 there are two solutions
# (mod 2**k-1), that is four solutions (mod 2**k), which can be
# obtained from the roots of x**2 = 0 (mod 8)
rv = [ZZ(1), ZZ(3), ZZ(5), ZZ(7)]
# hensel lift them to solutions of x**2 = 0 (mod 2**k)
# if r**2 - a = 0 mod 2**nx but not mod 2**(nx+1)
# then r + 2**(nx - 1) is a root mod 2**(nx+1)
n = 3
res = []
for r in rv:
nx = n
while nx < k:
r1 = (r**2 - a) >> nx
if r1 % 2:
r = r + (1 << (nx - 1))
#assert (r**2 - a)% (1 << (nx + 1)) == 0
nx += 1
if r not in res:
res.append(r)
x = r + (1 << (k - 1))
#assert (x**2 - a) % pk == 0
if x < (1 << nx) and x not in res:
if (x**2 - a) % pk == 0:
res.append(x)
return res
rv = _sqrt_mod_prime_power(a, p, 1)
if not rv:
return None
r = rv[0]
fr = r**2 - a
# hensel lifting with Newton iteration, see Ref.[3] chapter 9
# with f(x) = x**2 - a; one has f'(a) != 0 (mod p) for p != 2
n = 1
px = p
while 1:
n1 = n
n1 *= 2
if n1 > k:
break
n = n1
px = px**2
frinv = igcdex(2*r, px)[0]
r = (r - fr*frinv) % px
fr = r**2 - a
if n < k:
px = p**k
frinv = igcdex(2*r, px)[0]
r = (r - fr*frinv) % px
return [r, px - r]
def _sqrt_mod1(a, p, n):
"""
Find solution to ``x**2 == a mod p**n`` when ``a % p == 0``
see http://www.numbertheory.org/php/squareroot.html
"""
pn = p**n
a = a % pn
if a == 0:
# case gcd(a, p**k) = p**n
m = n // 2
if n % 2 == 1:
pm1 = p**(m + 1)
def _iter0a():
i = 0
while i < pn:
yield i
i += pm1
return _iter0a()
else:
pm = p**m
def _iter0b():
i = 0
while i < pn:
yield i
i += pm
return _iter0b()
# case gcd(a, p**k) = p**r, r < n
f = factorint(a)
r = f[p]
if r % 2 == 1:
return None
m = r // 2
a1 = a >> r
if p == 2:
if n - r == 1:
pnm1 = 1 << (n - m + 1)
pm1 = 1 << (m + 1)
def _iter1():
k = 1 << (m + 2)
i = 1 << m
while i < pnm1:
j = i
while j < pn:
yield j
j += k
i += pm1
return _iter1()
if n - r == 2:
res = _sqrt_mod_prime_power(a1, p, n - r)
if res is None:
return None
pnm = 1 << (n - m)
def _iter2():
s = set()
for r in res:
i = 0
while i < pn:
x = (r << m) + i
if x not in s:
s.add(x)
yield x
i += pnm
return _iter2()
if n - r > 2:
res = _sqrt_mod_prime_power(a1, p, n - r)
if res is None:
return None
pnm1 = 1 << (n - m - 1)
def _iter3():
s = set()
for r in res:
i = 0
while i < pn:
x = ((r << m) + i) % pn
if x not in s:
s.add(x)
yield x
i += pnm1
return _iter3()
else:
m = r // 2
a1 = a // p**r
res1 = _sqrt_mod_prime_power(a1, p, n - r)
if res1 is None:
return None
pm = p**m
pnr = p**(n-r)
pnm = p**(n-m)
def _iter4():
s = set()
pm = p**m
for rx in res1:
i = 0
while i < pnm:
x = ((rx + i) % pn)
if x not in s:
s.add(x)
yield x*pm
i += pnr
return _iter4()
def is_quad_residue(a, p):
"""
Returns True if ``a`` (mod ``p``) is in the set of squares mod ``p``,
i.e a % p in set([i**2 % p for i in range(p)]). If ``p`` is an odd
prime, an iterative method is used to make the determination:
>>> from sympy.ntheory import is_quad_residue
>>> sorted(set([i**2 % 7 for i in range(7)]))
[0, 1, 2, 4]
>>> [j for j in range(7) if is_quad_residue(j, 7)]
[0, 1, 2, 4]
See Also
========
legendre_symbol, jacobi_symbol
"""
a, p = as_int(a), as_int(p)
if p < 1:
raise ValueError('p must be > 0')
if a >= p or a < 0:
a = a % p
if a < 2 or p < 3:
return True
if not isprime(p):
if p % 2 and jacobi_symbol(a, p) == -1:
return False
r = sqrt_mod(a, p)
if r is None:
return False
else:
return True
return pow(a, (p - 1) // 2, p) == 1
def is_nthpow_residue(a, n, m):
"""
Returns True if ``x**n == a (mod m)`` has solutions.
References
==========
.. [1] P. Hackman "Elementary Number Theory" (2009), page 76
"""
a, n, m = [as_int(i) for i in (a, n, m)]
if m <= 0:
raise ValueError('m must be > 0')
if n < 0:
raise ValueError('n must be >= 0')
if a < 0:
raise ValueError('a must be >= 0')
if n == 0:
if m == 1:
return False
return a == 1
if n == 1:
return True
if n == 2:
return is_quad_residue(a, m)
return _is_nthpow_residue_bign(a, n, m)
def _is_nthpow_residue_bign(a, n, m):
"""Returns True if ``x**n == a (mod m)`` has solutions for n > 2."""
# assert n > 2
# assert a > 0 and m > 0
if primitive_root(m) is None:
# assert m >= 8
for prime, power in factorint(m).items():
if not _is_nthpow_residue_bign_prime_power(a, n, prime, power):
return False
return True
f = totient(m)
k = f // igcd(f, n)
return pow(a, k, m) == 1
def _is_nthpow_residue_bign_prime_power(a, n, p, k):
"""Returns True/False if a solution for ``x**n == a (mod(p**k))``
does/doesn't exist."""
# assert a > 0
# assert n > 2
# assert p is prime
# assert k > 0
if a % p:
if p != 2:
return _is_nthpow_residue_bign(a, n, pow(p, k))
if n & 1:
return True
c = trailing(n)
return a % pow(2, min(c + 2, k)) == 1
else:
a %= pow(p, k)
if not a:
return True
mu = multiplicity(p, a)
if mu % n:
return False
pm = pow(p, mu)
return _is_nthpow_residue_bign_prime_power(a//pm, n, p, k - mu)
def _nthroot_mod2(s, q, p):
f = factorint(q)
v = []
for b, e in f.items():
v.extend([b]*e)
for qx in v:
s = _nthroot_mod1(s, qx, p, False)
return s
def _nthroot_mod1(s, q, p, all_roots):
"""
Root of ``x**q = s mod p``, ``p`` prime and ``q`` divides ``p - 1``
References
==========
.. [1] A. M. Johnston "A Generalized qth Root Algorithm"
"""
g = primitive_root(p)
if not isprime(q):
r = _nthroot_mod2(s, q, p)
else:
f = p - 1
assert (p - 1) % q == 0
# determine k
k = 0
while f % q == 0:
k += 1
f = f // q
# find z, x, r1
f1 = igcdex(-f, q)[0] % q
z = f*f1
x = (1 + z) // q
w = pow(g, z, p)
r1 = pow(s, x, p)
s1 = pow(s, f, p)
y = pow(g, f, p)
h = pow(g, f*q, p)
t = discrete_log(p, s1, h)
g2 = pow(g, z*t, p)
g3 = igcdex(g2, p)[0]
r = r1*g3 % p
#assert pow(r, q, p) == s
res = [r]
h = pow(g, (p - 1) // q, p)
#assert pow(h, q, p) == 1
hx = r
for i in range(q - 1):
hx = (hx*h) % p
res.append(hx)
if all_roots:
res.sort()
return res
return min(res)
def nthroot_mod(a, n, p, all_roots=False):
"""
Find the solutions to ``x**n = a mod p``
Parameters
==========
a : integer
n : positive integer
p : positive integer
all_roots : if False returns the smallest root, else the list of roots
Examples
========
>>> from sympy.ntheory.residue_ntheory import nthroot_mod
>>> nthroot_mod(11, 4, 19)
8
>>> nthroot_mod(11, 4, 19, True)
[8, 11]
>>> nthroot_mod(68, 3, 109)
23
"""
from sympy.core.numbers import igcdex
if n == 2:
return sqrt_mod(a, p , all_roots)
f = totient(p)
# see Hackman "Elementary Number Theory" (2009), page 76
if not is_nthpow_residue(a, n, p):
return None
if primitive_root(p) == None:
raise NotImplementedError("Not Implemented for m without primitive root")
if (p - 1) % n == 0:
return _nthroot_mod1(a, n, p, all_roots)
# The roots of ``x**n - a = 0 (mod p)`` are roots of
# ``gcd(x**n - a, x**(p - 1) - 1) = 0 (mod p)``
pa = n
pb = p - 1
b = 1
if pa < pb:
a, pa, b, pb = b, pb, a, pa
while pb:
# x**pa - a = 0; x**pb - b = 0
# x**pa - a = x**(q*pb + r) - a = (x**pb)**q * x**r - a =
# b**q * x**r - a; x**r - c = 0; c = b**-q * a mod p
q, r = divmod(pa, pb)
c = pow(b, q, p)
c = igcdex(c, p)[0]
c = (c * a) % p
pa, pb = pb, r
a, b = b, c
if pa == 1:
if all_roots:
res = [a]
else:
res = a
elif pa == 2:
return sqrt_mod(a, p , all_roots)
else:
res = _nthroot_mod1(a, pa, p, all_roots)
return res
def quadratic_residues(p):
"""
Returns the list of quadratic residues.
Examples
========
>>> from sympy.ntheory.residue_ntheory import quadratic_residues
>>> quadratic_residues(7)
[0, 1, 2, 4]
"""
r = set()
for i in range(p // 2 + 1):
r.add(pow(i, 2, p))
return sorted(list(r))
def legendre_symbol(a, p):
r"""
Returns the Legendre symbol `(a / p)`.
For an integer ``a`` and an odd prime ``p``, the Legendre symbol is
defined as
.. math ::
\genfrac(){}{}{a}{p} = \begin{cases}
0 & \text{if } p \text{ divides } a\\
1 & \text{if } a \text{ is a quadratic residue modulo } p\\
-1 & \text{if } a \text{ is a quadratic nonresidue modulo } p
\end{cases}
Parameters
==========
a : integer
p : odd prime
Examples
========
>>> from sympy.ntheory import legendre_symbol
>>> [legendre_symbol(i, 7) for i in range(7)]
[0, 1, 1, -1, 1, -1, -1]
>>> sorted(set([i**2 % 7 for i in range(7)]))
[0, 1, 2, 4]
See Also
========
is_quad_residue, jacobi_symbol
"""
a, p = as_int(a), as_int(p)
if not isprime(p) or p == 2:
raise ValueError("p should be an odd prime")
a = a % p
if not a:
return 0
if is_quad_residue(a, p):
return 1
return -1
def jacobi_symbol(m, n):
r"""
Returns the Jacobi symbol `(m / n)`.
For any integer ``m`` and any positive odd integer ``n`` the Jacobi symbol
is defined as the product of the Legendre symbols corresponding to the
prime factors of ``n``:
.. math ::
\genfrac(){}{}{m}{n} =
\genfrac(){}{}{m}{p^{1}}^{\alpha_1}
\genfrac(){}{}{m}{p^{2}}^{\alpha_2}
...
\genfrac(){}{}{m}{p^{k}}^{\alpha_k}
\text{ where } n =
p_1^{\alpha_1}
p_2^{\alpha_2}
...
p_k^{\alpha_k}
Like the Legendre symbol, if the Jacobi symbol `\genfrac(){}{}{m}{n} = -1`
then ``m`` is a quadratic nonresidue modulo ``n``.
But, unlike the Legendre symbol, if the Jacobi symbol
`\genfrac(){}{}{m}{n} = 1` then ``m`` may or may not be a quadratic residue
modulo ``n``.
Parameters
==========
m : integer
n : odd positive integer
Examples
========
>>> from sympy.ntheory import jacobi_symbol, legendre_symbol
>>> from sympy import Mul, S
>>> jacobi_symbol(45, 77)
-1
>>> jacobi_symbol(60, 121)
1
The relationship between the ``jacobi_symbol`` and ``legendre_symbol`` can
be demonstrated as follows:
>>> L = legendre_symbol
>>> S(45).factors()
{3: 2, 5: 1}
>>> jacobi_symbol(7, 45) == L(7, 3)**2 * L(7, 5)**1
True
See Also
========
is_quad_residue, legendre_symbol
"""
m, n = as_int(m), as_int(n)
if n < 0 or not n % 2:
raise ValueError("n should be an odd positive integer")
if m < 0 or m > n:
m = m % n
if not m:
return int(n == 1)
if n == 1 or m == 1:
return 1
if igcd(m, n) != 1:
return 0
j = 1
if m < 0:
m = -m
if n % 4 == 3:
j = -j
while m != 0:
while m % 2 == 0 and m > 0:
m >>= 1
if n % 8 in [3, 5]:
j = -j
m, n = n, m
if m % 4 == 3 and n % 4 == 3:
j = -j
m %= n
if n != 1:
j = 0
return j
class mobius(Function):
"""
Möbius function maps natural number to {-1, 0, 1}
It is defined as follows:
1) `1` if `n = 1`.
2) `0` if `n` has a squared prime factor.
3) `(-1)^k` if `n` is a square-free positive integer with `k`
number of prime factors.
It is an important multiplicative function in number theory
and combinatorics. It has applications in mathematical series,
algebraic number theory and also physics (Fermion operator has very
concrete realization with Möbius Function model).
Parameters
==========
n : positive integer
Examples
========
>>> from sympy.ntheory import mobius
>>> mobius(13*7)
1
>>> mobius(1)
1
>>> mobius(13*7*5)
-1
>>> mobius(13**2)
0
References
==========
.. [1] http://en.wikipedia.org/wiki/M%C3%B6bius_function
.. [2] Thomas Koshy "Elementary Number Theory with Applications"
"""
@classmethod
def eval(cls, n):
if n.is_integer:
if n.is_positive is not True:
raise ValueError("n should be a positive integer")
else:
raise TypeError("n should be an integer")
if n.is_prime:
return S.NegativeOne
elif n is S.One:
return S.One
elif n.is_Integer:
a = factorint(n)
if any(i > 1 for i in a.values()):
return S.Zero
return S.NegativeOne**len(a)
def _discrete_log_trial_mul(n, a, b, order=None):
"""
Trial multiplication algorithm for computing the discrete logarithm of
``a`` to the base ``b`` modulo ``n``.
The algorithm finds the discrete logarithm using exhaustive search. This
naive method is used as fallback algorithm of ``discrete_log`` when the
group order is very small.
References
==========
.. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., &
Vanstone, S. A. (1997).
Examples
========
>>> from sympy.ntheory.residue_ntheory import _discrete_log_trial_mul
>>> _discrete_log_trial_mul(41, 15, 7)
3
See also
========
discrete_log
"""
a %= n
b %= n
if order is None:
order = n
x = 1
k = 1
for i in range(order):
if x == a:
return i
x = x * b % n
raise ValueError("Log does not exist")
def _discrete_log_shanks_steps(n, a, b, order=None):
"""
Baby-step giant-step algorithm for computing the discrete logarithm of
``a`` to the base ``b`` modulo ``n``.
The algorithm is a time-memory trade-off of the method of exhaustive
search. It uses `O(sqrt(m))` memory, where `m` is the group order.
References
==========
.. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., &
Vanstone, S. A. (1997).
Examples
========
>>> from sympy.ntheory.residue_ntheory import _discrete_log_shanks_steps
>>> _discrete_log_shanks_steps(41, 15, 7)
3
See also
========
discrete_log
"""
a %= n
b %= n
if order is None:
order = n_order(b, n)
m = isqrt(order) + 1
T = dict()
x = 1
for i in range(m):
T[x] = i
x = x * b % n
z = mod_inverse(b, n)
z = pow(z, m, n)
x = a
for i in range(m):
if x in T:
return i * m + T[x]
x = x * z % n
raise ValueError("Log does not exist")
def _discrete_log_pollard_rho(n, a, b, order=None, retries=10, rseed=None):
"""
Pollard's Rho algorithm for computing the discrete logarithm of ``a`` to
the base ``b`` modulo ``n``.
It is a randomized algorithm with the same expected running time as
``_discrete_log_shanks_steps``, but requires a negligible amount of memory.
References
==========
.. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., &
Vanstone, S. A. (1997).
Examples
========
>>> from sympy.ntheory.residue_ntheory import _discrete_log_pollard_rho
>>> _discrete_log_pollard_rho(227, 3**7, 3)
7
See also
========
discrete_log
"""
a %= n
b %= n
if order is None:
order = n_order(b, n)
prng = Random()
if rseed is not None:
prng.seed(rseed)
for i in range(retries):
aa = prng.randint(1, order - 1)
ba = prng.randint(1, order - 1)
xa = pow(b, aa, n) * pow(a, ba, n) % n
c = xa % 3
if c == 0:
xb = a * xa % n
ab = aa
bb = (ba + 1) % order
elif c == 1:
xb = xa * xa % n
ab = (aa + aa) % order
bb = (ba + ba) % order
else:
xb = b * xa % n
ab = (aa + 1) % order
bb = ba
for j in range(order):
c = xa % 3
if c == 0:
xa = a * xa % n
ba = (ba + 1) % order
elif c == 1:
xa = xa * xa % n
aa = (aa + aa) % order
ba = (ba + ba) % order
else:
xa = b * xa % n
aa = (aa + 1) % order
c = xb % 3
if c == 0:
xb = a * xb % n
bb = (bb + 1) % order
elif c == 1:
xb = xb * xb % n
ab = (ab + ab) % order
bb = (bb + bb) % order
else:
xb = b * xb % n
ab = (ab + 1) % order
c = xb % 3
if c == 0:
xb = a * xb % n
bb = (bb + 1) % order
elif c == 1:
xb = xb * xb % n
ab = (ab + ab) % order
bb = (bb + bb) % order
else:
xb = b * xb % n
ab = (ab + 1) % order
if xa == xb:
r = (ba - bb) % order
if r != 0:
return mod_inverse(r, order) * (ab - aa) % order
break
raise ValueError("Pollard's Rho failed to find logarithm")
def _discrete_log_pohlig_hellman(n, a, b, order=None):
"""
Pohlig-Hellman algorithm for computing the discrete logarithm of ``a`` to
the base ``b`` modulo ``n``.
In order to compute the discrete logarithm, the algorithm takes advantage
of the factorization of the group order. It is more efficient when the
group order factors into many small primes.
References
==========
.. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., &
Vanstone, S. A. (1997).
Examples
========
>>> from sympy.ntheory.residue_ntheory import _discrete_log_pohlig_hellman
>>> _discrete_log_pohlig_hellman(251, 210, 71)
197
See also
========
discrete_log
"""
from .modular import crt
a %= n
b %= n
if order is None:
order = n_order(b, n)
f = factorint(order)
l = [0] * len(f)
for i, (pi, ri) in enumerate(f.items()):
for j in range(ri):
gj = pow(b, l[i], n)
aj = pow(a * mod_inverse(gj, n), order // pi**(j + 1), n)
bj = pow(b, order // pi, n)
cj = discrete_log(n, aj, bj, pi, True)
l[i] += cj * pi**j
d, _ = crt([pi**ri for pi, ri in f.items()], l)
return d
def discrete_log(n, a, b, order=None, prime_order=None):
"""
Compute the discrete logarithm of ``a`` to the base ``b`` modulo ``n``.
This is a recursive function to reduce the discrete logarithm problem in
cyclic groups of composite order to the problem in cyclic groups of prime
order.
It employs different algorithms depending on the problem (subgroup order
size, prime order or not):
* Trial multiplication
* Baby-step giant-step
* Pollard's Rho
* Pohlig-Hellman
References
==========
.. [1] http://mathworld.wolfram.com/DiscreteLogarithm.html
.. [2] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., &
Vanstone, S. A. (1997).
Examples
========
>>> from sympy.ntheory import discrete_log
>>> discrete_log(41, 15, 7)
3
"""
if order is None:
order = n_order(b, n)
if prime_order is None:
prime_order = isprime(order)
if order < 1000:
return _discrete_log_trial_mul(n, a, b, order)
elif prime_order:
if order < 1000000000000:
return _discrete_log_shanks_steps(n, a, b, order)
return _discrete_log_pollard_rho(n, a, b, order)
return _discrete_log_pohlig_hellman(n, a, b, order)
| 32,762 | 24.221709 | 81 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/ntheory/primetest.py
|
"""
Primality testing
"""
from __future__ import print_function, division
from sympy.core.compatibility import range, as_int
from sympy.core.numbers import Float
from mpmath.libmp import bitcount as _bitlength
def _int_tuple(*i):
return tuple(int(_) for _ in i)
def is_square(n, prep=True):
"""Return True if n == a * a for some integer a, else False.
If n is suspected of *not* being a square then this is a
quick method of confirming that it is not.
References
==========
[1] http://mersenneforum.org/showpost.php?p=110896
See Also
========
sympy.core.power.integer_nthroot
"""
if prep:
n = as_int(n)
if n < 0:
return False
if n in [0, 1]:
return True
m = n & 127
if not ((m*0x8bc40d7d) & (m*0xa1e2f5d1) & 0x14020a):
m = n % 63
if not ((m*0x3d491df7) & (m*0xc824a9f9) & 0x10f14008):
from sympy.ntheory import perfect_power
if perfect_power(n, [2]):
return True
return False
def _test(n, base, s, t):
"""Miller-Rabin strong pseudoprime test for one base.
Return False if n is definitely composite, True if n is
probably prime, with a probability greater than 3/4.
"""
# do the Fermat test
b = pow(base, t, n)
if b == 1 or b == n - 1:
return True
else:
for j in range(1, s):
b = pow(b, 2, n)
if b == n - 1:
return True
# see I. Niven et al. "An Introduction to Theory of Numbers", page 78
if b == 1:
return False
return False
def mr(n, bases):
"""Perform a Miller-Rabin strong pseudoprime test on n using a
given list of bases/witnesses.
References
==========
- Richard Crandall & Carl Pomerance (2005), "Prime Numbers:
A Computational Perspective", Springer, 2nd edition, 135-138
A list of thresholds and the bases they require are here:
http://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test#Deterministic_variants_of_the_test
Examples
========
>>> from sympy.ntheory.primetest import mr
>>> mr(1373651, [2, 3])
False
>>> mr(479001599, [31, 73])
True
"""
from sympy.ntheory.factor_ import trailing
from sympy.polys.domains import ZZ
n = as_int(n)
if n < 2:
return False
# remove powers of 2 from n-1 (= t * 2**s)
s = trailing(n - 1)
t = n >> s
for base in bases:
# Bases >= n are wrapped, bases < 2 are invalid
if base >= n:
base %= n
if base >= 2:
base = ZZ(base)
if not _test(n, base, s, t):
return False
return True
def _lucas_sequence(n, P, Q, k):
"""Return the modular Lucas sequence (U_k, V_k, Q_k).
Given a Lucas sequence defined by P, Q, returns the kth values for
U and V, along with Q^k, all modulo n. This is intended for use with
possibly very large values of n and k, where the combinatorial functions
would be completely unusable.
The modular Lucas sequences are used in numerous places in number theory,
especially in the Lucas compositeness tests and the various n + 1 proofs.
Examples
========
>>> from sympy.ntheory.primetest import _lucas_sequence
>>> N = 10**2000 + 4561
>>> sol = U, V, Qk = _lucas_sequence(N, 3, 1, N//2); sol
(0, 2, 1)
"""
D = P*P - 4*Q
if n < 2:
raise ValueError("n must be >= 2")
if k < 0:
raise ValueError("k must be >= 0")
if D == 0:
raise ValueError("D must not be zero")
if k == 0:
return _int_tuple(0, 2, Q)
U = 1
V = P
Qk = Q
b = _bitlength(k)
if Q == 1:
# Optimization for extra strong tests.
while b > 1:
U = (U*V) % n
V = (V*V - 2) % n
b -= 1
if (k >> (b - 1)) & 1:
U, V = U*P + V, V*P + U*D
if U & 1:
U += n
if V & 1:
V += n
U, V = U >> 1, V >> 1
elif P == 1 and Q == -1:
# Small optimization for 50% of Selfridge parameters.
while b > 1:
U = (U*V) % n
if Qk == 1:
V = (V*V - 2) % n
else:
V = (V*V + 2) % n
Qk = 1
b -= 1
if (k >> (b-1)) & 1:
U, V = U + V, V + U*D
if U & 1:
U += n
if V & 1:
V += n
U, V = U >> 1, V >> 1
Qk = -1
else:
# The general case with any P and Q.
while b > 1:
U = (U*V) % n
V = (V*V - 2*Qk) % n
Qk *= Qk
b -= 1
if (k >> (b - 1)) & 1:
U, V = U*P + V, V*P + U*D
if U & 1:
U += n
if V & 1:
V += n
U, V = U >> 1, V >> 1
Qk *= Q
Qk %= n
return _int_tuple(U % n, V % n, Qk)
def _lucas_selfridge_params(n):
"""Calculates the Selfridge parameters (D, P, Q) for n. This is
method A from page 1401 of Baillie and Wagstaff.
References
==========
- "Lucas Pseudoprimes", Baillie and Wagstaff, 1980.
http://mpqs.free.fr/LucasPseudoprimes.pdf
"""
from sympy.core import igcd
from sympy.ntheory.residue_ntheory import jacobi_symbol
D = 5
while True:
g = igcd(abs(D), n)
if g > 1 and g != n:
return (0, 0, 0)
if jacobi_symbol(D, n) == -1:
break
if D > 0:
D = -D - 2
else:
D = -D + 2
return _int_tuple(D, 1, (1 - D)/4)
def _lucas_extrastrong_params(n):
"""Calculates the "extra strong" parameters (D, P, Q) for n.
References
==========
- OEIS A217719: Extra Strong Lucas Pseudoprimes
https://oeis.org/A217719
- https://en.wikipedia.org/wiki/Lucas_pseudoprime
"""
from sympy.core import igcd
from sympy.ntheory.residue_ntheory import jacobi_symbol
P, Q, D = 3, 1, 5
while True:
g = igcd(D, n)
if g > 1 and g != n:
return (0, 0, 0)
if jacobi_symbol(D, n) == -1:
break
P += 1
D = P*P - 4
return _int_tuple(D, P, Q)
def is_lucas_prp(n):
"""Standard Lucas compositeness test with Selfridge parameters. Returns
False if n is definitely composite, and True if n is a Lucas probable
prime.
This is typically used in combination with the Miller-Rabin test.
References
==========
- "Lucas Pseudoprimes", Baillie and Wagstaff, 1980.
http://mpqs.free.fr/LucasPseudoprimes.pdf
- OEIS A217120: Lucas Pseudoprimes
https://oeis.org/A217120
- https://en.wikipedia.org/wiki/Lucas_pseudoprime
Examples
========
>>> from sympy.ntheory.primetest import isprime, is_lucas_prp
>>> for i in range(10000):
... if is_lucas_prp(i) and not isprime(i):
... print(i)
323
377
1159
1829
3827
5459
5777
9071
9179
"""
n = as_int(n)
if n == 2:
return True
if n < 2 or (n % 2) == 0:
return False
if is_square(n, False):
return False
D, P, Q = _lucas_selfridge_params(n)
if D == 0:
return False
U, V, Qk = _lucas_sequence(n, P, Q, n+1)
return U == 0
def is_strong_lucas_prp(n):
"""Strong Lucas compositeness test with Selfridge parameters. Returns
False if n is definitely composite, and True if n is a strong Lucas
probable prime.
This is often used in combination with the Miller-Rabin test, and
in particular, when combined with M-R base 2 creates the strong BPSW test.
References
==========
- "Lucas Pseudoprimes", Baillie and Wagstaff, 1980.
http://mpqs.free.fr/LucasPseudoprimes.pdf
- OEIS A217255: Strong Lucas Pseudoprimes
https://oeis.org/A217255
- https://en.wikipedia.org/wiki/Lucas_pseudoprime
- https://en.wikipedia.org/wiki/Baillie-PSW_primality_test
Examples
========
>>> from sympy.ntheory.primetest import isprime, is_strong_lucas_prp
>>> for i in range(20000):
... if is_strong_lucas_prp(i) and not isprime(i):
... print(i)
5459
5777
10877
16109
18971
"""
from sympy.ntheory.factor_ import trailing
n = as_int(n)
if n == 2:
return True
if n < 2 or (n % 2) == 0:
return False
if is_square(n, False):
return False
D, P, Q = _lucas_selfridge_params(n)
if D == 0:
return False
# remove powers of 2 from n+1 (= k * 2**s)
s = trailing(n + 1)
k = (n+1) >> s
U, V, Qk = _lucas_sequence(n, P, Q, k)
if U == 0 or V == 0:
return True
for r in range(1, s):
V = (V*V - 2*Qk) % n
if V == 0:
return True
Qk = pow(Qk, 2, n)
return False
def is_extra_strong_lucas_prp(n):
"""Extra Strong Lucas compositeness test. Returns False if n is
definitely composite, and True if n is a "extra strong" Lucas probable
prime.
The parameters are selected using P = 3, Q = 1, then incrementing P until
(D|n) == -1. The test itself is as defined in Grantham 2000, from the
Mo and Jones preprint. The parameter selection and test are the same as
used in OEIS A217719, Perl's Math::Prime::Util, and the Lucas pseudoprime
page on Wikipedia.
With these parameters, there are no counterexamples below 2^64 nor any
known above that range. It is 20-50% faster than the strong test.
Because of the different parameters selected, there is no relationship
between the strong Lucas pseudoprimes and extra strong Lucas pseudoprimes.
In particular, one is not a subset of the other.
References
==========
- "Frobenius Pseudoprimes", Jon Grantham, 2000.
http://www.ams.org/journals/mcom/2001-70-234/S0025-5718-00-01197-2/
- OEIS A217719: Extra Strong Lucas Pseudoprimes
https://oeis.org/A217719
- https://en.wikipedia.org/wiki/Lucas_pseudoprime
Examples
========
>>> from sympy.ntheory.primetest import isprime, is_extra_strong_lucas_prp
>>> for i in range(20000):
... if is_extra_strong_lucas_prp(i) and not isprime(i):
... print(i)
989
3239
5777
10877
"""
# Implementation notes:
# 1) the parameters differ from Thomas R. Nicely's. His parameter
# selection leads to pseudoprimes that overlap M-R tests, and
# contradict Baillie and Wagstaff's suggestion of (D|n) = -1.
# 2) The MathWorld page as of June 2013 specifies Q=-1. The Lucas
# sequence must have Q=1. See Grantham theorem 2.3, any of the
# references on the MathWorld page, or run it and see Q=-1 is wrong.
from sympy.ntheory.factor_ import trailing
n = as_int(n)
if n == 2:
return True
if n < 2 or (n % 2) == 0:
return False
if is_square(n, False):
return False
D, P, Q = _lucas_extrastrong_params(n)
if D == 0:
return False
# remove powers of 2 from n+1 (= k * 2**s)
s = trailing(n + 1)
k = (n+1) >> s
U, V, Qk = _lucas_sequence(n, P, Q, k)
if U == 0 and (V == 2 or V == n - 2):
return True
if V == 0:
return True
for r in range(1, s):
V = (V*V - 2) % n
if V == 0:
return True
return False
def isprime(n):
"""
Test if n is a prime number (True) or not (False). For n < 2^64 the
answer is definitive; larger n values have a small probability of actually
being pseudoprimes.
Negative numbers (e.g. -2) are not considered prime.
The first step is looking for trivial factors, which if found enables
a quick return. Next, if the sieve is large enough, use bisection search
on the sieve. For small numbers, a set of deterministic Miller-Rabin
tests are performed with bases that are known to have no counterexamples
in their range. Finally if the number is larger than 2^64, a strong
BPSW test is performed. While this is a probable prime test and we
believe counterexamples exist, there are no known counterexamples.
Examples
========
>>> from sympy.ntheory import isprime
>>> isprime(13)
True
>>> isprime(15)
False
See Also
========
sympy.ntheory.generate.primerange : Generates all primes in a given range
sympy.ntheory.generate.primepi : Return the number of primes less than or equal to n
sympy.ntheory.generate.prime : Return the nth prime
References
==========
- http://en.wikipedia.org/wiki/Strong_pseudoprime
- "Lucas Pseudoprimes", Baillie and Wagstaff, 1980.
http://mpqs.free.fr/LucasPseudoprimes.pdf
- https://en.wikipedia.org/wiki/Baillie-PSW_primality_test
"""
if isinstance(n, (Float, float)):
return False
n = int(n)
# Step 1, do quick composite testing via trial division. The individual
# modulo tests benchmark faster than one or two primorial igcds for me.
# The point here is just to speedily handle small numbers and many
# composites. Step 2 only requires that n <= 2 get handled here.
if n in [2, 3, 5]:
return True
if n < 2 or (n % 2) == 0 or (n % 3) == 0 or (n % 5) == 0:
return False
if n < 49:
return True
if (n % 7) == 0 or (n % 11) == 0 or (n % 13) == 0 or (n % 17) == 0 or \
(n % 19) == 0 or (n % 23) == 0 or (n % 29) == 0 or (n % 31) == 0 or \
(n % 37) == 0 or (n % 41) == 0 or (n % 43) == 0 or (n % 47) == 0:
return False
if n < 2809:
return True
if n <= 23001:
return pow(2, n, n) == 2 and n not in [341, 561, 645, 1105, 1387, 1729,
1905, 2047, 2465, 2701, 2821,
3277, 4033, 4369, 4371, 4681,
5461, 6601, 7957, 8321, 8481,
8911, 10261, 10585, 11305,
12801, 13741, 13747, 13981,
14491, 15709, 15841, 16705,
18705, 18721, 19951, 23001]
# bisection search on the sieve if the sieve is large enough
from sympy.ntheory.generate import sieve as s
if n <= s._list[-1]:
l, u = s.search(n)
return l == u
# If we have GMPY2, skip straight to step 3 and do a strong BPSW test.
# This should be a bit faster than our step 2, and for large values will
# be a lot faster than our step 3 (C+GMP vs. Python).
from sympy.core.compatibility import HAS_GMPY
if HAS_GMPY == 2:
from gmpy2 import is_strong_prp, is_strong_selfridge_prp
return is_strong_prp(n, 2) and is_strong_selfridge_prp(n)
# Step 2: deterministic Miller-Rabin testing for numbers < 2^64. See:
# https://miller-rabin.appspot.com/
# for lists. We have made sure the M-R routine will successfully handle
# bases larger than n, so we can use the minimal set.
if n < 341531:
return mr(n, [9345883071009581737])
if n < 885594169:
return mr(n, [725270293939359937, 3569819667048198375])
if n < 350269456337:
return mr(n, [4230279247111683200, 14694767155120705706, 16641139526367750375])
if n < 55245642489451:
return mr(n, [2, 141889084524735, 1199124725622454117, 11096072698276303650])
if n < 7999252175582851:
return mr(n, [2, 4130806001517, 149795463772692060, 186635894390467037, 3967304179347715805])
if n < 585226005592931977:
return mr(n, [2, 123635709730000, 9233062284813009, 43835965440333360, 761179012939631437, 1263739024124850375])
if n < 18446744073709551616:
return mr(n, [2, 325, 9375, 28178, 450775, 9780504, 1795265022])
# We could do this instead at any point:
#if n < 18446744073709551616:
# return mr(n, [2]) and is_extra_strong_lucas_prp(n)
# Here are tests that are safe for MR routines that don't understand
# large bases.
#if n < 9080191:
# return mr(n, [31, 73])
#if n < 19471033:
# return mr(n, [2, 299417])
#if n < 38010307:
# return mr(n, [2, 9332593])
#if n < 316349281:
# return mr(n, [11000544, 31481107])
#if n < 4759123141:
# return mr(n, [2, 7, 61])
#if n < 105936894253:
# return mr(n, [2, 1005905886, 1340600841])
#if n < 31858317218647:
# return mr(n, [2, 642735, 553174392, 3046413974])
#if n < 3071837692357849:
# return mr(n, [2, 75088, 642735, 203659041, 3613982119])
#if n < 18446744073709551616:
# return mr(n, [2, 325, 9375, 28178, 450775, 9780504, 1795265022])
# Step 3: BPSW.
#
# Time for isprime(10**2000 + 4561), no gmpy or gmpy2 installed
# 44.0s old isprime using 46 bases
# 5.3s strong BPSW + one random base
# 4.3s extra strong BPSW + one random base
# 4.1s strong BPSW
# 3.2s extra strong BPSW
# Classic BPSW from page 1401 of the paper. See alternate ideas below.
return mr(n, [2]) and is_strong_lucas_prp(n)
# Using extra strong test, which is somewhat faster
#return mr(n, [2]) and is_extra_strong_lucas_prp(n)
# Add a random M-R base
#import random
#return mr(n, [2, random.randint(3, n-1)]) and is_strong_lucas_prp(n)
| 17,640 | 29.840909 | 120 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/ntheory/multinomial.py
|
from __future__ import print_function, division
from collections import defaultdict
from sympy.core.compatibility import range
def binomial_coefficients(n):
"""Return a dictionary containing pairs :math:`{(k1,k2) : C_kn}` where
:math:`C_kn` are binomial coefficients and :math:`n=k1+k2`.
Examples
========
>>> from sympy.ntheory import binomial_coefficients
>>> binomial_coefficients(9)
{(0, 9): 1, (1, 8): 9, (2, 7): 36, (3, 6): 84,
(4, 5): 126, (5, 4): 126, (6, 3): 84, (7, 2): 36, (8, 1): 9, (9, 0): 1}
See Also
========
binomial_coefficients_list, multinomial_coefficients
"""
d = {(0, n): 1, (n, 0): 1}
a = 1
for k in range(1, n//2 + 1):
a = (a * (n - k + 1))//k
d[k, n - k] = d[n - k, k] = a
return d
def binomial_coefficients_list(n):
""" Return a list of binomial coefficients as rows of the Pascal's
triangle.
Examples
========
>>> from sympy.ntheory import binomial_coefficients_list
>>> binomial_coefficients_list(9)
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
See Also
========
binomial_coefficients, multinomial_coefficients
"""
d = [1] * (n + 1)
a = 1
for k in range(1, n//2 + 1):
a = (a * (n - k + 1))//k
d[k] = d[n - k] = a
return d
def multinomial_coefficients0(m, n, _tuple=tuple, _zip=zip):
"""Return a dictionary containing pairs ``{(k1,k2,..,km) : C_kn}``
where ``C_kn`` are multinomial coefficients such that
``n=k1+k2+..+km``.
For example:
>>> from sympy import multinomial_coefficients
>>> multinomial_coefficients(2, 5) # indirect doctest
{(0, 5): 1, (1, 4): 5, (2, 3): 10, (3, 2): 10, (4, 1): 5, (5, 0): 1}
The algorithm is based on the following result:
Consider a polynomial and its ``n``-th exponent::
P(x) = sum_{i=0}^m p_i x^i
P(x)^n = sum_{k=0}^{m n} a(n,k) x^k
The coefficients ``a(n,k)`` can be computed using the
J.C.P. Miller Pure Recurrence [see D.E.Knuth, Seminumerical
Algorithms, The art of Computer Programming v.2, Addison
Wesley, Reading, 1981;]::
a(n,k) = 1/(k p_0) sum_{i=1}^m p_i ((n+1)i-k) a(n,k-i),
where ``a(n,0) = p_0^n``.
"""
if not m:
if n:
return {}
return {(): 1}
if m == 2:
return binomial_coefficients(n)
symbols = [(0,)*i + (1,) + (0,)*(m - i - 1) for i in range(m)]
s0 = symbols[0]
p0 = [_tuple(aa - bb for aa, bb in _zip(s, s0)) for s in symbols]
r = {_tuple(aa*n for aa in s0): 1}
l = [0] * (n*(m - 1) + 1)
l[0] = r.items()
for k in range(1, n*(m - 1) + 1):
d = defaultdict(int)
for i in range(1, min(m, k + 1)):
nn = (n + 1)*i - k
if not nn:
continue
t = p0[i]
for t2, c2 in l[k - i]:
tt = _tuple([aa + bb for aa, bb in _zip(t2, t)])
d[tt] += nn*c2
if not d[tt]:
del d[tt]
r1 = [(t, c//k) for (t, c) in d.items()]
l[k] = r1
r.update(r1)
return r
def multinomial_coefficients(m, n):
r"""Return a dictionary containing pairs ``{(k1,k2,..,km) : C_kn}``
where ``C_kn`` are multinomial coefficients such that
``n=k1+k2+..+km``.
For example:
>>> from sympy.ntheory import multinomial_coefficients
>>> multinomial_coefficients(2, 5) # indirect doctest
{(0, 5): 1, (1, 4): 5, (2, 3): 10, (3, 2): 10, (4, 1): 5, (5, 0): 1}
The algorithm is based on the following result:
.. math::
\binom{n}{k_1, \ldots, k_m} =
\frac{k_1 + 1}{n - k_1} \sum_{i=2}^m \binom{n}{k_1 + 1, \ldots, k_i - 1, \ldots}
Code contributed to Sage by Yann Laigle-Chapuy, copied with permission
of the author.
See Also
========
binomial_coefficients_list, binomial_coefficients
"""
if not m:
if n:
return {}
return {(): 1}
if m == 2:
return binomial_coefficients(n)
if m >= 2*n and n > 1:
return dict(multinomial_coefficients_iterator(m, n))
t = [n] + [0] * (m - 1)
r = {tuple(t): 1}
if n:
j = 0 # j will be the leftmost nonzero position
else:
j = m
# enumerate tuples in co-lex order
while j < m - 1:
# compute next tuple
tj = t[j]
if j:
t[j] = 0
t[0] = tj
if tj > 1:
t[j + 1] += 1
j = 0
start = 1
v = 0
else:
j += 1
start = j + 1
v = r[tuple(t)]
t[j] += 1
# compute the value
# NB: the initialization of v was done above
for k in range(start, m):
if t[k]:
t[k] -= 1
v += r[tuple(t)]
t[k] += 1
t[0] -= 1
r[tuple(t)] = (v * tj) // (n - t[0])
return r
def multinomial_coefficients_iterator(m, n, _tuple=tuple):
"""multinomial coefficient iterator
This routine has been optimized for `m` large with respect to `n` by taking
advantage of the fact that when the monomial tuples `t` are stripped of
zeros, their coefficient is the same as that of the monomial tuples from
``multinomial_coefficients(n, n)``. Therefore, the latter coefficients are
precomputed to save memory and time.
>>> from sympy.ntheory.multinomial import multinomial_coefficients
>>> m53, m33 = multinomial_coefficients(5,3), multinomial_coefficients(3,3)
>>> m53[(0,0,0,1,2)] == m53[(0,0,1,0,2)] == m53[(1,0,2,0,0)] == m33[(0,1,2)]
True
Examples
========
>>> from sympy.ntheory.multinomial import multinomial_coefficients_iterator
>>> it = multinomial_coefficients_iterator(20,3)
>>> next(it)
((3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), 1)
"""
if m < 2*n or n == 1:
mc = multinomial_coefficients(m, n)
for k, v in mc.items():
yield(k, v)
else:
mc = multinomial_coefficients(n, n)
mc1 = {}
for k, v in mc.items():
mc1[_tuple(filter(None, k))] = v
mc = mc1
t = [n] + [0] * (m - 1)
t1 = _tuple(t)
b = _tuple(filter(None, t1))
yield (t1, mc[b])
if n:
j = 0 # j will be the leftmost nonzero position
else:
j = m
# enumerate tuples in co-lex order
while j < m - 1:
# compute next tuple
tj = t[j]
if j:
t[j] = 0
t[0] = tj
if tj > 1:
t[j + 1] += 1
j = 0
else:
j += 1
t[j] += 1
t[0] -= 1
t1 = _tuple(t)
b = _tuple(filter(None, t1))
yield (t1, mc[b])
| 6,870 | 27.629167 | 88 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/ntheory/__init__.py
|
"""
Number theory module (primes, etc)
"""
from .generate import nextprime, prevprime, prime, primepi, primerange, \
randprime, Sieve, sieve, primorial, cycle_length, composite, compositepi
from .primetest import isprime
from .factor_ import divisors, factorint, multiplicity, perfect_power, \
pollard_pm1, pollard_rho, primefactors, totient, trailing, divisor_count, \
divisor_sigma, factorrat, reduced_totient, primenu, primeomega
from .partitions_ import npartitions
from .residue_ntheory import is_primitive_root, is_quad_residue, \
legendre_symbol, jacobi_symbol, n_order, sqrt_mod, quadratic_residues, \
primitive_root, nthroot_mod, is_nthpow_residue, sqrt_mod_iter, mobius, \
discrete_log
from .multinomial import binomial_coefficients, binomial_coefficients_list, \
multinomial_coefficients
from .continued_fraction import continued_fraction_periodic, \
continued_fraction_iterator, continued_fraction_reduce, \
continued_fraction_convergents
from .egyptian_fraction import egyptian_fraction
| 1,037 | 46.181818 | 79 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/ntheory/bbp_pi.py
|
'''
This implementation is a heavily modified fixed point implementation of
BBP_formula for calculating the nth position of pi. The original hosted
at: http://en.literateprograms.org/Pi_with_the_BBP_formula_(Python)
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sub-license, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Modifications:
1.Once the nth digit and desired number of digits is selected, the
number of digits of working precision is calculated to ensure that
the hexadecimal digits returned are accurate. This is calculated as
int(math.log(start + prec)/math.log(16) + prec + 3)
--------------------------------------- --------
/ /
number of hex digits additional digits
This was checked by the following code which completed without
errors (and dig are the digits included in the test_bbp.py file):
for i in range(0,1000):
for j in range(1,1000):
a, b = pi_hex_digits(i, j), dig[i:i+j]
if a != b:
print('%s\n%s'%(a,b))
Deceasing the additional digits by 1 generated errors, so '3' is
the smallest additional precision needed to calculate the above
loop without errors. The following trailing 10 digits were also
checked to be accurate (and the times were slightly faster with
some of the constant modifications that were made):
>> from time import time
>> t=time();pi_hex_digits(10**2-10 + 1, 10), time()-t
('e90c6cc0ac', 0.0)
>> t=time();pi_hex_digits(10**4-10 + 1, 10), time()-t
('26aab49ec6', 0.17100000381469727)
>> t=time();pi_hex_digits(10**5-10 + 1, 10), time()-t
('a22673c1a5', 4.7109999656677246)
>> t=time();pi_hex_digits(10**6-10 + 1, 10), time()-t
('9ffd342362', 59.985999822616577)
>> t=time();pi_hex_digits(10**7-10 + 1, 10), time()-t
('c1a42e06a1', 689.51800012588501)
2. The while loop to evaluate whether the series has converged quits
when the addition amount `dt` has dropped to zero.
3. the formatting string to convert the decimal to hexidecimal is
calculated for the given precision.
4. pi_hex_digits(n) changed to have coefficient to the formula in an
array (perhaps just a matter of preference).
'''
from __future__ import print_function, division
import math
from sympy.core.compatibility import range, as_int
def _series(j, n, prec=14):
# Left sum from the bbp algorithm
s = 0
D = _dn(n, prec)
D4 = 4 * D
k = 0
d = 8 * k + j
for k in range(n + 1):
s += (pow(16, n - k, d) << D4) // d
d += 8
# Right sum iterates to infinity for full precision, but we
# stop at the point where one iteration is beyond the precision
# specified.
t = 0
k = n + 1
e = 4*(D + n - k)
d = 8 * k + j
while True:
dt = (1 << e) // d
if not dt:
break
t += dt
# k += 1
e -= 4
d += 8
total = s + t
return total
def pi_hex_digits(n, prec=14):
"""Returns a string containing ``prec`` (default 14) digits
starting at the nth digit of pi in hex. Counting of digits
starts at 0 and the decimal is not counted, so for n = 0 the
returned value starts with 3; n = 1 corresponds to the first
digit past the decimal point (which in hex is 2).
Examples
========
>>> from sympy.ntheory.bbp_pi import pi_hex_digits
>>> pi_hex_digits(0)
'3243f6a8885a30'
>>> pi_hex_digits(0, 3)
'324'
References
==========
.. [1] http://www.numberworld.org/digits/Pi/
"""
n, prec = as_int(n), as_int(prec)
if n < 0:
raise ValueError('n cannot be negative')
if prec == 0:
return ''
# main of implementation arrays holding formulae coefficients
n -= 1
a = [4, 2, 1, 1]
j = [1, 4, 5, 6]
#formulae
D = _dn(n, prec)
x = + (a[0]*_series(j[0], n, prec)
- a[1]*_series(j[1], n, prec)
- a[2]*_series(j[2], n, prec)
- a[3]*_series(j[3], n, prec)) & (16**D - 1)
s = ("%0" + "%ix" % prec) % (x // 16**(D - prec))
return s
def _dn(n, prec):
# controller for n dependence on precision
# n = starting digit index
# prec = the number of total digits to compute
n += 1 # because we subtract 1 for _series
return int(math.log(n + prec)/math.log(16) + prec + 3)
| 5,269 | 31.530864 | 72 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/ntheory/partitions_.py
|
from __future__ import print_function, division
from mpmath.libmp import (fzero,
from_man_exp, from_int, from_rational,
fone, fhalf, bitcount, to_int, to_str, mpf_mul, mpf_div, mpf_sub,
mpf_add, mpf_sqrt, mpf_pi, mpf_cosh_sinh, pi_fixed, mpf_cos,
mpf_sin)
from sympy.core.numbers import igcd
import math
from sympy.core.compatibility import range
from .residue_ntheory import (_sqrt_mod_prime_power,
legendre_symbol, jacobi_symbol, is_quad_residue)
def _pre():
maxn = 10**5
global _factor
global _totient
_factor = [0]*maxn
_totient = [1]*maxn
lim = int(maxn**0.5) + 5
for i in range(2, lim):
if _factor[i] == 0:
for j in range(i*i, maxn, i):
if _factor[j] == 0:
_factor[j] = i
for i in range(2, maxn):
if _factor[i] == 0:
_factor[i] = i
_totient[i] = i-1
continue
x = _factor[i]
y = i//x
if y % x == 0:
_totient[i] = _totient[y]*x
else:
_totient[i] = _totient[y]*(x - 1)
def _a(n, k, prec):
""" Compute the inner sum in HRR formula [1]_
References
==========
.. [1] http://msp.org/pjm/1956/6-1/pjm-v6-n1-p18-p.pdf
"""
if k == 1:
return fone
k1 = k
e = 0
p = _factor[k]
while k1 % p == 0:
k1 //= p
e += 1
k2 = k//k1 # k2 = p^e
v = 1 - 24*n
pi = mpf_pi(prec)
if k1 == 1:
# k = p^e
if p == 2:
mod = 8*k
v = mod + v % mod
v = (v*pow(9, k - 1, mod)) % mod
m = _sqrt_mod_prime_power(v, 2, e + 3)[0]
arg = mpf_div(mpf_mul(
from_int(4*m), pi, prec), from_int(mod), prec)
return mpf_mul(mpf_mul(
from_int((-1)**e*jacobi_symbol(m - 1, m)),
mpf_sqrt(from_int(k), prec), prec),
mpf_sin(arg, prec), prec)
if p == 3:
mod = 3*k
v = mod + v % mod
if e > 1:
v = (v*pow(64, k//3 - 1, mod)) % mod
m = _sqrt_mod_prime_power(v, 3, e + 1)[0]
arg = mpf_div(mpf_mul(from_int(4*m), pi, prec),
from_int(mod), prec)
return mpf_mul(mpf_mul(
from_int(2*(-1)**(e + 1)*legendre_symbol(m, 3)),
mpf_sqrt(from_int(k//3), prec), prec),
mpf_sin(arg, prec), prec)
v = k + v % k
if v % p == 0:
if e == 1:
return mpf_mul(
from_int(jacobi_symbol(3, k)),
mpf_sqrt(from_int(k), prec), prec)
return fzero
if not is_quad_residue(v, p):
return fzero
_phi = p**(e - 1)*(p - 1)
v = (v*pow(576, _phi - 1, k))
m = _sqrt_mod_prime_power(v, p, e)[0]
arg = mpf_div(
mpf_mul(from_int(4*m), pi, prec),
from_int(k), prec)
return mpf_mul(mpf_mul(
from_int(2*jacobi_symbol(3, k)),
mpf_sqrt(from_int(k), prec), prec),
mpf_cos(arg, prec), prec)
if p != 2 or e >= 3:
d1, d2 = igcd(k1, 24), igcd(k2, 24)
e = 24//(d1*d2)
n1 = ((d2*e*n + (k2**2 - 1)//d1)*
pow(e*k2*k2*d2, _totient[k1] - 1, k1)) % k1
n2 = ((d1*e*n + (k1**2 - 1)//d2)*
pow(e*k1*k1*d1, _totient[k2] - 1, k2)) % k2
return mpf_mul(_a(n1, k1, prec), _a(n2, k2, prec), prec)
if e == 2:
n1 = ((8*n + 5)*pow(128, _totient[k1] - 1, k1)) % k1
n2 = (4 + ((n - 2 - (k1**2 - 1)//8)*(k1**2)) % 4) % 4
return mpf_mul(mpf_mul(
from_int(-1),
_a(n1, k1, prec), prec),
_a(n2, k2, prec))
n1 = ((8*n + 1)*pow(32, _totient[k1] - 1, k1)) % k1
n2 = (2 + (n - (k1**2 - 1)//8) % 2) % 2
return mpf_mul(_a(n1, k1, prec), _a(n2, k2, prec), prec)
def _d(n, j, prec, sq23pi, sqrt8):
"""
Compute the sinh term in the outer sum of the HRR formula.
The constants sqrt(2/3*pi) and sqrt(8) must be precomputed.
"""
j = from_int(j)
pi = mpf_pi(prec)
a = mpf_div(sq23pi, j, prec)
b = mpf_sub(from_int(n), from_rational(1, 24, prec), prec)
c = mpf_sqrt(b, prec)
ch, sh = mpf_cosh_sinh(mpf_mul(a, c), prec)
D = mpf_div(
mpf_sqrt(j, prec),
mpf_mul(mpf_mul(sqrt8, b), pi), prec)
E = mpf_sub(mpf_mul(a, ch), mpf_div(sh, c, prec), prec)
return mpf_mul(D, E)
def npartitions(n, verbose=False):
"""
Calculate the partition function P(n), i.e. the number of ways that
n can be written as a sum of positive integers.
P(n) is computed using the Hardy-Ramanujan-Rademacher formula [1]_.
The correctness of this implementation has been tested through 10**10.
Examples
========
>>> from sympy.ntheory import npartitions
>>> npartitions(25)
1958
References
==========
.. [1] http://mathworld.wolfram.com/PartitionFunctionP.html
"""
n = int(n)
if n < 0:
return 0
if n <= 5:
return [1, 1, 2, 3, 5, 7][n]
if '_factor' not in globals():
_pre()
# Estimate number of bits in p(n). This formula could be tidied
pbits = int((
math.pi*(2*n/3.)**0.5 -
math.log(4*n))/math.log(10) + 1) * \
math.log(10, 2)
prec = p = int(pbits*1.1 + 100)
s = fzero
M = max(6, int(0.24*n**0.5 + 4))
if M > 10**5:
raise ValueError("Input too big") # Corresponds to n > 1.7e11
sq23pi = mpf_mul(mpf_sqrt(from_rational(2, 3, p), p), mpf_pi(p), p)
sqrt8 = mpf_sqrt(from_int(8), p)
for q in range(1, M):
a = _a(n, q, p)
d = _d(n, q, p, sq23pi, sqrt8)
s = mpf_add(s, mpf_mul(a, d), prec)
if verbose:
print("step", q, "of", M, to_str(a, 10), to_str(d, 10))
# On average, the terms decrease rapidly in magnitude.
# Dynamically reducing the precision greatly improves
# performance.
p = bitcount(abs(to_int(d))) + 50
return int(to_int(mpf_add(s, fhalf, prec)))
__all__ = ['npartitions']
| 6,092 | 30.086735 | 74 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/ntheory/continued_fraction.py
|
from sympy.core.numbers import Integer, Rational
def continued_fraction_periodic(p, q, d=0):
r"""
Find the periodic continued fraction expansion of a quadratic irrational.
Compute the continued fraction expansion of a rational or a
quadratic irrational number, i.e. `\frac{p + \sqrt{d}}{q}`, where
`p`, `q` and `d \ge 0` are integers.
Returns the continued fraction representation (canonical form) as
a list of integers, optionally ending (for quadratic irrationals)
with repeating block as the last term of this list.
Parameters
==========
p : int
the rational part of the number's numerator
q : int
the denominator of the number
d : int, optional
the irrational part (discriminator) of the number's numerator
Examples
========
>>> from sympy.ntheory.continued_fraction import continued_fraction_periodic
>>> continued_fraction_periodic(3, 2, 7)
[2, [1, 4, 1, 1]]
Golden ratio has the simplest continued fraction expansion:
>>> continued_fraction_periodic(1, 2, 5)
[[1]]
If the discriminator is zero or a perfect square then the number will be a
rational number:
>>> continued_fraction_periodic(4, 3, 0)
[1, 3]
>>> continued_fraction_periodic(4, 3, 49)
[3, 1, 2]
See Also
========
continued_fraction_iterator, continued_fraction_reduce
References
==========
.. [1] http://en.wikipedia.org/wiki/Periodic_continued_fraction
.. [2] K. Rosen. Elementary Number theory and its applications.
Addison-Wesley, 3 Sub edition, pages 379-381, January 1992.
"""
from sympy.core.compatibility import as_int
from sympy.functions import sqrt
p, q, d = list(map(as_int, [p, q, d]))
sd = sqrt(d)
if q == 0:
raise ValueError("The denominator is zero.")
if d < 0:
raise ValueError("Delta supposed to be a non-negative "
"integer, got %d" % d)
elif d == 0 or sd.is_integer:
# the number is a rational number
return list(continued_fraction_iterator(Rational(p + sd, q)))
if (d - p**2)%q:
d *= q**2
sd *= q
p *= abs(q)
q *= abs(q)
terms = []
pq = {}
while (p, q) not in pq:
pq[(p, q)] = len(terms)
terms.append(int((p + sd)/q))
p = terms[-1]*q - p
q = (d - p**2)/q
i = pq[(p, q)]
return terms[:i] + [terms[i:]]
def continued_fraction_reduce(cf):
"""
Reduce a continued fraction to a rational or quadratic irrational.
Compute the rational or quadratic irrational number from its
terminating or periodic continued fraction expansion. The
continued fraction expansion (cf) should be supplied as a
terminating iterator supplying the terms of the expansion. For
terminating continued fractions, this is equivalent to
``list(continued_fraction_convergents(cf))[-1]``, only a little more
efficient. If the expansion has a repeating part, a list of the
repeating terms should be returned as the last element from the
iterator. This is the format returned by
continued_fraction_periodic.
For quadratic irrationals, returns the largest solution found,
which is generally the one sought, if the fraction is in canonical
form (all terms positive except possibly the first).
Examples
========
>>> from sympy.ntheory.continued_fraction import continued_fraction_reduce
>>> continued_fraction_reduce([1, 2, 3, 4, 5])
225/157
>>> continued_fraction_reduce([-2, 1, 9, 7, 1, 2])
-256/233
>>> continued_fraction_reduce([2, 1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8]).n(10)
2.718281835
>>> continued_fraction_reduce([1, 4, 2, [3, 1]])
(sqrt(21) + 287)/238
>>> continued_fraction_reduce([[1]])
1/2 + sqrt(5)/2
>>> from sympy.ntheory.continued_fraction import continued_fraction_periodic
>>> continued_fraction_reduce(continued_fraction_periodic(8, 5, 13))
(sqrt(13) + 8)/5
See Also
========
continued_fraction_periodic
"""
from sympy.core.symbol import Dummy
from sympy.solvers import solve
period = []
x = Dummy('x')
def untillist(cf):
for nxt in cf:
if isinstance(nxt, list):
period.extend(nxt)
yield x
break
yield nxt
a = Integer(0)
for a in continued_fraction_convergents(untillist(cf)):
pass
if period:
y = Dummy('y')
solns = solve(continued_fraction_reduce(period + [y]) - y, y)
solns.sort()
pure = solns[-1]
return a.subs(x, pure).radsimp()
else:
return a
def continued_fraction_iterator(x):
"""
Return continued fraction expansion of x as iterator.
Examples
========
>>> from sympy.core import Rational, pi
>>> from sympy.ntheory.continued_fraction import continued_fraction_iterator
>>> list(continued_fraction_iterator(Rational(3, 8)))
[0, 2, 1, 2]
>>> list(continued_fraction_iterator(Rational(-3, 8)))
[-1, 1, 1, 1, 2]
>>> for i, v in enumerate(continued_fraction_iterator(pi)):
... if i > 7:
... break
... print(v)
3
7
15
1
292
1
1
1
References
==========
.. [1] http://en.wikipedia.org/wiki/Continued_fraction
"""
from sympy.functions import floor
while True:
i = floor(x)
yield i
x -= i
if not x:
break
x = 1/x
def continued_fraction_convergents(cf):
"""
Return an iterator over the convergents of a continued fraction (cf).
The parameter should be an iterable returning successive
partial quotients of the continued fraction, such as might be
returned by continued_fraction_iterator. In computing the
convergents, the continued fraction need not be strictly in
canonical form (all integers, all but the first positive).
Rational and negative elements may be present in the expansion.
Examples
========
>>> from sympy.core import Rational, pi
>>> from sympy import S
>>> from sympy.ntheory.continued_fraction import \
continued_fraction_convergents, continued_fraction_iterator
>>> list(continued_fraction_convergents([0, 2, 1, 2]))
[0, 1/2, 1/3, 3/8]
>>> list(continued_fraction_convergents([1, S('1/2'), -7, S('1/4')]))
[1, 3, 19/5, 7]
>>> it = continued_fraction_convergents(continued_fraction_iterator(pi))
>>> for n in range(7):
... print(next(it))
3
22/7
333/106
355/113
103993/33102
104348/33215
208341/66317
See Also
========
continued_fraction_iterator
"""
p_2, q_2 = Integer(0), Integer(1)
p_1, q_1 = Integer(1), Integer(0)
for a in cf:
p, q = a*p_1 + p_2, a*q_1 + q_2
p_2, q_2 = p_1, q_1
p_1, q_1 = p, q
yield p/q
| 6,976 | 25.834615 | 80 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/ntheory/tests/test_egyptian_fraction.py
|
from sympy.core.numbers import Rational
from sympy.ntheory.egyptian_fraction import egyptian_fraction
from sympy.core.add import Add
from sympy.utilities.pytest import raises
from sympy.utilities.randtest import random_complex_number
def test_egyptian_fraction():
def test_equality(r, alg="Greedy"):
return r == Add(*[Rational(1, i) for i in egyptian_fraction(r, alg)])
r = random_complex_number(a=0, c=1, b=0, d=0, rational=True)
assert test_equality(r)
assert egyptian_fraction(Rational(4, 17)) == [5, 29, 1233, 3039345]
assert egyptian_fraction(Rational(7, 13), "Greedy") == [2, 26]
assert egyptian_fraction(Rational(23, 101), "Greedy") == \
[5, 37, 1438, 2985448, 40108045937720]
assert egyptian_fraction(Rational(18, 23), "Takenouchi") == \
[2, 6, 12, 35, 276, 2415]
assert egyptian_fraction(Rational(5, 6), "Graham Jewett") == \
[6, 7, 8, 9, 10, 42, 43, 44, 45, 56, 57, 58, 72, 73, 90, 1806, 1807,
1808, 1892, 1893, 1980, 3192, 3193, 3306, 5256, 3263442, 3263443,
3267056, 3581556, 10192056, 10650056950806]
assert egyptian_fraction(Rational(5, 6), "Golomb") == [2, 6, 12, 20, 30]
assert egyptian_fraction(Rational(5, 121), "Golomb") == [25, 1225, 3577, 7081, 11737]
raises(ValueError, lambda: egyptian_fraction(Rational(-4, 9)))
assert egyptian_fraction(Rational(8, 3), "Golomb") == [1, 2, 3, 4, 5, 6, 7,
14, 574, 2788, 6460,
11590, 33062, 113820]
assert egyptian_fraction(Rational(355, 113)) == [1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 27, 744, 893588,
1251493536607,
20361068938197002344405230]
| 1,886 | 52.914286 | 89 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/ntheory/tests/test_partitions.py
|
from sympy.core.compatibility import range
from sympy.ntheory import npartitions
def test_partitions():
assert [npartitions(k) for k in range(13)] == \
[1, 1, 2, 3, 5, 7, 11, 15, 22, 30, 42, 56, 77]
assert npartitions(100) == 190569292
assert npartitions(200) == 3972999029388
assert npartitions(1000) == 24061467864032622473692149727991
assert npartitions(2000) == 4720819175619413888601432406799959512200344166
assert npartitions(10000) % 10**10 == 6916435144
assert npartitions(100000) % 10**10 == 9421098519
| 550 | 38.357143 | 78 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/ntheory/tests/test_multinomial.py
|
from sympy import binomial_coefficients, binomial_coefficients_list, multinomial_coefficients
from sympy.core.compatibility import range
from sympy.ntheory.multinomial import multinomial_coefficients_iterator
def test_binomial_coefficients_list():
assert binomial_coefficients_list(0) == [1]
assert binomial_coefficients_list(1) == [1, 1]
assert binomial_coefficients_list(2) == [1, 2, 1]
assert binomial_coefficients_list(3) == [1, 3, 3, 1]
assert binomial_coefficients_list(4) == [1, 4, 6, 4, 1]
assert binomial_coefficients_list(5) == [1, 5, 10, 10, 5, 1]
assert binomial_coefficients_list(6) == [1, 6, 15, 20, 15, 6, 1]
def test_binomial_coefficients():
for n in range(15):
c = binomial_coefficients(n)
l = [c[k] for k in sorted(c)]
assert l == binomial_coefficients_list(n)
def test_multinomial_coefficients():
assert multinomial_coefficients(1, 1) == {(1,): 1}
assert multinomial_coefficients(1, 2) == {(2,): 1}
assert multinomial_coefficients(1, 3) == {(3,): 1}
assert multinomial_coefficients(2, 0) == {(0, 0): 1}
assert multinomial_coefficients(2, 1) == {(0, 1): 1, (1, 0): 1}
assert multinomial_coefficients(2, 2) == {(2, 0): 1, (0, 2): 1, (1, 1): 2}
assert multinomial_coefficients(2, 3) == {(3, 0): 1, (1, 2): 3, (0, 3): 1,
(2, 1): 3}
assert multinomial_coefficients(3, 1) == {(1, 0, 0): 1, (0, 1, 0): 1,
(0, 0, 1): 1}
assert multinomial_coefficients(3, 2) == {(0, 1, 1): 2, (0, 0, 2): 1,
(1, 1, 0): 2, (0, 2, 0): 1, (1, 0, 1): 2, (2, 0, 0): 1}
mc = multinomial_coefficients(3, 3)
assert mc == {(2, 1, 0): 3, (0, 3, 0): 1,
(1, 0, 2): 3, (0, 2, 1): 3, (0, 1, 2): 3, (3, 0, 0): 1,
(2, 0, 1): 3, (1, 2, 0): 3, (1, 1, 1): 6, (0, 0, 3): 1}
assert dict(multinomial_coefficients_iterator(2, 0)) == {(0, 0): 1}
assert dict(
multinomial_coefficients_iterator(2, 1)) == {(0, 1): 1, (1, 0): 1}
assert dict(multinomial_coefficients_iterator(2, 2)) == \
{(2, 0): 1, (0, 2): 1, (1, 1): 2}
assert dict(multinomial_coefficients_iterator(3, 3)) == mc
it = multinomial_coefficients_iterator(7, 2)
assert [next(it) for i in range(4)] == \
[((2, 0, 0, 0, 0, 0, 0), 1), ((1, 1, 0, 0, 0, 0, 0), 2),
((0, 2, 0, 0, 0, 0, 0), 1), ((1, 0, 1, 0, 0, 0, 0), 2)]
| 2,365 | 46.32 | 93 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/ntheory/tests/test_continued_fraction.py
|
from sympy import S, pi, GoldenRatio as phi, sqrt
from sympy.ntheory.continued_fraction import \
(continued_fraction_periodic as cf_p,
continued_fraction_iterator as cf_i,
continued_fraction_convergents as cf_c,
continued_fraction_reduce as cf_r)
from sympy.utilities.pytest import raises
def test_continued_fraction():
raises(ValueError, lambda: cf_p(1, 0, 0))
raises(ValueError, lambda: cf_p(1, 1, -1))
assert cf_p(4, 3, 0) == [1, 3]
assert cf_p(0, 3, 5) == [0, 1, [2, 1, 12, 1, 2, 2]]
assert cf_p(1, 1, 0) == [1]
assert cf_p(3, 4, 0) == [0, 1, 3]
assert cf_p(4, 5, 0) == [0, 1, 4]
assert cf_p(5, 6, 0) == [0, 1, 5]
assert cf_p(11, 13, 0) == [0, 1, 5, 2]
assert cf_p(16, 19, 0) == [0, 1, 5, 3]
assert cf_p(27, 32, 0) == [0, 1, 5, 2, 2]
assert cf_p(1, 2, 5) == [[1]]
assert cf_p(0, 1, 2) == [1, [2]]
assert cf_p(6, 7, 49) == [1, 1, 6]
assert cf_p(3796, 1387, 0) == [2, 1, 2, 1, 4]
assert cf_p(3245, 10000) == [0, 3, 12, 4, 13]
assert cf_p(1932, 2568) == [0, 1, 3, 26, 2]
assert cf_p(6589, 2569) == [2, 1, 1, 3, 2, 1, 3, 1, 23]
def take(iterator, n=7):
res = []
for i, t in enumerate(cf_i(iterator)):
if i >= n:
break
res.append(t)
return res
assert take(phi) == [1, 1, 1, 1, 1, 1, 1]
assert take(pi) == [3, 7, 15, 1, 292, 1, 1]
assert list(cf_i(S(17)/12)) == [1, 2, 2, 2]
assert list(cf_i(S(-17)/12)) == [-2, 1, 1, 2, 2]
assert list(cf_c([1, 6, 1, 8])) == [S(1), S(7)/6, S(8)/7, S(71)/62]
assert list(cf_c([2])) == [S(2)]
assert list(cf_c([1, 1, 1, 1, 1, 1, 1])) == [S.One, S(2), S(3)/2, S(5)/3,
S(8)/5, S(13)/8, S(21)/13]
assert list(cf_c([1, 6, S(-1)/2, 4])) == [S.One, S(7)/6, S(5)/4, S(3)/2]
assert cf_r([1, 6, 1, 8]) == S(71)/62
assert cf_r([3]) == S(3)
assert cf_r([-1, 5, 1, 4]) == S(-24)/29
assert (cf_r([0, 1, 1, 7, [24, 8]]) - (sqrt(3) + 2)/7).expand() == 0
assert cf_r([1, 5, 9]) == S(55)/46
assert (cf_r([[1]]) - (sqrt(5) + 1)/2).expand() == 0
| 2,128 | 37.017857 | 77 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/ntheory/tests/test_generate.py
|
from sympy import Sieve, sieve
from sympy.core.compatibility import range
from sympy.ntheory import isprime, totient, randprime, nextprime, prevprime, \
primerange, primepi, prime, primorial, composite, compositepi, reduced_totient
from sympy.ntheory.generate import cycle_length
from sympy.ntheory.primetest import mr
from sympy.utilities.pytest import raises
def test_prime():
assert prime(1) == 2
assert prime(2) == 3
assert prime(5) == 11
assert prime(11) == 31
assert prime(57) == 269
assert prime(296) == 1949
assert prime(559) == 4051
assert prime(3000) == 27449
assert prime(4096) == 38873
assert prime(9096) == 94321
assert prime(25023) == 287341
raises(ValueError, lambda: prime(0))
sieve.extend(3000)
assert prime(401) == 2749
def test_primepi():
assert primepi(1) == 0
assert primepi(2) == 1
assert primepi(5) == 3
assert primepi(11) == 5
assert primepi(57) == 16
assert primepi(296) == 62
assert primepi(559) == 102
assert primepi(3000) == 430
assert primepi(4096) == 564
assert primepi(9096) == 1128
assert primepi(25023) == 2763
assert primepi(10**8) == 5761455
assert primepi(253425253) == 13856396
assert primepi(8769575643) == 401464322
sieve.extend(3000)
assert primepi(2000) == 303
def test_composite():
from sympy.ntheory.generate import sieve
sieve._reset()
assert composite(1) == 4
assert composite(2) == 6
assert composite(5) == 10
assert composite(11) == 20
assert composite(41) == 58
assert composite(57) == 80
assert composite(296) == 370
assert composite(559) == 684
assert composite(3000) == 3488
assert composite(4096) == 4736
assert composite(9096) == 10368
assert composite(25023) == 28088
sieve.extend(3000)
assert composite(1957) == 2300
assert composite(2568) == 2998
raises(ValueError, lambda: composite(0))
def test_compositepi():
assert compositepi(1) == 0
assert compositepi(2) == 0
assert compositepi(5) == 1
assert compositepi(11) == 5
assert compositepi(57) == 40
assert compositepi(296) == 233
assert compositepi(559) == 456
assert compositepi(3000) == 2569
assert compositepi(4096) == 3531
assert compositepi(9096) == 7967
assert compositepi(25023) == 22259
assert compositepi(10**8) == 94238544
assert compositepi(253425253) == 239568856
assert compositepi(8769575643) == 8368111320
sieve.extend(3000)
assert compositepi(2321) == 1976
def test_generate():
from sympy.ntheory.generate import sieve
sieve._reset()
assert nextprime(-4) == 2
assert nextprime(2) == 3
assert nextprime(5) == 7
assert nextprime(12) == 13
assert prevprime(3) == 2
assert prevprime(7) == 5
assert prevprime(13) == 11
assert prevprime(19) == 17
assert prevprime(20) == 19
sieve.extend_to_no(9)
assert sieve._list[-1] == 23
assert sieve._list[-1] < 31
assert 31 in sieve
assert nextprime(90) == 97
assert nextprime(10**40) == (10**40 + 121)
assert prevprime(97) == 89
assert prevprime(10**40) == (10**40 - 17)
assert list(sieve.primerange(10, 1)) == []
assert list(primerange(10, 1)) == []
assert list(primerange(2, 7)) == [2, 3, 5]
assert list(primerange(2, 10)) == [2, 3, 5, 7]
assert list(primerange(1050, 1100)) == [1051, 1061,
1063, 1069, 1087, 1091, 1093, 1097]
s = Sieve()
for i in range(30, 2350, 376):
for j in range(2, 5096, 1139):
A = list(s.primerange(i, i + j))
B = list(primerange(i, i + j))
assert A == B
s = Sieve()
assert s[10] == 29
assert nextprime(2, 2) == 5
raises(ValueError, lambda: totient(0))
raises(ValueError, lambda: reduced_totient(0))
raises(ValueError, lambda: primorial(0))
assert mr(1, [2]) is False
func = lambda i: (i**2 + 1) % 51
assert next(cycle_length(func, 4)) == (6, 2)
assert list(cycle_length(func, 4, values=True)) == \
[17, 35, 2, 5, 26, 14, 44, 50, 2, 5, 26, 14]
assert next(cycle_length(func, 4, nmax=5)) == (5, None)
assert list(cycle_length(func, 4, nmax=5, values=True)) == \
[17, 35, 2, 5, 26]
sieve.extend(3000)
assert nextprime(2968) == 2969
assert prevprime(2930) == 2927
raises(ValueError, lambda: prevprime(1))
def test_randprime():
import random
random.seed(1234)
assert randprime(10, 1) is None
assert randprime(2, 3) == 2
assert randprime(1, 3) == 2
assert randprime(3, 5) == 3
raises(ValueError, lambda: randprime(20, 22))
for a in [100, 300, 500, 250000]:
for b in [100, 300, 500, 250000]:
p = randprime(a, a + b)
assert a <= p < (a + b) and isprime(p)
def test_primorial():
assert primorial(1) == 2
assert primorial(1, nth=0) == 1
assert primorial(2) == 6
assert primorial(2, nth=0) == 2
assert primorial(4, nth=0) == 6
def test_search():
assert 2 in sieve
assert 2.1 not in sieve
assert 1 not in sieve
assert 2**1000 not in sieve
raises(ValueError, lambda: sieve.search(1))
def test_sieve_slice():
assert sieve[5] == 11
assert list(sieve[5:10]) == [sieve[x] for x in range(5, 10)]
assert list(sieve[5:10:2]) == [sieve[x] for x in range(5, 10, 2)]
| 5,368 | 28.5 | 82 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/ntheory/tests/test_residue.py
|
from collections import defaultdict
from sympy import Symbol
from sympy.core.compatibility import range
from sympy.ntheory import n_order, is_primitive_root, is_quad_residue, \
legendre_symbol, jacobi_symbol, totient, primerange, sqrt_mod, \
primitive_root, quadratic_residues, is_nthpow_residue, nthroot_mod, \
sqrt_mod_iter, mobius, discrete_log
from sympy.ntheory.residue_ntheory import _primitive_root_prime_iter, \
_discrete_log_trial_mul, _discrete_log_shanks_steps, \
_discrete_log_pollard_rho, _discrete_log_pohlig_hellman
from sympy.polys.domains import ZZ
from sympy.utilities.pytest import raises
def test_residue():
assert n_order(2, 13) == 12
assert [n_order(a, 7) for a in range(1, 7)] == \
[1, 3, 6, 3, 6, 2]
assert n_order(5, 17) == 16
assert n_order(17, 11) == n_order(6, 11)
assert n_order(101, 119) == 6
assert n_order(11, (10**50 + 151)**2) == 10000000000000000000000000000000000000000000000030100000000000000000000000000000000000000000000022650
raises(ValueError, lambda: n_order(6, 9))
assert is_primitive_root(2, 7) is False
assert is_primitive_root(3, 8) is False
assert is_primitive_root(11, 14) is False
assert is_primitive_root(12, 17) == is_primitive_root(29, 17)
raises(ValueError, lambda: is_primitive_root(3, 6))
assert [primitive_root(i) for i in range(2, 31)] == [1, 2, 3, 2, 5, 3, \
None, 2, 3, 2, None, 2, 3, None, None, 3, 5, 2, None, None, 7, 5, \
None, 2, 7, 2, None, 2, None]
for p in primerange(3, 100):
it = _primitive_root_prime_iter(p)
assert len(list(it)) == totient(totient(p))
assert primitive_root(97) == 5
assert primitive_root(97**2) == 5
assert primitive_root(40487) == 5
# note that primitive_root(40487) + 40487 = 40492 is a primitive root
# of 40487**2, but it is not the smallest
assert primitive_root(40487**2) == 10
assert primitive_root(82) == 7
p = 10**50 + 151
assert primitive_root(p) == 11
assert primitive_root(2*p) == 11
assert primitive_root(p**2) == 11
raises(ValueError, lambda: primitive_root(-3))
assert is_quad_residue(3, 7) is False
assert is_quad_residue(10, 13) is True
assert is_quad_residue(12364, 139) == is_quad_residue(12364 % 139, 139)
assert is_quad_residue(207, 251) is True
assert is_quad_residue(0, 1) is True
assert is_quad_residue(1, 1) is True
assert is_quad_residue(0, 2) == is_quad_residue(1, 2) is True
assert is_quad_residue(1, 4) is True
assert is_quad_residue(2, 27) is False
assert is_quad_residue(13122380800, 13604889600) is True
assert [j for j in range(14) if is_quad_residue(j, 14)] == \
[0, 1, 2, 4, 7, 8, 9, 11]
raises(ValueError, lambda: is_quad_residue(1.1, 2))
raises(ValueError, lambda: is_quad_residue(2, 0))
assert quadratic_residues(12) == [0, 1, 4, 9]
assert quadratic_residues(13) == [0, 1, 3, 4, 9, 10, 12]
assert [len(quadratic_residues(i)) for i in range(1, 20)] == \
[1, 2, 2, 2, 3, 4, 4, 3, 4, 6, 6, 4, 7, 8, 6, 4, 9, 8, 10]
assert list(sqrt_mod_iter(6, 2)) == [0]
assert sqrt_mod(3, 13) == 4
assert sqrt_mod(3, -13) == 4
assert sqrt_mod(6, 23) == 11
assert sqrt_mod(345, 690) == 345
for p in range(3, 100):
d = defaultdict(list)
for i in range(p):
d[pow(i, 2, p)].append(i)
for i in range(1, p):
it = sqrt_mod_iter(i, p)
v = sqrt_mod(i, p, True)
if v:
v = sorted(v)
assert d[i] == v
else:
assert not d[i]
assert sqrt_mod(9, 27, True) == [3, 6, 12, 15, 21, 24]
assert sqrt_mod(9, 81, True) == [3, 24, 30, 51, 57, 78]
assert sqrt_mod(9, 3**5, True) == [3, 78, 84, 159, 165, 240]
assert sqrt_mod(81, 3**4, True) == [0, 9, 18, 27, 36, 45, 54, 63, 72]
assert sqrt_mod(81, 3**5, True) == [9, 18, 36, 45, 63, 72, 90, 99, 117,\
126, 144, 153, 171, 180, 198, 207, 225, 234]
assert sqrt_mod(81, 3**6, True) == [9, 72, 90, 153, 171, 234, 252, 315,\
333, 396, 414, 477, 495, 558, 576, 639, 657, 720]
assert sqrt_mod(81, 3**7, True) == [9, 234, 252, 477, 495, 720, 738, 963,\
981, 1206, 1224, 1449, 1467, 1692, 1710, 1935, 1953, 2178]
for a, p in [(26214400, 32768000000), (26214400, 16384000000),
(262144, 1048576), (87169610025, 163443018796875),
(22315420166400, 167365651248000000)]:
assert pow(sqrt_mod(a, p), 2, p) == a
n = 70
a, p = 5**2*3**n*2**n, 5**6*3**(n+1)*2**(n+2)
it = sqrt_mod_iter(a, p)
for i in range(10):
assert pow(next(it), 2, p) == a
a, p = 5**2*3**n*2**n, 5**6*3**(n+1)*2**(n+3)
it = sqrt_mod_iter(a, p)
for i in range(2):
assert pow(next(it), 2, p) == a
n = 100
a, p = 5**2*3**n*2**n, 5**6*3**(n+1)*2**(n+1)
it = sqrt_mod_iter(a, p)
for i in range(2):
assert pow(next(it), 2, p) == a
assert type(next(sqrt_mod_iter(9, 27))) is int
assert type(next(sqrt_mod_iter(9, 27, ZZ))) is type(ZZ(1))
assert type(next(sqrt_mod_iter(1, 7, ZZ))) is type(ZZ(1))
assert is_nthpow_residue(2, 1, 5)
#issue 10816
assert is_nthpow_residue(1, 0, 1) is False
assert is_nthpow_residue(1, 0, 2) is True
assert is_nthpow_residue(3, 0, 2) is False
assert is_nthpow_residue(0, 1, 8) is True
assert is_nthpow_residue(2, 3, 2) is False
assert is_nthpow_residue(2, 3, 9) is False
assert is_nthpow_residue(3, 5, 30) is True
assert is_nthpow_residue(21, 11, 20) is True
assert is_nthpow_residue(7, 10, 20) is False
assert is_nthpow_residue(5, 10, 20) is True
assert is_nthpow_residue(3, 10, 48) is False
assert is_nthpow_residue(1, 10, 40) is True
assert is_nthpow_residue(3, 10, 24) is False
assert is_nthpow_residue(1, 10, 24) is True
assert is_nthpow_residue(3, 10, 24) is False
assert is_nthpow_residue(2, 10, 48) is False
assert is_nthpow_residue(81, 3, 972) is False
assert is_nthpow_residue(243, 5, 5103) is True
assert is_nthpow_residue(243, 3, 1240029) is False
x = set([pow(i, 56, 1024) for i in range(1024)])
assert set([a for a in range(1024) if is_nthpow_residue(a, 56, 1024)]) == x
x = set([ pow(i, 256, 2048) for i in range(2048)])
assert set([a for a in range(2048) if is_nthpow_residue(a, 256, 2048)]) == x
x = set([ pow(i, 11, 324000) for i in range(1000)])
assert [ is_nthpow_residue(a, 11, 324000) for a in x]
x = set([ pow(i, 17, 22217575536) for i in range(1000)])
assert [ is_nthpow_residue(a, 17, 22217575536) for a in x]
assert is_nthpow_residue(676, 3, 5364)
assert is_nthpow_residue(9, 12, 36)
assert is_nthpow_residue(32, 10, 41)
assert is_nthpow_residue(4, 2, 64)
assert is_nthpow_residue(31, 4, 41)
assert not is_nthpow_residue(2, 2, 5)
assert is_nthpow_residue(8547, 12, 10007)
assert nthroot_mod(1801, 11, 2663) == 44
for a, q, p in [(51922, 2, 203017), (43, 3, 109), (1801, 11, 2663),
(26118163, 1303, 33333347), (1499, 7, 2663), (595, 6, 2663),
(1714, 12, 2663), (28477, 9, 33343)]:
r = nthroot_mod(a, q, p)
assert pow(r, q, p) == a
assert nthroot_mod(11, 3, 109) is None
raises(NotImplementedError, lambda: nthroot_mod(16, 5, 36))
raises(NotImplementedError, lambda: nthroot_mod(9, 16, 36))
for p in primerange(5, 100):
qv = range(3, p, 4)
for q in qv:
d = defaultdict(list)
for i in range(p):
d[pow(i, q, p)].append(i)
for a in range(1, p - 1):
res = nthroot_mod(a, q, p, True)
if d[a]:
assert d[a] == res
else:
assert res is None
assert legendre_symbol(5, 11) == 1
assert legendre_symbol(25, 41) == 1
assert legendre_symbol(67, 101) == -1
assert legendre_symbol(0, 13) == 0
assert legendre_symbol(9, 3) == 0
raises(ValueError, lambda: legendre_symbol(2, 4))
assert jacobi_symbol(25, 41) == 1
assert jacobi_symbol(-23, 83) == -1
assert jacobi_symbol(3, 9) == 0
assert jacobi_symbol(42, 97) == -1
assert jacobi_symbol(3, 5) == -1
assert jacobi_symbol(7, 9) == 1
assert jacobi_symbol(0, 3) == 0
assert jacobi_symbol(0, 1) == 1
assert jacobi_symbol(2, 1) == 1
assert jacobi_symbol(1, 3) == 1
raises(ValueError, lambda: jacobi_symbol(3, 8))
assert mobius(13*7) == 1
assert mobius(1) == 1
assert mobius(13*7*5) == -1
assert mobius(13**2) == 0
raises(ValueError, lambda: mobius(-3))
p = Symbol('p', integer=True, positive=True, prime=True)
x = Symbol('x', positive=True)
i = Symbol('i', integer=True)
assert mobius(p) == -1
raises(TypeError, lambda: mobius(x))
raises(ValueError, lambda: mobius(i))
assert _discrete_log_trial_mul(587, 2**7, 2) == 7
assert _discrete_log_trial_mul(941, 7**18, 7) == 18
assert _discrete_log_trial_mul(389, 3**81, 3) == 81
assert _discrete_log_trial_mul(191, 19**123, 19) == 123
assert _discrete_log_shanks_steps(442879, 7**2, 7) == 2
assert _discrete_log_shanks_steps(874323, 5**19, 5) == 19
assert _discrete_log_shanks_steps(6876342, 7**71, 7) == 71
assert _discrete_log_shanks_steps(2456747, 3**321, 3) == 321
assert _discrete_log_pollard_rho(6013199, 2**6, 2, rseed=0) == 6
assert _discrete_log_pollard_rho(6138719, 2**19, 2, rseed=0) == 19
assert _discrete_log_pollard_rho(36721943, 2**40, 2, rseed=0) == 40
assert _discrete_log_pollard_rho(24567899, 3**333, 3, rseed=0) == 333
assert _discrete_log_pohlig_hellman(98376431, 11**9, 11) == 9
assert _discrete_log_pohlig_hellman(78723213, 11**31, 11) == 31
assert _discrete_log_pohlig_hellman(32942478, 11**98, 11) == 98
assert _discrete_log_pohlig_hellman(14789363, 11**444, 11) == 444
assert discrete_log(587, 2**9, 2) == 9
assert discrete_log(2456747, 3**51, 3) == 51
assert discrete_log(32942478, 11**127, 11) == 127
assert discrete_log(432751500361, 7**324, 7) == 324
| 10,128 | 41.380753 | 146 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/ntheory/tests/test_factor_.py
|
from sympy import (Sieve, binomial_coefficients, binomial_coefficients_list,
Mul, S, Pow, sieve, Symbol, summation, Dummy,
factorial as fac)
from sympy.core.numbers import Integer, Rational
from sympy.core.compatibility import long, range
from sympy.ntheory import (isprime, n_order, is_primitive_root,
is_quad_residue, legendre_symbol, jacobi_symbol, npartitions, totient,
factorint, primefactors, divisors, randprime, nextprime, prevprime,
primerange, primepi, prime, pollard_rho, perfect_power, multiplicity,
trailing, divisor_count, primorial, pollard_pm1, divisor_sigma,
factorrat, reduced_totient)
from sympy.ntheory.factor_ import (smoothness, smoothness_p,
antidivisors, antidivisor_count, core, digits, udivisors, udivisor_sigma,
udivisor_count, primenu, primeomega)
from sympy.ntheory.generate import cycle_length
from sympy.ntheory.multinomial import (
multinomial_coefficients, multinomial_coefficients_iterator)
from sympy.ntheory.bbp_pi import pi_hex_digits
from sympy.ntheory.modular import crt, crt1, crt2, solve_congruence
from sympy.utilities.pytest import raises, slow
from sympy.utilities.iterables import capture
def fac_multiplicity(n, p):
"""Return the power of the prime number p in the
factorization of n!"""
if p > n:
return 0
if p > n//2:
return 1
q, m = n, 0
while q >= p:
q //= p
m += q
return m
def multiproduct(seq=(), start=1):
"""
Return the product of a sequence of factors with multiplicities,
times the value of the parameter ``start``. The input may be a
sequence of (factor, exponent) pairs or a dict of such pairs.
>>> multiproduct({3:7, 2:5}, 4) # = 3**7 * 2**5 * 4
279936
"""
if not seq:
return start
if isinstance(seq, dict):
seq = iter(seq.items())
units = start
multi = []
for base, exp in seq:
if not exp:
continue
elif exp == 1:
units *= base
else:
if exp % 2:
units *= base
multi.append((base, exp//2))
return units * multiproduct(multi)**2
def test_trailing():
assert trailing(0) == 0
assert trailing(1) == 0
assert trailing(-1) == 0
assert trailing(2) == 1
assert trailing(7) == 0
assert trailing(-7) == 0
for i in range(100):
assert trailing((1 << i)) == i
assert trailing((1 << i) * 31337) == i
assert trailing((1 << 1000001)) == 1000001
assert trailing((1 << 273956)*7**37) == 273956
def test_multiplicity():
for b in range(2, 20):
for i in range(100):
assert multiplicity(b, b**i) == i
assert multiplicity(b, (b**i) * 23) == i
assert multiplicity(b, (b**i) * 1000249) == i
# Should be fast
assert multiplicity(10, 10**10023) == 10023
# Should exit quickly
assert multiplicity(10**10, 10**10) == 1
# Should raise errors for bad input
raises(ValueError, lambda: multiplicity(1, 1))
raises(ValueError, lambda: multiplicity(1, 2))
raises(ValueError, lambda: multiplicity(1.3, 2))
raises(ValueError, lambda: multiplicity(2, 0))
raises(ValueError, lambda: multiplicity(1.3, 0))
# handles Rationals
assert multiplicity(10, Rational(30, 7)) == 0
assert multiplicity(Rational(2, 7), Rational(4, 7)) == 1
assert multiplicity(Rational(1, 7), Rational(3, 49)) == 2
assert multiplicity(Rational(2, 7), Rational(7, 2)) == -1
assert multiplicity(3, Rational(1, 9)) == -2
def test_perfect_power():
assert perfect_power(0) is False
assert perfect_power(1) is False
assert perfect_power(2) is False
assert perfect_power(3) is False
assert perfect_power(4) == (2, 2)
assert perfect_power(14) is False
assert perfect_power(25) == (5, 2)
assert perfect_power(22) is False
assert perfect_power(22, [2]) is False
assert perfect_power(137**(3*5*13)) == (137, 3*5*13)
assert perfect_power(137**(3*5*13) + 1) is False
assert perfect_power(137**(3*5*13) - 1) is False
assert perfect_power(103005006004**7) == (103005006004, 7)
assert perfect_power(103005006004**7 + 1) is False
assert perfect_power(103005006004**7 - 1) is False
assert perfect_power(103005006004**12) == (103005006004, 12)
assert perfect_power(103005006004**12 + 1) is False
assert perfect_power(103005006004**12 - 1) is False
assert perfect_power(2**10007) == (2, 10007)
assert perfect_power(2**10007 + 1) is False
assert perfect_power(2**10007 - 1) is False
assert perfect_power((9**99 + 1)**60) == (9**99 + 1, 60)
assert perfect_power((9**99 + 1)**60 + 1) is False
assert perfect_power((9**99 + 1)**60 - 1) is False
assert perfect_power((10**40000)**2, big=False) == (10**40000, 2)
assert perfect_power(10**100000) == (10, 100000)
assert perfect_power(10**100001) == (10, 100001)
assert perfect_power(13**4, [3, 5]) is False
assert perfect_power(3**4, [3, 10], factor=0) is False
assert perfect_power(3**3*5**3) == (15, 3)
assert perfect_power(2**3*5**5) is False
assert perfect_power(2*13**4) is False
assert perfect_power(2**5*3**3) is False
def test_factorint():
assert primefactors(123456) == [2, 3, 643]
assert factorint(0) == {0: 1}
assert factorint(1) == {}
assert factorint(-1) == {-1: 1}
assert factorint(-2) == {-1: 1, 2: 1}
assert factorint(-16) == {-1: 1, 2: 4}
assert factorint(2) == {2: 1}
assert factorint(126) == {2: 1, 3: 2, 7: 1}
assert factorint(123456) == {2: 6, 3: 1, 643: 1}
assert factorint(5951757) == {3: 1, 7: 1, 29: 2, 337: 1}
assert factorint(64015937) == {7993: 1, 8009: 1}
assert factorint(2**(2**6) + 1) == {274177: 1, 67280421310721: 1}
assert factorint(0, multiple=True) == [0]
assert factorint(1, multiple=True) == []
assert factorint(-1, multiple=True) == [-1]
assert factorint(-2, multiple=True) == [-1, 2]
assert factorint(-16, multiple=True) == [-1, 2, 2, 2, 2]
assert factorint(2, multiple=True) == [2]
assert factorint(24, multiple=True) == [2, 2, 2, 3]
assert factorint(126, multiple=True) == [2, 3, 3, 7]
assert factorint(123456, multiple=True) == [2, 2, 2, 2, 2, 2, 3, 643]
assert factorint(5951757, multiple=True) == [3, 7, 29, 29, 337]
assert factorint(64015937, multiple=True) == [7993, 8009]
assert factorint(2**(2**6) + 1, multiple=True) == [274177, 67280421310721]
assert multiproduct(factorint(fac(200))) == fac(200)
for b, e in factorint(fac(150)).items():
assert e == fac_multiplicity(150, b)
assert factorint(103005006059**7) == {103005006059: 7}
assert factorint(31337**191) == {31337: 191}
assert factorint(2**1000 * 3**500 * 257**127 * 383**60) == \
{2: 1000, 3: 500, 257: 127, 383: 60}
assert len(factorint(fac(10000))) == 1229
assert factorint(12932983746293756928584532764589230) == \
{2: 1, 5: 1, 73: 1, 727719592270351: 1, 63564265087747: 1, 383: 1}
assert factorint(727719592270351) == {727719592270351: 1}
assert factorint(2**64 + 1, use_trial=False) == factorint(2**64 + 1)
for n in range(60000):
assert multiproduct(factorint(n)) == n
assert pollard_rho(2**64 + 1, seed=1) == 274177
assert pollard_rho(19, seed=1) is None
assert factorint(3, limit=2) == {3: 1}
assert factorint(12345) == {3: 1, 5: 1, 823: 1}
assert factorint(
12345, limit=3) == {4115: 1, 3: 1} # the 5 is greater than the limit
assert factorint(1, limit=1) == {}
assert factorint(0, 3) == {0: 1}
assert factorint(12, limit=1) == {12: 1}
assert factorint(30, limit=2) == {2: 1, 15: 1}
assert factorint(16, limit=2) == {2: 4}
assert factorint(124, limit=3) == {2: 2, 31: 1}
assert factorint(4*31**2, limit=3) == {2: 2, 31: 2}
p1 = nextprime(2**32)
p2 = nextprime(2**16)
p3 = nextprime(p2)
assert factorint(p1*p2*p3) == {p1: 1, p2: 1, p3: 1}
assert factorint(13*17*19, limit=15) == {13: 1, 17*19: 1}
assert factorint(1951*15013*15053, limit=2000) == {225990689: 1, 1951: 1}
assert factorint(primorial(17) + 1, use_pm1=0) == \
{long(19026377261): 1, 3467: 1, 277: 1, 105229: 1}
# when prime b is closer than approx sqrt(8*p) to prime p then they are
# "close" and have a trivial factorization
a = nextprime(2**2**8) # 78 digits
b = nextprime(a + 2**2**4)
assert 'Fermat' in capture(lambda: factorint(a*b, verbose=1))
raises(ValueError, lambda: pollard_rho(4))
raises(ValueError, lambda: pollard_pm1(3))
raises(ValueError, lambda: pollard_pm1(10, B=2))
# verbose coverage
n = nextprime(2**16)*nextprime(2**17)*nextprime(1901)
assert 'with primes' in capture(lambda: factorint(n, verbose=1))
capture(lambda: factorint(nextprime(2**16)*1012, verbose=1))
n = nextprime(2**17)
capture(lambda: factorint(n**3, verbose=1)) # perfect power termination
capture(lambda: factorint(2*n, verbose=1)) # factoring complete msg
# exceed 1st
n = nextprime(2**17)
n *= nextprime(n)
assert '1000' in capture(lambda: factorint(n, limit=1000, verbose=1))
n *= nextprime(n)
assert len(factorint(n)) == 3
assert len(factorint(n, limit=p1)) == 3
n *= nextprime(2*n)
# exceed 2nd
assert '2001' in capture(lambda: factorint(n, limit=2000, verbose=1))
assert capture(
lambda: factorint(n, limit=4000, verbose=1)).count('Pollard') == 2
# non-prime pm1 result
n = nextprime(8069)
n *= nextprime(2*n)*nextprime(2*n, 2)
capture(lambda: factorint(n, verbose=1)) # non-prime pm1 result
# factor fermat composite
p1 = nextprime(2**17)
p2 = nextprime(2*p1)
assert factorint((p1*p2**2)**3) == {p1: 3, p2: 6}
# Test for non integer input
raises(ValueError, lambda: factorint(4.5))
def test_divisors_and_divisor_count():
assert divisors(-1) == [1]
assert divisors(0) == []
assert divisors(1) == [1]
assert divisors(2) == [1, 2]
assert divisors(3) == [1, 3]
assert divisors(17) == [1, 17]
assert divisors(10) == [1, 2, 5, 10]
assert divisors(100) == [1, 2, 4, 5, 10, 20, 25, 50, 100]
assert divisors(101) == [1, 101]
assert divisor_count(0) == 0
assert divisor_count(-1) == 1
assert divisor_count(1) == 1
assert divisor_count(6) == 4
assert divisor_count(12) == 6
assert divisor_count(180, 3) == divisor_count(180//3)
assert divisor_count(2*3*5, 7) == 0
def test_udivisors_and_udivisor_count():
assert udivisors(-1) == [1]
assert udivisors(0) == []
assert udivisors(1) == [1]
assert udivisors(2) == [1, 2]
assert udivisors(3) == [1, 3]
assert udivisors(17) == [1, 17]
assert udivisors(10) == [1, 2, 5, 10]
assert udivisors(100) == [1, 4, 25, 100]
assert udivisors(101) == [1, 101]
assert udivisors(1000) == [1, 8, 125, 1000]
assert udivisor_count(0) == 0
assert udivisor_count(-1) == 1
assert udivisor_count(1) == 1
assert udivisor_count(6) == 4
assert udivisor_count(12) == 4
assert udivisor_count(180) == 8
assert udivisor_count(2*3*5*7) == 16
def test_issue_6981():
S = set(divisors(4)).union(set(divisors(Integer(2))))
assert S == {1,2,4}
def test_totient():
assert [totient(k) for k in range(1, 12)] == \
[1, 1, 2, 2, 4, 2, 6, 4, 6, 4, 10]
assert totient(5005) == 2880
assert totient(5006) == 2502
assert totient(5009) == 5008
assert totient(2**100) == 2**99
m = Symbol("m", integer=True)
assert totient(m)
assert totient(m).subs(m, 3**10) == 3**10 - 3**9
assert summation(totient(m), (m, 1, 11)) == 42
n = Symbol("n", integer=True, positive=True)
assert totient(n).is_integer
def test_reduced_totient():
assert [reduced_totient(k) for k in range(1, 16)] == \
[1, 1, 2, 2, 4, 2, 6, 2, 6, 4, 10, 2, 12, 6, 4]
assert reduced_totient(5005) == 60
assert reduced_totient(5006) == 2502
assert reduced_totient(5009) == 5008
assert reduced_totient(2**100) == 2**98
m = Symbol("m", integer=True)
assert reduced_totient(m)
assert reduced_totient(m).subs(m, 2**3*3**10) == 3**10 - 3**9
assert summation(reduced_totient(m), (m, 1, 16)) == 68
n = Symbol("n", integer=True, positive=True)
assert reduced_totient(n).is_integer
def test_divisor_sigma():
assert [divisor_sigma(k) for k in range(1, 12)] == \
[1, 3, 4, 7, 6, 12, 8, 15, 13, 18, 12]
assert [divisor_sigma(k, 2) for k in range(1, 12)] == \
[1, 5, 10, 21, 26, 50, 50, 85, 91, 130, 122]
assert divisor_sigma(23450) == 50592
assert divisor_sigma(23450, 0) == 24
assert divisor_sigma(23450, 1) == 50592
assert divisor_sigma(23450, 2) == 730747500
assert divisor_sigma(23450, 3) == 14666785333344
m = Symbol("m", integer=True)
k = Symbol("k", integer=True)
assert divisor_sigma(m)
assert divisor_sigma(m, k)
assert divisor_sigma(m).subs(m, 3**10) == 88573
assert divisor_sigma(m, k).subs([(m, 3**10), (k, 3)]) == 213810021790597
assert summation(divisor_sigma(m), (m, 1, 11)) == 99
def test_udivisor_sigma():
assert [udivisor_sigma(k) for k in range(1, 12)] == \
[1, 3, 4, 5, 6, 12, 8, 9, 10, 18, 12]
assert [udivisor_sigma(k, 3) for k in range(1, 12)] == \
[1, 9, 28, 65, 126, 252, 344, 513, 730, 1134, 1332]
assert udivisor_sigma(23450) == 42432
assert udivisor_sigma(23450, 0) == 16
assert udivisor_sigma(23450, 1) == 42432
assert udivisor_sigma(23450, 2) == 702685000
assert udivisor_sigma(23450, 4) == 321426961814978248
m = Symbol("m", integer=True)
k = Symbol("k", integer=True)
assert udivisor_sigma(m)
assert udivisor_sigma(m, k)
assert udivisor_sigma(m).subs(m, 4**9) == 262145
assert udivisor_sigma(m, k).subs([(m, 4**9), (k, 2)]) == 68719476737
assert summation(udivisor_sigma(m), (m, 2, 15)) == 169
def test_issue_4356():
assert factorint(1030903) == {53: 2, 367: 1}
def test_divisors():
assert divisors(28) == [1, 2, 4, 7, 14, 28]
assert [x for x in divisors(3*5*7, 1)] == [1, 3, 5, 15, 7, 21, 35, 105]
assert divisors(0) == []
def test_divisor_count():
assert divisor_count(0) == 0
assert divisor_count(6) == 4
def test_antidivisors():
assert antidivisors(-1) == []
assert antidivisors(-3) == [2]
assert antidivisors(14) == [3, 4, 9]
assert antidivisors(237) == [2, 5, 6, 11, 19, 25, 43, 95, 158]
assert antidivisors(12345) == [2, 6, 7, 10, 30, 1646, 3527, 4938, 8230]
assert antidivisors(393216) == [262144]
assert sorted(x for x in antidivisors(3*5*7, 1)) == \
[2, 6, 10, 11, 14, 19, 30, 42, 70]
assert antidivisors(1) == []
def test_antidivisor_count():
assert antidivisor_count(0) == 0
assert antidivisor_count(-1) == 0
assert antidivisor_count(-4) == 1
assert antidivisor_count(20) == 3
assert antidivisor_count(25) == 5
assert antidivisor_count(38) == 7
assert antidivisor_count(180) == 6
assert antidivisor_count(2*3*5) == 3
def test_smoothness_and_smoothness_p():
assert smoothness(1) == (1, 1)
assert smoothness(2**4*3**2) == (3, 16)
assert smoothness_p(10431, m=1) == \
(1, [(3, (2, 2, 4)), (19, (1, 5, 5)), (61, (1, 31, 31))])
assert smoothness_p(10431) == \
(-1, [(3, (2, 2, 2)), (19, (1, 3, 9)), (61, (1, 5, 5))])
assert smoothness_p(10431, power=1) == \
(-1, [(3, (2, 2, 2)), (61, (1, 5, 5)), (19, (1, 3, 9))])
assert smoothness_p(21477639576571, visual=1) == \
'p**i=4410317**1 has p-1 B=1787, B-pow=1787\n' + \
'p**i=4869863**1 has p-1 B=2434931, B-pow=2434931'
def test_visual_factorint():
assert factorint(1, visual=1) == 1
forty2 = factorint(42, visual=True)
assert type(forty2) == Mul
assert str(forty2) == '2**1*3**1*7**1'
assert factorint(1, visual=True) is S.One
no = dict(evaluate=False)
assert factorint(42**2, visual=True) == Mul(Pow(2, 2, **no),
Pow(3, 2, **no),
Pow(7, 2, **no), **no)
assert -1 in factorint(-42, visual=True).args
def test_factorrat():
assert str(factorrat(S(12)/1, visual=True)) == '2**2*3**1'
assert str(factorrat(S(1)/1, visual=True)) == '1'
assert str(factorrat(S(25)/14, visual=True)) == '5**2/(2*7)'
assert str(factorrat(S(-25)/14/9, visual=True)) == '-5**2/(2*3**2*7)'
assert factorrat(S(12)/1, multiple=True) == [2, 2, 3]
assert factorrat(S(1)/1, multiple=True) == []
assert factorrat(S(25)/14, multiple=True) == [1/7, 1/2, 5, 5]
assert factorrat(S(12)/1, multiple=True) == [2, 2, 3]
assert factorrat(S(-25)/14/9, multiple=True) == \
[-1, 1/7, 1/3, 1/3, 1/2, 5, 5]
def test_visual_io():
sm = smoothness_p
fi = factorint
# with smoothness_p
n = 124
d = fi(n)
m = fi(d, visual=True)
t = sm(n)
s = sm(t)
for th in [d, s, t, n, m]:
assert sm(th, visual=True) == s
assert sm(th, visual=1) == s
for th in [d, s, t, n, m]:
assert sm(th, visual=False) == t
assert [sm(th, visual=None) for th in [d, s, t, n, m]] == [s, d, s, t, t]
assert [sm(th, visual=2) for th in [d, s, t, n, m]] == [s, d, s, t, t]
# with factorint
for th in [d, m, n]:
assert fi(th, visual=True) == m
assert fi(th, visual=1) == m
for th in [d, m, n]:
assert fi(th, visual=False) == d
assert [fi(th, visual=None) for th in [d, m, n]] == [m, d, d]
assert [fi(th, visual=0) for th in [d, m, n]] == [m, d, d]
# test reevaluation
no = dict(evaluate=False)
assert sm({4: 2}, visual=False) == sm(16)
assert sm(Mul(*[Pow(k, v, **no) for k, v in {4: 2, 2: 6}.items()], **no),
visual=False) == sm(2**10)
assert fi({4: 2}, visual=False) == fi(16)
assert fi(Mul(*[Pow(k, v, **no) for k, v in {4: 2, 2: 6}.items()], **no),
visual=False) == fi(2**10)
def test_core():
assert core(35**13, 10) == 42875
assert core(210**2) == 1
assert core(7776, 3) == 36
assert core(10**27, 22) == 10**5
assert core(537824) == 14
assert core(1, 6) == 1
def test_digits():
assert all([digits(n, 2)[1:] == [int(d) for d in format(n, 'b')]
for n in range(20)])
assert all([digits(n, 8)[1:] == [int(d) for d in format(n, 'o')]
for n in range(20)])
assert all([digits(n, 16)[1:] == [int(d, 16) for d in format(n, 'x')]
for n in range(20)])
assert digits(2345, 34) == [34, 2, 0, 33]
assert digits(384753, 71) == [71, 1, 5, 23, 4]
assert digits(93409) == [10, 9, 3, 4, 0, 9]
assert digits(-92838, 11) == [-11, 6, 3, 8, 2, 9]
def test_primenu():
assert primenu(2) == 1
assert primenu(2 * 3) == 2
assert primenu(2 * 3 * 5) == 3
assert primenu(3 * 25) == primenu(3) + primenu(25)
assert [primenu(p) for p in primerange(1, 10)] == [1, 1, 1, 1]
assert primenu(fac(50)) == 15
assert primenu(2 ** 9941 - 1) == 1
n = Symbol('n', integer=True)
assert primenu(n)
assert primenu(n).subs(n, 2 ** 31 - 1) == 1
assert summation(primenu(n), (n, 2, 30)) == 43
def test_primeomega():
assert primeomega(2) == 1
assert primeomega(2 * 2) == 2
assert primeomega(2 * 2 * 3) == 3
assert primeomega(3 * 25) == primeomega(3) + primeomega(25)
assert [primeomega(p) for p in primerange(1, 10)] == [1, 1, 1, 1]
assert primeomega(fac(50)) == 108
assert primeomega(2 ** 9941 - 1) == 1
n = Symbol('n', integer=True)
assert primeomega(n)
assert primeomega(n).subs(n, 2 ** 31 - 1) == 1
assert summation(primeomega(n), (n, 2, 30)) == 59
| 19,757 | 36 | 78 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/ntheory/tests/test_bbp_pi.py
|
from random import randint
from sympy.ntheory.bbp_pi import pi_hex_digits
from sympy.utilities.pytest import raises
# http://www.herongyang.com/Cryptography/Blowfish-First-8366-Hex-Digits-of-PI.html
# There are actually 8336 listed there; with the preppended 3 there are 8337
# below
dig=''.join('''
3243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89452821e638d013
77be5466cf34e90c6cc0ac29b7c97c50dd3f84d5b5b54709179216d5d98979fb1bd1310ba698dfb5
ac2ffd72dbd01adfb7b8e1afed6a267e96ba7c9045f12c7f9924a19947b3916cf70801f2e2858efc
16636920d871574e69a458fea3f4933d7e0d95748f728eb658718bcd5882154aee7b54a41dc25a59
b59c30d5392af26013c5d1b023286085f0ca417918b8db38ef8e79dcb0603a180e6c9e0e8bb01e8a
3ed71577c1bd314b2778af2fda55605c60e65525f3aa55ab945748986263e8144055ca396a2aab10
b6b4cc5c341141e8cea15486af7c72e993b3ee1411636fbc2a2ba9c55d741831f6ce5c3e169b8793
1eafd6ba336c24cf5c7a325381289586773b8f48986b4bb9afc4bfe81b6628219361d809ccfb21a9
91487cac605dec8032ef845d5de98575b1dc262302eb651b8823893e81d396acc50f6d6ff383f442
392e0b4482a484200469c8f04a9e1f9b5e21c66842f6e96c9a670c9c61abd388f06a51a0d2d8542f
68960fa728ab5133a36eef0b6c137a3be4ba3bf0507efb2a98a1f1651d39af017666ca593e82430e
888cee8619456f9fb47d84a5c33b8b5ebee06f75d885c12073401a449f56c16aa64ed3aa62363f77
061bfedf72429b023d37d0d724d00a1248db0fead349f1c09b075372c980991b7b25d479d8f6e8de
f7e3fe501ab6794c3b976ce0bd04c006bac1a94fb6409f60c45e5c9ec2196a246368fb6faf3e6c53
b51339b2eb3b52ec6f6dfc511f9b30952ccc814544af5ebd09bee3d004de334afd660f2807192e4b
b3c0cba85745c8740fd20b5f39b9d3fbdb5579c0bd1a60320ad6a100c6402c7279679f25fefb1fa3
cc8ea5e9f8db3222f83c7516dffd616b152f501ec8ad0552ab323db5fafd23876053317b483e00df
829e5c57bbca6f8ca01a87562edf1769dbd542a8f6287effc3ac6732c68c4f5573695b27b0bbca58
c8e1ffa35db8f011a010fa3d98fd2183b84afcb56c2dd1d35b9a53e479b6f84565d28e49bc4bfb97
90e1ddf2daa4cb7e3362fb1341cee4c6e8ef20cada36774c01d07e9efe2bf11fb495dbda4dae9091
98eaad8e716b93d5a0d08ed1d0afc725e08e3c5b2f8e7594b78ff6e2fbf2122b648888b812900df0
1c4fad5ea0688fc31cd1cff191b3a8c1ad2f2f2218be0e1777ea752dfe8b021fa1e5a0cc0fb56f74
e818acf3d6ce89e299b4a84fe0fd13e0b77cc43b81d2ada8d9165fa2668095770593cc7314211a14
77e6ad206577b5fa86c75442f5fb9d35cfebcdaf0c7b3e89a0d6411bd3ae1e7e4900250e2d2071b3
5e226800bb57b8e0af2464369bf009b91e5563911d59dfa6aa78c14389d95a537f207d5ba202e5b9
c5832603766295cfa911c819684e734a41b3472dca7b14a94a1b5100529a532915d60f573fbc9bc6
e42b60a47681e6740008ba6fb5571be91ff296ec6b2a0dd915b6636521e7b9f9b6ff34052ec58556
6453b02d5da99f8fa108ba47996e85076a4b7a70e9b5b32944db75092ec4192623ad6ea6b049a7df
7d9cee60b88fedb266ecaa8c71699a17ff5664526cc2b19ee1193602a575094c29a0591340e4183a
3e3f54989a5b429d656b8fe4d699f73fd6a1d29c07efe830f54d2d38e6f0255dc14cdd20868470eb
266382e9c6021ecc5e09686b3f3ebaefc93c9718146b6a70a1687f358452a0e286b79c5305aa5007
373e07841c7fdeae5c8e7d44ec5716f2b8b03ada37f0500c0df01c1f040200b3ffae0cf51a3cb574
b225837a58dc0921bdd19113f97ca92ff69432477322f547013ae5e58137c2dadcc8b576349af3dd
a7a94461460fd0030eecc8c73ea4751e41e238cd993bea0e2f3280bba1183eb3314e548b384f6db9
086f420d03f60a04bf2cb8129024977c795679b072bcaf89afde9a771fd9930810b38bae12dccf3f
2e5512721f2e6b7124501adde69f84cd877a5847187408da17bc9f9abce94b7d8cec7aec3adb851d
fa63094366c464c3d2ef1c18473215d908dd433b3724c2ba1612a14d432a65c45150940002133ae4
dd71dff89e10314e5581ac77d65f11199b043556f1d7a3c76b3c11183b5924a509f28fe6ed97f1fb
fa9ebabf2c1e153c6e86e34570eae96fb1860e5e0a5a3e2ab3771fe71c4e3d06fa2965dcb999e71d
0f803e89d65266c8252e4cc9789c10b36ac6150eba94e2ea78a5fc3c531e0a2df4f2f74ea7361d2b
3d1939260f19c279605223a708f71312b6ebadfe6eeac31f66e3bc4595a67bc883b17f37d1018cff
28c332ddefbe6c5aa56558218568ab9802eecea50fdb2f953b2aef7dad5b6e2f841521b628290761
70ecdd4775619f151013cca830eb61bd960334fe1eaa0363cfb5735c904c70a239d59e9e0bcbaade
14eecc86bc60622ca79cab5cabb2f3846e648b1eaf19bdf0caa02369b9655abb5040685a323c2ab4
b3319ee9d5c021b8f79b540b19875fa09995f7997e623d7da8f837889a97e32d7711ed935f166812
810e358829c7e61fd696dedfa17858ba9957f584a51b2272639b83c3ff1ac24696cdb30aeb532e30
548fd948e46dbc312858ebf2ef34c6ffeafe28ed61ee7c3c735d4a14d9e864b7e342105d14203e13
e045eee2b6a3aaabeadb6c4f15facb4fd0c742f442ef6abbb5654f3b1d41cd2105d81e799e86854d
c7e44b476a3d816250cf62a1f25b8d2646fc8883a0c1c7b6a37f1524c369cb749247848a0b5692b2
85095bbf00ad19489d1462b17423820e0058428d2a0c55f5ea1dadf43e233f70613372f0928d937e
41d65fecf16c223bdb7cde3759cbee74604085f2a7ce77326ea607808419f8509ee8efd85561d997
35a969a7aac50c06c25a04abfc800bcadc9e447a2ec3453484fdd567050e1e9ec9db73dbd3105588
cd675fda79e3674340c5c43465713e38d83d28f89ef16dff20153e21e78fb03d4ae6e39f2bdb83ad
f7e93d5a68948140f7f64c261c94692934411520f77602d4f7bcf46b2ed4a20068d40824713320f4
6a43b7d4b7500061af1e39f62e9724454614214f74bf8b88404d95fc1d96b591af70f4ddd366a02f
45bfbc09ec03bd97857fac6dd031cb850496eb27b355fd3941da2547e6abca0a9a28507825530429
f40a2c86dae9b66dfb68dc1462d7486900680ec0a427a18dee4f3ffea2e887ad8cb58ce0067af4d6
b6aace1e7cd3375fecce78a399406b2a4220fe9e35d9f385b9ee39d7ab3b124e8b1dc9faf74b6d18
5626a36631eae397b23a6efa74dd5b43326841e7f7ca7820fbfb0af54ed8feb397454056acba4895
2755533a3a20838d87fe6ba9b7d096954b55a867bca1159a58cca9296399e1db33a62a4a563f3125
f95ef47e1c9029317cfdf8e80204272f7080bb155c05282ce395c11548e4c66d2248c1133fc70f86
dc07f9c9ee41041f0f404779a45d886e17325f51ebd59bc0d1f2bcc18f41113564257b7834602a9c
60dff8e8a31f636c1b0e12b4c202e1329eaf664fd1cad181156b2395e0333e92e13b240b62eebeb9
2285b2a20ee6ba0d99de720c8c2da2f728d012784595b794fd647d0862e7ccf5f05449a36f877d48
fac39dfd27f33e8d1e0a476341992eff743a6f6eabf4f8fd37a812dc60a1ebddf8991be14cdb6e6b
0dc67b55106d672c372765d43bdcd0e804f1290dc7cc00ffa3b5390f92690fed0b667b9ffbcedb7d
9ca091cf0bd9155ea3bb132f88515bad247b9479bf763bd6eb37392eb3cc1159798026e297f42e31
2d6842ada7c66a2b3b12754ccc782ef11c6a124237b79251e706a1bbe64bfb63501a6b101811caed
fa3d25bdd8e2e1c3c9444216590a121386d90cec6ed5abea2a64af674eda86a85fbebfe98864e4c3
fe9dbc8057f0f7c08660787bf86003604dd1fd8346f6381fb07745ae04d736fccc83426b33f01eab
71b08041873c005e5f77a057bebde8ae2455464299bf582e614e58f48ff2ddfda2f474ef388789bd
c25366f9c3c8b38e74b475f25546fcd9b97aeb26618b1ddf84846a0e79915f95e2466e598e20b457
708cd55591c902de4cb90bace1bb8205d011a862487574a99eb77f19b6e0a9dc09662d09a1c43246
33e85a1f0209f0be8c4a99a0251d6efe101ab93d1d0ba5a4dfa186f20f2868f169dcb7da83573906
fea1e2ce9b4fcd7f5250115e01a70683faa002b5c40de6d0279af88c27773f8641c3604c0661a806
b5f0177a28c0f586e0006058aa30dc7d6211e69ed72338ea6353c2dd94c2c21634bbcbee5690bcb6
deebfc7da1ce591d766f05e4094b7c018839720a3d7c927c2486e3725f724d9db91ac15bb4d39eb8
fced54557808fca5b5d83d7cd34dad0fc41e50ef5eb161e6f8a28514d96c51133c6fd5c7e756e14e
c4362abfceddc6c837d79a323492638212670efa8e406000e03a39ce37d3faf5cfabc277375ac52d
1b5cb0679e4fa33742d382274099bc9bbed5118e9dbf0f7315d62d1c7ec700c47bb78c1b6b21a190
45b26eb1be6a366eb45748ab2fbc946e79c6a376d26549c2c8530ff8ee468dde7dd5730a1d4cd04d
c62939bbdba9ba4650ac9526e8be5ee304a1fad5f06a2d519a63ef8ce29a86ee22c089c2b843242e
f6a51e03aa9cf2d0a483c061ba9be96a4d8fe51550ba645bd62826a2f9a73a3ae14ba99586ef5562
e9c72fefd3f752f7da3f046f6977fa0a5980e4a91587b086019b09e6ad3b3ee593e990fd5a9e34d7
972cf0b7d9022b8b5196d5ac3a017da67dd1cf3ed67c7d2d281f9f25cfadf2b89b5ad6b4725a88f5
4ce029ac71e019a5e647b0acfded93fa9be8d3c48d283b57ccf8d5662979132e28785f0191ed7560
55f7960e44e3d35e8c15056dd488f46dba03a161250564f0bdc3eb9e153c9057a297271aeca93a07
2a1b3f6d9b1e6321f5f59c66fb26dcf3197533d928b155fdf5035634828aba3cbb28517711c20ad9
f8abcc5167ccad925f4de817513830dc8e379d58629320f991ea7a90c2fb3e7bce5121ce64774fbe
32a8b6e37ec3293d4648de53696413e680a2ae0810dd6db22469852dfd09072166b39a460a6445c0
dd586cdecf1c20c8ae5bbef7dd1b588d40ccd2017f6bb4e3bbdda26a7e3a59ff453e350a44bcb4cd
d572eacea8fa6484bb8d6612aebf3c6f47d29be463542f5d9eaec2771bf64e6370740e0d8de75b13
57f8721671af537d5d4040cb084eb4e2cc34d2466a0115af84e1b0042895983a1d06b89fb4ce6ea0
486f3f3b823520ab82011a1d4b277227f8611560b1e7933fdcbb3a792b344525bda08839e151ce79
4b2f32c9b7a01fbac9e01cc87ebcc7d1f6cf0111c3a1e8aac71a908749d44fbd9ad0dadecbd50ada
380339c32ac69136678df9317ce0b12b4ff79e59b743f5bb3af2d519ff27d9459cbf97222c15e6fc
2a0f91fc719b941525fae59361ceb69cebc2a8645912baa8d1b6c1075ee3056a0c10d25065cb03a4
42e0ec6e0e1698db3b4c98a0be3278e9649f1f9532e0d392dfd3a0342b8971f21e1b0a74414ba334
8cc5be7120c37632d8df359f8d9b992f2ee60b6f470fe3f11de54cda541edad891ce6279cfcd3e7e
6f1618b166fd2c1d05848fd2c5f6fb2299f523f357a632762393a8353156cccd02acf081625a75eb
b56e16369788d273ccde96629281b949d04c50901b71c65614e6c6c7bd327a140a45e1d006c3f27b
9ac9aa53fd62a80f00bb25bfe235bdd2f671126905b2040222b6cbcf7ccd769c2b53113ec01640e3
d338abbd602547adf0ba38209cf746ce7677afa1c52075606085cbfe4e8ae88dd87aaaf9b04cf9aa
7e1948c25c02fb8a8c01c36ae4d6ebe1f990d4f869a65cdea03f09252dc208e69fb74e6132ce77e2
5b578fdfe33ac372e6'''.split())
def test_hex_pi_nth_digits():
assert pi_hex_digits(0) == '3243f6a8885a30'
assert pi_hex_digits(1) == '243f6a8885a308'
assert pi_hex_digits(10000) == '68ac8fcfb8016c'
assert pi_hex_digits(13) == '08d313198a2e03'
assert pi_hex_digits(0, 3) == '324'
assert pi_hex_digits(0, 0) == ''
raises(ValueError, lambda: pi_hex_digits(-1))
raises(ValueError, lambda: pi_hex_digits(3.14))
# this will pick a random segment to compute every time
# it is run. If it ever fails, there is an error in the
# computation.
n = randint(0, len(dig))
prec = randint(0, len(dig) - n)
assert pi_hex_digits(n, prec) == dig[n: n + prec]
| 9,425 | 69.343284 | 82 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/ntheory/tests/__init__.py
| 0 | 0 | 0 |
py
|
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/ntheory/tests/test_primetest.py
|
from sympy.core.compatibility import range
from sympy.ntheory.generate import Sieve, sieve
from sympy.ntheory.primetest import (mr, is_lucas_prp, is_square,
is_strong_lucas_prp, is_extra_strong_lucas_prp, isprime)
from sympy.utilities.pytest import slow
@slow
def test_prps():
oddcomposites = [n for n in range(1, 10**5) if
n % 2 and not isprime(n)]
# A checksum would be better.
assert sum(oddcomposites) == 2045603465
assert [n for n in oddcomposites if mr(n, [2])] == [
2047, 3277, 4033, 4681, 8321, 15841, 29341, 42799, 49141,
52633, 65281, 74665, 80581, 85489, 88357, 90751]
assert [n for n in oddcomposites if mr(n, [3])] == [
121, 703, 1891, 3281, 8401, 8911, 10585, 12403, 16531,
18721, 19345, 23521, 31621, 44287, 47197, 55969, 63139,
74593, 79003, 82513, 87913, 88573, 97567]
assert [n for n in oddcomposites if mr(n, [325])] == [
9, 25, 27, 49, 65, 81, 325, 341, 343, 697, 1141, 2059,
2149, 3097, 3537, 4033, 4681, 4941, 5833, 6517, 7987, 8911,
12403, 12913, 15043, 16021, 20017, 22261, 23221, 24649,
24929, 31841, 35371, 38503, 43213, 44173, 47197, 50041,
55909, 56033, 58969, 59089, 61337, 65441, 68823, 72641,
76793, 78409, 85879]
assert not any(mr(n, [9345883071009581737]) for n in oddcomposites)
assert [n for n in oddcomposites if is_lucas_prp(n)] == [
323, 377, 1159, 1829, 3827, 5459, 5777, 9071, 9179, 10877,
11419, 11663, 13919, 14839, 16109, 16211, 18407, 18971,
19043, 22499, 23407, 24569, 25199, 25877, 26069, 27323,
32759, 34943, 35207, 39059, 39203, 39689, 40309, 44099,
46979, 47879, 50183, 51983, 53663, 56279, 58519, 60377,
63881, 69509, 72389, 73919, 75077, 77219, 79547, 79799,
82983, 84419, 86063, 90287, 94667, 97019, 97439]
assert [n for n in oddcomposites if is_strong_lucas_prp(n)] == [
5459, 5777, 10877, 16109, 18971, 22499, 24569, 25199, 40309,
58519, 75077, 97439]
assert [n for n in oddcomposites if is_extra_strong_lucas_prp(n)
] == [
989, 3239, 5777, 10877, 27971, 29681, 30739, 31631, 39059,
72389, 73919, 75077]
def test_isprime():
s = Sieve()
s.extend(100000)
ps = set(s.primerange(2, 100001))
for n in range(100001):
# if (n in ps) != isprime(n): print n
assert (n in ps) == isprime(n)
assert isprime(179424673)
assert isprime(20678048681)
assert isprime(1968188556461)
assert isprime(2614941710599)
assert isprime(65635624165761929287)
assert isprime(1162566711635022452267983)
assert isprime(77123077103005189615466924501)
assert isprime(3991617775553178702574451996736229)
assert isprime(273952953553395851092382714516720001799)
assert isprime(int('''
531137992816767098689588206552468627329593117727031923199444138200403\
559860852242739162502265229285668889329486246501015346579337652707239\
409519978766587351943831270835393219031728127'''))
# Some Mersenne primes
assert isprime(2**61 - 1)
assert isprime(2**89 - 1)
assert isprime(2**607 - 1)
# (but not all Mersenne's are primes
assert not isprime(2**601 - 1)
# pseudoprimes
#-------------
# to some small bases
assert not isprime(2152302898747)
assert not isprime(3474749660383)
assert not isprime(341550071728321)
assert not isprime(3825123056546413051)
# passes the base set [2, 3, 7, 61, 24251]
assert not isprime(9188353522314541)
# large examples
assert not isprime(877777777777777777777777)
# conjectured psi_12 given at http://mathworld.wolfram.com/StrongPseudoprime.html
assert not isprime(318665857834031151167461)
# conjectured psi_17 given at http://mathworld.wolfram.com/StrongPseudoprime.html
assert not isprime(564132928021909221014087501701)
# Arnault's 1993 number; a factor of it is
# 400958216639499605418306452084546853005188166041132508774506\
# 204738003217070119624271622319159721973358216316508535816696\
# 9145233813917169287527980445796800452592031836601
assert not isprime(int('''
803837457453639491257079614341942108138837688287558145837488917522297\
427376533365218650233616396004545791504202360320876656996676098728404\
396540823292873879185086916685732826776177102938969773947016708230428\
687109997439976544144845341155872450633409279022275296229414984230688\
1685404326457534018329786111298960644845216191652872597534901'''))
# Arnault's 1995 number; can be factored as
# p1*(313*(p1 - 1) + 1)*(353*(p1 - 1) + 1) where p1 is
# 296744956686855105501541746429053327307719917998530433509950\
# 755312768387531717701995942385964281211880336647542183455624\
# 93168782883
assert not isprime(int('''
288714823805077121267142959713039399197760945927972270092651602419743\
230379915273311632898314463922594197780311092934965557841894944174093\
380561511397999942154241693397290542371100275104208013496673175515285\
922696291677532547504444585610194940420003990443211677661994962953925\
045269871932907037356403227370127845389912612030924484149472897688540\
6024976768122077071687938121709811322297802059565867'''))
sieve.extend(3000)
assert isprime(2819)
assert not isprime(2931)
def test_is_square():
assert [i for i in range(25) if is_square(i)] == [0, 1, 4, 9, 16]
| 5,365 | 43.716667 | 85 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/ntheory/tests/test_modular.py
|
from sympy.core.singleton import S
from sympy.core.symbol import Symbol
from sympy.ntheory.modular import crt, crt1, crt2, solve_congruence
from sympy.utilities.pytest import raises
def test_crt():
def mcrt(m, v, r, symmetric=False):
assert crt(m, v, symmetric)[0] == r
mm, e, s = crt1(m)
assert crt2(m, v, mm, e, s, symmetric) == (r, mm)
mcrt([2, 3, 5], [0, 0, 0], 0)
mcrt([2, 3, 5], [1, 1, 1], 1)
mcrt([2, 3, 5], [-1, -1, -1], -1, True)
mcrt([2, 3, 5], [-1, -1, -1], 2*3*5 - 1, False)
assert crt([656, 350], [811, 133], symmetric=True) == (-56917, 114800)
def test_modular():
assert solve_congruence(*list(zip([3, 4, 2], [12, 35, 17]))) == (1719, 7140)
assert solve_congruence(*list(zip([3, 4, 2], [12, 6, 17]))) is None
assert solve_congruence(*list(zip([3, 4, 2], [13, 7, 17]))) == (172, 1547)
assert solve_congruence(*list(zip([-10, -3, -15], [13, 7, 17]))) == (172, 1547)
assert solve_congruence(*list(zip([-10, -3, 1, -15], [13, 7, 7, 17]))) is None
assert solve_congruence(
*list(zip([-10, -5, 2, -15], [13, 7, 7, 17]))) == (835, 1547)
assert solve_congruence(
*list(zip([-10, -5, 2, -15], [13, 7, 14, 17]))) == (2382, 3094)
assert solve_congruence(
*list(zip([-10, 2, 2, -15], [13, 7, 14, 17]))) == (2382, 3094)
assert solve_congruence(*list(zip((1, 1, 2), (3, 2, 4)))) is None
raises(
ValueError, lambda: solve_congruence(*list(zip([3, 4, 2], [12.1, 35, 17]))))
| 1,499 | 39.540541 | 84 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/benchmarks/bench_symbench.py
|
#!/usr/bin/env python
from __future__ import print_function, division
from sympy.core.compatibility import range
from random import random
from sympy import factor, I, Integer, pi, simplify, sin, sqrt, Symbol, sympify
from sympy.abc import x, y, z
from timeit import default_timer as clock
def bench_R1():
"real(f(f(f(f(f(f(f(f(f(f(i/2)))))))))))"
def f(z):
return sqrt(Integer(1)/3)*z**2 + I/3
e = f(f(f(f(f(f(f(f(f(f(I/2)))))))))).as_real_imag()[0]
def bench_R2():
"Hermite polynomial hermite(15, y)"
def hermite(n, y):
if n == 1:
return 2*y
if n == 0:
return 1
return (2*y*hermite(n - 1, y) - 2*(n - 1)*hermite(n - 2, y)).expand()
a = hermite(15, y)
def bench_R3():
"a = [bool(f==f) for _ in range(10)]"
f = x + y + z
a = [bool(f == f) for _ in range(10)]
def bench_R4():
# we don't have Tuples
pass
def bench_R5():
"blowup(L, 8); L=uniq(L)"
def blowup(L, n):
for i in range(n):
L.append( (L[i] + L[i + 1]) * L[i + 2] )
def uniq(x):
v = set(x)
return v
L = [x, y, z]
blowup(L, 8)
L = uniq(L)
def bench_R6():
"sum(simplify((x+sin(i))/x+(x-sin(i))/x) for i in range(100))"
s = sum(simplify((x + sin(i))/x + (x - sin(i))/x) for i in range(100))
def bench_R7():
"[f.subs(x, random()) for _ in range(10**4)]"
f = x**24 + 34*x**12 + 45*x**3 + 9*x**18 + 34*x**10 + 32*x**21
a = [f.subs(x, random()) for _ in range(10**4)]
def bench_R8():
"right(x^2,0,5,10^4)"
def right(f, a, b, n):
a = sympify(a)
b = sympify(b)
n = sympify(n)
x = f.atoms(Symbol).pop()
Deltax = (b - a)/n
c = a
est = 0
for i in range(n):
c += Deltax
est += f.subs(x, c)
return est*Deltax
a = right(x**2, 0, 5, 10**4)
def _bench_R9():
"factor(x^20 - pi^5*y^20)"
factor(x**20 - pi**5*y**20)
def bench_R10():
"v = [-pi,-pi+1/10..,pi]"
def srange(min, max, step):
v = [min]
while (max - v[-1]).evalf() > 0:
v.append(v[-1] + step)
return v[:-1]
v = srange(-pi, pi, sympify(1)/10)
def bench_R11():
"a = [random() + random()*I for w in [0..1000]]"
a = [random() + random()*I for w in range(1000)]
def bench_S1():
"e=(x+y+z+1)**7;f=e*(e+1);f.expand()"
e = (x + y + z + 1)**7
f = e*(e + 1)
f = f.expand()
if __name__ == '__main__':
benchmarks = [
bench_R1,
bench_R2,
bench_R3,
bench_R5,
bench_R6,
bench_R7,
bench_R8,
#_bench_R9,
bench_R10,
bench_R11,
#bench_S1,
]
report = []
for b in benchmarks:
t = clock()
b()
t = clock() - t
print("%s%65s: %f" % (b.__name__, b.__doc__, t))
| 2,868 | 20.734848 | 78 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/benchmarks/bench_meijerint.py
|
# conceal the implicit import from the code quality tester
from __future__ import print_function, division
exec("from sympy import *")
LT = laplace_transform
FT = fourier_transform
MT = mellin_transform
IFT = inverse_fourier_transform
ILT = inverse_laplace_transform
IMT = inverse_mellin_transform
from sympy.abc import t, x, y
nu, beta, rho = symbols('nu beta rho')
apos, bpos, cpos, dpos, posk, p = symbols('a b c d k p', positive=True)
k = Symbol('k', real=True)
negk = Symbol('k', negative=True)
mu1, mu2 = symbols('mu1 mu2', real=True, nonzero=True, finite=True)
sigma1, sigma2 = symbols('sigma1 sigma2', real=True, nonzero=True,
finite=True, positive=True)
rate = Symbol('lambda', real=True, positive=True, finite=True)
def normal(x, mu, sigma):
return 1/sqrt(2*pi*sigma**2)*exp(-(x - mu)**2/2/sigma**2)
def exponential(x, rate):
return rate*exp(-rate*x)
alpha, beta = symbols('alpha beta', positive=True)
betadist = x**(alpha - 1)*(1 + x)**(-alpha - beta)*gamma(alpha + beta) \
/gamma(alpha)/gamma(beta)
kint = Symbol('k', integer=True, positive=True)
chi = 2**(1 - kint/2)*x**(kint - 1)*exp(-x**2/2)/gamma(kint/2)
chisquared = 2**(-k/2)/gamma(k/2)*x**(k/2 - 1)*exp(-x/2)
dagum = apos*p/x*(x/bpos)**(apos*p)/(1 + x**apos/bpos**apos)**(p + 1)
d1, d2 = symbols('d1 d2', positive=True)
f = sqrt(((d1*x)**d1 * d2**d2)/(d1*x + d2)**(d1 + d2))/x \
/gamma(d1/2)/gamma(d2/2)*gamma((d1 + d2)/2)
nupos, sigmapos = symbols('nu sigma', positive=True)
rice = x/sigmapos**2*exp(-(x**2 + nupos**2)/2/sigmapos**2)*besseli(0, x*
nupos/sigmapos**2)
mu = Symbol('mu', real=True)
laplace = exp(-abs(x - mu)/bpos)/2/bpos
u = Symbol('u', polar=True)
tpos = Symbol('t', positive=True)
def E(expr):
res1 = integrate(expr*exponential(x, rate)*normal(y, mu1, sigma1),
(x, 0, oo), (y, -oo, oo), meijerg=True)
res2 = integrate(expr*exponential(x, rate)*normal(y, mu1, sigma1),
(y, -oo, oo), (x, 0, oo), meijerg=True)
bench = [
'MT(x**nu*Heaviside(x - 1), x, s)',
'MT(x**nu*Heaviside(1 - x), x, s)',
'MT((1-x)**(beta - 1)*Heaviside(1-x), x, s)',
'MT((x-1)**(beta - 1)*Heaviside(x-1), x, s)',
'MT((1+x)**(-rho), x, s)',
'MT(abs(1-x)**(-rho), x, s)',
'MT((1-x)**(beta-1)*Heaviside(1-x) + a*(x-1)**(beta-1)*Heaviside(x-1), x, s)',
'MT((x**a-b**a)/(x-b), x, s)',
'MT((x**a-bpos**a)/(x-bpos), x, s)',
'MT(exp(-x), x, s)',
'MT(exp(-1/x), x, s)',
'MT(log(x)**4*Heaviside(1-x), x, s)',
'MT(log(x)**3*Heaviside(x-1), x, s)',
'MT(log(x + 1), x, s)',
'MT(log(1/x + 1), x, s)',
'MT(log(abs(1 - x)), x, s)',
'MT(log(abs(1 - 1/x)), x, s)',
'MT(log(x)/(x+1), x, s)',
'MT(log(x)**2/(x+1), x, s)',
'MT(log(x)/(x+1)**2, x, s)',
'MT(erf(sqrt(x)), x, s)',
'MT(besselj(a, 2*sqrt(x)), x, s)',
'MT(sin(sqrt(x))*besselj(a, sqrt(x)), x, s)',
'MT(cos(sqrt(x))*besselj(a, sqrt(x)), x, s)',
'MT(besselj(a, sqrt(x))**2, x, s)',
'MT(besselj(a, sqrt(x))*besselj(-a, sqrt(x)), x, s)',
'MT(besselj(a - 1, sqrt(x))*besselj(a, sqrt(x)), x, s)',
'MT(besselj(a, sqrt(x))*besselj(b, sqrt(x)), x, s)',
'MT(besselj(a, sqrt(x))**2 + besselj(-a, sqrt(x))**2, x, s)',
'MT(bessely(a, 2*sqrt(x)), x, s)',
'MT(sin(sqrt(x))*bessely(a, sqrt(x)), x, s)',
'MT(cos(sqrt(x))*bessely(a, sqrt(x)), x, s)',
'MT(besselj(a, sqrt(x))*bessely(a, sqrt(x)), x, s)',
'MT(besselj(a, sqrt(x))*bessely(b, sqrt(x)), x, s)',
'MT(bessely(a, sqrt(x))**2, x, s)',
'MT(besselk(a, 2*sqrt(x)), x, s)',
'MT(besselj(a, 2*sqrt(2*sqrt(x)))*besselk(a, 2*sqrt(2*sqrt(x))), x, s)',
'MT(besseli(a, sqrt(x))*besselk(a, sqrt(x)), x, s)',
'MT(besseli(b, sqrt(x))*besselk(a, sqrt(x)), x, s)',
'MT(exp(-x/2)*besselk(a, x/2), x, s)',
# later: ILT, IMT
'LT((t-apos)**bpos*exp(-cpos*(t-apos))*Heaviside(t-apos), t, s)',
'LT(t**apos, t, s)',
'LT(Heaviside(t), t, s)',
'LT(Heaviside(t - apos), t, s)',
'LT(1 - exp(-apos*t), t, s)',
'LT((exp(2*t)-1)*exp(-bpos - t)*Heaviside(t)/2, t, s, noconds=True)',
'LT(exp(t), t, s)',
'LT(exp(2*t), t, s)',
'LT(exp(apos*t), t, s)',
'LT(log(t/apos), t, s)',
'LT(erf(t), t, s)',
'LT(sin(apos*t), t, s)',
'LT(cos(apos*t), t, s)',
'LT(exp(-apos*t)*sin(bpos*t), t, s)',
'LT(exp(-apos*t)*cos(bpos*t), t, s)',
'LT(besselj(0, t), t, s, noconds=True)',
'LT(besselj(1, t), t, s, noconds=True)',
'FT(Heaviside(1 - abs(2*apos*x)), x, k)',
'FT(Heaviside(1-abs(apos*x))*(1-abs(apos*x)), x, k)',
'FT(exp(-apos*x)*Heaviside(x), x, k)',
'IFT(1/(apos + 2*pi*I*x), x, posk, noconds=False)',
'IFT(1/(apos + 2*pi*I*x), x, -posk, noconds=False)',
'IFT(1/(apos + 2*pi*I*x), x, negk)',
'FT(x*exp(-apos*x)*Heaviside(x), x, k)',
'FT(exp(-apos*x)*sin(bpos*x)*Heaviside(x), x, k)',
'FT(exp(-apos*x**2), x, k)',
'IFT(sqrt(pi/apos)*exp(-(pi*k)**2/apos), k, x)',
'FT(exp(-apos*abs(x)), x, k)',
'integrate(normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True)',
'integrate(x*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True)',
'integrate(x**2*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True)',
'integrate(x**3*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True)',
'integrate(normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
'integrate(x*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
'integrate(y*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
'integrate(x*y*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
'integrate((x+y+1)*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
'integrate((x+y-1)*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
'integrate(x**2*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
'integrate(y**2*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
'integrate(exponential(x, rate), (x, 0, oo), meijerg=True)',
'integrate(x*exponential(x, rate), (x, 0, oo), meijerg=True)',
'integrate(x**2*exponential(x, rate), (x, 0, oo), meijerg=True)',
'E(1)',
'E(x*y)',
'E(x*y**2)',
'E((x+y+1)**2)',
'E(x+y+1)',
'E((x+y-1)**2)',
'integrate(betadist, (x, 0, oo), meijerg=True)',
'integrate(x*betadist, (x, 0, oo), meijerg=True)',
'integrate(x**2*betadist, (x, 0, oo), meijerg=True)',
'integrate(chi, (x, 0, oo), meijerg=True)',
'integrate(x*chi, (x, 0, oo), meijerg=True)',
'integrate(x**2*chi, (x, 0, oo), meijerg=True)',
'integrate(chisquared, (x, 0, oo), meijerg=True)',
'integrate(x*chisquared, (x, 0, oo), meijerg=True)',
'integrate(x**2*chisquared, (x, 0, oo), meijerg=True)',
'integrate(((x-k)/sqrt(2*k))**3*chisquared, (x, 0, oo), meijerg=True)',
'integrate(dagum, (x, 0, oo), meijerg=True)',
'integrate(x*dagum, (x, 0, oo), meijerg=True)',
'integrate(x**2*dagum, (x, 0, oo), meijerg=True)',
'integrate(f, (x, 0, oo), meijerg=True)',
'integrate(x*f, (x, 0, oo), meijerg=True)',
'integrate(x**2*f, (x, 0, oo), meijerg=True)',
'integrate(rice, (x, 0, oo), meijerg=True)',
'integrate(laplace, (x, -oo, oo), meijerg=True)',
'integrate(x*laplace, (x, -oo, oo), meijerg=True)',
'integrate(x**2*laplace, (x, -oo, oo), meijerg=True)',
'integrate(log(x) * x**(k-1) * exp(-x) / gamma(k), (x, 0, oo))',
'integrate(sin(z*x)*(x**2-1)**(-(y+S(1)/2)), (x, 1, oo), meijerg=True)',
'integrate(besselj(0,x)*besselj(1,x)*exp(-x**2), (x, 0, oo), meijerg=True)',
'integrate(besselj(0,x)*besselj(1,x)*besselk(0,x), (x, 0, oo), meijerg=True)',
'integrate(besselj(0,x)*besselj(1,x)*exp(-x**2), (x, 0, oo), meijerg=True)',
'integrate(besselj(a,x)*besselj(b,x)/x, (x,0,oo), meijerg=True)',
'hyperexpand(meijerg((-s - a/2 + 1, -s + a/2 + 1), (-a/2 - S(1)/2, -s + a/2 + S(3)/2), (a/2, -a/2), (-a/2 - S(1)/2, -s + a/2 + S(3)/2), 1))',
"combsimp(S('2**(2*s)*(-pi*gamma(-a + 1)*gamma(a + 1)*gamma(-a - s + 1)*gamma(-a + s - 1/2)*gamma(a - s + 3/2)*gamma(a + s + 1)/(a*(a + s)) - gamma(-a - 1/2)*gamma(-a + 1)*gamma(a + 1)*gamma(a + 3/2)*gamma(-s + 3/2)*gamma(s - 1/2)*gamma(-a + s + 1)*gamma(a - s + 1)/(a*(-a + s)))*gamma(-2*s + 1)*gamma(s + 1)/(pi*s*gamma(-a - 1/2)*gamma(a + 3/2)*gamma(-s + 1)*gamma(-s + 3/2)*gamma(s - 1/2)*gamma(-a - s + 1)*gamma(-a + s - 1/2)*gamma(a - s + 1)*gamma(a - s + 3/2))'))",
'mellin_transform(E1(x), x, s)',
'inverse_mellin_transform(gamma(s)/s, s, x, (0, oo))',
'mellin_transform(expint(a, x), x, s)',
'mellin_transform(Si(x), x, s)',
'inverse_mellin_transform(-2**s*sqrt(pi)*gamma((s + 1)/2)/(2*s*gamma(-s/2 + 1)), s, x, (-1, 0))',
'mellin_transform(Ci(sqrt(x)), x, s)',
'inverse_mellin_transform(-4**s*sqrt(pi)*gamma(s)/(2*s*gamma(-s + S(1)/2)),s, u, (0, 1))',
'laplace_transform(Ci(x), x, s)',
'laplace_transform(expint(a, x), x, s)',
'laplace_transform(expint(1, x), x, s)',
'laplace_transform(expint(2, x), x, s)',
'inverse_laplace_transform(-log(1 + s**2)/2/s, s, u)',
'inverse_laplace_transform(log(s + 1)/s, s, x)',
'inverse_laplace_transform((s - log(s + 1))/s**2, s, x)',
'laplace_transform(Chi(x), x, s)',
'laplace_transform(Shi(x), x, s)',
'integrate(exp(-z*x)/x, (x, 1, oo), meijerg=True, conds="none")',
'integrate(exp(-z*x)/x**2, (x, 1, oo), meijerg=True, conds="none")',
'integrate(exp(-z*x)/x**3, (x, 1, oo), meijerg=True,conds="none")',
'integrate(-cos(x)/x, (x, tpos, oo), meijerg=True)',
'integrate(-sin(x)/x, (x, tpos, oo), meijerg=True)',
'integrate(sin(x)/x, (x, 0, z), meijerg=True)',
'integrate(sinh(x)/x, (x, 0, z), meijerg=True)',
'integrate(exp(-x)/x, x, meijerg=True)',
'integrate(exp(-x)/x**2, x, meijerg=True)',
'integrate(cos(u)/u, u, meijerg=True)',
'integrate(cosh(u)/u, u, meijerg=True)',
'integrate(expint(1, x), x, meijerg=True)',
'integrate(expint(2, x), x, meijerg=True)',
'integrate(Si(x), x, meijerg=True)',
'integrate(Ci(u), u, meijerg=True)',
'integrate(Shi(x), x, meijerg=True)',
'integrate(cosint(u), u, meijerg=True)',
'integrate(Si(x)*exp(-x), (x, 0, oo), meijerg=True)',
'integrate(expint(1, x)*sin(x), (x, 0, oo), meijerg=True)'
]
from time import time
from sympy.core.cache import clear_cache
import sys
timings = []
if __name__ == '__main__':
for n, string in enumerate(bench):
clear_cache()
_t = time()
exec(string)
_t = time() - _t
timings += [(_t, string)]
sys.stdout.write('.')
sys.stdout.flush()
if n % (len(bench) // 10) == 0:
sys.stdout.write('%s' % (10*n // len(bench)))
print()
timings.sort(key=lambda x: -x[0])
for t, string in timings:
print('%.2fs %s' % (t, string))
| 11,186 | 42.870588 | 474 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/benchmarks/bench_discrete_log.py
|
from __future__ import print_function, division
import sys
from time import time
from sympy.ntheory.residue_ntheory import (discrete_log,
_discrete_log_trial_mul, _discrete_log_shanks_steps,
_discrete_log_pollard_rho, _discrete_log_pohlig_hellman)
# Cyclic group (Z/pZ)* with p prime, order p - 1 and generator g
data_set_1 = [
# p, p - 1, g
[191, 190, 19],
[46639, 46638, 6],
[14789363, 14789362, 2],
[4254225211, 4254225210, 2],
[432751500361, 432751500360, 7],
[158505390797053, 158505390797052, 2],
[6575202655312007, 6575202655312006, 5],
[8430573471995353769, 8430573471995353768, 3],
[3938471339744997827267, 3938471339744997827266, 2],
[875260951364705563393093, 875260951364705563393092, 5],
]
# Cyclic sub-groups of (Z/nZ)* with prime order p and generator g
# (n, p are primes and n = 2 * p + 1)
data_set_2 = [
# n, p, g
[227, 113, 3],
[2447, 1223, 2],
[24527, 12263, 2],
[245639, 122819, 2],
[2456747, 1228373, 3],
[24567899, 12283949, 3],
[245679023, 122839511, 2],
[2456791307, 1228395653, 3],
[24567913439, 12283956719, 2],
[245679135407, 122839567703, 2],
[2456791354763, 1228395677381, 3],
[24567913550903, 12283956775451, 2],
[245679135509519, 122839567754759, 2],
]
# Cyclic sub-groups of (Z/nZ)* with smooth order o and generator g
data_set_3 = [
# n, o, g
[2**118, 2**116, 3],
]
def bench_discrete_log(data_set, algo=None):
if algo is None:
f = discrete_log
elif algo == 'trial':
f = _discrete_log_trial_mul
elif algo == 'shanks':
f = _discrete_log_shanks_steps
elif algo == 'rho':
f = _discrete_log_pollard_rho
elif algo == 'ph':
f = _discrete_log_pohlig_hellman
else:
raise ValueError("Argument 'algo' should be one"
" of ('trial', 'shanks', 'rho' or 'ph')")
for i, data in enumerate(data_set):
for j, (n, p, g) in enumerate(data):
t = time()
l = f(n, pow(g, p - 1, n), g, p)
t = time() - t
print('[%02d-%03d] %15.10f' % (i, j, t))
assert l == p - 1
if __name__ == '__main__':
algo = sys.argv[1] \
if len(sys.argv) > 1 else None
data_set = [
data_set_1,
data_set_2,
data_set_3,
]
bench_discrete_log(data_set, algo)
| 2,523 | 28.011494 | 66 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/benchmarks/__init__.py
| 0 | 0 | 0 |
py
|
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/external/importtools.py
|
"""Tools to assist importing optional external modules."""
from __future__ import print_function, division
import sys
from distutils.version import StrictVersion
# Override these in the module to change the default warning behavior.
# For example, you might set both to False before running the tests so that
# warnings are not printed to the console, or set both to True for debugging.
WARN_NOT_INSTALLED = None # Default is False
WARN_OLD_VERSION = None # Default is True
def __sympy_debug():
# helper function from sympy/__init__.py
# We don't just import SYMPY_DEBUG from that file because we don't want to
# import all of sympy just to use this module.
import os
debug_str = os.getenv('SYMPY_DEBUG', 'False')
if debug_str in ('True', 'False'):
return eval(debug_str)
else:
raise RuntimeError("unrecognized value for SYMPY_DEBUG: %s" %
debug_str)
if __sympy_debug():
WARN_OLD_VERSION = True
WARN_NOT_INSTALLED = True
def import_module(module, min_module_version=None, min_python_version=None,
warn_not_installed=None, warn_old_version=None,
module_version_attr='__version__', module_version_attr_call_args=None,
__import__kwargs={}, catch=()):
"""
Import and return a module if it is installed.
If the module is not installed, it returns None.
A minimum version for the module can be given as the keyword argument
min_module_version. This should be comparable against the module version.
By default, module.__version__ is used to get the module version. To
override this, set the module_version_attr keyword argument. If the
attribute of the module to get the version should be called (e.g.,
module.version()), then set module_version_attr_call_args to the args such
that module.module_version_attr(*module_version_attr_call_args) returns the
module's version.
If the module version is less than min_module_version using the Python <
comparison, None will be returned, even if the module is installed. You can
use this to keep from importing an incompatible older version of a module.
You can also specify a minimum Python version by using the
min_python_version keyword argument. This should be comparable against
sys.version_info.
If the keyword argument warn_not_installed is set to True, the function will
emit a UserWarning when the module is not installed.
If the keyword argument warn_old_version is set to True, the function will
emit a UserWarning when the library is installed, but cannot be imported
because of the min_module_version or min_python_version options.
Note that because of the way warnings are handled, a warning will be
emitted for each module only once. You can change the default warning
behavior by overriding the values of WARN_NOT_INSTALLED and WARN_OLD_VERSION
in sympy.external.importtools. By default, WARN_NOT_INSTALLED is False and
WARN_OLD_VERSION is True.
This function uses __import__() to import the module. To pass additional
options to __import__(), use the __import__kwargs keyword argument. For
example, to import a submodule A.B, you must pass a nonempty fromlist option
to __import__. See the docstring of __import__().
This catches ImportError to determine if the module is not installed. To
catch additional errors, pass them as a tuple to the catch keyword
argument.
Examples
========
>>> from sympy.external import import_module
>>> numpy = import_module('numpy')
>>> numpy = import_module('numpy', min_python_version=(2, 7),
... warn_old_version=False)
>>> numpy = import_module('numpy', min_module_version='1.5',
... warn_old_version=False) # numpy.__version__ is a string
>>> # gmpy does not have __version__, but it does have gmpy.version()
>>> gmpy = import_module('gmpy', min_module_version='1.14',
... module_version_attr='version', module_version_attr_call_args=(),
... warn_old_version=False)
>>> # To import a submodule, you must pass a nonempty fromlist to
>>> # __import__(). The values do not matter.
>>> p3 = import_module('mpl_toolkits.mplot3d',
... __import__kwargs={'fromlist':['something']})
>>> # matplotlib.pyplot can raise RuntimeError when the display cannot be opened
>>> matplotlib = import_module('matplotlib',
... __import__kwargs={'fromlist':['pyplot']}, catch=(RuntimeError,))
"""
# keyword argument overrides default, and global variable overrides
# keyword argument.
warn_old_version = (WARN_OLD_VERSION if WARN_OLD_VERSION is not None
else warn_old_version or True)
warn_not_installed = (WARN_NOT_INSTALLED if WARN_NOT_INSTALLED is not None
else warn_not_installed or False)
import warnings
# Check Python first so we don't waste time importing a module we can't use
if min_python_version:
if sys.version_info < min_python_version:
if warn_old_version:
warnings.warn("Python version is too old to use %s "
"(%s or newer required)" % (
module, '.'.join(map(str, min_python_version))),
UserWarning)
return
# PyPy 1.6 has rudimentary NumPy support and importing it produces errors, so skip it
if module == 'numpy' and '__pypy__' in sys.builtin_module_names:
return
try:
mod = __import__(module, **__import__kwargs)
## there's something funny about imports with matplotlib and py3k. doing
## from matplotlib import collections
## gives python's stdlib collections module. explicitly re-importing
## the module fixes this.
from_list = __import__kwargs.get('fromlist', tuple())
for submod in from_list:
if submod == 'collections' and mod.__name__ == 'matplotlib':
__import__(module + '.' + submod)
except ImportError:
if warn_not_installed:
warnings.warn("%s module is not installed" % module, UserWarning)
return
except catch as e:
if warn_not_installed:
warnings.warn(
"%s module could not be used (%s)" % (module, repr(e)))
return
if min_module_version:
modversion = getattr(mod, module_version_attr)
if module_version_attr_call_args is not None:
modversion = modversion(*module_version_attr_call_args)
# NOTE: StrictVersion() is use here to make sure a comparison like
# '1.11.2' < '1.6.1' doesn't fail. There is not a straight forward way
# to create a unit test for this.
if StrictVersion(modversion) < StrictVersion(min_module_version):
if warn_old_version:
# Attempt to create a pretty string version of the version
from ..core.compatibility import string_types
if isinstance(min_module_version, string_types):
verstr = min_module_version
elif isinstance(min_module_version, (tuple, list)):
verstr = '.'.join(map(str, min_module_version))
else:
# Either don't know what this is. Hopefully
# it's something that has a nice str version, like an int.
verstr = str(min_module_version)
warnings.warn("%s version is too old to use "
"(%s or newer required)" % (module, verstr),
UserWarning)
return
return mod
| 7,627 | 41.853933 | 89 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/external/__init__.py
|
"""
Unified place for determining if external dependencies are installed or not.
You should import all external modules using the import_module() function.
For example
>>> from sympy.external import import_module
>>> numpy = import_module('numpy')
If the resulting library is not installed, or if the installed version
is less than a given minimum version, the function will return None.
Otherwise, it will return the library. See the docstring of
import_module() for more information.
"""
from sympy.external.importtools import import_module
| 549 | 27.947368 | 76 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/external/tests/test_numpy.py
|
# This testfile tests SymPy <-> NumPy compatibility
# Don't test any SymPy features here. Just pure interaction with NumPy.
# Always write regular SymPy tests for anything, that can be tested in pure
# Python (without numpy). Here we test everything, that a user may need when
# using SymPy with NumPy
from __future__ import division
from sympy.external import import_module
numpy = import_module('numpy')
if numpy:
array, matrix, ndarray = numpy.array, numpy.matrix, numpy.ndarray
else:
#bin/test will not execute any tests now
disabled = True
from sympy import (Rational, Symbol, list2numpy, matrix2numpy, sin, Float,
Matrix, lambdify, symarray, symbols, Integer)
import sympy
import mpmath
from sympy.abc import x, y, z
from sympy.utilities.decorator import conserve_mpmath_dps
# first, systematically check, that all operations are implemented and don't
# raise an exception
def test_systematic_basic():
def s(sympy_object, numpy_array):
x = sympy_object + numpy_array
x = numpy_array + sympy_object
x = sympy_object - numpy_array
x = numpy_array - sympy_object
x = sympy_object * numpy_array
x = numpy_array * sympy_object
x = sympy_object / numpy_array
x = numpy_array / sympy_object
x = sympy_object ** numpy_array
x = numpy_array ** sympy_object
x = Symbol("x")
y = Symbol("y")
sympy_objs = [
Rational(2, 3),
Float("1.3"),
x,
y,
pow(x, y)*y,
Integer(5),
Float(5.5),
]
numpy_objs = [
array([1]),
array([3, 8, -1]),
array([x, x**2, Rational(5)]),
array([x/y*sin(y), 5, Rational(5)]),
]
for x in sympy_objs:
for y in numpy_objs:
s(x, y)
# now some random tests, that test particular problems and that also
# check that the results of the operations are correct
def test_basics():
one = Rational(1)
zero = Rational(0)
assert array(1) == array(one)
assert array([one]) == array([one])
assert array([x]) == array([x])
assert array(x) == array(Symbol("x"))
assert array(one + x) == array(1 + x)
X = array([one, zero, zero])
assert (X == array([one, zero, zero])).all()
assert (X == array([one, 0, 0])).all()
def test_arrays():
one = Rational(1)
zero = Rational(0)
X = array([one, zero, zero])
Y = one*X
X = array([Symbol("a") + Rational(1, 2)])
Y = X + X
assert Y == array([1 + 2*Symbol("a")])
Y = Y + 1
assert Y == array([2 + 2*Symbol("a")])
Y = X - X
assert Y == array([0])
def test_conversion1():
a = list2numpy([x**2, x])
#looks like an array?
assert isinstance(a, ndarray)
assert a[0] == x**2
assert a[1] == x
assert len(a) == 2
#yes, it's the array
def test_conversion2():
a = 2*list2numpy([x**2, x])
b = list2numpy([2*x**2, 2*x])
assert (a == b).all()
one = Rational(1)
zero = Rational(0)
X = list2numpy([one, zero, zero])
Y = one*X
X = list2numpy([Symbol("a") + Rational(1, 2)])
Y = X + X
assert Y == array([1 + 2*Symbol("a")])
Y = Y + 1
assert Y == array([2 + 2*Symbol("a")])
Y = X - X
assert Y == array([0])
def test_list2numpy():
assert (array([x**2, x]) == list2numpy([x**2, x])).all()
def test_Matrix1():
m = Matrix([[x, x**2], [5, 2/x]])
assert (array(m.subs(x, 2)) == array([[2, 4], [5, 1]])).all()
m = Matrix([[sin(x), x**2], [5, 2/x]])
assert (array(m.subs(x, 2)) == array([[sin(2), 4], [5, 1]])).all()
def test_Matrix2():
m = Matrix([[x, x**2], [5, 2/x]])
assert (matrix(m.subs(x, 2)) == matrix([[2, 4], [5, 1]])).all()
m = Matrix([[sin(x), x**2], [5, 2/x]])
assert (matrix(m.subs(x, 2)) == matrix([[sin(2), 4], [5, 1]])).all()
def test_Matrix3():
a = array([[2, 4], [5, 1]])
assert Matrix(a) == Matrix([[2, 4], [5, 1]])
assert Matrix(a) != Matrix([[2, 4], [5, 2]])
a = array([[sin(2), 4], [5, 1]])
assert Matrix(a) == Matrix([[sin(2), 4], [5, 1]])
assert Matrix(a) != Matrix([[sin(0), 4], [5, 1]])
def test_Matrix4():
a = matrix([[2, 4], [5, 1]])
assert Matrix(a) == Matrix([[2, 4], [5, 1]])
assert Matrix(a) != Matrix([[2, 4], [5, 2]])
a = matrix([[sin(2), 4], [5, 1]])
assert Matrix(a) == Matrix([[sin(2), 4], [5, 1]])
assert Matrix(a) != Matrix([[sin(0), 4], [5, 1]])
def test_Matrix_sum():
M = Matrix([[1, 2, 3], [x, y, x], [2*y, -50, z*x]])
m = matrix([[2, 3, 4], [x, 5, 6], [x, y, z**2]])
assert M + m == Matrix([[3, 5, 7], [2*x, y + 5, x + 6], [2*y + x, y - 50, z*x + z**2]])
assert m + M == Matrix([[3, 5, 7], [2*x, y + 5, x + 6], [2*y + x, y - 50, z*x + z**2]])
assert M + m == M.add(m)
def test_Matrix_mul():
M = Matrix([[1, 2, 3], [x, y, x]])
m = matrix([[2, 4], [x, 6], [x, z**2]])
assert M*m == Matrix([
[ 2 + 5*x, 16 + 3*z**2],
[2*x + x*y + x**2, 4*x + 6*y + x*z**2],
])
assert m*M == Matrix([
[ 2 + 4*x, 4 + 4*y, 6 + 4*x],
[ 7*x, 2*x + 6*y, 9*x],
[x + x*z**2, 2*x + y*z**2, 3*x + x*z**2],
])
a = array([2])
assert a[0] * M == 2 * M
assert M * a[0] == 2 * M
def test_Matrix_array():
class matarray(object):
def __array__(self):
from numpy import array
return array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matarr = matarray()
assert Matrix(matarr) == Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
def test_matrix2numpy():
a = matrix2numpy(Matrix([[1, x**2], [3*sin(x), 0]]))
assert isinstance(a, ndarray)
assert a.shape == (2, 2)
assert a[0, 0] == 1
assert a[0, 1] == x**2
assert a[1, 0] == 3*sin(x)
assert a[1, 1] == 0
def test_matrix2numpy_conversion():
a = Matrix([[1, 2, sin(x)], [x**2, x, Rational(1, 2)]])
b = array([[1, 2, sin(x)], [x**2, x, Rational(1, 2)]])
assert (matrix2numpy(a) == b).all()
assert matrix2numpy(a).dtype == numpy.dtype('object')
c = matrix2numpy(Matrix([[1, 2], [10, 20]]), dtype='int8')
d = matrix2numpy(Matrix([[1, 2], [10, 20]]), dtype='float64')
assert c.dtype == numpy.dtype('int8')
assert d.dtype == numpy.dtype('float64')
def test_issue_3728():
assert (Rational(1, 2)*array([2*x, 0]) == array([x, 0])).all()
assert (Rational(1, 2) + array(
[2*x, 0]) == array([2*x + Rational(1, 2), Rational(1, 2)])).all()
assert (Float("0.5")*array([2*x, 0]) == array([Float("1.0")*x, 0])).all()
assert (Float("0.5") + array(
[2*x, 0]) == array([2*x + Float("0.5"), Float("0.5")])).all()
@conserve_mpmath_dps
def test_lambdify():
mpmath.mp.dps = 16
sin02 = mpmath.mpf("0.198669330795061215459412627")
f = lambdify(x, sin(x), "numpy")
prec = 1e-15
assert -prec < f(0.2) - sin02 < prec
try:
f(x) # if this succeeds, it can't be a numpy function
assert False
except AttributeError:
pass
def test_lambdify_matrix():
f = lambdify(x, Matrix([[x, 2*x], [1, 2]]), [{'ImmutableMatrix': numpy.array}, "numpy"])
assert (f(1) == array([[1, 2], [1, 2]])).all()
def test_lambdify_matrix_multi_input():
M = sympy.Matrix([[x**2, x*y, x*z],
[y*x, y**2, y*z],
[z*x, z*y, z**2]])
f = lambdify((x, y, z), M, [{'ImmutableMatrix': numpy.array}, "numpy"])
xh, yh, zh = 1.0, 2.0, 3.0
expected = array([[xh**2, xh*yh, xh*zh],
[yh*xh, yh**2, yh*zh],
[zh*xh, zh*yh, zh**2]])
actual = f(xh, yh, zh)
assert numpy.allclose(actual, expected)
def test_lambdify_matrix_vec_input():
X = sympy.DeferredVector('X')
M = Matrix([
[X[0]**2, X[0]*X[1], X[0]*X[2]],
[X[1]*X[0], X[1]**2, X[1]*X[2]],
[X[2]*X[0], X[2]*X[1], X[2]**2]])
f = lambdify(X, M, [{'ImmutableMatrix': numpy.array}, "numpy"])
Xh = array([1.0, 2.0, 3.0])
expected = array([[Xh[0]**2, Xh[0]*Xh[1], Xh[0]*Xh[2]],
[Xh[1]*Xh[0], Xh[1]**2, Xh[1]*Xh[2]],
[Xh[2]*Xh[0], Xh[2]*Xh[1], Xh[2]**2]])
actual = f(Xh)
assert numpy.allclose(actual, expected)
def test_lambdify_transl():
from sympy.utilities.lambdify import NUMPY_TRANSLATIONS
for sym, mat in NUMPY_TRANSLATIONS.items():
assert sym in sympy.__dict__
assert mat in numpy.__dict__
def test_symarray():
"""Test creation of numpy arrays of sympy symbols."""
import numpy as np
import numpy.testing as npt
syms = symbols('_0,_1,_2')
s1 = symarray("", 3)
s2 = symarray("", 3)
npt.assert_array_equal(s1, np.array(syms, dtype=object))
assert s1[0] == s2[0]
a = symarray('a', 3)
b = symarray('b', 3)
assert not(a[0] == b[0])
asyms = symbols('a_0,a_1,a_2')
npt.assert_array_equal(a, np.array(asyms, dtype=object))
# Multidimensional checks
a2d = symarray('a', (2, 3))
assert a2d.shape == (2, 3)
a00, a12 = symbols('a_0_0,a_1_2')
assert a2d[0, 0] == a00
assert a2d[1, 2] == a12
a3d = symarray('a', (2, 3, 2))
assert a3d.shape == (2, 3, 2)
a000, a120, a121 = symbols('a_0_0_0,a_1_2_0,a_1_2_1')
assert a3d[0, 0, 0] == a000
assert a3d[1, 2, 0] == a120
assert a3d[1, 2, 1] == a121
def test_vectorize():
assert (numpy.vectorize(
sin)([1, 2, 3]) == numpy.array([sin(1), sin(2), sin(3)])).all()
| 9,441 | 28.41433 | 92 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/external/tests/test_sage.py
|
# This testfile tests SymPy <-> Sage compatibility
#
# Execute this test inside Sage, e.g. with:
# sage -python bin/test sympy/external/tests/test_sage.py
#
# This file can be tested by Sage itself by:
# sage -t sympy/external/tests/test_sage.py
# and if all tests pass, it should be copied (verbatim) to Sage, so that it is
# automatically doctested by Sage. Note that this second method imports the
# version of SymPy in Sage, whereas the -python method imports the local version
# of SymPy (both use the local version of the tests, however).
#
# Don't test any SymPy features here. Just pure interaction with Sage.
# Always write regular SymPy tests for anything, that can be tested in pure
# Python (without Sage). Here we test everything, that a user may need when
# using SymPy with Sage.
import os
import re
import sys
from sympy.external import import_module
sage = import_module('sage.all', __import__kwargs={'fromlist': ['all']})
if not sage:
#bin/test will not execute any tests now
disabled = True
if sys.version_info[0] == 3:
# Sage does not support Python 3 currently
disabled = True
import sympy
from sympy.utilities.pytest import XFAIL
def check_expression(expr, var_symbols, only_from_sympy=False):
"""
Does eval(expr) both in Sage and SymPy and does other checks.
"""
# evaluate the expression in the context of Sage:
if var_symbols:
sage.var(var_symbols)
a = globals().copy()
# safety checks...
a.update(sage.__dict__)
assert "sin" in a
is_different = False
try:
e_sage = eval(expr, a)
assert not isinstance(e_sage, sympy.Basic)
except (NameError, TypeError):
is_different = True
pass
# evaluate the expression in the context of SymPy:
if var_symbols:
sympy_vars = sympy.var(var_symbols)
b = globals().copy()
b.update(sympy.__dict__)
assert "sin" in b
b.update(sympy.__dict__)
e_sympy = eval(expr, b)
assert isinstance(e_sympy, sympy.Basic)
# Sympy func may have specific _sage_ method
if is_different:
_sage_method = getattr(e_sympy.func, "_sage_")
e_sage = _sage_method(sympy.S(e_sympy))
# Do the actual checks:
if not only_from_sympy:
assert sympy.S(e_sage) == e_sympy
assert e_sage == sage.SR(e_sympy)
def test_basics():
check_expression("x", "x")
check_expression("x**2", "x")
check_expression("x**2+y**3", "x y")
check_expression("1/(x+y)**2-x**3/4", "x y")
def test_complex():
check_expression("I", "")
check_expression("23+I*4", "x")
@XFAIL
def test_complex_fail():
# Sage doesn't properly implement _sympy_ on I
check_expression("I*y", "y")
check_expression("x+I*y", "x y")
def test_integer():
check_expression("4*x", "x")
check_expression("-4*x", "x")
def test_real():
check_expression("1.123*x", "x")
check_expression("-18.22*x", "x")
def test_E():
assert sympy.sympify(sage.e) == sympy.E
assert sage.e == sage.SR(sympy.E)
def test_pi():
assert sympy.sympify(sage.pi) == sympy.pi
assert sage.pi == sage.SR(sympy.pi)
def test_euler_gamma():
assert sympy.sympify(sage.euler_gamma) == sympy.EulerGamma
assert sage.euler_gamma == sage.SR(sympy.EulerGamma)
def test_oo():
assert sympy.sympify(sage.oo) == sympy.oo
assert sage.oo == sage.SR(sympy.oo)
assert sympy.sympify(-sage.oo) == -sympy.oo
assert -sage.oo == sage.SR(-sympy.oo)
#assert sympy.sympify(sage.UnsignedInfinityRing.gen()) == sympy.zoo
#assert sage.UnsignedInfinityRing.gen() == sage.SR(sympy.zoo)
def test_NaN():
assert sympy.sympify(sage.NaN) == sympy.nan
assert sage.NaN == sage.SR(sympy.nan)
def test_Catalan():
assert sympy.sympify(sage.catalan) == sympy.Catalan
assert sage.catalan == sage.SR(sympy.Catalan)
def test_GoldenRation():
assert sympy.sympify(sage.golden_ratio) == sympy.GoldenRatio
assert sage.golden_ratio == sage.SR(sympy.GoldenRatio)
def test_functions():
# Test at least one Function without own _sage_ method
assert not "_sage_" in sympy.factorial.__dict__
check_expression("factorial(x)", "x")
check_expression("sin(x)", "x")
check_expression("cos(x)", "x")
check_expression("tan(x)", "x")
check_expression("cot(x)", "x")
check_expression("asin(x)", "x")
check_expression("acos(x)", "x")
check_expression("atan(x)", "x")
check_expression("atan2(y, x)", "x, y")
check_expression("acot(x)", "x")
check_expression("sinh(x)", "x")
check_expression("cosh(x)", "x")
check_expression("tanh(x)", "x")
check_expression("coth(x)", "x")
check_expression("asinh(x)", "x")
check_expression("acosh(x)", "x")
check_expression("atanh(x)", "x")
check_expression("acoth(x)", "x")
check_expression("exp(x)", "x")
check_expression("log(x)", "x")
check_expression("re(x)", "x")
check_expression("im(x)", "x")
check_expression("sign(x)", "x")
check_expression("abs(x)", "x")
check_expression("arg(x)", "x")
check_expression("conjugate(x)", "x")
# The following tests differently named functions
check_expression("besselj(y, x)", "x, y")
check_expression("bessely(y, x)", "x, y")
check_expression("besseli(y, x)", "x, y")
check_expression("besselk(y, x)", "x, y")
check_expression("DiracDelta(x)", "x")
check_expression("KroneckerDelta(x, y)", "x, y")
check_expression("expint(y, x)", "x, y")
check_expression("Si(x)", "x")
check_expression("Ci(x)", "x")
check_expression("Shi(x)", "x")
check_expression("Chi(x)", "x")
check_expression("loggamma(x)", "x")
check_expression("Ynm(n,m,x,y)", "n, m, x, y")
check_expression("hyper((n,m),(m,n),x)", "n, m, x")
def test_issue_4023():
sage.var("a x")
log = sage.log
i = sympy.integrate(log(x)/a, (x, a, a + 1))
i2 = sympy.simplify(i)
s = sage.SR(i2)
assert s == (a*log(1 + a) - a*log(a) + log(1 + a) - 1)/a
def test_integral():
#test Sympy-->Sage
check_expression("Integral(x, (x,))", "x", only_from_sympy=True)
check_expression("Integral(x, (x, 0, 1))", "x", only_from_sympy=True)
check_expression("Integral(x*y, (x,), (y, ))", "x,y", only_from_sympy=True)
check_expression("Integral(x*y, (x,), (y, 0, 1))", "x,y", only_from_sympy=True)
check_expression("Integral(x*y, (x, 0, 1), (y,))", "x,y", only_from_sympy=True)
check_expression("Integral(x*y, (x, 0, 1), (y, 0, 1))", "x,y", only_from_sympy=True)
check_expression("Integral(x*y*z, (x, 0, 1), (y, 0, 1), (z, 0, 1))", "x,y,z", only_from_sympy=True)
@XFAIL
def test_integral_failing():
# Note: sage may attempt to turn this into Integral(x, (x, x, 0))
check_expression("Integral(x, (x, 0))", "x", only_from_sympy=True)
check_expression("Integral(x*y, (x,), (y, 0))", "x,y", only_from_sympy=True)
check_expression("Integral(x*y, (x, 0, 1), (y, 0))", "x,y", only_from_sympy=True)
def test_undefined_function():
f = sympy.Function('f')
sf = sage.function('f')
x = sympy.symbols('x')
sx = sage.var('x')
assert bool(sf(sx) == f(x)._sage_())
#assert bool(f == sympy.sympify(sf))
# This string contains Sage doctests, that execute all the functions above.
# When you add a new function, please add it here as well.
"""
TESTS::
sage: test_basics()
sage: test_basics()
sage: test_complex()
sage: test_integer()
sage: test_real()
sage: test_E()
sage: test_pi()
sage: test_euler_gamma()
sage: test_oo()
sage: test_NaN()
sage: test_Catalan()
sage: test_GoldenRation()
sage: test_functions()
sage: test_issue_4023()
sage: test_integral()
sage: test_undefined_function()
Sage has no symbolic Lucas function at the moment::
sage: check_expression("lucas(x)", "x")
Traceback (most recent call last):
...
AttributeError: 'module' object has no attribute 'lucas'
"""
| 7,944 | 30.035156 | 103 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/external/tests/test_scipy.py
|
# This testfile tests SymPy <-> SciPy compatibility
# Don't test any SymPy features here. Just pure interaction with SciPy.
# Always write regular SymPy tests for anything, that can be tested in pure
# Python (without scipy). Here we test everything, that a user may need when
# using SymPy with SciPy
from sympy.external import import_module
scipy = import_module('scipy')
if not scipy:
#bin/test will not execute any tests now
disabled = True
from sympy import jn_zeros
def eq(a, b, tol=1e-6):
for x, y in zip(a, b):
if not (abs(x - y) < tol):
return False
return True
def test_jn_zeros():
assert eq(jn_zeros(0, 4, method="scipy"),
[3.141592, 6.283185, 9.424777, 12.566370])
assert eq(jn_zeros(1, 4, method="scipy"),
[4.493409, 7.725251, 10.904121, 14.066193])
assert eq(jn_zeros(2, 4, method="scipy"),
[5.763459, 9.095011, 12.322940, 15.514603])
assert eq(jn_zeros(3, 4, method="scipy"),
[6.987932, 10.417118, 13.698023, 16.923621])
assert eq(jn_zeros(4, 4, method="scipy"),
[8.182561, 11.704907, 15.039664, 18.301255])
| 1,147 | 30.888889 | 76 |
py
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.