What does numpy.gradient do?

后端 未结 4 1534
旧巷少年郎
旧巷少年郎 2020-12-23 02:15

So I know what the gradient of a (mathematical) function is, so I feel like I should know what numpy.gradient does. But I don\'t. The documentation is not reall

4条回答
  •  借酒劲吻你
    2020-12-23 02:31

    Also in the documentation1:

    >>> y = np.array([1, 2, 4, 7, 11, 16], dtype=np.float)
    >>> j = np.gradient(y)
    >>> j 
    array([ 1. ,  1.5,  2.5,  3.5,  4.5,  5. ])
    
    • Gradient is defined as (change in y)/(change in x).
    • x, here, is the index, so the difference between adjacent values is 1.

    • At the boundaries, the first difference is calculated. This means that at each end of the array, the gradient given is simply, the difference between the end two values (divided by 1)

    • Away from the boundaries the gradient for a particular index is given by taking the difference between the the values either side and dividing by 2.

    So, the gradient of y, above, is calculated thus:

    j[0] = (y[1]-y[0])/1 = (2-1)/1  = 1
    j[1] = (y[2]-y[0])/2 = (4-1)/2  = 1.5
    j[2] = (y[3]-y[1])/2 = (7-2)/2  = 2.5
    j[3] = (y[4]-y[2])/2 = (11-4)/2 = 3.5
    j[4] = (y[5]-y[3])/2 = (16-7)/2 = 4.5
    j[5] = (y[5]-y[4])/1 = (16-11)/1 = 5
    

    You could find the minima of all the absolute values in the resulting array to find the turning points of a curve, for example.


    1The array is actually called x in the example in the docs, I've changed it to y to avoid confusion.

提交回复
热议问题