I have a function that should return a gradient.
JavaScript
x
5
1
def numerical_derivative_2d(func, epsilon):
2
def grad_func(x):
3
grad_func = (func(x + np.array([epsilon, 0])) - func(x)) / epsilon, (func(x + np.array([0, epsilon])) - func(x)) / epsilon
4
return grad_func
5
But when calculating the gradient at a specific point, I get None.
JavaScript
1
6
1
t1 = lambda x: (
2
-1 / ((x[0] - 1)**2 + (x[1] - 1.5)**2 + 1)
3
* np.cos(2 * (x[0] - 1)**2 + 2 * (x[1] - 1.5)**2))
4
t2 = numerical_derivative_2d(t, 0.1)
5
t3 = t2([3, 4])
6
Object classes: t1-function, t2-function, t3-None (I want to get a two-dimensional point)
Please tell me how to change this line
JavaScript
1
2
1
grad_func = (func(x + np.array([epsilon, 0])) - func(x)) / epsilon, (func(x + np.array([0, epsilon])) - func(x)) / epsilon
2
to make it work?
PS. I understand that there are built-in methods for calculating the gradient. But this is a homework assignment in one of the courses. I would like to understand the error and do it according to the template.
PPS.This may be unnecessary, but I will give an example of a task for a single variable function that works as I expect.
JavaScript
1
11
11
1
def numerical_derivative_1d(func, epsilon):
2
def deriv_func(x):
3
return (func(x + epsilon) - func(x)) / epsilon
4
return deriv_func
5
6
def polynom_to_prime(x):
7
return 20 * x**5 + x**3 - 5 * x**2 + 2 * x + 2.0
8
9
t2 = numerical_derivative_1d(polynom_to_prime, 1e-5)
10
t3 = t2(3)
11
and t3 is a number (dot), not None
Advertisement
Answer
In def grad_func(x)
, you don’t return anything. Inside that function, grad_func
is a local variable. Consider writing that like:
JavaScript
1
5
1
def numerical_derivative_2d(func, epsilon):
2
def grad_func(x):
3
return (func(x + np.array([epsilon, 0])) - func(x)) / epsilon, (func(x + np.array([0, epsilon])) - func(x)) / epsilon
4
return grad_func
5