代数(Symbolic math)を使う〜sympy

  • x^4+3x^3+\sqrt{2x}に使われるxは何の値が入るかわからないわけだが、このxに数値を入れずに「代数」として扱うのがsymbolic math
  • 代数変数を作る
from sympy import *
x = Symbol('x') # 代数としてのx
y = Symbol('y') # 代数としてのy

x+2*x + y - y
Out[3]: 3*x
  • 分数も、割ってしまわずに、そのまま使う
Rational(1,2) + Rational(1,3)
Out[25]: 5/6

Rational(1,2) + Rational(1,3) + Rational(1,6)
Rational(1,2) + Rational(1,3) + Rational(1,6)
Out[26]: 1
  • 式の展開と簡単化
expand((x+y)**3)
Out[30]: x**3 + 3*x**2*y + 3*x*y**2 + y**3
simplify((x**2-1)/(x+1))
Out[31]: x - 1

simplify(sin(x)/cos(x))
Out[32]: tan(x)

simplify(sin(x)/cos(x+pi/2))
Out[33]: -1
    • 式展開は普通のそれ、複素数のそれ、三角関数のそれ、などオプションがある
expand(x+y, complex=True)
Out[42]: re(x) + re(y) + I*im(x) + I*im(y)

expand(cos(x+y), trig=True)
Out[44]: -sin(x)*sin(y) + cos(x)*cos(y)

expand(sin(2*x)*cos(3*y),trig=True)
Out[46]: 8*sin(x)*cos(x)*cos(y)**3 - 6*sin(x)*cos(x)*cos(y)
factor(x**3-3*x**2+3*x-1)
Out[82]: (x - 1)**3
  • 任意精度
pi.evalf(2)
Out[35]: 3.1

pi.evalf(100)
Out[36]: 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117068
  • 無限大
oo > 2**1000
Out[37]: True

atan(oo)
Out[41]: pi/2
  • 極限
limit(1/(x-1),x,1)
Out[50]: oo

limit(y/(x-1),x,1)
Out[51]: oo*sign(y)
fx = 3*x**3 + x + 1

fy = 2*y - 1

diff(fx * fy,x)
Out[57]: (9*x**2 + 1)*(2*y - 1)

diff(fx * fy,y)
Out[58]: 6*x**3 + 2*x + 2
diff(fx,x,0)
Out[59]: 3*x**3 + x + 1

diff(fx,x,1)
Out[61]: 9*x**2 + 1

diff(fx,x,2)
Out[62]: 18*x

diff(fx,x,3)
Out[63]: 18

diff(fx,x,4)
Out[64]: 0

diff(diff(fx,x,1))
Out[65]: 18*x
series(cos(x), x ,n=1)
Out[69]: 1 + O(x)

series(cos(x), x ,n=2)
Out[70]: 1 + O(x**2)

series(cos(x), x ,n=3)
Out[71]: 1 - x**2/2 + O(x**3)

series(cos(x), x ,n=6)
Out[72]: 1 - x**2/2 + x**4/24 + O(x**6)

series(cos(x), x ,n=12)
Out[73]: 1 - x**2/2 + x**4/24 - x**6/720 + x**8/40320 - x**10/3628800 + O(x**12)

series(cos(x), x ) # デフォルト
Out[74]: 1 - x**2/2 + x**4/24 + O(x**6)

series(cos(x), x, x0=1 )
Out[75]: cos(1) - x*sin(1) - x**2*cos(1)/2 + x**3*sin(1)/6 + x**4*cos(1)/24 - x**5*sin(1)/120 + O(x**6)

series(cos(x), x, x0=0 )
Out[76]: 1 - x**2/2 + x**4/24 + O(x**6)
integrate(6 * x ** 5 + 3 * x,x)
Out[80]: x**6 + 3*x**2/2

integrate(exp(x**2),(x,0,1))
Out[81]: sqrt(pi)*erfi(1)/2
  • 解を求める
solve(x**4 - 1, x)
Out[83]: [-1, 1, -I, I]

solve([x**2+y**2-1,x-y],[x,y])
Out[94]: [(-sqrt(2)/2, -sqrt(2)/2), (sqrt(2)/2, sqrt(2)/2)]