示例#1
0
def reduce_po_lat(l_csl_p, l_p_po, tol):
    l_p_po = np.array(l_p_po, dtype='double')
    l_csl_po = l_p_po.dot(l_csl_p)
    lInt_csl_po, m1 = iman.int_approx(l_csl_po, tol)
    inp_args = {}
    inp_args['mat'] = lInt_csl_po
    lllInt_csl_po = call_sage_math('./compute_LLL.py', inp_args)
    lllInt_csl_po = Matrix(lllInt_csl_po)
    Sz = lllInt_csl_po.shape
    if Sz[0] == Sz[1]:
        if lllInt_csl_po.det() < 0:
            if Sz[0] == 3:
                M4 = Matrix([[0, 1, 0], [1, 0, 0], [0, 0, 1]])
                lllInt_csl_po = lllInt_csl_po * M4
            if Sz[0] == 2:
                M4 = Matrix([[0, 1], [1, 0]])
                lllInt_csl_po = lllInt_csl_po * M4

        Tmat = ((Matrix(lInt_csl_po)).inv()) * (lllInt_csl_po)
    else:
        A1 = (np.array(lllInt_csl_po, dtype='int64'))
        A2 = (np.array(lInt_csl_po, dtype='int64'))
        # A1inv = np.linalg.pinv(A1)
        A2inv = np.linalg.pinv(A2)
        Tmat = Matrix(np.dot(A2inv, A1))

    cond1 = iman.check_int_mat(Tmat, 1e-12)
    if cond1:
        Tmat1 = Matrix(
            np.array(np.around(np.array(Tmat, dtype='double')), dtype='int64'))
        return Tmat1
    else:
        raise Exception("Tmat is not an integer matrix.")
 def _find_plane(p: tuple, v1: np.ndarray, v2: np.ndarray) -> Expr:
     """ Helper method tp find plane that fits point p and two non-collinear vectors """
     x, y, z = symbols('x, y, z')
     matrix = Matrix([[x - p[0], y - p[1], z - p[2]], [v1[0], v1[1], v1[2]],
                      [v2[0], v2[1], v2[2]]])
     plane = matrix.det()
     assert plane != Zero, 'vector1 and vector2 must be non-collinear'
     return plane
示例#3
0
def cv9():
    m_a = Matrix([[a, 1, 1, 1], [1, a, 1, 1], [1, 1, a, 1], [1, 1, 1, a]])
    b = Matrix([1, 1, 1, 1])
    det_a = m_a.det()
    p_s = linsolve((m_a, b), [p_1, p_2, p_3, p_4])
    print("\\mA={} \\\\".format(latex(m_a)))
    print("det(A)={}={} \\\\".format(latex(det_a), latex(factor(det_a))))
    print("p={}".format(latex(p_s)))
    def _jacobian(self, x: Symbol, y: Symbol, p: tuple) -> float:
        subs_dict = {self._x: p[0], self._y: p[1], self._z: p[2]}

        matrix = Matrix([[
            diff(self._f, x).subs(subs_dict),
            diff(self._f, y).subs(subs_dict)
        ], [
            diff(self._g, x).subs(subs_dict),
            diff(self._g, y).subs(subs_dict)
        ]])
        if self._logging:
            print(
                f'Jacobian d(f, g) / d({x}, {y}) at point {p} is |{matrix}| = {matrix.det()}'
            )
        return matrix.det()
def sylvester_det(p4, p2):
    p4degree = len(p4) - 1
    p2degree = len(p2) - 1
    smatsize = p4degree + p2degree
    nzeros4 = (smatsize - len(p4))
    nzeroes2 = (smatsize - len(p2))
    smatlist = []
    for i in range(nzeros4 + 1):
        smatlist.append([0]*i + p4 + [0]*(nzeros4 - i))
    for i in range(nzeroes2 + 1):
        smatlist.append([0]*i + p2 + [0]*(nzeroes2 - i))

    smat = Matrix(smatlist)
    det = smat.det(method='berkowitz')
    det = sympy.expand(det)
    return det
