single
Visualizing Multivariate Functions
Scorri per mostrare il menu
Visualizing functions of two or three variables is essential for understanding their behavior. The most common methods are contour plots and 3D surface plots. Contour plots show level curves – lines where the function takes a constant value – helping you see how the function changes in different directions. Surface plots give a three-dimensional view, allowing you to observe peaks, valleys, and saddle points.
To interpret a contour plot, follow these steps:
- Identify the axes, which represent the variables (such as x and y);
- Note the contour lines, each corresponding to a specific function value;
- Observe the spacing between contours: closely spaced lines indicate rapid change, while widely spaced lines show gradual change;
- Look for patterns: closed curves may indicate local maxima or minima, while lines that never close may suggest a saddle or ridge;
- Compare with the surface plot to see how these level curves translate into rises and dips on the surface.
Level curves are especially useful for understanding gradients and optimization, as they highlight where the function remains constant and where it changes most rapidly.
12345678910111213141516171819202122232425262728293031323334import numpy as np import matplotlib.pyplot as plt # Define a sample function of two variables def f(x, y): return np.sin(x) * np.cos(y) # Create a grid of x and y values x = np.linspace(-3 * np.pi, 3 * np.pi, 100) y = np.linspace(-3 * np.pi, 3 * np.pi, 100) X, Y = np.meshgrid(x, y) Z = f(X, Y) # Create a contour plot plt.figure(figsize=(8, 6)) contour = plt.contour(X, Y, Z, levels=20, cmap="viridis") plt.clabel(contour, inline=True, fontsize=8) plt.title("Contour Plot of f(x, y) = sin(x) * cos(y)") plt.xlabel("x") plt.ylabel("y") plt.show() # Create a 3D surface plot from mpl_toolkits.mplot3d import Axes3D fig = plt.figure(figsize=(10, 7)) ax = fig.add_subplot(111, projection="3d") surf = ax.plot_surface(X, Y, Z, cmap="viridis", edgecolor="none", alpha=0.8) ax.set_title("Surface Plot of f(x, y) = sin(x) * cos(y)") ax.set_xlabel("x") ax.set_ylabel("y") ax.set_zlabel("f(x, y)") fig.colorbar(surf, shrink=0.5, aspect=5) plt.show()
Scorri per iniziare a programmare
Practice your visualization skills by generating a contour plot for a simple function of two variables.
- Define a grid of
xandyvalues ranging from -2 to 2. - Compute the function values for
f(x, y) = x^2 + y^2on this grid. - Create a contour plot of the function with 10 contour levels.
- Add labels for the contour lines, and set appropriate axis labels and a title.
Soluzione
Grazie per i tuoi commenti!
single
Chieda ad AI
Chieda ad AI
Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione