222 - Topic 7.5 - Gradients

2385 days ago by Professor222

John Travis

Mississippi College

Showing the gradient vector at a student-entered point along with a tangent vector in the gradient direction.

The tangent vector is plotted using the vector  $ \left \langle f_x,f_y,\left || \bigtriangledown f \right ||^2 \right \rangle $.

var('x,y') @interact def _(f = cos(x+1)*sin(x^2+y^2),x0=slider(-6/5,6/5,1/20,0),y0=slider(-6/5,6/5,1/20,1),In3D = checkbox(default=True)): H = plot3d(f,(x, -1.5, 1.7), (y, -1.5, 1.9),opacity=0.8) fx = derivative(f,x) fy = derivative(f,y) H += point3d([(x0,y0,f(x=x0,y=y0))],size=20,zorder=2,color='red') gradnorm = (fx(x=x0,y=y0)^2+fy(x=x0,y=y0)^2) H += arrow((x0,y0,f(x=x0,y=y0)),(x0+fx(x=x0,y=y0),y0+fy(x=x0,y=y0),f(x=x0,y=y0)),color='green') H += arrow((x0,y0,f(x=x0,y=y0)),(x0+fx(x=x0,y=y0),y0+fy(x=x0,y=y0),f(x=x0,y=y0)+gradnorm),color='lightgreen') if In3D: H.show(spin=True,stereo='redcyan') else: H.show(spin=True) 
       

Click to the left again to hide and once more to show the dynamic interactive window

# showing that the gradient vectors always point in the direction of steepest ascent var('x,y') f(x,y) = cos(x+1)*sin(x^2+y^2) G = contour_plot(f, (x, -1.4, 1.7), (y, -1.5, 1.9),contours= 21, plot_points=150,colorbar=1,cmap='Greys') H = plot3d(f,(x, -1.4, 1.7), (y, -1.5, 1.9),opacity=0.8) fx = derivative(f,x) fy = derivative(f,y) xs = [0,1.12,1.375,0.57,-0.05,-0.5,0.1] ys=[-0.69,0.78,0,1.68,1,0.9,0] show_grads = True for k in range(len(xs)): x0 = xs[k] y0 = ys[k] G += point2d([(x0,y0)],size=60,zorder=2,color='red') if show_grads: G += arrow((x0,y0),(x0+fx(x0,y0),y0+fy(x0,y0)),color='green') H += point3d([(x0,y0,f(x=x0,y=y0))],size=20,zorder=2,color='red') if show_grads: gradnorm = (fx(x=x0,y=y0)^2+fy(x=x0,y=y0)^2) H += arrow((x0,y0,f(x=x0,y=y0)),(x0+fx(x=x0,y=y0),y0+fy(x=x0,y=y0),f(x=x0,y=y0)),color='green') H += arrow((x0,y0,f(x=x0,y=y0)),(x0+fx(x=x0,y=y0),y0+fy(x=x0,y=y0),f(x=x0,y=y0)+gradnorm),color='lightgreen') G.show() H.show(figsize=(10,15),spin=True)