示例#6
0
def handle(msg):
    chat_id = msg["chat"]["id"]
    if not "text" in msg:
        bot.sendMessage(chat_id, "I only understand text at the moment :(")
        return

    text = msg["text"]

    print "%s: %s" % (msg["from"]["first_name"], text)

    if text == "/start":
        bot.sendMessage(chat_id, start_message)
        return

    matrix = parseMatrix(text)
    if matrix is None:
        bot.sendMessage(chat_id,
                        "Can't parse matrix, please use a different format!")
        return

    if not check_dim(matrix):
        bot.sendMessage(
            chat_id, "Different row length detected, please check your input!")
        return

    if len(matrix) < 2 or len(matrix[0]) < 2:
        bot.sendMessage(chat_id, "Matrix have to be at least 2x2!")
        return

    if len(matrix) != len(matrix[0]):
        bot.sendMessage(chat_id,
                        "The two dimensions of the matrix must be equal!")
        return

    # calculate determinante
    m = Matrix(matrix)
    det = m.det()
    if len(det.free_symbols) > 0:
        bot.sendMessage(chat_id, 'determinante: %s' % det)
    else:
        bot.sendMessage(chat_id, 'determinante: %s = %s' % (det, det.evalf(4)))
示例#7
0
def alexander_polynomial(braid, t=t, modulus=None, seifert=False):
    """ Calculate Alexander Polynomial."""
    if seifert:
        M = Matrix(seifert_matrix(braid).tolist())
        if modulus is None:
            apoly = M - t*M.transpose()
        else:
            apoly = (M - t*M.transpose()) % modulus
        apoly = apoly.det()
    else:
        deleted = False
        h = generators(braid)
        M = alexander_matrix(braid, t, modulus)
        for i in range(len(braid)):
            if h[i] == 0:
                deleted = True
                M.row_del(i)
                M.col_del(i)
                break
        if not deleted:
            M.row_del(-1)
            M.col_del(-1)
        apoly = M.det()
    return _normalize_apoly(apoly)
示例#8
0
def test_legacy_det():
    # Minimal support for legacy keys for 'method' in det()
    # Partially copied from test_determinant()

    M = Matrix(((3, -2, 0, 5), (-2, 1, -2, 2), (0, -2, 5, 0), (5, 0, 3, 4)))

    assert M.det(method="bareis") == -289
    assert M.det(method="det_lu") == -289
    assert M.det(method="det_LU") == -289

    M = Matrix(((3, 2, 0, 0, 0), (0, 3, 2, 0, 0), (0, 0, 3, 2, 0),
                (0, 0, 0, 3, 2), (2, 0, 0, 0, 3)))

    assert M.det(method="bareis") == 275
    assert M.det(method="det_lu") == 275
    assert M.det(method="Bareis") == 275

    M = Matrix(((1, 0, 1, 2, 12), (2, 0, 1, 1, 4), (2, 1, 1, -1, 3),
                (3, 2, -1, 1, 8), (1, 1, 1, 0, 6)))

    assert M.det(method="bareis") == -55
    assert M.det(method="det_lu") == -55
    assert M.det(method="BAREISS") == -55

    M = Matrix(((3, 0, 0, 0), (-2, 1, 0, 0), (0, -2, 5, 0), (5, 0, 3, 4)))

    assert M.det(method="bareiss") == 60
    assert M.det(method="berkowitz") == 60
    assert M.det(method="lu") == 60

    M = Matrix(((1, 0, 0, 0), (5, 0, 0, 0), (9, 10, 11, 0), (13, 14, 15, 16)))

    assert M.det(method="bareiss") == 0
    assert M.det(method="berkowitz") == 0
    assert M.det(method="lu") == 0

    M = Matrix(((3, 2, 0, 0, 0), (0, 3, 2, 0, 0), (0, 0, 3, 2, 0),
                (0, 0, 0, 3, 2), (0, 0, 0, 0, 3)))

    assert M.det(method="bareiss") == 243
    assert M.det(method="berkowitz") == 243
    assert M.det(method="lu") == 243

    M = Matrix(((-5, 2, 3, 4, 5), (1, -4, 3, 4, 5), (1, 2, -3, 4, 5),
                (1, 2, 3, -2, 5), (1, 2, 3, 4, -1)))

    assert M.det(method="bareis") == 11664
    assert M.det(method="det_lu") == 11664
    assert M.det(method="BERKOWITZ") == 11664

    M = Matrix(((2, 7, -1, 3, 2), (0, 0, 1, 0, 1), (-2, 0, 7, 0, 2),
                (-3, -2, 4, 5, 3), (1, 0, 0, 0, 1)))

    assert M.det(method="bareis") == 123
    assert M.det(method="det_lu") == 123
    assert M.det(method="LU") == 123
