0

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
6
  • Why do you think you are doing something wrong? Can you provide example code, demonstrating how you are using it and stating why you think it is wrong? Have you read the documentation? Commented Feb 12, 2019 at 12:27
  • I've just updated Commented Feb 12, 2019 at 12:41
  • Can you please give a small example of an input, the output that you would expect for that input and the output that you program gives you instead? Commented Feb 12, 2019 at 12:52
  • It's run through an autograder so unfortunately, I have no way to find out. I can't figure out what I'm doing wrong or what the correct answer would be Commented Feb 12, 2019 at 12:55
  • @user611988, this is an assignment question and I think the course instructors will be able to help. Is there a reason for not seeking support on the course forum? Commented Feb 12, 2019 at 13:18

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.