トップ 差分 一覧 ソース 検索 ヘルプ 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]