Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)).

  • Is this a valid way of going about this calculation?
  • Are there better (or equivalent) alternatives without using np.gradient?
like image 370
user929304 Avatar asked Jan 01 '26 08:01

user929304


1 Answers

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

like image 93
FHTMitchell Avatar answered Jan 02 '26 22:01

FHTMitchell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!