my sympy and python cheat sheet
Nasser M. Abbasi
July 19, 2019 Compiled on July 19, 2019 at 6:49pm
Contents
1 How to solve a first oder ODE? 1
2 How to solve a first oder ODE with initial condition? 2
3 How to solve and ODE and convert the result to latex string? 2
4 How to solve a PDE in sympy? 2
5 How to check if something is derivative? 3
6 How to find function name and its arguments in a proc? 3
1 How to solve a first oder ODE?
Solve y 0 (x) = 1 + 2x for y(x)
import sympy
x = [Link]('x')
y = [Link]('y')
ode = [Link]([Link](y(x),x),1+2*x)
sol = [Link](ode,y(x))
# Eq(y(x), C1 + x**2 + x)
[Link](ode,sol)
# (True, 0)
1
2
2 How to solve a first oder ODE with initial
condition?
Solve y 0 (x) = 1 + 2x for y(x) with y(0) = 3
import sympy
x = [Link]('x')
y = [Link]('y')
ode = [Link]([Link](y(x),x),1+2*x)
sol = [Link](ode,y(x),ics={y(0):3})
# Eq(y(x), x**2 + x + 3)
[Link](ode,sol)
# (True, 0)
3 How to solve and ODE and convert the result to
latex string?
Solve y 0 (x) = 1 + 2x for y(x) with y(0) = 3
import sympy
x = [Link]('x')
y = [Link]('y')
ode = [Link]([Link](y(x),x),1+2*x)
sol = [Link](ode,y(x),ics={y(0):3})
# Eq(y(x), x**2 + x + 3)
[Link](sol)
y(x) = x2 + x + 3
4 How to solve a PDE in sympy?
PDE solving is still limited in sympy. Here is how to solve first order pde
Solve ut (x, t) = ux (x, t)
import sympy as sp
x,t = [Link]('x t')
u = [Link]('u')
pde = [Link]( [Link](u(x,t),t) , [Link](u(x,t),x))
sol = [Link](pde)
[Link](sol)
u(x, t) = F (t + x)
3
5 How to check if something is derivative?
import sympy
x = [Link]('x')
y = [Link]('y')
expr = [Link](y(x),x)
type(expr) is [Link]
#True
if type(expr) is [Link]:
print("yes")
#yes
This also works, which seems to be the more prefered way
isinstance(expr,[Link])
#True
6 How to find function name and its arguments in a
proc?
Suppose one passes y(x) to a function, and the function wants to find the name of this
function and its argument. Here is an example
def process(the_function):
print("the function argument is ", the_function.args[0])
print("the function name itself is ", the_function.name)
import sympy
x = [Link]('x')
y = [Link]('y')
process(y(x))
This prints
the function argument is x
the function name itself is y