コード例 #1
0
ファイル: trees.py プロジェクト: KevinGoodsell/sympy
def main():
    x=Symbol("x")
    s = Poly(A(x), x)
    num = [s.coeff(n) for n in range(11)]

    print s.as_basic()
    print num
コード例 #2
0
def main():
    x = Symbol("x")
    s = Poly(A(x), x)
    num = list(reversed(s.coeffs()))[:11]

    print(s.as_expr())
    print(num)
コード例 #3
0
ファイル: common.py プロジェクト: B-Rich/hermes-legacy
def gauss_lobatto_points(p):
    """
    Returns the list of Gauss-Lobatto points of the order 'p'.
    """
    x = Symbol("x")
    print "creating"
    e = legendre(p, x).diff(x)
    e = Poly(e, x)
    print "polydone"
    if e == 0:
        return []
    print "roots"
    if e == 1:
        r = []
    else:
        with workdps(40):
            r, err = polyroots(e.all_coeffs(), error=True)
        #if err > 1e-40:
        #    raise Exception("Internal Error: Root is not precise")
    print "done"
    p = []
    p.append("-1.0")
    for x in r:
        if abs(x) < 1e-40: x = 0
        p.append(str(x))
    p.append("1.0")
    return p
コード例 #4
0
    def _eval_expand_func(self, **hints):
        from sympy import exp, I, floor, Add, Poly, Dummy, exp_polar, unpolarify
        z, s, a = self.args
        if z == 1:
            return zeta(s, a)
        if s.is_Integer and s <= 0:
            t = Dummy('t')
            p = Poly((t + a)**(-s), t)
            start = 1/(1 - t)
            res = S(0)
            for c in reversed(p.all_coeffs()):
                res += c*start
                start = t*start.diff(t)
            return res.subs(t, z)

        if a.is_Rational:
            # See section 18 of
            #   Kelly B. Roach.  Hypergeometric Function Representations.
            #   In: Proceedings of the 1997 International Symposium on Symbolic and
            #   Algebraic Computation, pages 205-211, New York, 1997. ACM.
            # TODO should something be polarified here?
            add = S(0)
            mul = S(1)
            # First reduce a to the interaval (0, 1]
            if a > 1:
                n = floor(a)
                if n == a:
                    n -= 1
                a -= n
                mul = z**(-n)
                add = Add(*[-z**(k - n)/(a + k)**s for k in xrange(n)])
            elif a <= 0:
                n = floor(-a) + 1
                a += n
                mul = z**n
                add = Add(*[z**(n - 1 - k)/(a - k - 1)**s for k in xrange(n)])

            m, n = S([a.p, a.q])
            zet = exp_polar(2*pi*I/n)
            root = z**(1/n)
            return add + mul*n**(s - 1)*Add(
                *[polylog(s, zet**k*root)._eval_expand_func(**hints)
                  / (unpolarify(zet)**k*root)**m for k in xrange(n)])

        # TODO use minpoly instead of ad-hoc methods when issue 2789 is fixed
        if z.func is exp and (z.args[0]/(pi*I)).is_Rational or z in [-1, I, -I]:
            # TODO reference?
            if z == -1:
                p, q = S([1, 2])
            elif z == I:
                p, q = S([1, 4])
            elif z == -I:
                p, q = S([-1, 4])
            else:
                arg = z.args[0]/(2*pi*I)
                p, q = S([arg.p, arg.q])
            return Add(*[exp(2*pi*I*k*p/q)/q**s*zeta(s, (k + a)/q)
                         for k in xrange(q)])

        return lerchphi(z, s, a)
コード例 #5
0
ファイル: test_polynomial.py プロジェクト: fperez/sympy
def test_squarefree():
    assert Poly(x-1, x).is_squarefree == True
    assert Poly((x-1)**2, x).is_squarefree == False

    assert Poly(3*x**2, x).as_squarefree() == Poly(3*x, x)
    assert Poly(x**2+2*x+1, x).as_squarefree() == Poly(x+1, x)
    assert Poly(x**5-x**4-x+1, x).as_squarefree() == Poly(x**4-1, x)

    assert poly_sqf(1, x) == [Poly(1, x)]
    assert poly_sqf(x, x) == [Poly(x, x)]

    assert poly_sqf(3*x**2, x) == [Poly(3, x), Poly(x, x)]
    assert poly_sqf(x**2+2*x+1, x) == [Poly(1, x), Poly(x+1, x)]

    assert poly_sqf(x**5-x**4-x+1, x) == \
        [Poly(x**3 + x**2 + x + 1, x), Poly(x-1, x)]
    assert poly_sqf(x**8+6*x**6+12*x**4+8*x**2, x) == \
        [Poly(1, x), Poly(x, x), Poly(x**2+2, x)]

    # Bronstein, Symbolic Integration, pp. 52

    A = Poly(x**4 - 3*x**2 + 6, x)
    D = Poly(x**6 - 5*x**4 + 5*x**2 + 4, x)

    f, g = D, A - D.diff(x).mul_term(t)

    res, R = poly_subresultants(f, g)
    S = poly_sqf(Poly(res, t))

    assert S == [Poly(45796, t), Poly(1, t), Poly(4*t**2 + 1, t)]
コード例 #6
0
ファイル: trees.py プロジェクト: Aang/sympy
def main():
    x=Symbol("x")
    s = Poly(A(x), x)
    num = list(reversed(s.coeffs()))[:11]

    print s.as_basic()
    print num
コード例 #7
0
ファイル: transforms.py プロジェクト: ALGHeArT/sympy
 def linear_arg(arg):
     """ Test if arg is of form a*s+b, raise exception if not. """
     if not arg.is_polynomial(s):
         raise exception(fact)
     p = Poly(arg, s)
     if p.degree() != 1:
         raise exception(fact)
     return p.all_coeffs()
コード例 #8
0
def test_coeff():
    p = Poly(3*x**2*y + 4*x*y**2 + 1, x, y)

    assert p.coeff(0, 0) == p.coeff() == 1

    assert p.coeff(2, 1) == 3
    assert p.coeff(1, 2) == 4
    assert p.coeff(1, 1) == 0
コード例 #9
0
ファイル: test_expr.py プロジェクト: qmattpap/sympy
def test_has_any():
    x,y,z,t,u = symbols('x y z t u')
    f = Function("f")
    g = Function("g")
    p = Wild('p')

    assert sin(x).has(x)
    assert sin(x).has(sin)
    assert not sin(x).has(y)
    assert not sin(x).has(cos)
    assert f(x).has(x)
    assert f(x).has(f)
    assert not f(x).has(y)
    assert not f(x).has(g)

    assert f(x).diff(x).has(x)
    assert f(x).diff(x).has(f)
    assert f(x).diff(x).has(Derivative)
    assert not f(x).diff(x).has(y)
    assert not f(x).diff(x).has(g)
    assert not f(x).diff(x).has(sin)

    assert (x**2).has(Symbol)
    assert not (x**2).has(Wild)
    assert (2*p).has(Wild)

    i = Integer(4400)

    assert i.has(x) is False

    assert (i*x**i).has(x)
    assert (i*y**i).has(x) is False
    assert (i*y**i).has(x, y)

    expr = x**2*y + sin(2**t + log(z))

    assert expr.has(u) is False

    assert expr.has(x)
    assert expr.has(y)
    assert expr.has(z)
    assert expr.has(t)

    assert expr.has(x, y, z, t)
    assert expr.has(x, y, z, t, u)

    from sympy.physics.units import m, s

    assert (x*m/s).has(x)
    assert (x*m/s).has(y, z) is False

    poly = Poly(x**2 + x*y*sin(z), x, y, t)

    assert poly.has(x)
    assert poly.has(x, y, z)
    assert poly.has(x, y, z, t)

    assert FockState((x, y)).has(x)
コード例 #10
0
def test_add_sub_term():
    f = Poly((), x, y, z)

    assert Poly(2, x) - Poly(1, x) == Poly(1, x)
    assert Poly(1, x) - Poly(1, x) == Poly(0, x)
    assert Poly(1, x) - Poly(2, x) == Poly(-1, x)

    assert f.add_term(12, (1,2,3)) == Poly(((12,), ((1,2,3),)), x,y,z)
    assert f.sub_term(12, (1,2,3)) == Poly(((-12,), ((1,2,3),)), x,y,z)
コード例 #11
0
ファイル: newLT.py プロジェクト: nbliss/polyDiv
	def LM(self,poly):
		from sympy import S,Poly
		if poly==0:return poly
		poly = Poly(poly,self.variables)
		polyDict = poly.as_dict()
		exponents = polyDict.keys()
		largest = exponents[0]
		for i in xrange(len(polyDict)):
			if self.compare(exponents[i],largest): largest = exponents[i]
		return Poly({largest:S(1)},self.variables)