示例#9
0
    def find_linear_recurrence(self,n,d=None,gfvar=None):
        """
        Finds the shortest linear recurrence that satisfies the first n
        terms of sequence of order `\leq` n/2 if possible.
        If d is specified, find shortest linear recurrence of order
        `\leq` min(d, n/2) if possible.
        Returns list of coefficients ``[b(1), b(2), ...]`` corresponding to the
        recurrence relation ``x(n) = b(1)*x(n-1) + b(2)*x(n-2) + ...``
        Returns ``[]`` if no recurrence is found.
        If gfvar is specified, also returns ordinary generating function as a
        function of gfvar.

        Examples
        ========

        >>> from sympy import sequence, sqrt, oo, lucas
        >>> from sympy.abc import n, x, y
        >>> sequence(n**2).find_linear_recurrence(10, 2)
        []
        >>> sequence(n**2).find_linear_recurrence(10)
        [3, -3, 1]
        >>> sequence(2**n).find_linear_recurrence(10)
        [2]
        >>> sequence(23*n**4+91*n**2).find_linear_recurrence(10)
        [5, -10, 10, -5, 1]
        >>> sequence(sqrt(5)*(((1 + sqrt(5))/2)**n - (-(1 + sqrt(5))/2)**(-n))/5).find_linear_recurrence(10)
        [1, 1]
        >>> sequence(x+y*(-2)**(-n), (n, 0, oo)).find_linear_recurrence(30)
        [1/2, 1/2]
        >>> sequence(3*5**n + 12).find_linear_recurrence(20,gfvar=x)
        ([6, -5], 3*(-21*x + 5)/((x - 1)*(5*x - 1)))
        >>> sequence(lucas(n)).find_linear_recurrence(15,gfvar=x)
        ([1, 1], (x - 2)/(x**2 + x - 1))
        """
        from sympy.matrices import Matrix
        x = [simplify(expand(t)) for t in self[:n]]
        lx = len(x)
        if d == None:
            r = lx//2
        else:
            r = min(d,lx//2)
        coeffs = []
        for l in range(1, r+1):
            l2 = 2*l
            mlist = []
            for k in range(l):
                mlist.append(x[k:k+l])
            m = Matrix(mlist)
            if m.det() != 0:
                y = simplify(m.LUsolve(Matrix(x[l:l2])))
                if lx == l2:
                    coeffs = flatten(y[::-1])
                    break
                mlist = []
                for k in range(l,lx-l):
                    mlist.append(x[k:k+l])
                m = Matrix(mlist)
                if m*y == Matrix(x[l2:]):
                    coeffs = flatten(y[::-1])
                    break
        if gfvar == None:
            return coeffs
        else:
            l = len(coeffs)
            if l == 0:
                return [], None
            else:
                n, d = x[l-1]*gfvar**(l-1), 1 - coeffs[l-1]*gfvar**l
                for i in range(l-1):
                    n += x[i]*gfvar**i
                    for j in range(l-i-1):
                        n -= coeffs[i]*x[j]*gfvar**(i+j+1)
                    d -= coeffs[i]*gfvar**(i+1)
                return coeffs, simplify(factor(n)/factor(d))
示例#10
0
tlr = taylor_to_var(r_star, rho, alpha_pi, alpha_z, sigma_R, tau_1, tau_2)
vcx = [a13, a23, a33, b13, b23, b33, b43]

eq = []
for i in range(7):
    eq.append(vcx[i] - tlr[i])

inv_taylor = sympy.solve(
    eq, [r_star, rho, alpha_pi, alpha_z, sigma_R, tau_1, tau_2])[0]
g_inv = sympy.lambdify(vcx, inv_taylor)

from sympy.matrices import Matrix
from scipy.stats import multivariate_normal
J = Matrix(7, 7, lambda i, j: sympy.diff(inv_taylor[i], vcx[j]))

Jdet = sympy.lambdify(vcx, J.det())

from collections import OrderedDict


class TaylorRulePrior(SimsZhaSVARPrior):
    def __init__(self, taylor_args, *args, **kwargs):

        # Initialize the baseclass
        super(TaylorRulePrior, self).__init__(*args, **kwargs)

        # r_loc  = ordering[0]
        # pi_loc = ordering[1]
        # y_loc  = ordering[2]

        npara = self.n * (self.n +
示例#11
0
class Context(object):
    """some context where variables exists"""
    def __init__(self, size):
        self.numberOfVariables = size
        self.x = s.symbols('x:' + str(size))
        self.fn = None
        self.hessian = None
        self.detHessian = None

    def setFn(self, expression):
        self.fn = expression

    def getHessian(self):

        expr = self.fn

        hessianRows = []
        for idx in range(0, self.numberOfVariables):

            hessianRow = []

            diffWrt = s.diff(expr, self.x[idx])

            for idx2ndDeriv in range(0, self.numberOfVariables):

                hessianRow.append(s.diff(diffWrt, self.x[idx2ndDeriv]))

            hessianRows.append(hessianRow)

        self.hessian = Matrix(hessianRows)

        return self.hessian

    # compute the determinate of the hessian at point [x1 .. xn]
    def detHessianAt(self, subs):

        if len(subs) != self.numberOfVariables:

            raise Exception('airity mismatch: detHessianAt')

        if self.hessian == None:

            self.hessian = self.getHessian()

        if self.detHessian == None:

            self.detHessian = self.hessian.det()

        detHessian = self.detHessian

        for idx in range(0, self.numberOfVariables):

            detHessian = detHessian.subs(self.x[idx], subs[idx])

        return detHessian

    def secondPartialTest(self, subs):

        dValue = self.detHessianAt(subs).evalf()

        if (dValue < 0):

            return "Saddle Point at f(" + str(subs) + ")"

        if (dValue == 0):

            return "Inconclusive at f(" + str(subs) + ")"

        # get the function at the top left of the hession
        secondDerivAtSub = self.hessian[0, 0]

        value = secondDerivAtSub

        for idx in range(0, self.numberOfVariables):

            value = value.subs(self.x[idx], subs[idx])

        value = value.evalf()

        if value > 0:

            return "Relative Minimum at f(" + str(subs) + ")"

        if value < 0:

            return "Relative Maximum at f(" + str(subs) + ")"
示例#12
0
class Context(object):
	"""some context where variables exists"""
	def __init__(self, size):
		self.numberOfVariables = size
		self.x = s.symbols('x:'+str(size))
		self.fn = None
		self.hessian = None
		self.detHessian = None

	def setFn(self, expression):
		self.fn = expression

	def getHessian(self):

		expr = self.fn

		hessianRows = []
		for idx in range(0, self.numberOfVariables):

			hessianRow = []

			diffWrt = s.diff(expr, self.x[idx])

			for idx2ndDeriv in range(0, self.numberOfVariables):

				hessianRow.append(s.diff(diffWrt, self.x[idx2ndDeriv]))

			hessianRows.append(hessianRow)

		self.hessian = Matrix(hessianRows)

		return self.hessian

	# compute the determinate of the hessian at point [x1 .. xn]
	def detHessianAt(self, subs):

		if len(subs) != self.numberOfVariables:

			raise Exception('airity mismatch: detHessianAt')

		if self.hessian == None:

			self.hessian = self.getHessian()

		if self.detHessian == None:

			self.detHessian = self.hessian.det()

		detHessian = self.detHessian

		for idx in range(0, self.numberOfVariables):

			detHessian = detHessian.subs(self.x[idx], subs[idx]);

		return detHessian


	def secondPartialTest(self, subs):

		dValue = self.detHessianAt(subs).evalf()

		if(dValue < 0):

			return "Saddle Point at f(" + str(subs) + ")"

		if(dValue == 0):

			return "Inconclusive at f(" + str(subs) + ")"

		# get the function at the top left of the hession
		secondDerivAtSub = self.hessian[0,0]

		value = secondDerivAtSub

		for idx in range(0, self.numberOfVariables):

			value = value.subs(self.x[idx], subs[idx]);

		value = value.evalf()

		if value > 0:

			return "Relative Minimum at f(" + str(subs) + ")"

		if value < 0:

			return "Relative Maximum at f(" + str(subs) + ")"
示例#13
0
def test_det():
    a = Matrix(2, 3, [1, 2, 3, 4, 5, 6])
    raises(NonSquareMatrixError, lambda: a.det())

    z = zeros_Determinant(2)
    ey = eye_Determinant(2)
    assert z.det() == 0
    assert ey.det() == 1

    x = Symbol('x')
    a = Matrix(0, 0, [])
    b = Matrix(1, 1, [5])
    c = Matrix(2, 2, [1, 2, 3, 4])
    d = Matrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 8])
    e = Matrix(4, 4, [x, 1, 2, 3, 4, 5, 6, 7, 2, 9, 10, 11, 12, 13, 14, 14])
    from sympy.abc import i, j, k, l, m, n
    f = Matrix(3, 3, [i, l, m, 0, j, n, 0, 0, k])
    g = Matrix(3, 3, [i, 0, 0, l, j, 0, m, n, k])
    h = Matrix(3, 3, [x**3, 0, 0, i, x**-1, 0, j, k, x**-2])
    # the method keyword for `det` doesn't kick in until 4x4 matrices,
    # so there is no need to test all methods on smaller ones

    assert a.det() == 1
    assert b.det() == 5
    assert c.det() == -2
    assert d.det() == 3
    assert e.det() == 4 * x - 24
    assert e.det(method="domain-ge") == 4 * x - 24
    assert e.det(method='bareiss') == 4 * x - 24
    assert e.det(method='berkowitz') == 4 * x - 24
    assert f.det() == i * j * k
    assert g.det() == i * j * k
    assert h.det() == 1
    raises(ValueError, lambda: e.det(iszerofunc="test"))
