Hint: Use a recursive routine. If an operation is unary plus or minus, leave the plus or minus sign alone and continue with the operand. (That means, recursively call the derivative routine on the operand.) If an operation is addition or subtraction, leave the plus or minus sign alone and recursively find the derivative of each operand. If the operation is multiplication, use the product rule. If the operation is division, use the quotient rule. If the operation is exponentiation, use the generalized power rule. (Do you know that rule, for u ^ v? It is not given in most first-year calculus books but is easy to find using logarithmic differentiation.) (Now that you have clarified in a comment that there will be no variable in the exponent, you can use the regular power rule (u^n)' = n * u^(n-1) * u' where n is a constant.) And at the base of the recursion, the derivative of x is 1 and the derivative of a constant is zero.

The result of such an algorithm would be very un-simplified but it would meet your stated requirements. Since this algorithm looks at an operation then looks at the operands, having the expression in Polish notation may be simpler than reverse Polish or "regular expression." But you could still do it for the expression in those forms.

If you need more detail, show us more of your work.

Answer from Rory Daulton on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › how do you make a python program to calculate the derivative or integration of an expression without using sympy?
r/learnpython on Reddit: How do you make a python program to calculate the derivative or integration of an expression without using sympy?
March 1, 2020 - Subclasses such as Polynomial could override these in cases where something can easily be simplified (such as adding two polynomials), falling back on the generic implementations otherwise. The __call__ and derivative methods are very straightforward to implement.
Top answer
1 of 9
208

You have four options

  1. Finite Differences
  2. Automatic Derivatives
  3. Symbolic Differentiation
  4. Compute derivatives by hand.

Finite differences require no external tools but are prone to numerical error and, if you're in a multivariate situation, can take a while.

Symbolic differentiation is ideal if your problem is simple enough. Symbolic methods are getting quite robust these days. SymPy is an excellent project for this that integrates well with NumPy. Look at the autowrap or lambdify functions or check out Jensen's blogpost about a similar question.

Automatic derivatives are very cool, aren't prone to numeric errors, but do require some additional libraries (google for this, there are a few good options). This is the most robust but also the most sophisticated/difficult to set up choice. If you're fine restricting yourself to numpy syntax then Theano might be a good choice.

Here is an example using SymPy

In [1]: from sympy import *
In [2]: import numpy as np
In [3]: x = Symbol('x')
In [4]: y = x**2 + 1
In [5]: yprime = y.diff(x)
In [6]: yprime
Out[6]: 2⋅x

In [7]: f = lambdify(x, yprime, 'numpy')
In [8]: f(np.ones(5))
Out[8]: [ 2.  2.  2.  2.  2.]
2 of 9
82

The most straight-forward way I can think of is using numpy's gradient function:

x = numpy.linspace(0,10,1000)
dx = x[1]-x[0]
y = x**2 + 1
dydx = numpy.gradient(y, dx)

This way, dydx will be computed using central differences and will have the same length as y, unlike numpy.diff, which uses forward differences and will return (n-1) size vector.

Top answer
1 of 1
2

It is hard to read your code when it is so compact on one line. Is there a reason you want it so compact and hard to read (are you in a coding competition?). I would recommend to spread your code out a little, then you can easily see what to do (and others can too).

It looks like your code is not handling the constant and linear cases very well. We should also point out that a derivative is really easy if I had a list of coefficients. Maybe some functions, like:

def list_to_poly(coef_list): 
    poly_list = [] 
    if not coef_list or coef_list==[0]: 
        poly_list.append('0') 
    if len(coef_list)>=1 and coef_list[0]: 
        poly_list.append(f'{coef_list[0]}') 
    if len(coef_list)>=2 and coef_list[1]: 
        poly_list.append(f'{coef_list[1] if coef_list[1]!=1 else ""}x') 
    poly_list.extend([f'{i if i!=1 else ""}x^{j+2}' for j,i in enumerate(coef_list[2:]) if i]) 
    return ' + '.join(poly_list) 

def poly_to_list(string): 
    terms     = string.split(' + ') 
    poly_list = [] 
    for term in terms: 
        if 'x^' not in term: 
            if 'x' not in term: 
                poly_list.append(int(term)) 
            else: 
                linear_coef = term.split('x')[0] 
                poly_list.append(int(linear_coef) if linear_coef else 1) 
        else: 
            coef,exp = term.split('x^') 
            for i in range(len(poly_list),int(exp)): 
                poly_list.append(0) 
            poly_list.append(int(coef) if coef else 1) 
    return poly_list 

def derivative(string): 
    poly_list  = poly_to_list(string) 
    derivative = [i*j for i,j in enumerate(poly_list)][1:] 
    d_string   = list_to_poly(derivative) 
    return d_string 

print(derivative('0'))
print(derivative('3 + 5x'))
print(derivative('3 + x^5 + -3x^7'))
🌐
Turing
turing.com › kb › derivative-functions-in-python
How to Calculate Derivative Functions in Python
Using derivatives, researchers and analysts can extract valuable insights from complex datasets and build accurate models that capture underlying patterns and relationships. Python, with its rich ecosystem of libraries and intuitive syntax, has emerged as a versatile tool for scientific computing and mathematical analysis. Its extensive mathematical libraries, such as NumPy and SciPy, along with specialized packages like SymPy and autograd, make it well-suited for calculating derivatives.
🌐
YouTube
youtube.com › shorts › MPcHmfDgAVs
TWO Ways To Take A Derivative In PYTHON #python #coding #shorts - YouTube
Check out my course on UDEMY: learn the skills you need for coding in STEM:https://www.udemy.com/course/python-stem-essentials/A quick tutorial for numerical...
Published   November 15, 2022
Find elsewhere
🌐
Quora
quora.com › How-do-you-write-a-code-that-calculates-the-derivative-numerically-of-the-function-f-x-2sin-x-10cos-2x-2-in-Python-NumPy-Matplotlib
How to write a code that calculates the derivative numerically of the function f(x) = 2sin(x) +10cos(2x) +2 in Python (NumPy, Matplotlib) - Quora
Answer (1 of 3): I assume you’re aware of the sympy library? That would give you the means to generate a symbolic solution. However you’re asking for a numeric solution. After you define the function f in ordinary Python (see below), compute a large number of (f(x+h) - f(x))/h slope values, call...
🌐
Towards Data Science
towardsdatascience.com › home › latest › hands-on numerical derivative with python, from zero to hero
Hands-On Numerical Derivative with Python, from Zero to Hero | Towards Data Science
January 13, 2025 - The derivative is extremely unstable but the signal is not increasing or decreasing anywhere. It is changing locally, but it’s just a random variation of the noise that we are not interested in. So what do we do in those cases? Let’s see it together: Let’s explore a real case and let’s do it in Python.
Top answer
1 of 3
7

Your function fprime is not the derivative. It is a function that returns the derivative (as a Sympy expression). To evaluate it, you can use .subs to plug values into this expression:

>>> fprime(x, y).evalf(subs={x: 1, y: 1})
3.00000000000000

If you want fprime to actually be the derivative, you should assign the derivative expression directly to fprime, rather than wrapping it in a function. Then you can evalf it directly:

>>> fprime = sym.diff(f(x,y),x)
>>> fprime.evalf(subs={x: 1, y: 1})
3.00000000000000
2 of 3
2

The answer to this question is pretty simple. Sure, the subs option given in the other answer works for evaluating the derivative at a number, but it doesn't work if you want to plot the derivative. There is a way to fix this: lambdify, as explained below.

Use lambdify to convert all of the sympy functions (which can be differentiated but not evaluated) to their numpy counterparts (which can be evaluated, plotted, etc., but not differentiated). For example, sym.sin(x) will be replaced with np.sin(x). The idea is: define the function using sympy functions, differentiate as needed, and then define a new function which is the lambdified version of the original function.

As in the code below, sym.lambdify takes the following inputs:

sym.lambdify(variable, function(variable), "numpy")

The third input, "numpy", is what replaces sympy functions with their numpy counterparts. An example is:

def f(x):
    return sym.cos(x)

def fprime(x):
    return sym.diff(f(x),x)

fprimeLambdified = sym.lambdify(x,f(x),"numpy")

Then the function fprime(x) returns -sym.sin(x), and the function fprimeLambdified(x) returns -np.sin(x). We can "call"/evaluate fprimeLambdified at specific input values now, whereas we cannot "call"/evaluate fprime, since the former is composed of numpy expressions and the latter sympy expressions. In other words, it makes sense to input fprimelambdified(math.pi), and this will return an output, while fprime(math.pi) will return an error.

An example of using sym.lambdify in more than one variable is seen below.

import sympy as sym
import math


def f(x,y):
    return x**2 + x*y**2


x, y = sym.symbols('x y')

def fprime(x,y):
    return sym.diff(f(x,y),x)

print(fprime(x,y)) #This works.

DerivativeOfF = sym.lambdify((x,y),fprime(x,y),"numpy")

