Implement derivation of data logs in python
We have two lists of data (vectors), y and x, and we can imagine that
x is the time step (0,1, 2,…) and y
some system properties are calculated based on each value of
x
.
I’m interested in calculating the derivative
of the log of y
relative to the
question is how to perform such calculations in Python?log
of x, and the
We can start using numpy
to calculate logs: logy = np.log(y) and logx = np.log(
x).
So what method do we use to distinguish dlog(y)/dlog(x)?
One option that comes to mind is to use np.gradient()
as follows:
deriv = np.gradient(logy,np.gradient(logx)).
- Is this an efficient way to do this calculation?
- Is there a better (or equivalent) alternative without
using np.gradient
?
Solution
After viewing the source code of np.gradient
here Look around and you can see that it changed in numpy version 1.14, So the documentation has changed.
I have version 1.11. So I think gradient defined as def gradient(y, x) -> dy/dx
if isinstance(x, np.ndarray)
is now but not in version 1.11.
In my opinion, executing np.gradient(y, np.array(...))
is actually undefined behavior!
However, np.gradient(
y)/np.gradient(x)
applies to 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()
It looks a lot like a cos
wave