sympy 计算表达式

 

from sympy import *

def test_matrix():
    A = Matrix([[x, x*y], [sin(z)+4, x**z]])
    sol = Matrix([[1, 2], [sin(3)+4, 1]])
    f = lambdify((x,y,z), A, modules="sympy")
    assert f(1,2,3) == sol
    f = lambdify((x,y,z), (A, [A]), modules="sympy")
    assert f(1,2,3) == (sol,[sol])

 

 

https://www.kutu66.com/Python-Module-Examples/article_66605

实例 1

 

复制

def test_threaded():
    @threaded
    def function(expr, *args):
        return 2*expr + sum(args)
    assert function(Matrix([[x, y], [1, x]]), 1, 2) == 
        Matrix([[2*x + 3, 2*y + 3], [5, 2*x + 3]])
    assert function(Eq(x, y), 1, 2) == Eq(2*x + 3, 2*y + 3)
    assert function([x, y], 1, 2) == [2*x + 3, 2*y + 3]
    assert function((x, y), 1, 2) == (2*x + 3, 2*y + 3)
    assert function(set([x, y]), 1, 2) == set([2*x + 3, 2*y + 3])
    @threaded
    def function(expr, n):
        return expr**n
    assert function(x + y, 2) == x**2 + y**2
    assert function(x, 2) == x**2
 

实例 2

 

复制

def test_prde_linear_constraints():
    DE = DifferentialExtension(extension={'D': [Poly(1, x)]})
    G = [(Poly(2*x**3 + 3*x + 1, x), Poly(x**2 - 1, x)), (Poly(1, x), Poly(x - 1, x)),
        (Poly(1, x), Poly(x + 1, x))]
    assert prde_linear_constraints(Poly(1, x), Poly(0, x), G, DE) == 
        ((Poly(2*x, x), Poly(0, x), Poly(0, x)), Matrix([[1, 1, -1], [5, 1, 1]]))
    G = [(Poly(t, t), Poly(1, t)), (Poly(t**2, t), Poly(1, t)), (Poly(t**3, t), Poly(1, t))]
    DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]})
    assert prde_linear_constraints(Poly(t + 1, t), Poly(t**2, t), G, DE) == 
        ((Poly(t, t), Poly(t**2, t), Poly(t**3, t)), Matrix())
    G = [(Poly(2*x, t), Poly(t, t)), (Poly(-x, t), Poly(t, t))]
    DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]})
    prde_linear_constraints(Poly(1, t), Poly(0, t), G, DE) == 
        ((Poly(0, t), Poly(0, t)), Matrix([[2*x, -x]]))
 

实例 3

 

复制

def z_sub(substr, n=5):
    """Generate a z vector with the subscript substr."""
    states = ['x','th','M','V']
    varnames = [item+substr for item in states]
    mylist = []
    for item in varnames:
        mylist.append([item])
    if n == 5:
        mylist.append(['1'])
    mat_str = str(mylist)
    code = 'z_vect = sympy.Matrix(%s)' % mat_str
    exec(code)
    return z_vect
 

实例 4

 

复制

def z(x, F):
    z_mat = sympy.Matrix([[x],[F],[1]])
    return z_mat
 

实例 5

 

复制

def test_threaded():
    x, y = symbols('xy')
    @threaded()
    def function(expr, *args):
        return 2*expr + sum(args)
    assert function(Matrix([[x, y], [1, x]]), 1, 2) == 
        Matrix([[2*x+3, 2*y+3], [5, 2*x+3]])
    assert function(Eq(x, y), 1, 2) == Eq(2*x+3, 2*y+3)
    assert function([x, y], 1, 2) == [2*x+3, 2*y+3]
    assert function((x, y), 1, 2) == (2*x+3, 2*y+3)
    assert function(set([x, y]), 1, 2) == set([2*x+3, 2*y+3])
    @threaded()
    def function(expr, n):
        return expr**n
    assert function(x + y, 2) == x**2 + y**2
    assert function(x, 2) == x**2
    @threaded(use_add=False)
    def function(expr, n):
        return expr**n
    assert function(x + y, 2) == (x + y)**2
 

实例 6

 

复制

