简体   繁体   中英

Derivative of 1D Numpy Array

If I have a 1D numpy array and I want to return a 1D numpy array containing first derivatives with respect to x, then do I use np.gradient(x)? I think I am doing something wrong

This is the code that I have but it tells me my answer is incorrect.

def dfunc(x):
'''
Parameters
x: 1D numpy array
Returns
df: 1D numpy array containing first derivatives wrt x
'''
# WRITE YOUR CODE HERE
df = np.gradient(x)
return df

The numpy gradient function computes the second order centered finite difference approximation for the gradient.

you can read in the Wikipedia finite difference page more abut the method.

let's see how we will get the right gradient with a simple example

f = np.linspace(0,100,1000) * 2

of curse the gradient of f should be 2 but

np.gradient(f)

will return array full with values 0.2002002 and thats because np.gradient default spacing between element is 1.0 so to get the right answer we should specify the spacing between elements in the f array.

np.gradient(f, varargs=np.linspace(0,100, 1000)[1])

will return the array fill with 2.0 as expected

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM