Skip to content

Instantly share code, notes, and snippets.

@iandewancker
Created February 5, 2018 19:34
Show Gist options
  • Save iandewancker/61186c21bfe411343adb434180ffdf0d to your computer and use it in GitHub Desktop.
Save iandewancker/61186c21bfe411343adb434180ffdf0d to your computer and use it in GitHub Desktop.
quick numerical gradient in numpy
def test_f(x):
x1 = x[0]
y1 = x[1]
return 2*x1**2 + 2*x1 + 10 + y1**2 - 5*y1
"""
f : reference to python function that takes
x_0 : numpy array of shape (1,N) where N is dependent on function
"""
def finite_difference_grad(f, x_0, h):
unit_vectors = np.eye(x_0.shape[0])
grad = np.array([(f(x_0 + unit_vectors[i]*h) - f(x_0 - unit_vectors[i]*h)) / (2*h) for i in xrange(unit_vectors.shape[0])])
return grad
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment