Draw a rudimentary contour map of the function
$$ z = xy\;(2 − x − 2y) $$Tip: first draw lines for $z = 0$ and then think about the values of $z$ in the regions between these contours.
Check your answer by plotting the contour map in Python (see hint below). Find the stationary points of the function. Determine from the sketch which are maxima, minima or saddle points. Check your answer by applying the test on P.5 of the maths data book.
Python hint
First, we need to sample $z$ on a two-dimensional grid, just like the grid in Figure 1. Suppose we are interested in $x$ values in the range -2 to 4, and we want to sample $z$ at intervals of 0.1. We set up a suitable vector of $x$ and $y$ values using:
import numpy as np
X = np.arange(-2, 4, 0.1)
Y = np.arange(-2, 4, 0.1)
Next, we stretch these values over the two-dimensional grid using:
X, Y = np.meshgrid(X, Y)
This produces matrices X
and Y
containing the $x$ and y coordinates of every point on the grid. Finally, we produce the grid of $z$ values using:
Z = X*Y*(2 - X - 2*Y)
Note the element-by-element multiplication indicated by .*
- we do not want matrix multiplication here. We can now produce a contour plot of $Z$ using:
import matplotlib.pyplot as plt
plt.contour(X, Y, Z)
Not enough contours?
plt.contour(X, Y, Z, np.arange(-5.0, 5.0, 0.1))
will show all contours in the range -5 to 5, at intervals of 0.1. Also:
plt.contour(X, Y, Z, 50)
will draw contours up to 50 automatically-chosen levels. To label the legend on each contour, you can use:
CS = plt.contour(X, Y, Z)
plt.clabel(CS, inline=1, fontsize=10)
# Import numpy and matplotlib
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
Here, we generate the 2D mesh grid and calculate the value of $z$ over the grid.
# Create 2D mesh grid
X = np.arange(-2, 4, 0.1)
Y = np.arange(-2, 4, 0.1)
X, Y = np.meshgrid(X, Y)
# Calculate the value of Z on the grid
Z = X*Y*(2-X-2*Y)
# Initialise the figure size and plot the contours
CS = plt.contour(X, Y, Z, 50)
plt.clabel(CS, inline=1)
plt.xlabel('$x$')
plt.ylabel('$y$');
Below is the code to generate a 3D surface plot for $z$. Details are not be provided, but curious students are encouraged to further understand the 3D plotting mechanism in Matplotlib.
# Import 3D plotting toolkit
from mpl_toolkits.mplot3d import Axes3D
# Plot the 3D surface of the function
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_surface(X, Y, Z)
ax.set_xlabel('$x$')
ax.set_ylabel('$y$')
ax.set_zlabel('$z$');