Have a go at it. The editor and the docs panel are open, and your code is saved as you type. Running it needs a free account — you’ll come back to exactly what you wrote.
The Directional Derivative
The gradient tells you the steepest direction. The directional derivative tells you the slope along any direction you choose:
— the dot product of the gradient with a unit vector. The unit part is essential: without normalising, doubling the length of u would double the answer, and you would be measuring your arrow rather than the surface.
Three consequences fall straight out of :
grad = [3, 4] ||grad|| = 5 u = [1, 0] -> normalised [1, 0] D = 3 u = [3, 4] -> normalised [0.6, 0.8] D = 5 <- the maximum u = [-4, 3] -> normalised [-0.8, 0.6] D = 0 <- along a contour
Your task:
Implement directional_derivative(grad, u), normalising u yourself, and returning the slope as a float.
Example Tests
Along the x axis you feel only the x component of the gradient
Input: {"u":[1,0],"grad":[3,4]}
Expected: 3
Along the gradient itself the slope is its full magnitude
Input: {"u":[3,4],"grad":[3,4]}
Expected: 5
Perpendicular to the gradient the function does not change
Input: {"u":[-4,3],"grad":[3,4]}
Expected: 0
import numpy as np
def directional_derivative(grad, u):
"""
Slope of f along the direction u.
Args:
grad: the gradient at the point, shape (n,)
u: a direction, shape (n,), NOT necessarily unit length
Returns:
float: grad . (u / ||u||)
"""
# YOUR CODE HERE
pass