import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.widgets import Slider
# Generate knowledge
x = np.linspace(-1.0, 1.0, 50)
y = np.linspace(-1.0, 1.0, 50)
xx = []
yy = []
zz = []
for i in vary(50):
for j in vary(50):
xx.append(x[i])
yy.append(y[j])
zz.append(x[i] * x[i] + x[i] * y[j] + y[j] * y[j])
x = np.array(xx)
y = np.array(yy)
z = np.array(zz)
# Operate to compute gradient
def gradient(x, y):
dz_dx = 2 * x + y
dz_dy = 2 * y + x
return np.array([dz_dx, dz_dy])
# Plotting
fig = plt.determine()
ax = fig.add_subplot(111, projection=’3d’)
# Scatter plot with a colormap for higher visualization
sc = ax.scatter(x, y, z, c=z, cmap=’viridis’)
# Add a coloration bar for reference
cbar = plt.colorbar(sc)
cbar.set_label(‘Z worth’)
# Outline preliminary level for tangent line
initial_x = 0.0
initial_y = 0.0
initial_z = initial_x**2 + initial_x*initial_y + initial_y**2
# Plot the preliminary level
initial_point, = ax.plot([initial_x], [initial_y], [initial_z], ‘ro’)
# Compute and plot the preliminary tangent line
grad = gradient(initial_x, initial_y)
tangent_line_x = np.linspace(initial_x – 0.5, initial_x + 0.5, 10)
tangent_line_y = np.linspace(initial_y – 0.5, initial_y + 0.5, 10)
tangent_line_z = (initial_x**2 + initial_x*initial_y + initial_y**2 +
grad[0] * (tangent_line_x – initial_x) +
grad[1] * (tangent_line_y – initial_y))
tangent_line, = ax.plot(tangent_line_x, tangent_line_y, tangent_line_z, ‘g’)
# Add sliders for interactive management
ax_slider_x = plt.axes([0.25, 0.1, 0.65, 0.03])
ax_slider_y = plt.axes([0.25, 0.05, 0.65, 0.03])
slider_x = Slider(ax_slider_x, ‘X’, -1.0, 1.0, valinit=initial_x)
slider_y = Slider(ax_slider_y, ‘Y’, -1.0, 1.0, valinit=initial_y)
def replace(val):
x_val = slider_x.val
y_val = slider_y.val
z_val = x_val**2 + x_val*y_val + y_val**2
initial_point.set_data([x_val], [y_val])
initial_point.set_3d_properties([z_val])
grad = gradient(x_val, y_val)
tangent_line_x = np.linspace(x_val – 0.5, x_val + 0.5, 10)
tangent_line_y = np.linspace(y_val – 0.5, y_val + 0.5, 10)
tangent_line_z = (x_val**2 + x_val*y_val + y_val**2 +
grad[0] * (tangent_line_x – x_val) +
grad[1] * (tangent_line_y – y_val))
tangent_line.set_data(tangent_line_x, tangent_line_y)
tangent_line.set_3d_properties(tangent_line_z)
plt.draw()
print(f”Slope at ({x_val}, {y_val}): {grad}”)
slider_x.on_changed(replace)
slider_y.on_changed(replace)
ax.set_xlabel(‘X Label’)
ax.set_ylabel(‘Y Label’)
ax.set_zlabel(‘Z Label’)
plt.present()
#at this level the worth of m is minimal , now we will see by altering the worth of every axis