Solve Differential equations in python

Solve Differential equations in python

Contents of this blog
  • How to define Symbols by using sympy
  • How to write and print differential  equations in python jupyter
  • Solving Differential equations with python


In this blog, we will learn how to do differentiation in python. This is very important from engineering point of view so let's see how to do it.This blog is very useful for beginners who don't know how to solve differential equation or how to solve calculus in python





How to define Symbols by using sympy

first we need to import sympy library

import sympy as s
s.init_session(quiet =True) # this line print calculus equation in readable format 

x= s.Symbol('x') # use this Symbol if you only want to define a symbol only if you try more than one you will get error

x,y,z= s.symbols('x,y,z') #use symbols if you want to define multiple symbol 

#x,y,z symbol can be anything a real number, an integer , complex number and other things sometime we need to define what is that symbol signify

s.Symbol("x",imaginary =True).is_real # here we define x is a imaginary and you can check it by simply typing .is_real  if the ouput is True it means the no. is real if its false it means the no. is not real in our it is a imaginary no.


How to write and print calculus equations in jupyter


Differential equation printing
Note : command use here only print equation they don't do calculus operation we will discuss calculus operation later onwards in this blog

import sympy as s
s.init_session(quiet =True)
x,y,z = s.symbols('x,y,z')
f = s.Function('f')(x)
s.diff(f,x,2)


Output
𝑑2𝑑𝑥2𝑓(𝑥)


s.Derivative(x**2*cos(x),x)  # here x**2*cos(x) is the equation , singnify differentiate with respect to x

Output

𝑑𝑑𝑥𝑥2cos(𝑥)


What is you want to show differentiation of higher order ?

in that case 
s.Derivative(x**2*cos(x),x,4)  # just type the upto order you want to differentiate

𝑑4𝑑𝑥4𝑥2cos(𝑥)


What is you want to show equation containing more then a single variable
eq = y**3+z**2
s.Derivative(eq,x,2,y,2) # here 2 after x and y represent differentiation of x and y 2 times in equation

4𝑦2𝑥2(𝑦3+𝑧2)


How to Solve Differential Equation in python

eq1 = x*cos(x) +sin(x)
s.diff(eq1,x,1)  # s.diff will do differntial of the equation note 1 reperesent order of differentiation by increasing the power you can control the power of differentiation

Output
𝑥sin(𝑥)+2cos(𝑥)


In case if you have multiple variable then 
eq1 = x**2
eq2 = y**2
s.diff(eq1,x) +s.diff(eq2,y)

Output
2𝑥+2𝑦

Please share this blog to motivate

𝑑4


𝑑𝑥4
𝑥2cos(𝑥)
𝑑4𝑑𝑥4𝑥2cos(𝑥)

How to solve calculus equation in jupyter

Post a Comment

0 Comments