示例#14
0
def test_determinant():
    M = Matrix()

    assert M.det() == 1
    # Evaluating these directly because they are never reached via M.det()
    assert M._eval_det_bareiss() == 1
    assert M._eval_det_berkowitz() == 1
    assert M._eval_det_lu() == 1

    M = Matrix([[0]])

    assert M.det() == 0
    assert M._eval_det_bareiss() == 0
    assert M._eval_det_berkowitz() == 0
    assert M._eval_det_lu() == 0

    M = Matrix([[5]])

    assert M.det() == 5
    assert M._eval_det_bareiss() == 5
    assert M._eval_det_berkowitz() == 5
    assert M._eval_det_lu() == 5

    M = Matrix(((-3, 2), (8, -5)))

    assert M.det(method="domain-ge") == -1
    assert M.det(method="bareiss") == -1
    assert M.det(method="berkowitz") == -1
    assert M.det(method="lu") == -1

    M = Matrix(((x, 1), (y, 2 * y)))

    assert M.det(method="domain-ge") == 2 * x * y - y
    assert M.det(method="bareiss") == 2 * x * y - y
    assert M.det(method="berkowitz") == 2 * x * y - y
    assert M.det(method="lu") == 2 * x * y - y

    M = Matrix(((1, 1, 1), (1, 2, 3), (1, 3, 6)))

    assert M.det(method="domain-ge") == 1
    assert M.det(method="bareiss") == 1
    assert M.det(method="berkowitz") == 1
    assert M.det(method="lu") == 1

    M = Matrix(((3, -2, 0, 5), (-2, 1, -2, 2), (0, -2, 5, 0), (5, 0, 3, 4)))

    assert M.det(method="domain-ge") == -289
    assert M.det(method="bareiss") == -289
    assert M.det(method="berkowitz") == -289
    assert M.det(method="lu") == -289

    M = Matrix(((1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16)))

    assert M.det(method="domain-ge") == 0
    assert M.det(method="bareiss") == 0
    assert M.det(method="berkowitz") == 0
    assert M.det(method="lu") == 0

    M = Matrix(((3, 2, 0, 0, 0), (0, 3, 2, 0, 0), (0, 0, 3, 2, 0),
                (0, 0, 0, 3, 2), (2, 0, 0, 0, 3)))

    assert M.det(method="domain-ge") == 275
    assert M.det(method="bareiss") == 275
    assert M.det(method="berkowitz") == 275
    assert M.det(method="lu") == 275

    M = Matrix(((3, 0, 0, 0), (-2, 1, 0, 0), (0, -2, 5, 0), (5, 0, 3, 4)))

    assert M.det(method="domain-ge") == 60
    assert M.det(method="bareiss") == 60
    assert M.det(method="berkowitz") == 60
    assert M.det(method="lu") == 60

    M = Matrix(((1, 0, 0, 0), (5, 0, 0, 0), (9, 10, 11, 0), (13, 14, 15, 16)))

    assert M.det(method="domain-ge") == 0
    assert M.det(method="bareiss") == 0
    assert M.det(method="berkowitz") == 0
    assert M.det(method="lu") == 0

    M = Matrix(((3, 2, 0, 0, 0), (0, 3, 2, 0, 0), (0, 0, 3, 2, 0),
                (0, 0, 0, 3, 2), (0, 0, 0, 0, 3)))

    assert M.det(method="domain-ge") == 243
    assert M.det(method="bareiss") == 243
    assert M.det(method="berkowitz") == 243
    assert M.det(method="lu") == 243

    M = Matrix(((1, 0, 1, 2, 12), (2, 0, 1, 1, 4), (2, 1, 1, -1, 3),
                (3, 2, -1, 1, 8), (1, 1, 1, 0, 6)))

    assert M.det(method="domain-ge") == -55
    assert M.det(method="bareiss") == -55
    assert M.det(method="berkowitz") == -55
    assert M.det(method="lu") == -55

    M = Matrix(((-5, 2, 3, 4, 5), (1, -4, 3, 4, 5), (1, 2, -3, 4, 5),
                (1, 2, 3, -2, 5), (1, 2, 3, 4, -1)))

    assert M.det(method="domain-ge") == 11664
    assert M.det(method="bareiss") == 11664
    assert M.det(method="berkowitz") == 11664
    assert M.det(method="lu") == 11664

    M = Matrix(((2, 7, -1, 3, 2), (0, 0, 1, 0, 1), (-2, 0, 7, 0, 2),
                (-3, -2, 4, 5, 3), (1, 0, 0, 0, 1)))

    assert M.det(method="domain-ge") == 123
    assert M.det(method="bareiss") == 123
    assert M.det(method="berkowitz") == 123
    assert M.det(method="lu") == 123

    M = Matrix(((x, y, z), (1, 0, 0), (y, z, x)))

    assert M.det(method="domain-ge") == z**2 - x * y
    assert M.det(method="bareiss") == z**2 - x * y
    assert M.det(method="berkowitz") == z**2 - x * y
    assert M.det(method="lu") == z**2 - x * y

    # issue 13835
    a = symbols('a')
    M = lambda n: Matrix([[i + a * j for i in range(n)] for j in range(n)])
    assert M(5).det() == 0
    assert M(6).det() == 0
    assert M(7).det() == 0
