SymPy學習之Gotchas and Pitfalls

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章