コード例 #12
0
ファイル: sym.py プロジェクト: shawakaze/sailfish
def poly_factorize(poly):
    """Factorize multivariate polynomials into a sum of products of monomials.

    This function can be used to decompose polynomials into a form which
    minimizes the number of additions and multiplications, and which thus
    can be evaluated efficently."""
    max_deg = {}

    if 'horner' in dir(sympy):
        return sympy.horner(poly)

    if not isinstance(poly, Poly):
        poly = Poly(sympy.expand(poly), *poly.atoms(Symbol))

    denom, poly = poly.as_integer()

    # Determine the order of factorization.  We proceed through the
    # symbols, starting with the one present in the highest order
    # in the polynomial.
    for i, sym in enumerate(poly.symbols):
        max_deg[i] = 0

    for monom in poly.monoms:
        for i, symvar in enumerate(monom):
            max_deg[i] = max(max_deg[i], symvar)

    ret_poly = 0
    monoms = list(poly.monoms)

    for isym, maxdeg in sorted(max_deg.items(), key=itemgetter(1), reverse=True):
        drop_idx = []
        new_poly = []

        for i, monom in enumerate(monoms):
            if monom[isym] > 0:
                drop_idx.append(i)
                new_poly.append((poly.coeff(*monom), monom))

        if not new_poly:
            continue

        ret_poly += sympy.factor(Poly(new_poly, *poly.symbols))

        for idx in reversed(drop_idx):
            del monoms[idx]

    # Add any remaining O(1) terms.
    new_poly = []
    for i, monom in enumerate(monoms):
        new_poly.append((poly.coeff(*monom), monom))

    if new_poly:
        ret_poly += Poly(new_poly, *poly.symbols)

    return ret_poly / denom
コード例 #13
0
def test_iterators():
    f = Poly(x**5 + x, x)

    assert list(f.iter_all_coeffs()) == \
        [1, 0, 0, 0, 1, 0]

    assert list(f.iter_all_monoms()) == \
        [(5,), (4,), (3,), (2,), (1,), (0,)]

    assert list(f.iter_all_terms()) == \
        [(1, (5,)), (0, (4,)), (0, (3,)), (0, (2,)), (1, (1,)), (0, (0,))]
コード例 #14
0
ファイル: test_expr.py プロジェクト: Botouls/sympy
def test_as_poly_as_expr():
    f = x ** 2 + 2 * x * y

    assert f.as_poly().as_expr() == f
    assert f.as_poly(x, y).as_expr() == f

    assert (f + sin(x)).as_poly(x, y) is None

    p = Poly(f, x, y)

    assert p.as_poly() == p
コード例 #15
0
def test_map_coeffs():
    p = Poly(x**2 + 2*x*y, x, y)
    q = p.map_coeffs(lambda c: 2*c)

    assert q.as_basic() == 2*x**2 + 4*x*y

    p = Poly(u*x**2 + v*x*y, x, y)
    q = p.map_coeffs(expand, complex=True)

    assert q.as_basic() == x**2*(I*im(u) + re(u)) + x*y*(I*im(v) + re(v))

    raises(PolynomialError, "p.map_coeffs(lambda c: x*c)")
コード例 #16
0
ファイル: test_basic.py プロジェクト: KevinGoodsell/sympy
def test_as_poly_basic():
    x, y = symbols('xy')

    f = x**2 + 2*x*y

    assert f.as_poly().as_basic() == f
    assert f.as_poly(x, y).as_basic() == f

    assert (f + sin(x)).as_poly(x, y) is None

    p = Poly(f, x, y)

    assert p.as_poly() == p
コード例 #17
0
	def reduce(self, debug=False, inputFilename=None, outputFilename=None):
		previousLeftBlockRegion = -1
		previousRightBlockRegion = -1
		equationCount = 0
		partIndex = 0
		equationInPartIndex = 0

		output = None
		if debug:
			input = open(inputFilename, 'r')
			output = open(outputFilename, 'w')
		else:
			input = sys.stdin

		for strEquation in input:
			equationCount += 1
			index, strEquation = strEquation.strip().split('\t')
			equation, symbols = decodeExpression(strEquation)
			equation = Poly(equation, symbols)
			equationCoefficients = [0] * len(symbols)
			for monom, coeff in equation.terms():
				try:
					i = list(monom).index(1)
					equationCoefficients[i] = 1 if coeff != 0 else 0
				except ValueError:
					continue

			equationLen = len(equationCoefficients)
			rightColumnIndex = equationLen - 1
			leftColumnIndex = 0

			while leftColumnIndex < equationLen and equationCoefficients[leftColumnIndex] != 1:
				leftColumnIndex += 1
			while rightColumnIndex > 0 and equationCoefficients[rightColumnIndex] != 1:
				rightColumnIndex -= 1

			if previousLeftBlockRegion != leftColumnIndex or previousRightBlockRegion != rightColumnIndex:
				if equationInPartIndex > 0:
					partIndex += 1
					equationInPartIndex = 0
				previousLeftBlockRegion = leftColumnIndex
				previousRightBlockRegion = rightColumnIndex
			if output is not None:
				output.write('{0}\t{1}\t{2}\n'.format(str(partIndex), index, strEquation))
			else:
				print('{0}\t{1}\t{2}'.format(str(partIndex), index, strEquation))
			equationInPartIndex += 1
		if debug:
			input.close()
		if output is not None:
			output.close()
コード例 #18
0
ファイル: internal_functions.py プロジェクト: Grahack/geophar
def _simplify(expr):
    u"""Simplifie une expression.

    Alias de simplify (sympy 0.6.4).
    Mais simplify n'est pas garanti d'être stable dans le temps.
    (Cf. simplify.__doc__)."""
    return together(expand(Poly.cancel(powsimp(expr))))
コード例 #19
0
ファイル: common.py プロジェクト: MathPhys/hermes
def gauss_lobatto_points(p):
    """
    Returns the list of Gauss-Lobatto points of the order 'p'.
    """
    x = Symbol("x")
    e = (1-x**2)*legendre(p, x).diff(x)
    e = Poly(e, x)
    if e == 0:
        return []
    with workdps(40):
        r, err = polyroots(e.all_coeffs(), error=True)
    if err > 1e-40:
        raise Exception("Internal Error: Root is not precise")
    p = []
    for x in r:
        if abs(x) < 1e-40: x = 0
        p.append(str(x))
    return p
コード例 #20
0
def test_mul_div_term():
    f = Poly(x*y**2 + 2*y, x, y)

    assert f.mul_term(0, (0, 1)) == Poly(0, x, y)

    assert f.mul_term(1) == Poly(x*y**2 + 2*y, x, y)
    assert f.mul_term(1, (0, 1)) == Poly(x*y**3 + 2*y**2, x, y)

    raises(ZeroDivisionError, "f.div_term(0)")

    assert f.div_term(1) == Poly(x*y**2 + 2*y, x, y)
    assert f.div_term(1, (0, 1)) == Poly(x*y + 2, x, y)

    assert f.mul_term(2) == Poly(2*x*y**2 + 4*y, x, y)
    assert f.mul_term(2, (0, 1)) == Poly(2*x*y**3 + 4*y**2, x, y)

    assert f.div_term(2) == Poly(x*y**2 / 2 + y, x, y)
    assert f.div_term(2, (0, 1)) == Poly(x*y / 2 + 1, x, y)
コード例 #21
0
ファイル: misc_functions.py プロジェクト: jtksai/PyCOOL
def new_poly(V_s, fields, n_coeffs):
    """Make a new polynomial function that has the same powers as V_s function
       but with coefficients C1, C2..."""
    
    from sympy import Poly
    from sympy import diff, Symbol, var, simplify, sympify, S
    from sympy.core.sympify import SympifyError
    
    P = Poly(V_s,*fields)
    d = P.as_dict()
    e = {}
    
    for key in d.iterkeys():
        #print d[key], str(d[key])
        for i in xrange(1, n_coeffs+1):
            if 'C' + str(i) in str(d[key]):
                e[key] = sympify('C'+str(i))

    P2 = Poly(e,*fields)
    return str(P2.as_basic())
コード例 #22
0
    def get_matrix(self):
        """
        Returns
        -------
        macaulay_matrix: Matrix
            The Macaulay's matrix
        """
        rows = []
        row_coefficients = self.get_row_coefficients()
        for i in range(self.n):
            for multiplier in row_coefficients[i]:
                coefficients = []
                poly = Poly(self.polynomials[i] * multiplier,
                            *self.variables)

                for mono in self.monomial_set:
                    coefficients.append(poly.coeff_monomial(mono))
                rows.append(coefficients)

        macaulay_matrix = Matrix(rows)
        return macaulay_matrix
コード例 #23
0
def discrete_realization_tustin(n0, n1, d0, T):
    z = symbols('z')
    s = 2/T*(z-1)/(z+1)
    num = ((n1*s + n0)*T*(z + 1)).simplify()
    den = ((s + d0)*T*(z + 1)).simplify()
    num_poly = Poly(num, z)
    den_poly = Poly(den, z)

    n1_z, n0_z = num_poly.coeffs()
    d1_z, d0_z = den_poly.coeffs()

    # Make denominator monic and divide numerator appropriately
    n1_z /= d1_z
    n0_z /= d1_z
    d0_z /= d1_z

    a = -d0_z
    b_times_c = (n0_z - n1_z * d0_z).simplify()
    d = n1_z

    return a, b_times_c, d