示例#15
0
def test_determinant():

    for M in [Matrix(), Matrix([[1]])]:
        assert (M.det() == M._eval_det_bareiss() == M._eval_det_berkowitz() ==
                M._eval_det_lu() == 1)

    M = Matrix(((-3, 2), (8, -5)))

    assert M.det(method="bareiss") == -1
    assert M.det(method="berkowitz") == -1
    assert M.det(method="lu") == -1

    M = Matrix(((x, 1), (y, 2 * y)))

    assert M.det(method="bareiss") == 2 * x * y - y
    assert M.det(method="berkowitz") == 2 * x * y - y
    assert M.det(method="lu") == 2 * x * y - y

    M = Matrix(((1, 1, 1), (1, 2, 3), (1, 3, 6)))

    assert M.det(method="bareiss") == 1
    assert M.det(method="berkowitz") == 1
    assert M.det(method="lu") == 1

    M = Matrix(((3, -2, 0, 5), (-2, 1, -2, 2), (0, -2, 5, 0), (5, 0, 3, 4)))

    assert M.det(method="bareiss") == -289
    assert M.det(method="berkowitz") == -289
    assert M.det(method="lu") == -289

    M = Matrix(((1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16)))

    assert M.det(method="bareiss") == 0
    assert M.det(method="berkowitz") == 0
    assert M.det(method="lu") == 0

    M = Matrix(((3, 2, 0, 0, 0), (0, 3, 2, 0, 0), (0, 0, 3, 2, 0),
                (0, 0, 0, 3, 2), (2, 0, 0, 0, 3)))

    assert M.det(method="bareiss") == 275
    assert M.det(method="berkowitz") == 275
    assert M.det(method="lu") == 275

    M = Matrix(((3, 0, 0, 0), (-2, 1, 0, 0), (0, -2, 5, 0), (5, 0, 3, 4)))

    assert M.det(method="bareiss") == 60
    assert M.det(method="berkowitz") == 60
    assert M.det(method="lu") == 60

    M = Matrix(((1, 0, 0, 0), (5, 0, 0, 0), (9, 10, 11, 0), (13, 14, 15, 16)))

    assert M.det(method="bareiss") == 0
    assert M.det(method="berkowitz") == 0
    assert M.det(method="lu") == 0

    M = Matrix(((3, 2, 0, 0, 0), (0, 3, 2, 0, 0), (0, 0, 3, 2, 0),
                (0, 0, 0, 3, 2), (0, 0, 0, 0, 3)))

    assert M.det(method="bareiss") == 243
    assert M.det(method="berkowitz") == 243
    assert M.det(method="lu") == 243

    M = Matrix(((1, 0, 1, 2, 12), (2, 0, 1, 1, 4), (2, 1, 1, -1, 3),
                (3, 2, -1, 1, 8), (1, 1, 1, 0, 6)))

    assert M.det(method="bareiss") == -55
    assert M.det(method="berkowitz") == -55
    assert M.det(method="lu") == -55

    M = Matrix(((-5, 2, 3, 4, 5), (1, -4, 3, 4, 5), (1, 2, -3, 4, 5),
                (1, 2, 3, -2, 5), (1, 2, 3, 4, -1)))

    assert M.det(method="bareiss") == 11664
    assert M.det(method="berkowitz") == 11664
    assert M.det(method="lu") == 11664

    M = Matrix(((2, 7, -1, 3, 2), (0, 0, 1, 0, 1), (-2, 0, 7, 0, 2),
                (-3, -2, 4, 5, 3), (1, 0, 0, 0, 1)))

    assert M.det(method="bareiss") == 123
    assert M.det(method="berkowitz") == 123
    assert M.det(method="lu") == 123

    M = Matrix(((x, y, z), (1, 0, 0), (y, z, x)))

    assert M.det(method="bareiss") == z**2 - x * y
    assert M.det(method="berkowitz") == z**2 - x * y
    assert M.det(method="lu") == z**2 - x * y

    # issue 13835
    a = symbols('a')
    M = lambda n: Matrix([[i + a * j for i in range(n)] for j in range(n)])
    assert M(5).det() == 0
    assert M(6).det() == 0
    assert M(7).det() == 0
