Equals Signs (=)
Single Equals Sign
#单个等号用于赋值
>>> from sympy.abc import x, y
>>> a = x - y
>>> print(a)
x - y
Double Equals Signs
#双等号用于判断内部结构相等
>>> (x + 1)**2 == x**2 + 2*x + 1
False
>>> (x + 1)**2 == (x + 1)**2
True
>>> srepr(((x + 1)**2 ))
Pow(Add(Symbol(′x′),Integer(1)),Integer(2))
>>> srepr(x**2 + 2*x + 1)
Add(Pow(Symbol(′x′),Integer(2)),Mul(Integer(2),Symbol(′x′)),Integer(1))
#判断符号相等可以做差后用一些函数进行化简
>>> from sympy import simplify, cos, sin, expand
>>> simplify((x + 1)**2 - (x**2 + 2*x + 1))
0
>>> eq = sin(2*x) - 2*sin(x)*cos(x)
>>> simplify(eq)
0
>>> expand(eq, trig=True)
0
Variables
Variables Assignment does not Create a Relation Between Expressions
#sympy有自己内部变量,Symbol函数将python变量与sympy变量关联
>>> from sympy import Symbol
>>> a = Symbol('a') # Symbol, `a`, stored as variable "a"
>>> b = a + 1 # an expression involving `a` stored as variable "b"
>>> print(b)
a + 1
>>> a = 4 # "a" now points to literal integer 4, not Symbol('a')
>>> print(a)
4
>>> print(b) # "b" is still pointing at the expression involving `a`
a + 1
Symbols
#先声明,后使用
>>> import sympy
>>> z**2 # z is not defined yet
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'z' is not defined
>>> sympy.var('z') # This is the easiest way to define z as a standard symbol
z
>>> z**2
z**2
Symbolic Expressions
Python numbers vs. SymPy Numbers
#用simpify或者S转换成sympy表达式
>>> 6.2 # Python float. Notice the floating point accuracy problems.
6.2000000000000002
>>> type(6.2) # <type 'float'> in Python 2.x, <class 'float'> in Py3k
<... 'float'>
>>> S(6.2) # SymPy Float has no such problems because of arbitrary precision.
6.20000000000000
>>> type(S(6.2))
<class 'sympy.core.numbers.Float'>
#带有sympy变量时,会自动转换
>>> x**(1/2) # evaluates to x**0 or x**0.5
x**0.5
>>> x**(S(1)/2) # sympyify one of the ints
sqrt(x)
>>> x**Rational(1, 2) # use the Rational class
sqrt(x)
#sqrt在内部被转换成1/2次方
>>> sqrt(x) == x**Rational(1, 2)
True
Evaluating Expressions with Floats and Rationals
>>> Float(100)
100.000000000000
>>> Float('100', 5)
100.00
#与长度相等的精确度用空字符串
>>> Float(100, '')
100.
>>> Float('12.34')
12.3400000000000
>>> Float('12.34', '')
12.34
>>> _.n(10) #用.n修改精确度
100.0000000
#精确度不等时取最长
>>> Float('0.1', 10) + Float('0.1', 3)
0.2000061035