C:\Users\Administrator>pip install Sympy

C:\Users\Administrator>pip list
Package            Version
------------------ --------
appdirs            1.4.4
distlib            0.3.1
filelock           3.0.12
importlib-metadata 4.3.1
mpmath             1.2.1
pip                21.1.2
setuptools         40.8.0
six                1.16.0
sympy              1.8
typing-extensions  3.10.0.0
virtualenv         20.4.7
zipp               3.4.1

 

1. 연립1차방정식

>>> from sympy import Symbol, solve, Eq
>>> x = Symbol('x')
>>> y = Symbol('y')
>>> 
>>> 
>>> eq1 = x + 2*y - 3 #eq1 = Eq(2*y, -x + 3)
>>> eq2 = 3*x - y + 2 #eq2 = Eq(y, 3*x + 2)
>>> result = solve((eq1, eq2))
>>> print(result)
{x: -1/7, y: 11/7}
>>> result = solve((eq1, eq2), dict=True)
>>> print(result)
[{x: -1/7, y: 11/7}]

 

2. 미분

2-1. 멱의 법칙(Power Rule)

>>> import sympy as sp
>>> x = sp.symbols('x')
>>> y = x**3 + 3*x**2 + 4
>>> result = sp.diff(y)
>>> print(result)
3*x**2 + 6*x

 

2-2. 곱의 법칙(Product Rule)

>>> import sympy as sp
>>> x = sp.symbols('x')
>>> y = (x**2 + 1) * sp.cos(x)
>>> result = sp.diff(y)
>>> print(result)
2*x*cos(x) - (x**2 + 1)*sin(x)

 

2-3. 연쇄 법칙(Chain Rule)

>>> import sympy as sp
>>> x = sp.symbols('x')
>>> y = (x**2 - 3*x - 5)**3
>>> result = sp.diff(y)
>>> print(result)
(6*x - 9)*(x**2 - 3*x - 5)**2

 

2-4. 편미분

>>> import sympy as sp
>>> x, y, z = sp.symbols('x y x')
>>> z = 3*x**2 + 5*x*y + 3*y**3
>>> result = sp.diff(z, x)
>>> print(result)
6*x + 5*y
>>> 
>>> result = sp.diff(z, y)
>>> print(result)
5*x + 9*y**2

x로 편미분하면 : y는 상수로 취급하고 미분한다.

y로 편미분하면 : x는 상수로 취급하고 미분한다.

 

3. 변수에 값대입하여 연산하기

>>> import sympy as sp
>>> x, y, z = sp.symbols('x y x')
>>> z = 3*x**2 + 5*x*y + 3*y**3
>>> z = z.subs([(x, 2), (y, -1)])
>>> print(z)
-1
>>> z = 3*x**2 + 5*x*y + 3*y**3
>>> z = z.subs([(x, 2), (y, 1)])
>>> print(z)
25