LaVOZs

The World’s Largest Online Community for Developers

'; python - Recursively find the nth order derivative with autograd grad() - LavOzs.Com

I am trying to find the nth derivative of a function using the grad function from the autograd library. grad(x) gives the 1st order derivative, but it doesn't allow a variable to find let's say the 3rd order derivative etc. Is there a way I might be able to do this recursively so the user can ender the derivative order they want to see?

import matplotlib.pyplot as plt
from autograd import grad
import autograd.numpy as np


# a named Python function
g = lambda w: w**2

w_vals = np.linspace(-5,5,200)
nabla_g = grad(g)   #A function here that can find the nth derivative
# evaluate gradient over input range
g_vals = [g(v) for v in w_vals]
grad_vals = [nabla_g(v) for v in w_vals]

It is quite simple. You should nest your grad function

# import matplotlib.pyplot as plt
from autograd import grad
import autograd.numpy as np

def my_grad(fun, ord):
    for i in range(ord):
        fun = grad(fun)
    return fun

# a named Python function
g = lambda w: w**3

# derivative x^3 = 3x^2
# derivative 3x^2 = 6x
# derivative 6x = 6
w_vals = np.linspace(-5,5,200)
nabla_g = my_grad(g, 3)   # recursive call to grad lead to 3° derivative
g_vals = [g(v) for v in w_vals]
grad_vals = [nabla_g(v) for v in w_vals]
print(grad_vals) #should output 6 for every input

I also developed the recursive version of my_grad:

def my_grad(fun, ord):
    if ord == 0:
       return fun
    return my_grad(grad(fun), ord-1)
Related
What does Ruby have that Python doesn't, and vice versa?
How to use glob() to find files recursively?
How to recursively find and list the latest modified files in a directory with subdirectories and times?
Recursive best first search and finding the best path
Returning automatic derivatives with Sympy
Higher order gradients in pytorch
Sum of second order derivatives in Tensorflow
Higher-order multivariate derivatives