print(DerivativeOfF(1,1))
🌐
Medium
medium.com › @jamesetaylor › create-a-derivative-calculator-in-python-72ee7bc734a4
Create A Derivative Calculator in Python | by James Taylor | Medium
February 13, 2018 - Simple enough. Now we have to derive it. I created a new python function that would take two paraments. The first parameter was a function — like f — and the value at which to derive and find the slope.
🌐
Quora
quora.com › How-do-I-modify-this-Python-program-so-that-it-gives-me-the-derivative-of-a-function-f-x-at-point-x
How to modify this Python program so that it gives me the derivative of a function f(x) at point x - Quora
Answer (1 of 3): First, I will assume that you want an approach that does not use an implementation already specified in a library. As you probably already know from your introductory calculus / analysis course, one way of defining the derivative of a function f(x) is through a limiting process,...
🌐
Towards Data Science
towardsdatascience.com › home › latest › taking derivatives in python
Taking Derivatives in Python | Towards Data Science
January 28, 2025 - As you can see, x squared plus ... do it in Python: Also straightforward. Make sure to watch where you put those brackets though. Also, note that you can’t use cosine from math or numpy libraries, you need to use the one from sympy. If you decide to dive deeper into machine learning algorithms you’ll see chain rule popping up everywhere – gradient descent, backpropagation, you name it. It deals with nested functions, for example, f(g(x)) and states that the derivative is calculated ...
🌐
Medium
medium.com › data-science › taking-derivatives-in-python-d6229ba72c64
Taking Derivatives in Python. Learn how to deal with Calculus part of… | by Dario Radečić | TDS Archive | Medium
March 14, 2022 - Taking Derivatives in Python The idea behind this post is to revisit some calculus topics needed in data science and machine learning and to take them one step further — calculate them in Python …
🌐
Reddit
reddit.com › r/physics › how to take derivatives in python: 3 different types of scenarios
r/Physics on Reddit: How To Take Derivatives In Python: 3 Different Types of Scenarios
August 9, 2021 - Subreddit for posting questions and asking for general advice about all topics related to learning python. ... I made a derivative calculator using Python!
Top answer
1 of 2
5

diff is a "wrapper" method that it is going to instantiate the Derivative class. So, doing this:

from sympy import *
expr = x**2
expr.diff(x)

# out: 2*x

is equivalent to do:

Derivative(expr, x).doit()

# out: 2*x

However, the Derivative class might be useful to delay the evaluation of a derivative. For example:

Derivative(expr, x)

# out: Derivative(x**2, x)

But the same thing can also be achieved with:

expr.diff(x, evaluate=False)

# out: Derivative(x**2, x)

So, to answer your question, in the example you provided there is absolutely no difference in using diff vs Derivative.

If expr.diff(variable) can be evaluated, it will return an instance of Expr (either a symbol, a number, multiplication, addition, power operation, depending on expr). Otherwise, it will return an object of type Derivative.

2 of 2
2

The Derivative object represents an unevaluated derivative. It will never evaluate, for example:

>>> Derivative(x**2, x)
Derivative(x**2, x)

diff is a function which always tries to evaluate the derivative. If the derivative in question cannot be evaluated, it just returns an unevaluated Derivative object.

>>> diff(x**2, x)
2*x

Since undefined functions are always things whose derivatives won't be evaluated, Derivative and diff are the same.

>>> diff(f(x), x)
Derivative(f(x), x)
>>> Derivative(f(x), x)
Derivative(f(x), x)

There's only a difference between the two in cases where the derivative can be evaluated. For ODEs, this means that it generally doesn't matter, except maybe if you have something like the following that you don't want expanded

>>> diff(x*f(x), x)
x*Derivative(f(x), x) + f(x)
>>> Derivative(x*f(x), x)
Derivative(x*f(x), x)
🌐
Svitla Systems
svitla.com › home › articles › blog › numerical differentiation methods in python
Python for Numerical Differentiation: Methods & Tools
January 14, 2021 - To get more information about scipy.misc.derivative, please refer to this manual. It allows you to calculate the first order derivative, second order derivative, and so on. It accepts functions as input and this function can be represented as a Python function.
Price   $$$
Address   100 Meadowcreek Drive, Suite 102, 94925, Corte Madera
🌐
Byu
emc2.byu.edu › winter-labs › lab09.html
Lab 9: Symbolic Python and Partial Differentiation — Math 495R EMC2 Python Labs
Chances are you have used a tool similar to Wolfram Alpha to simplify, integrate, or differentiate a complicated algebraic expression. Although Python is primarily used for crunching, relating, or visualizing numerical data, using the SymPy module one can also do symbolic mathematics in Python, including algebra, differentiation, integration, and more.