def test_apart():
    assert apart(1/(x+2)/(x+1), x) == 1/(1 + x) - 1/(2 + x)
    assert apart(1/(x+1)/(x+5), x) == -1/(5 + x)/4 + 1/(1 + x)/4
    f = apart(1/(x-y)/(x-z), x)
    assert f.subs({y:1,z:2}) == apart(1/(x-1)/(x-2), x)
    assert apart((E*x+2)/(x-pi)*(x-1), x) in [
        2 - E + E*pi + E*x - 1/(x - pi)*( 2 - 2*pi + E*pi - E*pi**2),
        2 - E + E*pi + E*x + 1/(x - pi)*(-2 + 2*pi - E*pi + E*pi**2),
    ]
    M = Matrix(2, 2, lambda i, j: 1/(x-(i+1))/(x-(1-j)))
    assert apart(M, x) in [
            Matrix([
                [(x-1)**(-2),     -1/x-1/(1-x)          ],
                [1/(1-x)-1/(2-x), -S.Half/x-S.Half/(2-x)],
            ]),
            Matrix([
                [(-1+x)**(-2),     -1/x+1/(-1+x)          ],
                [-1/(-1+x)+1/(-2+x), -S.Half/x+S.Half/(-2+x)],
            ]),
            ]
    assert apart(Eq((x**2+1)/(x+1), sin(x)), x) == 
        Eq(x - 1 + 2/(x+1), sin(x))
    assert str(apart(1/(1+x**5), x, evaluate=False)) in [
        "RootSum(Lambda(_a, -1/5/(x - _a)*_a), x**5 + 1, x)",
        "RootSum(Lambda(_a, -_a/(5*(x - _a))), x**5 + 1, x)"]
 

实例 7

 

复制

def test_nsolve():
    # onedimensional
    from sympy import Symbol, sin, pi
    x = Symbol('x')
    assert nsolve(sin(x), 2) - pi.evalf() < 1e-16
    assert nsolve(Eq(2*x, 2), x, -10) == nsolve(2*x - 2, -10)
    # multidimensional
    x1 = Symbol('x1')
    x2 = Symbol('x2')
    f1 = 3 * x1**2 - 2 * x2**2 - 1
    f2 = x1**2 - 2 * x1 + x2**2 + 2 * x2 - 8
    f = Matrix((f1, f2)).T
    F = lambdify((x1, x2), f.T, modules='mpmath')
    for x0 in [(-1, 1), (1, -2), (4, 4), (-4, -4)]:
        x = nsolve(f, (x1, x2), x0, tol=1.e-8)
        assert mnorm(F(*x),1) <= 1.e-10
    # The Chinese mathematician Zhu Shijie was the very first to solve this
    # nonlinear system 700 years ago (z was added to make it 3-dimensional)
    x = Symbol('x')
    y = Symbol('y')
    z = Symbol('z')
    f1 = -x + 2*y
    f2 = (x**2 + x*(y**2 - 2) - 4*y)  /  (x + 4)
    f3 = sqrt(x**2 + y**2)*z
    f = Matrix((f1, f2, f3)).T
    F = lambdify((x, y, z), f.T, modules='mpmath')
    def getroot(x0):
        root = nsolve((f1, f2, f3), (x, y, z), x0)
        assert mnorm(F(*root),1) <= 1.e-8
        return root
    assert map(round, getroot((1, 1, 1))) == [2.0, 1.0, 0.0]
    a = Symbol('a')
    assert nsolve(1/(0.001 + a)**3 - 6/(0.9 - a)**3, a, 0.3).ae(
        mpf('0.31883011387318591'))
 

实例 8

 

复制

def test_matrix():
    A = Matrix([[x, x*y], [sin(z)+4, x**z]])
    sol = Matrix([[1, 2], [sin(3)+4, 1]])
    f = lambdify((x,y,z), A, modules="sympy")
    assert f(1,2,3) == sol
    f = lambdify((x,y,z), (A, [A]), modules="sympy")
    assert f(1,2,3) == (sol,[sol])
 

实例 9

 

复制

def main():
    Format()
    a = Matrix ( 2, 2, ( 1, 2, 3, 4 ) )
    b = Matrix ( 2, 1, ( 5, 6 ) )
    c = a * b
    print a,b,'=',c
    x, y = symbols ('x, y')
    d = Matrix ( 1, 2, ( x ** 3, y ** 3 ))
    e = Matrix ( 2, 2, ( x ** 2, 2 * x * y, 2 * x * y, y ** 2 ) )
    f = d * e
    print '%',d,e,'=',f
    xpdf()
    return
 

实例 10

 

复制

def main():
    Format()
    a = Matrix ( 2, 2, ( 1, 2, 3, 4 ) )
    b = Matrix ( 2, 1, ( 5, 6 ) )
    c = a * b
    print a,b,'=',c
    x, y = symbols ( 'x, y' )
    d = Matrix ( 1, 2, ( x ** 3, y ** 3 ))
    e = Matrix ( 2, 2, ( x ** 2, 2 * x * y, 2 * x * y, y ** 2 ) )
    f = d * e
    print '%',d,e,'=',f
    xdvi()
    return
 

实例 11

 

复制

