My Coding > Programming language > Python > Python libraries and packages > Python SymPy > Analytical differentiation with SymPy

Analytical differentiation with SymPy

SymPy give you power tool to solve algebraic problems analytically, in symbols, which can helps you to check your knowledges.

Do bind a derivative of any function with SymPy you need to do:

import SymPy library and declare formal symbol for mathematical manipulation within SymPy library.


import sympy as sp
x = sp.Symbol('x')

At the next step it is necessary to write text string with required formula. You must follow the correct syntacsys for equation and mention all mathematical operations. For example, I will write three equations for differentiation


y1 = '2*x**3 - 4*x**2 + x -8'
y2 = '1/(x**2 + 1)'
y3 = 'sin(3*x**2)'

Next step is differentiation itself with function diff from SymPy library.


dy1 = sp.diff(y1, x)
dy2 = sp.diff(y2, x)
dy3 = sp.diff(y3, x)

Job done. Now you need to output results:


print(f'''y1 = {y1}; y1' = {dy1}''')
print(f'''y2 = {y2}; y2' = {dy2}''')
print(f'''y3 = {y3}; y3' = {dy3}''')

Python code for analytical derivatives

And now full code with output


import sympy as sp
# variable for using in SymPy
x = sp.Symbol('x')
# declaration of function for differentiation
y1 = '2*x**3 - 4*x**2 + x -8'
y2 = '1/(x**2 + 1)'
y3 = 'sin(3*x**2)'
# analytical differentiation
dy1 = sp.diff(y1, x)
dy2 = sp.diff(y2, x)
dy3 = sp.diff(y3, x)
# output
print(f'''y1 = {y1}; y1' = {dy1}''')
print(f'''y2 = {y2}; y2' = {dy2}''')
print(f'''y3 = {y3}; y3' = {dy3}''')

output:


y1 = 2*x**3 - 4*x**2 + x -8; y1' = 6*x**2 - 8*x + 1
y2 = 1/(x**2 + 1); y2' = -2*x/(x**2 + 1)**2
y3 = sin(3*x**2); y3' = 6*x*cos(3*x**2)

Some theory behind these derivative with main rules for differentiation you can find in this video


Published: 2022-07-17 01:27:14

Last 10 artitles


9 popular artitles

© 2020 MyCoding.uk -My blog about coding and further learning. This blog was writen with pure Perl and front-end output was performed with TemplateToolkit.