Search code examples
pythonnumpymathderivative

Python differentiation using numpy not producing expected output


So, I am working on some numerical computation. I have calculated some 100,000 points of a function (return_times) only computable numerically, and now want to take it's derivate using numpy.gradient. As I understand (doc), for an f(x)I can give the following arguments: numpy.gradient(arr_of_fx_datapoints, arr_of_their_x_values) to make it work. And that's what I (intended to) do.

Except that it doesn't work. The result is almost (but not exactly) zero everywhere. The bug is reproduced by this abstract of my code below (sin^2(x) has a shape alike to my original function):

import matplotlib.pyplot as plt
import numpy as np

def find_times(t_arr):
    return np.power(np.sin(t_arr), 2)

t_0 = 0
t_max = np.pi-1E-10
datapoints = 100000

dt = (t_max - t_0) / datapoints
t_points = np.arange(t_0, t_max, dt, dtype=np.float64)
return_times = find_times(t_points)
gd = np.gradient(return_times, t_points)
plt.plot(t_points, gd)
plt.plot(t_points, return_times)
plt.show()

The result is disappointing:
enter image description here

If I print gd, it shows it is indeed not entriely zero:

[             inf   6.28318530e-05   6.28318529e-05 ...,  -1.25666419e-09
  -6.28326813e-10  -3.14161265e-10]

So: What did I miss? What is the Ultimate Proper Way to numerically derivate in Python?

Enviroment: Linux Mint 18.2 OS, Geany editor, NumPy 1.11.0.


Solution

  • The docs don't mention it, but coordinate array support is very new, NumPy 1.13. In previous NumPy versions, you can only specify a fixed scalar step value for each dimension.

    NumPy 1.12 has a check to catch non-scalar steps, but NumPy 1.11, which you're on, doesn't notice the array-valued input and silently does the wrong thing by trying to treat the array as a step.