def matrix(self):
        if self.spinor:
            self.lt_dict = {}
            for base in self.Ga.basis:
                self.lt_dict[base] = self(base).simplify()
            self.spinor = False
            mat = self.matrix()
            self.spinor = True
            return(mat)
        else:
            mat_rep = []
            for base in self.Ga.basis:
                if base in self.lt_dict:
                    row = []
                    image = (self.lt_dict[base])
                    if isinstance(image, mv.Mv):
                        image = image.obj
                    (coefs, bases) = metric.linear_expand(image)
                    for base in self.Ga.basis:
                        try:
                            i = bases.index(base)
                            row.append(coefs[i])
                        except:
                            row.append(0)
                    mat_rep.append(row)
                else:
                    mat_rep.append(self.Ga.n * [0])
            return(Matrix(mat_rep).transpose())
 

实例 12

 

复制

def _issue_7853_dep_check(namespaces, namespace, expr):
    """Used for checking things passed into modules kwarg for deprecation
    issue #7853. This function and the call to it in lambdify should be
    deleted once the cycle has ended."""
    # If some module changed `ImmutableMatrix` to be something else
    mat = namespace.get('ImmutableMatrix', False)
    if not mat or 'numpy' not in namespaces or ('%s.%s' % (mat.__module__,
            mat.__name__) == 'numpy.matrixlib.defmatrix.matrix'):
        return
    dicts = [m for m in namespaces if isinstance(m, dict)]
    def test(expr):
        return hasattr(expr, 'is_Matrix') and expr.is_Matrix
    if test(expr) and not [d for d in dicts if 'ImmutableMatrix' in d]:
        SymPyDeprecationWarning(
            "Currently, `sympy.Matrix` is replaced with `numpy.matrix` if "
            "the NumPy package is utilized in lambdify. In future versions "
            "of SymPy (> 0.7.6), we will default to replacing "
            "`sympy.Matrix` with `numpy.array`. To use the future "
            "behavior now, supply the kwarg "
            "`modules=[{'ImmutableMatrix': numpy.array}, 'numpy']`. "
            "The old behavior can be retained in future versions by "
            "supplying `modules=[{'ImmutableMatrix': numpy.matrix}, "
            "'numpy']`.", issue=7853).warn()
 

实例 13

 

复制

def test_threaded():
    @threaded
    def function(expr, *args):
        return 2*expr + sum(args)
    assert function(Matrix([[x, y], [1, x]]), 1, 2) == 
        Matrix([[2*x + 3, 2*y + 3], [5, 2*x + 3]])
    assert function(Eq(x, y), 1, 2) == Eq(2*x + 3, 2*y + 3)
    assert function([x, y], 1, 2) == [2*x + 3, 2*y + 3]
    assert function((x, y), 1, 2) == (2*x + 3, 2*y + 3)
    assert function({x, y}, 1, 2) == {2*x + 3, 2*y + 3}
    @threaded
    def function(expr, n):
        return expr**n
    assert function(x + y, 2) == x**2 + y**2
    assert function(x, 2) == x**2
 

实例 14

 

复制

def test_constant_system():
    A = Matrix([[-(x + 3)/(x - 1), (x + 1)/(x - 1), 1],
                [-x - 3, x + 1, x - 1],
                [2*(x + 3)/(x - 1), 0, 0]])
    u = Matrix([(x + 1)/(x - 1), x + 1, 0])
    DE = DifferentialExtension(extension={'D': [Poly(1, x)]})
    assert constant_system(A, u, DE) == 
        (Matrix([[1, 0, 0],
                 [0, 1, 0],
                 [0, 0, 0],
                 [0, 0, 1]]), Matrix([0, 1, 0, 0]))
 

实例 15

 

复制

def _eval_term( self, sol, term, args, sops ):
        """Works for scalar, single unknown terms only!"""
        expr = term.symbolic['expression']
        arg_map = term.symbolic['map']
        env = {'x' : sops.Symbol( 'x' ),
               'y' : sops.Symbol( 'y' ),
               'z' : sops.Symbol( 'z' ),
               'dim' : dim}
        for key, val in arg_map.iteritems():
            if val == 'state':
                env[key] = sol
            else:
                env[key] = term.get_args( [val], **args )[0]
            if val[:8] == 'material':
                aux = nm.array( env[key] )
                if nm.prod( aux.shape ) == 1:
                    env[key] = aux.squeeze()
                else:
                    import sympy
                    env[key] = sympy.Matrix( aux )
#        print env
        self.report( '  <= ', sol )
        sops.set_dim( dim )
        val = str( eval( expr, sops.__dict__, env ) )
        self.report( '   =>', val )
        return val
    ##
    # c: 07.05.2007, r: 30.06.2008

你可能感兴趣的:(python)