-2

Suppose I have defined a function

def func(x):
    return x**2;

Is there a method XXX which takes "func" as an argument and returns another function which is a derivative? For example,

dfunc = XXX(func);

print(dfunc(3))

gives me 6.

I need to have a function which returns the derivative of bessel function of first kind of order one for my homework>

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
rims
  • 133
  • 1
  • 8
  • 3
    Short answer, no. Long answer, I believe there are special libraries which do this. Functions in python are not the same as functions in maths. – dangee1705 Oct 20 '18 at 18:32

1 Answers1

0

There are two ways this can be done:

  1. Using symbolic maths, which are basically like encoding an algebraic expression and then letting the computer figure out an analytical expression of the derivative; these can be quite powerful but are restricted to certain types of problems: https://www.sympy.org/en/index.html

  2. Using finite differencing. This is a very common and powerful concept founded on the idea of using the definition of the derivative with delta_x being small and finite instead of tending towards zero: https://en.wikipedia.org/wiki/Finite_difference

For your particular problem, this could be done, for instance:

import numpy as np
import matplotlib.pyplot as plt

def func(x):
    return x**2

def finiteDifference(f, limits, deltaX):
    # create values of the function at specific locations
    x = np.arange(limits[0], limits[1]+deltaX, deltaX)
    y = np.zeros(len(x))
    for i in range(len(x)):
        y[i] = f(x[i])
    # construct the derivative
    dydx = np.zeros(len(x))
    # first order at the ends
    dydx[0] = (y[1]-y[0]) / deltaX
    dydx[-1] = (y[-1]-y[-2]) / deltaX
    # central 2nd order elsewhere
    for i in range(1, len(x)-1):
        dydx[i] = (y[i+1] - y[i-1]) / (2.*deltaX)

    return x, y, dydx

x, y, dydx = finiteDifference(func, (-2, 2), 0.1)
plt.plot(x, y, "r-", x, dydx, "b-", lw=2)
# compare with analytical f'=2x
plt.plot(x, 2.*x, "gx", ms=5, mew=2)
plt.show()
Artur
  • 407
  • 2
  • 8