Search code examples
pythonnumpyscipyderivative

How to calculate derivatives at the boundary in SciPy?


I have a script drawing a set of (x,y) curves at various z.

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0,1,100)
z = np.linspace(0,30,30)

def y(z, x):
    return z**(1-x)

for i in z:
    plt.plot(x, y(i,x))

How can I draw dy/dx at x=0 versus z?

plt.plot(z, dy/dx at x=0)

In fact, I need to calculate the slope at the x=0 boundary for each (x,y) curve (shown below), then plot the slopes against z.

enter image description here


Solution

  • You must use the derivative function:

    scipy.misc.derivative(func, x0, dx=1.0, n=1, args=(), order=3)

    Find the n-th derivative of a function at a point.

    Given a function, use a central difference formula with spacing dx to compute the n-th derivative at x0.

    Parameters:

    func : function Input function.

    x0 : float The point at which n-th derivative is found.

    dx : float, optional Spacing.

    n : int,optional Order of the derivative. Default is 1.

    args : tuple, optional Arguments order : int, optional Number of points to use, must be odd.

    In your case:

    import numpy as np
    import matplotlib.pyplot as plt
    
    from scipy.misc import derivative
    
    x = np.linspace(0,1,100)
    z = np.linspace(0,30,30)
    
    x0 = 0
    
    def y(z, x):
        return z**(1-x)
    
    dydx = [derivative(lambda x : y(zi, x) , x0) for zi in z]
    
    plt.plot(z, dydx)
    
    plt.show()
    

    Screenshot:

    enter image description here