コード例 #24
0
ファイル: test_expr.py プロジェクト: rainly/sympy
def test_has_all():
    x,y,z,t,u = symbols('xyztu')
    u = symbols('u')

    i = Integer(4400)

    assert i.has(x, all=True) is False

    assert (i*x**i).has(x, all=True)
    assert (i*y**i).has(x, all=True) is False

    expr = x**2*y + sin(2**t + log(z))

    assert expr.has(y, z, t, all=True)
    assert expr.has(x, z, t, all=True)
    assert expr.has(x, y, t, all=True)
    assert expr.has(x, y, z, all=True)

    assert expr.has(y, u, t, all=True) is False
    assert expr.has(x, z, u, all=True) is False
    assert expr.has(u, y, z, all=True) is False

    assert expr.has(x, y, z, t, all=True)
    assert expr.has(x, y, z, t, u, all=True) is False

    from sympy.physics.units import m, s

    assert (x*m/s).has(x, all=True)
    assert (x*m/s).has(x, y, all=True) is False

    poly = Poly(x**2 + x*y*sin(z), x, y, t)

    assert poly.has(x, y, z, all=True)
    assert poly.has(x, y, z, t, all=True) is False

    f = FockState((x, y))
    assert f.has(x, y, all=True)
    assert f.has(x, y, z, all=True) is False
コード例 #25
0
def test_unify():
    p = Poly(x**2+x*y, x, y)
    q = Poly(x**2+2*x*y+1, x)
    r = Poly(x*z+y*z+1, x,y,z)

    assert p.unify_with(q) == p.unify_with(x**2+2*x*y+1) == \
        (Poly(x**2+x*y, x, y), Poly(x**2+2*x*y+1, x, y))

    assert p.unify_with([q, r]) == p.unify_with([x**2+2*x*y+1, r]) == \
        (Poly(x**2+x*y, x, y, z), [Poly(x**2+2*x*y+1, x,y,z), Poly(x*z+y*z+1, x,y,z)])

    assert p.unify_with((q, r)) == p.unify_with((x**2+2*x*y+1, r)) == \
        (Poly(x**2+x*y, x, y, z), (Poly(x**2+2*x*y+1, x,y,z), Poly(x*z+y*z+1, x,y,z)))
コード例 #26
0
def test_diff():
    f = Poly(a*x**2 + b*x + 2, x)

    assert f.diff(x) == Poly(2*a*x + b, x)
    assert f.diff(y) == Poly(0, x)
    assert f.diff(a) == Poly(x**2, x)
    assert f.diff(b) == Poly(x, x)

    assert f.diff() == Poly(2*a*x + b, x)

    g = Poly(a*x**2 + b*x*y + 2, x, y)

    assert g.diff(x) == Poly(2*a*x + b*y, x, y)
    assert g.diff(y) == Poly(b*x, x, y)
    assert g.diff(a) == Poly(x**2, x, y)
    assert g.diff(b) == Poly(x*y, x, y)

    assert g.diff() == g
コード例 #27
0
def test_evaluate():
    f = x**2*y*z + 2*x*y*z**3 + 3*x*y + 4*y*z

    p = Poly(f, x, y, z)

    assert p.evaluate({x: 7}) == Poly(f.subs({x: 7}), y, z)
    assert p.evaluate({x: 7, y: 5}) == Poly(f.subs({x: 7, y: 5}), z)
    assert p.evaluate({x: 7, y: 5, z: 4}) == f.subs({x: 7, y: 5, z: 4})

    p = Poly(x**2 + x*y*sin(z), x, y, order='lex')

    assert p.evaluate({x: 3, y: 0}) == 9
    assert p.evaluate({x: 0, y: 0}) == 0

    q = p.evaluate({x: 0})

    assert q == Poly(0, y, order='lex')
    assert q.is_zero == True

    assert p.evaluate({y: 0}) == \
        Poly(x**2, x, order='lex')

    raises(PolynomialError, "Poly(x + y, x, y).evaluate({x: y})")
コード例 #28
0
ファイル: evalf.py プロジェクト: arghdos/sympy
def check_convergence(numer, denom, n):
    """
    Returns (h, g, p) where
    -- h is:
        > 0 for convergence of rate 1/factorial(n)**h
        < 0 for divergence of rate factorial(n)**(-h)
        = 0 for geometric or polynomial convergence or divergence

    -- abs(g) is:
        > 1 for geometric convergence of rate 1/h**n
        < 1 for geometric divergence of rate h**n
        = 1 for polynomial convergence or divergence

        (g < 0 indicates an alternating series)

    -- p is:
        > 1 for polynomial convergence of rate 1/n**h
        <= 1 for polynomial divergence of rate n**(-h)

    """
    from sympy import Poly
    npol = Poly(numer, n)
    dpol = Poly(denom, n)
    p = npol.degree()
    q = dpol.degree()
    rate = q - p
    if rate:
        return rate, None, None
    constant = dpol.LC() / npol.LC()
    if abs(constant) != 1:
        return rate, constant, None
    if npol.degree() == dpol.degree() == 0:
        return rate, constant, 0
    pc = npol.all_coeffs()[1]
    qc = dpol.all_coeffs()[1]
    return rate, constant, (qc - pc)/dpol.LC()
コード例 #29
0
def ratint_ratpart(f, g, x):
    """Horowitz-Ostrogradsky algorithm.

       Given a field K and polynomials f and g in K[x], such that f and g
       are coprime and deg(f) < deg(g), returns fractions A and B in K(x),
       such that f/g = A' + B and B has square-free denominator.

    """
    f, g = Poly(f, x), Poly(g, x)

    u = poly_gcd(g, g.diff())
    v = poly_div(g, u)[0]

    n = u.degree - 1
    m = v.degree - 1
    d = g.degree

    A_coeff = [ Symbol('a' + str(n-i), dummy=True) for i in xrange(0, n+1) ]
    B_coeff = [ Symbol('b' + str(m-i), dummy=True) for i in xrange(0, m+1) ]

    symbols = A_coeff + B_coeff

    A = Poly(zip(A_coeff, xrange(n, -1, -1)), x)
    B = Poly(zip(B_coeff, xrange(m, -1, -1)), x)

    H = f - A.diff()*v + A*poly_div(u.diff()*v, u)[0] - B*u

    result = solve(H.coeffs, symbols)

    A = A.subs(result)
    B = B.subs(result)

    rat_part = Poly.cancel((A, u), x)
    log_part = Poly.cancel((B, v), x)

    return rat_part, log_part
コード例 #30
0
ファイル: test_basic.py プロジェクト: KevinGoodsell/sympy
def test_has_any_symbols():
    x,y,z,t,u = symbols('xyztu')

    i = Integer(4400)

    assert i.has_any_symbols(x) == False

    assert (i*x**i).has_any_symbols(x) == True
    assert (i*y**i).has_any_symbols(x) == False
    assert (i*y**i).has_any_symbols(x, y) == True

    expr = x**2*y + sin(2**t + log(z))

    assert expr.has_any_symbols(u) == False

    assert expr.has_any_symbols(x) == True
    assert expr.has_any_symbols(y) == True
    assert expr.has_any_symbols(z) == True
    assert expr.has_any_symbols(t) == True

    assert expr.has_any_symbols(x, y, z, t) == True
    assert expr.has_any_symbols(x, y, z, t, u)  == True

    from sympy.physics.units import m, s

    assert (x*m/s).has_any_symbols(x) == True
    assert (x*m/s).has_all_symbols(x) == True

    assert (x*m/s).has_any_symbols(y, z) == False
    assert (x*m/s).has_all_symbols(x, y) == False

    poly = Poly(x**2 + x*y*sin(z), x, y, t)

    assert poly.has_any_symbols(x) == True
    assert poly.has_any_symbols(x, y, z) == True
    assert poly.has_any_symbols(x, y, z, t) == True

    assert poly.has_all_symbols(x, y, z) == True
    assert poly.has_all_symbols(x, y, z, t) == False
コード例 #31
0
def test_weak_normalizer():
    a = Poly((1 + x)*t**5 + 4*t**4 + (-1 - 3*x)*t**3 - 4*t**2 + (-2 + 2*x)*t, t)
    d = Poly(t**4 - 3*t**2 + 2, t)
    DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]})
    r = weak_normalizer(a, d, DE, z)
    assert r == (Poly(t**5 - t**4 - 4*t**3 + 4*t**2 + 4*t - 4, t),
        (Poly((1 + x)*t**2 + x*t, t), Poly(t + 1, t)))
    assert weak_normalizer(r[1][0], r[1][1], DE) == (Poly(1, t), r[1])
    r = weak_normalizer(Poly(1 + t**2), Poly(t**2 - 1, t), DE, z)
    assert r == (Poly(t**4 - 2*t**2 + 1, t), (Poly(-3*t**2 + 1, t), Poly(t**2 - 1, t)))
    assert weak_normalizer(r[1][0], r[1][1], DE, z) == (Poly(1, t), r[1])
    DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1 + t**2)]})
    r = weak_normalizer(Poly(1 + t**2), Poly(t, t), DE, z)
    assert r == (Poly(t, t), (Poly(0, t), Poly(1, t)))
    assert weak_normalizer(r[1][0], r[1][1], DE, z) == (Poly(1, t), r[1])
