Googlebot
Googlebot

Reputation: 15673

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

Upvotes: 0

Views: 879

Answers (2)

eyllanesc
eyllanesc

Reputation: 243947

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

Upvotes: 3

Alex
Alex

Reputation: 1262

You mixed up the variables in the description. I assume you have a function y in variables (x,z). So you need to calculate dy/dx and dy/dz.

You have a few options to calculate the derivative, including symbolic calcultation (using SymPY) or just straightfoward finite differences calculation (prone to numerical errors) See this: How do I compute derivative using Numpy?.

But, you cannot plot this derivative since you are calculating it at a point (x=0,z=0), therefore the result is a float number, and not a function. To make the plot you want you need to calculate the general symbolic derivative (dydx) and make the plot you suggested. To get the result at point (0,0), just dydx(0,0).

Btw, dydz = (1-x)z**(-x) and dydx = -ln(z)*z**(1-x) using this.

Upvotes: 1

Related Questions