My Coding >
Numerical simulations >
Numerical Differentiation >
How to calculate numerical derivative with Python
How to calculate numerical derivative with PythonThis is a simplest code for numerical calculating of a derivative of any analytical function, which you can calculate in any points. Definition of derivativesBy definition, the derivative of function f(x) in the point x is equal [f(x+Δx) – f(x)]/Δx, when Δx is approaching to 0. Roughly speaking, the lest Δx you taking for calculations, the more accurate value of derivative you will get. Therefore, if we have tabulated for function data eventually distributed over the X axis, then the numerical derivative in the simplest case will be f’(x_{i}) = (f(x_{i+1})f(x_{i}))/dx. Coding for differentiationNow we will implement this idea into Python code with NumPy library. For example I will calculate the derivative of sin(x) and then visually compare it with theoretical solution cos(x) Including librariesFor the derivative calculations we only need NumPy library and matplotlib for graphical output.
Calculating of our function and derivativeFunctions for calculating of function value and theoretical derivative we can take from numpy library also. For this example we will take f(x) = sin(x), then , the derivative will be f’(x) = cos(x).
Physical domain and bordersFor calculation we will need to define physical size of our domain, or area of calculations. We will take user defined s_x start of the domain and e_x end of the domain. Also we need to know number of cots or cells in this domain n_x Border will be defines as 1 – good enough for this algorithm. And the we will store these user difined values into a compact structure x, used in all calculations.
Calculating all valuesfirst of all we will uniformly arrange x values in our domain with np.arange function Then we need to prepare numpy array for numerical derivative U, calculate our function Y and theoretical derivative dY
Function for differentiationWe need to code f’(x_{i}) = (f(x_{i+1})f(x_{i}))/dx function with numpy array.
Graphical outputDraw everything for visual inspection. Yellow – our function. Black – theoretical derivative. Red crosses – numerically calculated derivatives.
and the result will be:
Full codeFor better understanding, you can watch video about simple derivative calculation: And the final code is:

Last 10 artitles
9 popular artitles


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