user929304
user929304

Reputation: 485

Implementing derivatives of logs of data in python

We have two lists (vectors) of data, y and x, we can imagine x being time steps (0,1,2,...) and y some system property computed at value each value of x. I'm interested in calculating the derivative of log of y with respect to log of x, and the question is how to perform such calculations in Python? We can start off by using numpy to calculate the logs: logy = np.log(y) and logx = np.log(x). Then what method do we use for the differentiation dlog(y)/dlog(x)?

One option that comes to mind is using np.gradient() in the following way:

deriv = np.gradient(logy,np.gradient(logx)).

Upvotes: 3

Views: 2272

Answers (1)

FHTMitchell
FHTMitchell

Reputation: 12156

Right after looking at the source of np.gradient here and looking around you can see it changed in numpy version 1.14, hence why the docs change.

I have version 1.11. So I think that gradient is defined as def gradient(y, x) -> dy/dx if isinstance(x, np.ndarray) now but isn't in version 1.11. Doing np.gradient(y, np.array(...)) is actually, I think, undefined behaviour!

However, np.gradient(y) / np.gradient(x) works for all numpy versions. Use that!

Proof:

import numpy as np
import matplotlib.pyplot as plt
x = np.sort(np.random.random(10000)) * 2 * np.pi
y = np.sin(x)
dy_dx = np.gradient(y) / np.gradient(x)
plt.plot(x, dy_dx)
plt.show()

Looks an awful lot like a cos wave

enter image description here

Upvotes: 3

Related Questions