Created
February 5, 2018 19:34
-
-
Save iandewancker/61186c21bfe411343adb434180ffdf0d to your computer and use it in GitHub Desktop.
quick numerical gradient in numpy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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