# Create the identity matrix
eye(3)

# Create an empty matrix
zeros(3,2)

# Create a matrix with ones
ones(4,2)

# Creates a square matrix with only the diagonal elements filled in
diag(2,2,2,2,2)

# To compute the determinant, use det
M = Matrix([[1, 0, 1], [2, -1, 3], [4, 3, 2]])

M.det()

# Conversions between radians to degrees
rtd = 180./np.pi # radians to degrees
dtr = np.pi/180. # degrees to radians

# Now we create the rotation matrices for elementary rotations about the X, Y, and Z axes, respectively.

# The about Z rotation matrix is derived on page 45


R_x = Matrix([[ 1,              0,        0],
              [ 0,        cos(q1), -sin(q1)],
              [ 0,        sin(q1),  cos(q1)]])
# Rotation about X axis
示例#17
0
    def find_linear_recurrence(self, n, d=None, gfvar=None):
        r"""
        Finds the shortest linear recurrence that satisfies the first n
        terms of sequence of order `\leq` ``n/2`` if possible.
        If ``d`` is specified, find shortest linear recurrence of order
        `\leq` min(d, n/2) if possible.
        Returns list of coefficients ``[b(1), b(2), ...]`` corresponding to the
        recurrence relation ``x(n) = b(1)*x(n-1) + b(2)*x(n-2) + ...``
        Returns ``[]`` if no recurrence is found.
        If gfvar is specified, also returns ordinary generating function as a
        function of gfvar.

        Examples
        ========

        >>> from sympy import sequence, sqrt, oo, lucas
        >>> from sympy.abc import n, x, y
        >>> sequence(n**2).find_linear_recurrence(10, 2)
        []
        >>> sequence(n**2).find_linear_recurrence(10)
        [3, -3, 1]
        >>> sequence(2**n).find_linear_recurrence(10)
        [2]
        >>> sequence(23*n**4+91*n**2).find_linear_recurrence(10)
        [5, -10, 10, -5, 1]
        >>> sequence(sqrt(5)*(((1 + sqrt(5))/2)**n - (-(1 + sqrt(5))/2)**(-n))/5).find_linear_recurrence(10)
        [1, 1]
        >>> sequence(x+y*(-2)**(-n), (n, 0, oo)).find_linear_recurrence(30)
        [1/2, 1/2]
        >>> sequence(3*5**n + 12).find_linear_recurrence(20,gfvar=x)
        ([6, -5], 3*(5 - 21*x)/((x - 1)*(5*x - 1)))
        >>> sequence(lucas(n)).find_linear_recurrence(15,gfvar=x)
        ([1, 1], (x - 2)/(x**2 + x - 1))
        """
        from sympy.matrices import Matrix
        x = [simplify(expand(t)) for t in self[:n]]
        lx = len(x)
        if d is None:
            r = lx // 2
        else:
            r = min(d, lx // 2)
        coeffs = []
        for l in range(1, r + 1):
            l2 = 2 * l
            mlist = []
            for k in range(l):
                mlist.append(x[k:k + l])
            m = Matrix(mlist)
            if m.det() != 0:
                y = simplify(m.LUsolve(Matrix(x[l:l2])))
                if lx == l2:
                    coeffs = flatten(y[::-1])
                    break
                mlist = []
                for k in range(l, lx - l):
                    mlist.append(x[k:k + l])
                m = Matrix(mlist)
                if m * y == Matrix(x[l2:]):
                    coeffs = flatten(y[::-1])
                    break
        if gfvar is None:
            return coeffs
        else:
            l = len(coeffs)
            if l == 0:
                return [], None
            else:
                n, d = x[l - 1] * gfvar**(l - 1), 1 - coeffs[l - 1] * gfvar**l
                for i in range(l - 1):
                    n += x[i] * gfvar**i
                    for j in range(l - i - 1):
                        n -= coeffs[i] * x[j] * gfvar**(i + j + 1)
                    d -= coeffs[i] * gfvar**(i + 1)
                return coeffs, simplify(factor(n) / factor(d))
示例#18
0
# In[59]:

C * A

# El **determinante** de una matriz podemos calcularlo mediante la función `det`:

# In[60]:

det(B)

# O bien, mediante el propio método `det`:

# In[61]:

B.det()

# La **matriz inversa** podemos calcularla utilizando el método `inv`:

# In[62]:

A.inv()

# In[63]:

A.inv() * A

# La **transpuesta** de una matriz se puede obtener accediendo al atributo `T`

# In[64]: