[PYTHON] With Sympy, don't worry

Calculation using Sympy

Preparing for use with Google Colab

#Sympy 1 in the current Google Colab.1.Contains 1.
# Sympy 1.Since 1 cannot calculate the "special solution" described later, 1.Upgrade to 3.
!pip install sympy==1.3
Collecting sympy==1.3
[?25l  Downloading https://files.pythonhosted.org/packages/dd/f6/ed485ff22efdd7b371d0dbbf6d77ad61c3b3b7e0815a83c89cbb38ce35de/sympy-1.3.tar.gz (5.9MB)
      |████████████████████████████████| 5.9MB 4.1MB/s 
[?25hRequirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.6/dist-packages (from sympy==1.3) (1.1.0)
Building wheels for collected packages: sympy
  Building wheel for sympy (setup.py) ... [?25l[?25hdone
  Created wheel for sympy: filename=sympy-1.3-cp36-none-any.whl size=5199947 sha256=bc14a07ac6744969566fce4c541612a22adecb5bc83223ccc225ed28f415c38d
  Stored in directory: /root/.cache/pip/wheels/6c/59/86/478e3c0f298368c119095cc5985dedac57c0e35a85c737f823
Successfully built sympy
Installing collected packages: sympy
  Found existing installation: sympy 1.1.1
    Uninstalling sympy-1.1.1:
      Successfully uninstalled sympy-1.1.1
Successfully installed sympy-1.3
import sympy as sym
from sympy.plotting import plot
sym.init_printing(use_unicode=True)
%matplotlib inline
#If you are using Google Colab, run it to support TeX display by Sympy
def custom_latex_printer(exp,**options):
    from google.colab.output._publish import javascript
    url = "https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.3/latest.js?config=default"
    javascript(url=url)
    return sym.printing.latex(exp,**options)

sym.init_printing(use_latex="mathjax",latex_printer=custom_latex_printer)

Symbol definition

Treats the specified character as a symbol (character representing a variable).

a = sym.Symbol('a')

If you want to define them all together, do as follows.

a, b, c, x, y = sym.symbols("a b c x y")

Treats the specified character as a function.

f = sym.Function('f')
g = sym.Function('g')

Simple polynomial

#The formula is in English numerial expression or numerical formula
expr = x**2-12*x+8
expr
x^{2} - 12 x + 8
#Illustrated the obtained function
plot(expr, (x, -20, 20))

output_12_0.png

<sympy.plotting.plot.Plot at 0x7faf57ced080>

Factor

#Factorization
expr = x**2 + 2*x + 1
sym.factor(expr)
\left(x + 1\right)^{2}

Solve the equation

#The equation is in English equation or equality
eq = sym.Eq(expr)
eq
x^{2} - 12 x + 8 = 0
#You may specify the right side like this
eq = sym.Eq(x**2-12*x, -8)
eq
x^{2} - 12 x = -8
#Solve the equation
sym.solve(eq)
\left [ - 2 \sqrt{7} + 6, \quad 2 \sqrt{7} + 6\right ]
#Can handle expressions using algebra
eq = sym.Eq(a * x ** 2 + b * x + c)
eq
a x^{2} + b x + c = 0
#Solve for x
sym.solve(eq, x)
\left [ \frac{- b + \sqrt{- 4 a c + b^{2}}}{2 a}, \quad - \frac{b + \sqrt{- 4 a c + b^{2}}}{2 a}\right ]
#Simultaneous equations
eq1 = 3 * x + 5 * y - 29
eq2 = x + y - 7

sym.solve([eq1, eq2])
x : 3, y : 4

differential

expr = 2 * x ** 2 + 5 * x - 3
expr
2 x^{2} + 5 x - 3
#differential
sym.Derivative(expr)
\frac{d}{d x} \left(2 x^{2} + 5 x - 3\right)
#Calculate the derivative
sym.Derivative(expr).doit()
4 x + 5
#It is the same even if it is written like this
sym.diff(expr)
4 x + 5
# sym.Notated as an equation using Eq
sym.Eq(sym.Derivative(expr), sym.diff(expr))
\frac{d}{d x} \left(2 x^{2} + 5 x - 3\right) = 4 x + 5
#It has the same meaning as above, but if there is only one variable, it can be omitted as above.
#If there are two or more variables, you must specify what you want to differentiate.
sym.Eq(sym.Derivative(expr, x), sym.diff(expr, x))
\frac{d}{d x} \left(2 x^{2} + 5 x - 3\right) = 4 x + 5
#Second derivative
sym.Eq(sym.Derivative(expr, x, 2), sym.diff(expr, x, 2))
\frac{d^{2}}{d x^{2}} \left(2 x^{2} + 5 x - 3\right) = 4
#Differentiate with respect to x x=Substitute 1
sym.diff(expr).subs(x, 1)
9
#Differentiate about x
expr = a * x ** 2 + b * x * y + c * y ** 2
sym.diff(expr, x)
2 a x + b y
#Differentiate with respect to x x=Substitute 1
sym.diff(expr, x).subs(x, 1)
2 a + b y

Exercise 1

Complete the following derivative formula using Sympy. [Hint] When using a function such as sin in Sympy, write it as sym.sin.

1-1.

\frac{\partial}{\partial x} x^{a} =

1-2.

\frac{d}{d x} \sin{\left (x \right )} =

1-3.

\frac{d}{d x} \cos{\left (x \right )} =

1-4.

\frac{d}{d x} e^{x} =

1-5.

\frac{\partial}{\partial x} a^{x} =

1-6.

\frac{d}{d x} \log{\left (x \right )} =

1-7.

\frac{d}{d x} \sqrt{x} =

1-8.

\frac{d}{d x} \tan{\left (x \right )} =

1-9.

\frac{\partial}{\partial x} \sin^{a}{\left (x \right )} =

1-10.

\frac{\partial}{\partial x} \cos^{a}{\left (x \right )} =

1-11.

\frac{\partial}{\partial x} \tan^{a}{\left (x \right )} =

1-12.

\frac{\partial}{\partial x} \log{\left (x \right )}^{a} =

1-13.

\frac{d}{d x} f{\left (x \right )} g{\left (x \right )} =

1-14.

\frac{d}{d x} \frac{f{\left (x \right )}}{g{\left (x \right )}} =

Ordinary differential equation

Solve $ 2 f'(x) + 5 f (x) = 0 $

#Ordinary differential equation
eq = sym.Eq(2 * f(x).diff(x,1) + 5 * f(x))
eq
5 f{\left (x \right )} + 2 \frac{d}{d x} f{\left (x \right )} = 0
#General solution
ans = sym.dsolve(eq)
print(ans)
ans
Eq(f(x), C1*exp(-5*x/2))
f{\left (x \right )} = C_{1} e^{- \frac{5 x}{2}}
#Special solution
ans = sym.dsolve(eq, ics={f(0):1})
print(ans)
ans
Eq(f(x), exp(-5*x/2))
f{\left (x \right )} = e^{- \frac{5 x}{2}}
plot(ans.rhs, (x, -10, 10)) #rhs is the right side(Right-hand side)Meaning of

output_52_0.png

<sympy.plotting.plot.Plot at 0x7faf54dd4320>
#Special solution x=When
print(ans.subs(x, 2))
ans.subs(x, 2)
Eq(f(2), exp(-5))
f{\left (2 \right )} = e^{-5}
#If you use a method called evalf, it will expand to floating point
ans.subs(x, 2).evalf()
f{\left (2 \right )} = 0.00673794699908547

Exercise 2

Answer the following questions about the ordinary differential equation $ f'' (x) + f'(x) + 4 f (x) = 0 $.

[Hint] ʻics = {f (0): 1, f () .diff (x, 1) .subs (, _): 1} Write `` and fill in _ appropriately to solve it.

Integral

#Integral formula
expr  = x ** a
integ = sym.Integral(expr, x)
print(integ)
integ
Integral(x**a, x)
\int x^{a}\, dx
#Perform integration
integ.doit()
\begin{cases} \frac{x^{a + 1}}{a + 1} & \text{for}\: a \neq -1 \\\log{\left (x \right )} & \text{otherwise} \end{cases}
#It is the same even if it is written like this
sym.integrate(expr, x)
\begin{cases} \frac{x^{a + 1}}{a + 1} & \text{for}\: a \neq -1 \\\log{\left (x \right )} & \text{otherwise} \end{cases}
# sym.Notated as an equation using Eq
eq = sym.Eq(sym.Integral(expr, x), sym.integrate(expr, x))
print(eq)
eq
Eq(Integral(x**a, x), Piecewise((x**(a + 1)/(a + 1), Ne(a, -1)), (log(x), True)))
\int x^{a}\, dx = \begin{cases} \frac{x^{a + 1}}{a + 1} & \text{for}\: a \neq -1 \\\log{\left (x \right )} & \text{otherwise} \end{cases}

Exercise 3

Complete the following integral formula using Sympy.

3-1.

\int \frac{1}{x}\, dx =

3-2.

\int a^{x}\, dx =

3-3.

\int e^{x}\, dx =

3-4.

\int \sin{\left (x \right )}\, dx =

3-5.

\int \cos{\left (x \right )}\, dx =

3-6.

\int \tan{\left (x \right )}\, dx =

3-7.

\int \log{\left (x \right )}\, dx =

3-8.

\int \frac{1}{\cos^{2}{\left (x \right )}}\, dx =

3-9.

\int \frac{1}{\sin^{2}{\left (x \right )}}\, dx =

3-10.

\int \left(- a + x\right)^{b}\, dx =

3-11.

\int \frac{1}{\sin{\left (x \right )}}\, dx =

Definite integral

expr = (x-a)*(b-x)
eq = sym.Eq(sym.Integral(expr, (x, a, b)), sym.integrate(expr, (x, a, b))).factor()
print(eq)
eq
Eq(-Integral((-a + x)*(-b + x), (x, a, b)), -(a - b)**3/6)
- \int_{a}^{b} \left(- a + x\right) \left(- b + x\right)\, dx = - \frac{\left(a - b\right)^{3}}{6}
expr = x/(x**2 + 1)
eq = sym.Eq(sym.Integral(expr, (x, 1, 2)), sym.integrate(expr, (x, 1, 2)))
print(eq)
eq
Eq(Integral(x/(x**2 + 1), (x, 1, 2)), -log(2)/2 + log(5)/2)
\int_{1}^{2} \frac{x}{x^{2} + 1}\, dx = - \frac{\log{\left (2 \right )}}{2} + \frac{\log{\left (5 \right )}}{2}
sym.integrate(expr, (x, 1, 2)).evalf()
0.458145365937078

Exercise 4

Solve the following definite integral equation using Sympy.

\int_{0}^{1} \frac{4}{x^{2} + 1}\, dx =

Recommended Posts

With Sympy, don't worry
Overlay graphs with sympy
Equation of motion with sympy
Play with Poincare series and SymPy
Writing C language with Sympy (metaprogramming)
Free from hard-coding functions with SymPy
Multiple integrals with Python and Sympy
Let's calculate Godel's β function with SymPy