トップ 差分 一覧 ソース 検索 ヘルプ RSS ログイン

tips-sympy

Sympyとは?

Pythonの記号計算ライブラリ
公式ドキュメント : http://www.sympy.org/en/index.html
日本語資料 : http://www.turbare.net/transl/scipy-lecture-notes/packages/sympy.html

使い方

In [3]: from sympy import *
In [4]: init_session() 
IPython console for SymPy 0.7.6 (Python 3.4.6-64-bit) (ground types: python)

These commands were executed:
>>> from __future__ import division
>>> from sympy import *
>>> x, y, z, t = symbols('x y z t')
>>> k, m, n = symbols('k m n', integer=True)
>>> f, g, h = symbols('f g h', cls=Function)
>>> init_printing()
 

Symbols - 変数定義

In [1]: from sympy import *
In [2]: x + 1
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-2-4cf92658b648> in <module>()
----> 1 x + 1

NameError: name 'x' is not defined

In [3]: x = symbols('x')
In [4]: x + 1
Out[4]: x + 1

π : 円周率
In [13]: pi
Out[13]: π

In [14]: pi.evalf(50)
Out[14]: 3.1415926535897932384626433832795028841971693993751

expand - 展開

In [5]: expand((x + 1)**2)
Out[5]: x**2 + 2*x + 1
factor - 因数分解

In [6]: factor(x**4 - 3*x**2 + 1)
Out[6]: (1 + x - x**2)*(1 - x - x**2)

simplify - 簡約

In [7]: simplify((x**3 + x**2 - x - 1)/(x**2 + 2*x + 1))
Out[7]: x - 1

limit - 極限

In [8]: limit(x, x, oo)
Out[8]: oo

diff - 微分

In [9]: diff(cos(x), x)
Out[9]: -sin(x)
In [10]: diff(x**3 + x**2 - x - 1, x)
Out[10]: 3*x**2 + 2*x - 1

integrate - 積分

In [11]: integrate(cos(x), x)
Out[11]: sin(x)
In [12]: integrate(x**3 + x**2 - x - 1, x)
Out[12]: x**4/4 + x**3/3 - x**2/2 - x

Matrix - 行列

In [13]: Matrix([[1, 2, 3], [-2, 0, 4]])
Out[13]:
Matrix([
[ 1, 2, 3],
[-2, 0, 4]])

solve - 式を解く

In [14]: solve(x**2 - 1, x)
Out[14]: [-1, 1]

   import sympy as sp     
   K1, K2, P1, P2, x, y, rd = sp.symbols('K1 K2 P1 P2 x y rd')
   #
   xd = (1+K1*rd**2+K2*rd**4) * x +( 2*P1 * x * y + P2 * ( rd**2 + 2 * x**2 ) )
   yd = (1+K1*rd**2+K2*rd**4) * y +( 2*P2 * x * y + P1 * ( rd**2 + 2 * y**2 ) )
   #
   xdd = xd.copy()
   ydd = yd.copy()
   # 変数xへ数値(1)を代入 sympy.subs()
   print("代入")
   print(xd.subs(x, 1))
   print(xd.subs(x, y))
   # 式の展開: sympy.expand()
   xd = xdd.copy()
   print("展開")
   print(sp.expand(xd))
   # 式の因数分解: sympy.factor()
   xd = xdd.copy()
   print("因数分解")
   print(sp.factor(xd))
   # 方程式の解法: sympy.solve()
   print("方程式の解法")
   xd = xdd.copy()
   print(sp.solve(xd, x))
   # 微分: sympy.diff()
   xd = xdd.copy()
   print("微分")
   print(sp.diff(xd, x))
   # 積分: sympy.integrate()
   xd = xdd.copy()
   print("積分")
   print(sp.integrate(xd, x))
   # print(sympy.diff(sympy.cos(x))) # -sin(x) と表示される