コード例 #32
0
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(y, x))
    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)

    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
コード例 #33
0
def test_DifferentialExtension_exp():
    assert DifferentialExtension(exp(x) + exp(x**2), x)._important_attrs == \
        (Poly(t1 + t0, t1), Poly(1, t1), [Poly(1, x,), Poly(t0, t0),
        Poly(2*x*t1, t1)], [x, t0, t1], [Lambda(i, exp(i)),
        Lambda(i, exp(i**2))], [], [None, 'exp', 'exp'], [None, x, x**2])
    assert DifferentialExtension(exp(x) + exp(2*x), x)._important_attrs == \
        (Poly(t0**2 + t0, t0), Poly(1, t0), [Poly(1, x), Poly(t0, t0)], [x, t0],
        [Lambda(i, exp(i))], [], [None, 'exp'], [None, x])
    assert DifferentialExtension(exp(x) + exp(x/2), x)._important_attrs == \
        (Poly(t0**2 + t0, t0), Poly(1, t0), [Poly(1, x), Poly(t0/2, t0)],
        [x, t0], [Lambda(i, exp(i/2))], [], [None, 'exp'], [None, x/2])
    assert DifferentialExtension(exp(x) + exp(x**2) + exp(x + x**2), x)._important_attrs == \
        (Poly((1 + t0)*t1 + t0, t1), Poly(1, t1), [Poly(1, x), Poly(t0, t0),
        Poly(2*x*t1, t1)], [x, t0, t1], [Lambda(i, exp(i)),
        Lambda(i, exp(i**2))], [], [None, 'exp', 'exp'], [None, x, x**2])
    assert DifferentialExtension(exp(x) + exp(x**2) + exp(x + x**2 + 1), x)._important_attrs == \
        (Poly((1 + S.Exp1*t0)*t1 + t0, t1), Poly(1, t1), [Poly(1, x),
        Poly(t0, t0), Poly(2*x*t1, t1)], [x, t0, t1], [Lambda(i, exp(i)),
        Lambda(i, exp(i**2))], [], [None, 'exp', 'exp'], [None, x, x**2])
    assert DifferentialExtension(exp(x) + exp(x**2) + exp(x/2 + x**2), x)._important_attrs == \
        (Poly((t0 + 1)*t1 + t0**2, t1), Poly(1, t1), [Poly(1, x),
        Poly(t0/2, t0), Poly(2*x*t1, t1)], [x, t0, t1],
        [Lambda(i, exp(i/2)), Lambda(i, exp(i**2))],
        [(exp(x/2), sqrt(exp(x)))], [None, 'exp', 'exp'], [None, x/2, x**2])
    assert DifferentialExtension(exp(x) + exp(x**2) + exp(x/2 + x**2 + 3), x)._important_attrs == \
        (Poly((t0*exp(3) + 1)*t1 + t0**2, t1), Poly(1, t1), [Poly(1, x),
        Poly(t0/2, t0), Poly(2*x*t1, t1)], [x, t0, t1], [Lambda(i, exp(i/2)),
        Lambda(i, exp(i**2))], [(exp(x/2), sqrt(exp(x)))], [None, 'exp', 'exp'],
        [None, x/2, x**2])
    assert DifferentialExtension(sqrt(exp(x)), x)._important_attrs == \
        (Poly(t0, t0), Poly(1, t0), [Poly(1, x), Poly(t0/2, t0)], [x, t0],
        [Lambda(i, exp(i/2))], [(exp(x/2), sqrt(exp(x)))], [None, 'exp'], [None, x/2])

    assert DifferentialExtension(exp(x/2), x)._important_attrs == \
        (Poly(t0, t0), Poly(1, t0), [Poly(1, x), Poly(t0/2, t0)], [x, t0],
        [Lambda(i, exp(i/2))], [], [None, 'exp'], [None, x/2])
コード例 #34
0
def test_DifferentialExtension_symlog():
    # See comment on test_risch_integrate below
    assert DifferentialExtension(log(x**x), x)._important_attrs == \
        (Poly(t0*x, t1), Poly(1, t1), [Poly(1, x), Poly(1/x, t0), Poly((t0 +
            1)*t1, t1)], [x, t0, t1], [Lambda(i, log(i)), Lambda(i, exp(i*t0))],
            [(exp(x*log(x)), x**x)], [None, 'log', 'exp'], [None, x, t0*x])
    assert DifferentialExtension(log(x**y), x)._important_attrs == \
        (Poly(y*t0, t0), Poly(1, t0), [Poly(1, x), Poly(1/x, t0)], [x, t0],
        [Lambda(i, log(i))], [(y*log(x), log(x**y))], [None, 'log'],
        [None, x])
    assert DifferentialExtension(log(sqrt(x)), x)._important_attrs == \
        (Poly(t0, t0), Poly(2, t0), [Poly(1, x), Poly(1/x, t0)], [x, t0],
        [Lambda(i, log(i))], [(log(x)/2, log(sqrt(x)))], [None, 'log'],
        [None, x])
コード例 #35
0
def test_order_at():
    a = Poly(t**4, t)
    b = Poly((t**2 + 1)**3*t, t)
    c = Poly((t**2 + 1)**6*t, t)
    d = Poly((t**2 + 1)**10*t**10, t)
    e = Poly((t**2 + 1)**100*t**37, t)
    p1 = Poly(t, t)
    p2 = Poly(1 + t**2, t)
    assert order_at(a, p1, t) == 4
    assert order_at(b, p1, t) == 1
    assert order_at(c, p1, t) == 1
    assert order_at(d, p1, t) == 10
    assert order_at(e, p1, t) == 37
    assert order_at(a, p2, t) == 0
    assert order_at(b, p2, t) == 3
    assert order_at(c, p2, t) == 6
    assert order_at(d, p1, t) == 10
    assert order_at(e, p2, t) == 100
    assert order_at(Poly(0, t), Poly(t, t), t) == oo
    assert order_at_oo(Poly(t**2 - 1, t), Poly(t + 1), t) == \
        order_at_oo(Poly(t - 1, t), Poly(1, t), t) == -1
    assert order_at_oo(Poly(0, t), Poly(1, t), t) == oo
コード例 #36
0
def test_solve_poly_rde_cancel():
    # exp
    DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]})
    assert cancel_exp(Poly(2*x, t), Poly(2*x, t), 0, DE) == \
        Poly(1, t)
    assert cancel_exp(Poly(2*x, t), Poly((1 + 2*x)*t, t), 1, DE) == \
        Poly(t, t)
    # TODO: Add more exp tests, including tests that require is_deriv_in_field()

    # primitive
    DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]})

    # If the DecrementLevel context manager is working correctly, this shouldn't
    # cause any problems with the further tests.
    raises(NonElementaryIntegralException, lambda: cancel_primitive(Poly(1, t), Poly(t, t), oo, DE))

    assert cancel_primitive(Poly(1, t), Poly(t + 1/x, t), 2, DE) == \
        Poly(t, t)
    assert cancel_primitive(Poly(4*x, t), Poly(4*x*t**2 + 2*t/x, t), 3, DE) == \
        Poly(t**2, t)
コード例 #37
0
def test_splitfactor():
    p = Poly(4 * x**4 * t**5 + (-4 * x**3 - 4 * x**4) * t**4 +
             (-3 * x**2 + 2 * x**3) * t**3 +
             (2 * x + 7 * x**2 + 2 * x**3) * t**2 +
             (1 - 4 * x - 4 * x**2) * t - 1 + 2 * x,
             t,
             field=True)
    DE = DifferentialExtension(extension={
        'D': [Poly(1, x),
              Poly(-t**2 - 3 / (2 * x) * t + 1 / (2 * x), t)]
    })
    assert splitfactor(p, DE) == (Poly(
        4 * x**4 * t**3 + (-8 * x**3 - 4 * x**4) * t**2 +
        (4 * x**2 + 8 * x**3) * t - 4 * x**2,
        t), Poly(t**2 + 1 / x * t + (1 - 2 * x) / (4 * x**2),
                 t,
                 domain='ZZ(x)'))
    assert splitfactor(Poly(x, t), DE) == (Poly(x, t), Poly(1, t))
    r = Poly(
        -4 * x**4 * z**2 + 4 * x**6 * z**2 - z * x**3 - 4 * x**5 * z**3 +
        4 * x**3 * z**3 + x**4 + z * x**5 - x**6, t)
    DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1 / x, t)]})
    assert splitfactor(r, DE, coefficientD=True) == \
        (Poly(x*z - x**2 - z*x**3 + x**4, t), Poly(-x**2 + 4*x**2*z**2, t))
    assert splitfactor_sqf(r, DE, coefficientD=True) == \
        (((Poly(x*z - x**2 - z*x**3 + x**4, t), 1),), ((Poly(-x**2 + 4*x**2*z**2, t), 1),))
    assert splitfactor(Poly(0, t), DE) == (Poly(0, t), Poly(1, t))
    assert splitfactor_sqf(Poly(0, t), DE) == (((Poly(0, t), 1), ), ())
コード例 #38
0
def test_canonical_representation():
    DE = DifferentialExtension(
        extension={'D': [Poly(1, x), Poly(1 + t**2, t)]})
    assert canonical_representation(Poly(x - t, t), Poly(t**2, t), DE) == \
        (Poly(0, t), (Poly(0, t),
        Poly(1, t)), (Poly(-t + x, t),
        Poly(t**2, t)))
    DE = DifferentialExtension(
        extension={'D': [Poly(1, x), Poly(t**2 + 1, t)]})
    assert canonical_representation(Poly(t**5 + t**3 + x**2*t + 1, t),
    Poly((t**2 + 1)**3, t), DE) == \
        (Poly(0, t), (Poly(t**5 + t**3 + x**2*t + 1, t),
        Poly(t**6 + 3*t**4 + 3*t**2 + 1, t)), (Poly(0, t), Poly(1, t)))
コード例 #39
0
ファイル: polynomial.py プロジェクト: Notgnoshi/cryptography
from itertools import product
from sympy import Symbol, div, Poly


x = Symbol('x')
gf28_mod = Poly(x ** 8 + x ** 4 + x ** 3 + x + 1, x, modulus=2)


def reduce_gf28(poly):
    """
        Reduces the given sympy polynomial under the GF(2**8) polynomial x**8 + x**4 + x**3 + x + 1

        Example:

        >>> # Example taken from the textbook
        >>> f = Poly(x**2 * (x**7 + x**6 + x**3 + x + 1), x, domain='GF(2)')
        >>> f
        Poly(x**9 + x**8 + x**5 + x**3 + x**2, x, modulus=2)
        >>> reduce_gf28(f)
        Poly(1, x, modulus=2)
        >>> reduce_gf28(Poly((x**2 + x + 1) * (x**8 + x**6 + x**2 + 1), x, modulus=2))
        Poly(x**7 + 1, x, modulus=2)
    """
    _, remainder = div(poly, gf28_mod, x)
    # GF(2) sets coefficients as elements of Z_2
    return remainder.as_poly(x, domain='GF(2)')


def coeffs2poly(coeffs):
    """
        Given a list of coefficients (mod 2), most significant coefficient first, return a sympy
コード例 #40
0
ファイル: test_sympify.py プロジェクト: zachetienne/sympy
def test_sympify_poly():
    p = Poly(x**2 + x + 1, x)

    assert _sympify(p) is p
    assert sympify(p) is p
コード例 #41
0
def test_solve_poly_inequality():
    assert psolve(Poly(0, x), '==') == [S.Reals]
    assert psolve(Poly(1, x), '==') == [S.EmptySet]
    assert psolve(PurePoly(x + 1, x), ">") == [Interval(-1, oo, True, False)]
コード例 #42
0
ファイル: test_wester.py プロジェクト: twobitlogic/sympy
def test_H19():
    a = symbols('a')
    # The idea is to let a**2 == 2, then solve 1/(a-1). Answer is a+1")
    assert Poly(a - 1).invert(Poly(a**2 - 2)) == a + 1
コード例 #43
0
def test_issue_19161():
    polynomial = Poly('x**2').simplify()
    assert (polynomial - x**2).simplify() == 0
コード例 #44
0
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

    # minimal polynomial of I
    assert minimal_polynomial(I, x, domain=QQ.algebraic_field(I)) == x - I
    K = QQ.algebraic_field(I * (sqrt(2) + 1))
    assert minimal_polynomial(I, x, domain=K) == x - I
    assert minimal_polynomial(I, x, domain=QQ) == x**2 + 1
    assert minimal_polynomial(I, x, domain='QQ(y)') == x**2 + 1
コード例 #45
0
def optimize_lsq(p, nodes):

    # Define phi
    x1, x2, x3, x4 = symbols('x1, x2, x3, x4')
    h1, h2, h3, h4, J12, J13, J23, J24, J34, a, b = symbols(
        'h1, h2, h3, h4, J12, J13, J23, J24, J34, a, b')

    phi = x1 * h1 + x2 * h2 + x3 * h3 + x4 * h4 + J12 * x1 * x2 + J13 * x1 * x3 + J23 * x2 * x3 + J24 * x2 * x4 + J34 * x3 * x4 + a + b
    phi1 = x1 * h1 + x2 * h2 + x3 * h3 + J12 * x1 * x2 + J13 * x1 * x3 + J23 * x2 * x3 + a
    phi2 = x2 * h2 + x3 * h3 + x4 * h4 + J23 * x2 * x3 + J24 * x2 * x4 + J34 * x3 * x4 + b
    coeff = Poly(phi, (h1, h2, h3, h4, J12, J13, J23, J24, J34, a, b)).coeffs()
    coeff1 = Poly(phi1, (h1, h2, h3, J12, J13, J23, a)).coeffs()
    coeff2 = Poly(phi2, (h2, h3, h4, J23, J24, J34, b)).coeffs()

    A = np.zeros(shape=(2**len(nodes), 11))
    A1 = np.zeros(shape=(2**len(nodes), 11))

    for i, v in enumerate(list(itertools.product([0, 1], repeat=len(nodes)))):
        A[i] = [
            ii.subs({
                x1: v[0],
                x2: v[1],
                x3: v[2],
                x4: v[3]
            }) for ii in coeff
        ]

    for i, v in enumerate(
            list(itertools.product([0, 1], repeat=len(nodes) - 1))):
        A1[i, [0, 1, 2, 4, 5, 6, 9]] = [
            ii.subs({
                x1: v[0],
                x2: v[1],
                x3: v[2]
            }) for ii in coeff1
        ]
        A1[i + 8, [1, 2, 3, 6, 7, 8, 10]] = [
            ii.subs({
                x2: v[0],
                x3: v[1],
                x4: v[2]
            }) for ii in coeff2
        ]

    for i, v in enumerate(
            list(itertools.product([0, 1], repeat=len(nodes) - 1))):
        A1[i, [0, 1, 2, 4, 5, 6, 9]] = [
            ii.subs({
                x1: v[0],
                x2: v[1],
                x3: v[2]
            }) for ii in coeff1
        ]
        A1[i + 8, [1, 2, 3, 6, 7, 8, 10]] = [
            ii.subs({
                x2: v[0],
                x3: v[1],
                x4: v[2]
            }) for ii in coeff2
        ]

    p_true_view = p[[bit2int(v) for v in A1[:, :4]]]
    B = np.array(A[:, :9])

    ## CONST_IN_ISING = False

    ## if not CONST_IN_ISING:
    ##     A = A[:, :-1]
    ##     plt.suptitle('No constant in QUBO')
    ## solve y = A*x

    Z_lsq = 1.0
    y = -np.log(Z_lsq * (p_true_view + 1e-20))
    x = np.linalg.lstsq(A1, y, rcond=None)
    hJ = x[0][:9]

    ## Visualize the solution
    plt.bar(np.array(range(len(y))), y, width=0.3, label='true y')
    plt.bar(np.array(range(len(y))) + 0.3,
            np.dot(A1, x[0]),
            width=0.3,
            label='lsq-fit')
    plt.xlabel('x')
    plt.ylabel('probability')
    plt.legend()
    print('Z_lsq', np.sum(np.exp(-np.dot(A, x[0]))))

    return hJ
コード例 #46
0
def test_log_to_atan():
    f, g = (Poly(x + S.Half, x, domain='QQ'), Poly(sqrt(3) / 2, x,
                                                   domain='EX'))
    fg_ans = 2 * atan(2 * sqrt(3) * x / 3 + sqrt(3) / 3)
    assert log_to_atan(f, g) == fg_ans
    assert log_to_atan(g, f) == -fg_ans
コード例 #47
0
def test_DifferentialExtension_misc():
    # Odd ends
    assert DifferentialExtension(sin(y)*exp(x), x)._important_attrs == \
        (Poly(sin(y)*t0, t0, domain='ZZ[sin(y)]'), Poly(1, t0, domain='ZZ'),
        [Poly(1, x, domain='ZZ'), Poly(t0, t0, domain='ZZ')], [x, t0],
        [Lambda(i, exp(i))], [], [None, 'exp'], [None, x])
    raises(NotImplementedError, lambda: DifferentialExtension(sin(x), x))
    assert DifferentialExtension(10**x, x)._important_attrs == \
        (Poly(t0, t0), Poly(1, t0), [Poly(1, x), Poly(log(10)*t0, t0)], [x, t0],
        [Lambda(i, exp(i*log(10)))], [(exp(x*log(10)), 10**x)], [None, 'exp'],
        [None, x*log(10)])
    assert DifferentialExtension(log(x) + log(x**2), x)._important_attrs in [
        (Poly(3 * t0, t0), Poly(2, t0), [Poly(1, x),
                                         Poly(2 / x, t0)], [x, t0],
         [Lambda(i, log(i**2))], [], [
             None,
         ], [], [1], [x**2]),
        (Poly(3 * t0, t0), Poly(1, t0), [Poly(1, x),
                                         Poly(1 / x, t0)], [x, t0],
         [Lambda(i, log(i))], [], [None, 'log'], [None, x])
    ]
    assert DifferentialExtension(S.Zero, x)._important_attrs == \
        (Poly(0, x), Poly(1, x), [Poly(1, x)], [x], [], [], [None], [None])
    assert DifferentialExtension(tan(atan(x).rewrite(log)), x)._important_attrs == \
        (Poly(x, x), Poly(1, x), [Poly(1, x)], [x], [], [], [None], [None])
コード例 #48
0
def test_normal_denom():
    DE = DifferentialExtension(extension={'D': [Poly(1, x)]})
    raises(NonElementaryIntegralException, lambda: normal_denom(Poly(1, x), Poly(1, x),
    Poly(1, x), Poly(x, x), DE))
    fa, fd = Poly(t**2 + 1, t), Poly(1, t)
    ga, gd = Poly(1, t), Poly(t**2, t)
    DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**2 + 1, t)]})
    assert normal_denom(fa, fd, ga, gd, DE) == \
        (Poly(t, t), (Poly(t**3 - t**2 + t - 1, t), Poly(1, t)), (Poly(1, t),
        Poly(1, t)), Poly(t, t))
コード例 #49
0
def test_solve_poly_rde_no_cancel():
    # deg(b) large
    DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1 + t**2, t)]})
    assert solve_poly_rde(Poly(t**2 + 1, t), Poly(t**3 + (x + 1)*t**2 + t + x + 2, t),
    oo, DE) == Poly(t + x, t)
    # deg(b) small
    DE = DifferentialExtension(extension={'D': [Poly(1, x)]})
    assert solve_poly_rde(Poly(0, x), Poly(x/2 - S(1)/4, x), oo, DE) == \
        Poly(x**2/4 - x/4, x)
    DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**2 + 1, t)]})
    assert solve_poly_rde(Poly(2, t), Poly(t**2 + 2*t + 3, t), 1, DE) == \
        Poly(t + 1, t, x)
    # deg(b) == deg(D) - 1
    DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**2 + 1, t)]})
    assert no_cancel_equal(Poly(1 - t, t),
    Poly(t**3 + t**2 - 2*x*t - 2*x, t), oo, DE) == \
        (Poly(t**2, t), 1, Poly((-2 - 2*x)*t - 2*x, t))
コード例 #50
0
def test_integrate_primitive():
    DE = DifferentialExtension(extension={
        'D': [Poly(1, x), Poly(1 / x, t)],
        'Tfuncs': [log]
    })
    assert integrate_primitive(Poly(t, t), Poly(1, t),
                               DE) == (x * log(x), -1, True)
    assert integrate_primitive(Poly(x, t), Poly(t, t),
                               DE) == (0, NonElementaryIntegral(x / log(x),
                                                                x), False)

    DE = DifferentialExtension(
        extension={
            'D': [Poly(1, x),
                  Poly(1 / x, t1),
                  Poly(1 / (x + 1), t2)],
            'Tfuncs': [log, Lambda(i, log(i + 1))]
        })
    assert integrate_primitive(Poly(t1, t2), Poly(t2, t2), DE) == \
        (0, NonElementaryIntegral(log(x)/log(1 + x), x), False)

    DE = DifferentialExtension(
        extension={
            'D': [Poly(1, x),
                  Poly(1 / x, t1),
                  Poly(1 / (x * t1), t2)],
            'Tfuncs': [log, Lambda(i, log(log(i)))]
        })
    assert integrate_primitive(Poly(t2, t2), Poly(t1, t2), DE) == \
        (0, NonElementaryIntegral(log(log(x))/log(x), x), False)

    DE = DifferentialExtension(extension={
        'D': [Poly(1, x), Poly(1 / x, t0)],
        'Tfuncs': [log]
    })
    assert integrate_primitive(Poly(x**2*t0**3 + (3*x**2 + x)*t0**2 + (3*x**2
    + 2*x)*t0 + x**2 + x, t0), Poly(x**2*t0**4 + 4*x**2*t0**3 + 6*x**2*t0**2 +
    4*x**2*t0 + x**2, t0), DE) == \
        (-1/(log(x) + 1), NonElementaryIntegral(1/(log(x) + 1), x), False)
コード例 #51
0
def test_DifferentialExtension_handle_first():
    assert DifferentialExtension(exp(x)*log(x), x, handle_first='log')._important_attrs == \
        (Poly(t0*t1, t1), Poly(1, t1), [Poly(1, x), Poly(1/x, t0),
        Poly(t1, t1)], [x, t0, t1], [Lambda(i, log(i)), Lambda(i, exp(i))],
        [], [None, 'log', 'exp'], [None, x, x])
    assert DifferentialExtension(exp(x)*log(x), x, handle_first='exp')._important_attrs == \
        (Poly(t0*t1, t1), Poly(1, t1), [Poly(1, x), Poly(t0, t0),
        Poly(1/x, t1)], [x, t0, t1], [Lambda(i, exp(i)), Lambda(i, log(i))],
        [], [None, 'exp', 'log'], [None, x, x])

    # This one must have the log first, regardless of what we set it to
    # (because the log is inside of the exponential: x**x == exp(x*log(x)))
    assert DifferentialExtension(-x**x*log(x)**2 + x**x - x**x/x, x,
    handle_first='exp')._important_attrs == \
        DifferentialExtension(-x**x*log(x)**2 + x**x - x**x/x, x,
        handle_first='log')._important_attrs == \
        (Poly((-1 + x - x*t0**2)*t1, t1), Poly(x, t1),
            [Poly(1, x), Poly(1/x, t0), Poly((1 + t0)*t1, t1)], [x, t0, t1],
            [Lambda(i, log(i)), Lambda(i, exp(t0*i))], [(exp(x*log(x)), x**x)],
            [None, 'log', 'exp'], [None, x, t0*x])
コード例 #52
0
def test_integrate_hyperexponential():
    # TODO: Add tests for integrate_hyperexponential() from the book
    a = Poly(
        (1 + 2 * t1 + t1**2 + 2 * t1**3) * t**2 + (1 + t1**2) * t + 1 + t1**2,
        t)
    d = Poly(1, t)
    DE = DifferentialExtension(
        extension={
            'D': [Poly(1, x),
                  Poly(1 + t1**2, t1),
                  Poly(t * (1 + t1**2), t)],
            'Tfuncs': [tan, Lambda(i, exp(tan(i)))]
        })
    assert integrate_hyperexponential(a, d, DE) == \
        (exp(2*tan(x))*tan(x) + exp(tan(x)), 1 + t1**2, True)
    a = Poly((t1**3 + (x + 1) * t1**2 + t1 + x + 2) * t, t)
    assert integrate_hyperexponential(a, d, DE) == \
        ((x + tan(x))*exp(tan(x)), 0, True)

    a = Poly(t, t)
    d = Poly(1, t)
    DE = DifferentialExtension(extension={
        'D': [Poly(1, x), Poly(2 * x * t, t)],
        'Tfuncs': [Lambda(i, exp(x**2))]
    })

    assert integrate_hyperexponential(a, d, DE) == \
        (0, NonElementaryIntegral(exp(x**2), x), False)

    DE = DifferentialExtension(extension={
        'D': [Poly(1, x), Poly(t, t)],
        'Tfuncs': [exp]
    })
    assert integrate_hyperexponential(a, d, DE) == (exp(x), 0, True)

    a = Poly(
        25 * t**6 - 10 * t**5 + 7 * t**4 - 8 * t**3 + 13 * t**2 + 2 * t - 1, t)
    d = Poly(25 * t**6 + 35 * t**4 + 11 * t**2 + 1, t)
    assert integrate_hyperexponential(a, d, DE) == \
        (-(11 - 10*exp(x))/(5 + 25*exp(2*x)) + log(1 + exp(2*x)), -1, True)
    DE = DifferentialExtension(
        extension={
            'D': [Poly(1, x), Poly(t0, t0),
                  Poly(t0 * t, t)],
            'Tfuncs': [exp, Lambda(i, exp(exp(i)))]
        })
    assert integrate_hyperexponential(Poly(2 * t0 * t**2, t), Poly(1, t),
                                      DE) == (exp(2 * exp(x)), 0, True)

    DE = DifferentialExtension(
        extension={
            'D': [Poly(1, x), Poly(t0, t0),
                  Poly(-t0 * t, t)],
            'Tfuncs': [exp, Lambda(i, exp(-exp(i)))]
        })
    assert integrate_hyperexponential(Poly(-27*exp(9) - 162*t0*exp(9) +
    27*x*t0*exp(9), t), Poly((36*exp(18) + x**2*exp(18) - 12*x*exp(18))*t, t), DE) == \
        (27*exp(exp(x))/(-6*exp(9) + x*exp(9)), 0, True)

    DE = DifferentialExtension(extension={
        'D': [Poly(1, x), Poly(t, t)],
        'Tfuncs': [exp]
    })
    assert integrate_hyperexponential(Poly(x**2/2*t, t), Poly(1, t), DE) == \
        ((2 - 2*x + x**2)*exp(x)/2, 0, True)
    assert integrate_hyperexponential(Poly(1 + t, t), Poly(t, t), DE) == \
        (-exp(-x), 1, True)  # x - exp(-x)
    assert integrate_hyperexponential(Poly(x, t), Poly(t + 1, t), DE) == \
        (0, NonElementaryIntegral(x/(1 + exp(x)), x), False)

    DE = DifferentialExtension(
        extension={
            'D': [Poly(1, x),
                  Poly(1 / x, t0),
                  Poly(2 * x * t1, t1)],
            'Tfuncs': [log, Lambda(i, exp(i**2))]
        })

    elem, nonelem, b = integrate_hyperexponential(
        Poly(
            (8 * x**7 - 12 * x**5 + 6 * x**3 - x) * t1**4 +
            (8 * t0 * x**7 - 8 * t0 * x**6 - 4 * t0 * x**5 + 2 * t0 * x**3 +
             2 * t0 * x**2 - t0 * x + 24 * x**8 - 36 * x**6 - 4 * x**5 +
             22 * x**4 + 4 * x**3 - 7 * x**2 - x + 1) * t1**3 +
            (8 * t0 * x**8 - 4 * t0 * x**6 - 16 * t0 * x**5 - 2 * t0 * x**4 +
             12 * t0 * x**3 + t0 * x**2 - 2 * t0 * x + 24 * x**9 - 36 * x**7 -
             8 * x**6 + 22 * x**5 + 12 * x**4 - 7 * x**3 - 6 * x**2 + x + 1) *
            t1**2 + (8 * t0 * x**8 - 8 * t0 * x**6 - 16 * t0 * x**5 +
                     6 * t0 * x**4 + 10 * t0 * x**3 - 2 * t0 * x**2 - t0 * x +
                     8 * x**10 - 12 * x**8 - 4 * x**7 + 2 * x**6 + 12 * x**5 +
                     3 * x**4 - 9 * x**3 - x**2 + 2 * x) * t1 + 8 * t0 * x**7 -
            12 * t0 * x**6 - 4 * t0 * x**5 + 8 * t0 * x**4 - t0 * x**2 -
            4 * x**7 + 4 * x**6 + 4 * x**5 - 4 * x**4 - x**3 + x**2, t1),
        Poly((8 * x**7 - 12 * x**5 + 6 * x**3 - x) * t1**4 +
             (24 * x**8 + 8 * x**7 - 36 * x**6 - 12 * x**5 + 18 * x**4 +
              6 * x**3 - 3 * x**2 - x) * t1**3 +
             (24 * x**9 + 24 * x**8 - 36 * x**7 - 36 * x**6 + 18 * x**5 +
              18 * x**4 - 3 * x**3 - 3 * x**2) * t1**2 +
             (8 * x**10 + 24 * x**9 - 12 * x**8 - 36 * x**7 + 6 * x**6 +
              18 * x**5 - x**4 - 3 * x**3) * t1 + 8 * x**10 - 12 * x**8 +
             6 * x**6 - x**4, t1), DE)

    assert factor(elem) == -((x - 1) * log(x) / ((x + exp(x**2)) *
                                                 (2 * x**2 - 1)))
    assert (nonelem,
            b) == (NonElementaryIntegral(exp(x**2) / (exp(x**2) + 1),
                                         x), False)
コード例 #53
0
def test_derivation():
    p = Poly(
        4 * x**4 * t**5 + (-4 * x**3 - 4 * x**4) * t**4 +
        (-3 * x**2 + 2 * x**3) * t**3 + (2 * x + 7 * x**2 + 2 * x**3) * t**2 +
        (1 - 4 * x - 4 * x**2) * t - 1 + 2 * x, t)
    DE = DifferentialExtension(extension={
        'D': [Poly(1, x),
              Poly(-t**2 - 3 / (2 * x) * t + 1 / (2 * x), t)]
    })
    assert derivation(p, DE) == Poly(
        -20 * x**4 * t**6 + (2 * x**3 + 16 * x**4) * t**5 +
        (21 * x**2 + 12 * x**3) * t**4 +
        (7 * x / 2 - 25 * x**2 - 12 * x**3) * t**3 +
        (-5 - 15 * x / 2 + 7 * x**2) * t**2 -
        (3 - 8 * x - 10 * x**2 - 4 * x**3) / (2 * x) * t + (1 - 4 * x**2) /
        (2 * x), t)
    assert derivation(Poly(1, t), DE) == Poly(0, t)
    assert derivation(Poly(t, t), DE) == DE.d
    assert derivation(Poly(t**2 + 1/x*t + (1 - 2*x)/(4*x**2), t), DE) == \
        Poly(-2*t**3 - 4/x*t**2 - (5 - 2*x)/(2*x**2)*t - (1 - 2*x)/(2*x**3), t, domain='ZZ(x)')
    DE = DifferentialExtension(
        extension={'D': [Poly(1, x), Poly(1 / x, t1),
                         Poly(t, t)]})
    assert derivation(Poly(x * t * t1, t), DE) == Poly(t * t1 + x * t * t1 + t,
                                                       t)
    assert derivation(Poly(x*t*t1, t), DE, coefficientD=True) == \
        Poly((1 + t1)*t, t)
    DE = DifferentialExtension(extension={'D': [Poly(1, x)]})
    assert derivation(Poly(x, x), DE) == Poly(1, x)
    # Test basic option
    assert derivation((x + 1) / (x - 1), DE,
                      basic=True) == -2 / (1 - 2 * x + x**2)
    DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]})
    assert derivation((t + 1) / (t - 1), DE,
                      basic=True) == -2 * t / (1 - 2 * t + t**2)
    assert derivation(t + 1, DE, basic=True) == t
コード例 #54
0
def test_spde():
    DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**2 + 1, t)]})
    raises(NonElementaryIntegralException, lambda: spde(Poly(t, t), Poly((t - 1)*(t**2 + 1), t), Poly(1, t), 0, DE))
    DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]})
    assert spde(Poly(t**2 + x*t*2 + x**2, t), Poly(t**2/x**2 + (2/x - 1)*t, t),
    Poly(t**2/x**2 + (2/x - 1)*t, t), 0, DE) == \
        (Poly(0, t), Poly(0, t), 0, Poly(0, t), Poly(1, t))
    DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t0/x**2, t0), Poly(1/x, t)]})
    assert spde(Poly(t**2, t), Poly(-t**2/x**2 - 1/x, t),
    Poly((2*x - 1)*t**4 + (t0 + x)/x*t**3 - (t0 + 4*x**2)/(2*x)*t**2 + x*t, t), 3, DE) == \
        (Poly(0, t), Poly(0, t), 0, Poly(0, t),
        Poly(t0*t**2/2 + x**2*t**2 - x**2*t, t))
    DE = DifferentialExtension(extension={'D': [Poly(1, x)]})
    assert spde(Poly(x**2 + x + 1, x), Poly(-2*x - 1, x), Poly(x**5/2 +
    3*x**4/4 + x**3 - x**2 + 1, x), 4, DE) == \
        (Poly(0, x), Poly(x/2 - S(1)/4, x), 2, Poly(x**2 + x + 1, x), Poly(5*x/4, x))
    assert spde(Poly(x**2 + x + 1, x), Poly(-2*x - 1, x), Poly(x**5/2 +
    3*x**4/4 + x**3 - x**2 + 1, x), n, DE) == \
        (Poly(0, x), Poly(x/2 - S(1)/4, x), -2 + n, Poly(x**2 + x + 1, x), Poly(5*x/4, x))
    DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1, t)]})
    raises(NonElementaryIntegralException, lambda: spde(Poly((t - 1)*(t**2 + 1)**2, t), Poly((t - 1)*(t**2 + 1), t), Poly(1, t), 0, DE))
    DE = DifferentialExtension(extension={'D': [Poly(1, x)]})
    assert spde(Poly(x**2 - x, x), Poly(1, x), Poly(9*x**4 - 10*x**3 + 2*x**2, x), 4, DE) == (Poly(0, x), Poly(0, x), 0, Poly(0, x), Poly(3*x**3 - 2*x**2, x))
    assert spde(Poly(x**2 - x, x), Poly(x**2 - 5*x + 3, x), Poly(x**7 - x**6 - 2*x**4 + 3*x**3 - x**2, x), 5, DE) == \
        (Poly(1, x), Poly(x + 1, x), 1, Poly(x**4 - x**3, x), Poly(x**3 - x**2, x))
コード例 #55
0
ファイル: test_matrices.py プロジェクト: pyc111/sympy
def test_eigen():
    x, y = symbols('x y')

    R = Rational

    assert eye(3).charpoly(x) == Poly((x - 1)**3, x)
    assert eye(3).charpoly(y) == Poly((y - 1)**3, y)

    M = Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]])

    assert M.eigenvals() == {S.One: 3}

    assert canonicalize(M.eigenvects()) == canonicalize([
        (1, 3, [Matrix([1, 0, 0]),
                Matrix([0, 1, 0]),
                Matrix([0, 0, 1])])
    ])

    M = Matrix([[0, 1, 1], [1, 0, 0], [1, 1, 1]])

    assert M.eigenvals() == {2 * S.One: 1, -S.One: 1, S.Zero: 1}

    assert canonicalize(M.eigenvects()) == canonicalize([
        (2, 1, [Matrix([R(2, 3), R(1, 3), 1])]), (-1, 1, [Matrix([-1, 1, 0])]),
        (0, 1, [Matrix([0, -1, 1])])
    ])

    M = Matrix([[1, -1], [1, 3]])
    assert canonicalize(M.eigenvects()) == canonicalize(
        [[2, 2, [Matrix(1, 2, [-1, 1])]]])

    M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    a = R(15, 2)
    b = 3 * 33**R(1, 2)
    c = R(13, 2)
    d = (R(33, 8) + 3 * b / 8)
    e = (R(33, 8) - 3 * b / 8)

    def NS(e, n):
        return str(N(e, n))

    r = [
        (a - b / 2, 1, [
            Matrix([
                (12 + 24 / (c - b / 2)) / ((c - b / 2) * e) + 3 / (c - b / 2),
                (6 + 12 / (c - b / 2)) / e, 1
            ])
        ]),
        (0, 1, [Matrix([1, -2, 1])]),
        (a + b / 2, 1, [
            Matrix([
                (12 + 24 / (c + b / 2)) / ((c + b / 2) * d) + 3 / (c + b / 2),
                (6 + 12 / (c + b / 2)) / d, 1
            ])
        ]),
    ]
    r1 = [(NS(r[i][0], 2), NS(r[i][1], 2), [NS(j, 2) for j in r[i][2][0]])
          for i in range(len(r))]
    r = M.eigenvects()
    r2 = [(NS(r[i][0], 2), NS(r[i][1], 2), [NS(j, 2) for j in r[i][2][0]])
          for i in range(len(r))]
    assert sorted(r1) == sorted(r2)

    eps = Symbol('eps', real=True)

    M = Matrix([[abs(eps), I * eps], [-I * eps, abs(eps)]])

    assert canonicalize(M.eigenvects()) == canonicalize([
        (2 * abs(eps), 1, [Matrix([[I * eps / abs(eps)], [1]])]),
        (0, 1, [Matrix([[-I * eps / abs(eps)], [1]])])
    ])
コード例 #56
0
def test_special_denom():
    # TODO: add more tests here
    DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]})
    assert special_denom(Poly(1, t), Poly(t**2, t), Poly(1, t), Poly(t**2 - 1, t),
    Poly(t, t), DE) == \
        (Poly(1, t), Poly(t**2 - 1, t), Poly(t**2 - 1, t), Poly(t, t))
#    assert special_denom(Poly(1, t), Poly(2*x, t), Poly((1 + 2*x)*t, t), DE) == 1

    # issue 3940
    # Note, this isn't a very good test, because the denominator is just 1,
    # but at least it tests the exp cancellation case
    DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(-2*x*t0, t0),
        Poly(I*k*t1, t1)]})
    DE.decrement_level()
    assert special_denom(Poly(1, t0), Poly(I*k, t0), Poly(1, t0), Poly(t0, t0),
    Poly(1, t0), DE) == \
        (Poly(1, t0), Poly(I*k, t0), Poly(t0, t0), Poly(1, t0))
コード例 #57
0
def test_integrate_hyperexponential_polynomial():
    # Without proper cancellation within integrate_hyperexponential_polynomial(),
    # this will take a long time to complete, and will return a complicated
    # expression
    p = Poly(
        (-28 * x**11 * t0 - 6 * x**8 * t0 + 6 * x**9 * t0 - 15 * x**8 * t0**2 +
         15 * x**7 * t0**2 + 84 * x**10 * t0**2 - 140 * x**9 * t0**3 -
         20 * x**6 * t0**3 + 20 * x**7 * t0**3 - 15 * x**6 * t0**4 +
         15 * x**5 * t0**4 + 140 * x**8 * t0**4 - 84 * x**7 * t0**5 -
         6 * x**4 * t0**5 + 6 * x**5 * t0**5 + x**3 * t0**6 - x**4 * t0**6 +
         28 * x**6 * t0**6 - 4 * x**5 * t0**7 + x**9 - x**10 + 4 * x**12) /
        (-8 * x**11 * t0 + 28 * x**10 * t0**2 - 56 * x**9 * t0**3 +
         70 * x**8 * t0**4 - 56 * x**7 * t0**5 + 28 * x**6 * t0**6 -
         8 * x**5 * t0**7 + x**4 * t0**8 + x**12) * t1**2 +
        (-28 * x**11 * t0 - 12 * x**8 * t0 + 12 * x**9 * t0 -
         30 * x**8 * t0**2 + 30 * x**7 * t0**2 + 84 * x**10 * t0**2 -
         140 * x**9 * t0**3 - 40 * x**6 * t0**3 + 40 * x**7 * t0**3 -
         30 * x**6 * t0**4 + 30 * x**5 * t0**4 + 140 * x**8 * t0**4 -
         84 * x**7 * t0**5 - 12 * x**4 * t0**5 + 12 * x**5 * t0**5 -
         2 * x**4 * t0**6 + 2 * x**3 * t0**6 + 28 * x**6 * t0**6 -
         4 * x**5 * t0**7 + 2 * x**9 - 2 * x**10 + 4 * x**12) /
        (-8 * x**11 * t0 + 28 * x**10 * t0**2 - 56 * x**9 * t0**3 +
         70 * x**8 * t0**4 - 56 * x**7 * t0**5 + 28 * x**6 * t0**6 -
         8 * x**5 * t0**7 + x**4 * t0**8 + x**12) * t1 +
        (-2 * x**2 * t0 + 2 * x**3 * t0 + x * t0**2 - x**2 * t0**2 + x**3 -
         x**4) / (-4 * x**5 * t0 + 6 * x**4 * t0**2 - 4 * x**3 * t0**3 +
                  x**2 * t0**4 + x**6),
        t1,
        z,
        expand=False)
    DE = DifferentialExtension(
        extension={'D': [Poly(1, x),
                         Poly(1 / x, t0),
                         Poly(2 * x * t1, t1)]})
    assert integrate_hyperexponential_polynomial(p, DE, z) == (Poly(
        (x - t0) * t1**2 + (-2 * t0 + 2 * x) * t1,
        t1), Poly(-2 * x * t0 + x**2 + t0**2, t1), True)

    DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t0, t0)]})
    assert integrate_hyperexponential_polynomial(Poly(0, t0),
                                                 DE, z) == (Poly(0, t0),
                                                            Poly(1, t0), True)
コード例 #58
0
def test_ratint_logpart():
    assert ratint_logpart(x, x**2 - 9, x, t) == \
        [(Poly(x**2 - 9, x), Poly(-2*t + 1, t))]
    assert ratint_logpart(x**2, x**3 - 5, x, t) == \
        [(Poly(x**3 - 5, x), Poly(-3*t + 1, t))]
コード例 #59
0
ファイル: prob_2d.py プロジェクト: Notgnoshi/cryptography
#!/usr/bin/python3
from itertools import product
import sys
from sympy import Poly
sys.path.append('../../')
from crypto.math import x, coeffs2poly, reduce_gf28

f = Poly(x**5 + 1, x, modulus=2)
# Iterate over all 8 term (7th degree) polynomials
for coeffs in product([0, 1], repeat=8):
    poly = coeffs2poly(coeffs)
    result = reduce_gf28(f * poly)

    # If the multiplication gave us the multiplicative identity
    # we found the multiplicative inverse
    if result == Poly(1, x, modulus=2):
        print(poly, 'is the multiplicative inverse of', f)
コード例 #60
0
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_aliased == 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_aliased == 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_aliased == True

    assert AlgebraicNumber(sqrt(2), []).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_aliased == 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_aliased == 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_aliased == 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) == False and (a != x) == 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())
    b = AlgebraicNumber(sqrt(2), alias='alpha')
    assert b.args == (sqrt(2), Tuple(), Symbol('alpha'))

    a = AlgebraicNumber(sqrt(2), [1, 2, 3])
    assert a.args == (sqrt(2), Tuple(1, 2, 3))