Torrence-6 2,6 3
Torrence-6 2,6 3
4. Near the beginning of this section, we did several computations using general vectors of the form
u1 , u2 . The subscripts are obtained from the keyboard by typing, for instance, u ŹÎ_Ï 1. The
FullForm of the resulting expression is Subscript[u,1]. Many textbooks will (in the course of a
proof, for instance) write, “Let u ;u1 , u2 ?.” While this is a convenient notation, it cannot be
replicated in Mathematica. If you were to enter the input u u1 , u2 , what would happen? The
same bad thing will happen if you enter the more simple input u u1 . Try it, then explain
what’s going on. As the blues singer Kelly Joe Phelps put it, “It’s not so far to go to find trouble.”
5. Use Mathematica to verify the parallelogram law in 53 : For any pair of vectors u and v ,
2 2 2 2
u v u v 2u 2v .
To evaluate a function defined in this fashion, one uses replacement rules. For instance, here is
f .0, S s 4 2:
6.2 Real-Valued Functions of Two or More Variables 257
In[6]:= f s. x 0, y Ss4 !
1
Out[6]=
2
In[7]:= f s. x 1 S, y 1 S
In[8]:= Simplify#'
Out[8]= 0
Out[9]=
Grab such a plot with your mouse and drag. This will rotate the image so that you can see it from
any vantage point you like. Hold down the Ø key while you drag and you can zoom in and out.
It’s a beautiful thing.
Note that it is a simple matter to produce a sketch of any vertical cross-section (sometimes called a
trace) for such a plot in either the x or y direction. Simply set one of the two variables to a numerical
value and make a Plot using the other as the independent variable.
258 Multivariable Calculus
0.5
Out[10]=
x
2 1 1 2
0.5
Out[11]=
0.4
0.6
0.8
We’ll discuss how one can use the Mesh option to superimpose these traces onto the original
Plot3D of f in the subsection “Controlling the Mesh Lines” on page 265. See Exercise 6 for more on
cross-sections.
There are a host of options available that will allow you to tweak the output of these plotting
commands in some incredible ways. Among the options that are essentially the same as the familiar
options for Plot (see Section 3.3, see page 59) are such common settings as AxesLabel, PlotLabel,
PlotPoints, MaxRecursion and PlotRange. Other options, such as Mesh and MeshFunctions, work
in a similar manner as they do in Plot, but now everything is one dimension higher. In short, they
will take some getting used to.
In[12]:= Table$Plot3D$ÆSin#x y' , x, S, S, y, S, S , Mesh m, MaxRecursion 4(,
m, None, All(
Out[12]= , !
Note that like Plot, Plot3D uses an adaptive algorithm that recursively subdivides the surface into
smaller polygons in areas where the surface bends more sharply. PlotPoints settings control how
many equally spaced points are initially sampled in each direction (so a setting of 50 will force
Mathematica to sample 50 50 2500 points in the domain). MaxRecursion controls the number of
recursive subdivisions permitted to fine-tune the image. Large settings for these options produce
beautiful images, but may result in perceptibly slower rendering times, and will definitely produce
larger file sizes when the notebook is saved. See Exercise 2.
x2 y5 x5 y2 2
y2 0
In[13]:= Table%Plot3D% Æ,x , x, 3, 3, y, 3, 3 , ClippingStyle k),
100
k, Automatic, None)
Out[13]= , !
The setting PlotRange All will force Mathematica to show the entire graph. Notice, however, that
the bump in the middle of the plot vanishes from view due to the compression of the vertical axis:
260 Multivariable Calculus
x2 y5 x5 y2 2
y2 0
In[14]:= Plot3D% Æ,x , x, 3, 3, y, 3, 3 , PlotRange All)
100
Out[14]=
The option BoxRatios determines the relative dimensions of the bounding box. The simple setting
BoxRatios 1 will produce a cubical bounding box, while the setting BoxRatios Automatic will
scale the bounding box so that all axes have the same scale; it is analogous to the option AspectRag
tio used in two-dimensional plots. Be careful to not use this setting in cases such as the one above
where one axis would be dramatically longer than the others. A setting such as BoxRatios {1, 1, 2}
will produce a bounding box whose horizontal sides are the same length, but whose vertical dimen-
sion is twice as long.
In[15]:= Plot3D$Sin$x Cos$y((, x, 6, 6, y, 3, 3 , BoxRatios Automatic(
Out[15]=
In[16]:= Plot3D$Sin$x Cos$y((, x, 6, 6, y, 3, 3 , BoxRatios Automatic, Boxed False,
Axes False, False, True, AxesEdge Automatic, Automatic, 1, 1(
Out[16]=
ViewPoint specifies the position in space (relative to the center of the graphic) from which it is
seen. The setting {0, 0, 4}, for instance, will give a view from above, while the setting {3, 0, 1} will
yield a vantage point that is three units from the origin along the positive x axis, and one unit up.
Out[17]=
The ColorFunction
The option ColorFunction controls the coloring of the graph. Any of the color gradients available in
the ColorData archive may be used to color a plot. Type and enter ColorData["Gradients"] for a
listing of available gradients. For instance, here we color a plot using a color gradient reminiscent of
that used in topographical maps, where low regions are colored dark blue, middle regions are shaded
with greens and browns, and peaks are white.
2
y2 0
In[18]:= Plot3D%Æ,x , x, 3, 3, y, 3, 3 , BoxRatios Automatic,
Out[18]=
262 Multivariable Calculus
ColorFunction allows you to assume complete control over the manner in which color is applied to
a surface. With a bit of work, the graph of a function may be colored (using any color gradient you
like) according to the values of any other function. See Exercise 1.
PlotStyle is used to set the intrinsic surface color, and to specify the surface’s diffusive and reflective
properties. Several settings may be simultaneously given by wrapping them within the Directive
command. There are three potential specifications. A straight color or opacity setting like Blue
and/or Opacity[.5] can be given to set the intrinsic surface color or transparency. This color will
interact with the lighting. A Glow setting, such as Glow[Red], will emanate from the surface irrespec-
tive of the color of the lighting. Finally, a Specularity setting determines the diffusive and reflective
properties of the surface. Specularity can accept two arguments. The first determines the color and
amount of diffusion added to reflected light. A numerical value of 1 is equivalent to a color setting
of White; in this case 100% of the light is reflected back, with no alteration to its color other than
that determined by the surface’s color. The second argument controls the shininess of the surface.
Typical values range from 1 (dull) to 50 (shiny). The setting Specularity[White, 20] is good for
creating the appearance of an anodized metallic surface:
In[19]:= Plot3D$x Cos$x y(, x, 3, 3, y, 2, 2 , Mesh None, MaxRecursion 4,
PlotStyle Directive$Lighter#Red', Specularity#White, 20'((
Out[19]=
Lighting can be adjusted in numerous ways. The default setting includes both ambient light and
four colored light sources (although if an explicit ColorFunction is specified, white light from these
same sources will be used instead). The simple setting Lighting "Neutral" will force the use of
white rather than colored lights.
6.2 Real-Valued Functions of Two or More Variables 263
In[20]:= Plot3D$x Cos$x y(, x, 3, 3, y, 2, 2 , Mesh None, MaxRecursion 4,
PlotStyle Directive$Lighter#Red', Specularity#White, 20'(, Lighting "Neutral"(
Out[20]=
The Documentation Center page for Lighting gives information on setting ambient, spot, and
directional light sources. We note here that the setting Lighting {{"Ambient", White}} is similar to
the setting Lighting "Neutral", but the latter includes point light sources and the shadows they
create, and so is better at giving the illusion of depth. The former may be appropriate when a special
ColorFunction is used and shadows would interfere with the information that the color provides.
In[21]:= GraphicsRow%
Plot3D% x2 y2 , x, 1, 1, y, 1, 1 ), Plot3D% x2 y2 , x, 1, 1, y, 1, 1 ,
Out[21]=
The setting Function$x, y , x2 y2 1( is a pure function. It takes a coordinate pair ,x, y0 as input,
and returns True precisely if that coordinate pair lies within the unit circle. In the resulting plot, the
domain is restricted to the region where this region function returns True. The setting in the second
264 Multivariable Calculus
plot above could also have been given in the shorter form RegionFunction ,Ó12 Ó22 1 &0.
Pure functions are discussed in Section 8.4.
RegionFunction also provides an excellent means of plotting over a punctured domain. A classic
x 2 y
example is the function f ,x, y0 , which is not defined at the origin, and which has an essential
x4 y2
discontinuity there. We remove a small disk from the center of the domain, and get a beautiful
image:
x2 y
In[22]:= Plot3D% , x, 1, 1, y, 1, 1 ,
x4 y2
RegionFunction Function%x, y , .1 x2 y2 ),
Out[22]=
Another approach to controlling the domain is by defining a function whose value outside a desired
region is 0. This is easily accomplished using a Piecewise function. The Exclusions option is useful
for specifying discontinuities; note how easy it is to specify the locus of discontinuities as an
equation.
x2 y2 x2 y 2 1
In[23]:= f ;
0 x2 y 2 1
Out[24]=
6.2 Real-Valued Functions of Two or More Variables 265
x2 y
In[25]:= Plot3D% , x, 3, 3, y, 3, 3 , Mesh 5, 30)
x2 y2
Out[25]=
You may also specify lists of specific x and y values through which mesh lines should be drawn. A
Mesh setting of 2, 1 will place one line at x 2 and another at y 1. This is useful for visually
approximating the partial derivatives at the point +2, 1/. See Exercise 6.
x2 y
In[26]:= Plot3D% , x, 3, 3, y, 3, 3 , Mesh 2, 1)
x2 y2
Out[26]=
The MeshFunctions option gives you even more control over the rendering of the mesh lines on a
plot. The price of this versatility is that it will take a bit of practice to master. Your efforts here will
be well rewarded, so read on.
By default there are two mesh functions, one for all the mesh lines corresponding to fixed x values,
and one for the perpendicular collection of mesh lines corresponding to fixed y values. Together
they form the familiar grid pattern that graces your Plot3D outputs. This default specification, if you
were to manually type it, would read:
266 Multivariable Calculus
It is a list of two pure functions, where each takes three arguments (one for each coordinate position
in three-space). Equivalently, this default setting could be entered using the common shorthand
notation: MeshFunctions Ó1 &, Ó2 &. Pure functions are discussed in Section 8.4. In any event,
mesh lines will be drawn where the mesh functions assume constant values; by default 15 evenly
spaced values will be displayed.
Perhaps the most common non-default setting is the following, which places level curves on your
plot. That is, the third variable (we usually call it z) is set to 15 evenly spaced values within the plot
range, and a mesh curve is added to the surface at each of these values.
In[27]:= Plot3D$x2 y3 +x 1/2 y, x, 2, 2, y, 2, 2 , MeshFunctions Ó3 &(
Out[27]=
But of course you may define any mesh function you like. Here we place mesh lines according to
distance from the origin. In other words, each mesh line lies on the surface of an invisible sphere
centered at the origin.
In[28]:= Plot3D$x2 y3 +x 1/2 y, x, 2, 2, y, 2, 2 ,
MeshFunctions Norm#Ó1, Ó2, Ó3' &, PlotRange 2, BoxRatios 1(
Out[28]=
6.2 Real-Valued Functions of Two or More Variables 267
MeshShading
The MeshShading option allows the regions between mesh lines to receive specific color directives.
The setting for this option has the same list structure as MeshFunctions; if there is a list of two
mesh functions, you should have a list of two MeshShading settings. Each such setting is itself a list
of directives that will by used cyclically (if this list is shorter than the number of mesh regions).
Setting the Lighting to "Neutral" will replace the default colored lighting with white lights, so that
the colors specified in the MeshShading are accurately rendered. For instance:
In[29]:= Plot3D$x2 y3 +x 1/2 y, x, 3, 3, y, 3, 3 , BoxRatios 1, MeshFunctions Ó3 &,
Mesh 20, MeshShading Red, Green, Lighting "Neutral"(
Out[29]=
Set it to a list whose length matches the Mesh setting, and you will cycle precisely once through the
list of directives. To utilize an entire color gradient, keep in mind that each color gradient function
(such as ColorData["StarryNightColors"]) is defined on the domain 0 t 1.
In[30]:= Plot3D$x2 y3 +x 1/2 y, x, 3, 3, y, 3, 3 , BoxRatios 1,
MeshFunctions Ó3 &, Mesh 20, MeshShading
Table$ColorData$"StarryNightColors"(#t', t, 0, 1, 1 s 20(, Lighting "Neutral"(
Out[30]=
The output above is very similar to that produced with the setting ColorFunction "StarryNightCol
ors" (and no MeshShading or Lighting specifications). When MeshShading is used, each band
268 Multivariable Calculus
between mesh lines is uniformly shaded. When ColorFunction is used, the shading varies continu-
ously. When there are multiple MeshFunctions, the colors will criss-cross like a woven basket.
Below we use the default MeshFunctions setting {#1&,#2&}:
In[31]:= Plot3D$x2 y3 +x 1/2 y, x, 3, 3, y, 3, 3 , BoxRatios 1, Mesh 20,
MeshShading Yellow, Green, Black, White, Lighting "Neutral"(
Out[31]=
We’ve previously used ContourPlot to plot solutions of equations (such as sin,x cos y0 0). This
solution curve can be regarded as a single contour line for the function f ,x, y0 sin,x cos y0. To
produce a full contour plot, use ContourPlot in a manner identical to that of Plot3D. Here we see a
ContourPlot and a Plot3D of the same function, showing the same level curves and using similar
shading:
6.2 Real-Valued Functions of Two or More Variables 269
Out[32]= , !
Perhaps the most commonly used option setting is Contours. Set it to a positive integer, say 20, and
you will see 20 contour lines in the resulting plot. Set it to a specific list of values and you will see
the contour lines through precisely those z values. If this list has a single value (as in the second plot
below), you will essentially be viewing the set of solutions to an equation in two variables.
In[33]:= GraphicsRow ContourPlot$,1 x2 0,1 y2 0, x, 2, 2, y, 2, 2 , Contours 20(,
ContourPlot$,1 x2 0,1 y2 0, x, 2, 2, y, 2, 2 , Contours 4(,
ContourPlot$,1 x2 0,1 y2 0 m 4, x, 2, 2, y, 2, 2 (
Out[33]=
The ContourShading option works much like the MeshShading option for Plot3D. Note that you
may set this option to None. As was the case with Plot3D, the ColorFunction may be set to any
named color gradient.
270 Multivariable Calculus
In[34]:= GraphicsRow
ContourPlot$,1 x2 0,1 y2 0, x, 2, 2, y, 2, 2 , ContourShading Red, Blue(,
ContourPlot$,1 x2 0,1 y2 0, x, 2, 2, y, 2, 2 , ContourShading None(,
ContourPlot$,1 x2 0,1 y2 0, x, 2, 2,
y, 2, 2 , ColorFunction "IslandColors"(
Out[34]=
Also important are PlotPoints and MaxRecursion, which (as you might expect) can be employed to
x2
improve image quality. The function is not defined along the line y x 1, and ContourPlot
1xy
with its default settings has difficulty in the vicinity of this line. The Exclusions option provides
another means of dealing with such discontinuities.
x2
In[35]:= GraphicsRow ContourPlot% , x, 2, 2, y, 2, 2 ),
1xy
x2
ContourPlot% , x, 2, 2, y, 2, 2 , PlotPoints 30, MaxRecursion 3),
1xy
x2
ContourPlot% , x, 2, 2, y, 2, 2 , Exclusions y m x 1 )!
1xy
Out[35]=
ContourPlot accepts many of the same options as Plot3D. Exceptions are those options that are
specific to two-dimensional graphics. For instance, one uses AspectRatio rather than BoxRatios to
6.2 Real-Valued Functions of Two or More Variables 271
adjust the relative dimensions of a graphic produced by ContourPlot. Note that by default, a
ContourPlot will be square.
Out[36]=
ContourPlot will embed tooltips into its output. Position the tip of the cursor along a level curve to
see the value of the z coordinate for all points on that curve. The option setting ContourLabels
Automatic can be used to place these values directly onto the graphic.
In[37]:= ContourPlot$Sin$x Cos$y((, x, 1, 1, y, 1, 1 , ContourLabels Automatic(
Out[37]=
While the placement of these labels on the graphic is handled automatically, the appearance and
indeed the function used to calculate each label can be adjusted. Below we use the default function
value (displaying the z coordinate at the point ,x, y0), but make the text gray in a six point font. We
also use the ColorData["LightTerrain"] color gradient.
272 Multivariable Calculus
Out[38]=
It is not difficult to write a command that will place a key next to a ContourPlot, as in the example
below. See Exercise 5.
If MeshFunctions are specified along with specific Mesh values, the curves where these functions
are equal to the respective Mesh values will be displayed. By default, there are no MeshFunctions
displayed in a ContourPlot (this is different from Plot3D, where the default MeshFunctions are
{#1&, #2&}, which produces the familiar grid pattern). Mesh curves will be superimposed on top of
the level curves. Here, for instance, we display the ellipse x2 2y2 1 in yellow on the plot:
6.2 Real-Valued Functions of Two or More Variables 273
4x y
In[39]:= ContourPlot%x2 , x, 2, 2, y, 2, 2 , MeshFunctions Ó12 2Ó22 & ,
y2 1
Out[39]=
And here we display in dashed red the curve where the partial derivative with respect to x is zero,
and in yellow the curves (lines in this case) where the partial derivative with respect to y is equal to
zero. The critical points (and hence all maxima and minima for the function being plotted) occur at
the intersection points of these curves.
4x y
In[40]:= ContourPlot%x2 , x, 2, 2, y, 2, 2 ,
y2 1
4y
MeshFunctions Function%x, y, z , 2 x ),
1 y2
8 x y2 4x
Function%x, y, z , )!, Mesh 0, 0,
2 2 1 y2
,1 y 0
Out[40]=
274 Multivariable Calculus
In general, it’s not a bad idea when including multiple MeshFunctions to use MeshStyle to make
the first one Dashed or Dotted. That way, if two curves happen to coincide, the top curve won’t
completely obscure the bottom one.
In[41]:= ContourPlot3D$x2 y2 z2 m 1, x, 1, 1, y, 1, 1 , z, 1, 1(
Out[41]=
And just as ContourPlot may be used to render a collection of level curves for a function of two
variables (as discussed in the previous subsection of this chapter), ContourPlot3D may be used to
render a collection of level surfaces for a function of three variables:
Out[42]=
Note that three iterators are needed, one for each of the three coordinate variables. Virtually all
options are either identical to those of Plot3D, or can be surmised from those of ContourPlot. For
instance, the Contours option works just as it does in ContourPlot. The ContourStyle option can
6.2 Real-Valued Functions of Two or More Variables 275
be used to assign style directives to each level surface. The ColorFunction option can also be used
for this purpose; the plot on the right uses a ColorData gradient specified by ColorFunction.
Out[43]=
2 S 5S
In[44]:= ContourPlot3D%Cos#x'2 Sin$y( m 1 Sin#z', x, 0, 2S, y, , !, z, 0, 2S,
2 2
Mesh None, ContourStyle Directive$Brown, Specularity#White, 10'()
Out[44]=
Constructing 3D plots of solids (rather than surfaces) can be accomplished with RegionPlot3D. This
command is discussed in the subsection “Finding Bounds of Integration and Plotting Regions in the
Plane and in Space” on page 294.
276 Multivariable Calculus
Graphics3D Primitives
Just as one can use the Graphics command to “manually” construct a two-dimensional graphic
from primitive Point, Line, Polygon, and Text objects, one can use the Graphics3D command to
build three-dimensional graphics. The Graphics command was discussed in Section 3.9 on page
114. In most cases you will use higher level commands such as Plot3D to generate 3D images. But
there may come a time when you want to create a graphic from scratch, or to add a simple sphere or
cylinder to the output of a command such as Plot3D. This section provides a basic introduction to
such endeavors.
The primitive 3D objects that can be used to build a Graphics3D are many. They include familiar
objects such as Point, Line, Polygon, and Text, and new ones such as Cuboid, Cylinder, and
Sphere. Here are a few simple examples to get you started:
Out[45]=
Out[46]=
6.2 Real-Valued Functions of Two or More Variables 277
In[47]:= Graphics3D$
Sphere#0, 0, 0, 3',
Sphere#0, 0, 4, 2',
Sphere#0, 0, 6.5, 1',
Cylinder#0, 0, 7.5, 0, .5, 9, .8',
Cylinder#0, 0, 7.5, 0, .03, 7.6, 1.5',
Cylinder#2, 0, 4, 4, 0, 5, .2',
Cylinder#2, 0, 4, 4, 0, 5, .2'
, Boxed False(
Out[47]=
The overall situation is completely analogous to that for building Graphics. The single argument
given to Graphics3D is (most simply) a primitive or a list of primitives. Here we’ve used only
Sphere and Cylinder primitives. Sphere takes two arguments: the coordinates of its center, and its
radius. Cylinder also takes two arguments. The first is a list of two points: the endpoints of its
central axis. The second is its radius.
As is the case with Graphics, one can also apply one or more directives to each primitive. Directives
are used to customize the appearance of the individual primitive elements, and may include color,
opacity, and/or specularity settings. To apply a directive to any primitive object, replace the primi-
tive with the list {directive, primitive}. If more than one directive is to be applied, wrap them in the
Directive command, as in Directive[Red, Opacity[.8]].
278 Multivariable Calculus
In[48]:= Graphics3D$
Directive$Red, Opacity#.7'(, Sphere#0, 0, 0, 3' ,
Opacity#.5', Sphere#0, 0, 4, 2'
(
Out[48]=
One may also include Graphics3D option settings, such as Boxed False. Many of these have been
discussed in Section 6.2. In particular, the setting Lighting "Neutral" can be used to turn off the
colored lights that are used by default when rendering a Graphics3D. This will provide a more
honest rendering of any colors you introduce. Note that by default, surface primitives will be white
(they appear colored because of the colored lights). Here, for instance, we make a white snowman
with black hat and arms:
In[49]:= Graphics3D$
Sphere#0, 0, 0, 3',
Sphere#0, 0, 4, 2',
Sphere#0, 0, 6.5, 1',
Lighter#Black',
Cylinder#0, 0, 7.5, 0, .5, 9, .8',
Cylinder#0, 0, 7.5, 0, .03, 7.6, 1.5',
Cylinder#2, 0, 4, 4, 0, 5, .2',
Cylinder#2, 0, 4, 4, 0, 5, .2'
, Boxed False, Lighting "Neutral"(
6.2 Real-Valued Functions of Two or More Variables 279
Out[49]=
It is common to combine a Graphics3D with the output from one of the plotting commands. Here
we use Plot3D to render the function f ,x, y0 xy with MeshFunctions set to measure distance on
the surface to the point +0, 0, 3/. The plot is colored according to this distance using MeshShading.
We use Graphics3D to place a small green sphere at the point +0, 0, 3/. We put the two images
together with Show:
In[50]:= Show%Plot3D%x y, x, 3, 3, y, 3, 3 , PlotRange 4, 4,
Lighting "Neutral", BoxRatios 1, Mesh 15,
Out[50]=
280 Multivariable Calculus
¿ When using commands such as Plot that produce Graphics (as opposed to Graphics3D)
output, it is common to add an Epilog option to place Graphics primitives directly on the
image. This makes the use of Show unnecessary. While Epilog may also be used with com-
mands such as Plot3D, it cannot be used to place 3D primitives on the plot (such as the
Sphere above). So in a 3D setting, Show is the best way to add primitive Graphics3D objects
to an image.
Out[53]= 2 x Cos$x2 y2 (
In[54]:= D$f, y(
Out[54]= 2 y Cos$x2 y2 (
In[55]:= s. x 0, y S!
Out[55]= 2 S
Alternatively, you can calculate partial derivatives with the palette version of the D command by
using the f e button on the BasicMathInput palette. The subscript indicates the variable with
respect to which the derivative should be taken. Move from one placeholder to the next with the Í
key.
In[56]:= x f
Out[56]= 2 x Cos$x2 y2 (
If you use the palette version of D directly on a function such as x2 2xy, it is best to first type the
function expression, then highlight it, and then push the palette button. If you deviate from this
convention by pushing the palette button first, be sure to put grouping parentheses around the
function expression so that you don’t end up only differentiating the first summand:
6.2 Real-Valued Functions of Two or More Variables 281
In[57]:= x x2 2x y
Out[57]= 2x2xy
Out[58]= 2x2y
2 f
To find the second partial derivative , you can use the D command exactly as in Chapter 5:
x2
2 f
To find the mixed second partial derivative , simply do this:
x y
In[60]:= D$f, x, y(
Out[60]= 4 x y Sin$x2 y2 (
Alternatively, you may use the f,f e key on the BasicMathInput palette:
In[61]:= x,x f
In[62]:= x,y f
Out[62]= 4 x y Sin$x2 y2 (
The Gradient
The gradient of a function of two or more variables is a vector whose components are the various
partial derivatives of the function. For instance, for a function f of two variables, the gradient is the
vector <x f , y f @. In Mathematica one can simply do this:
In[64]:= x f, y f
There is no built-in command for producing gradients, but if you need to make extensive use of
them it is not hard to create your own:
This command takes two arguments. The first is the function whose gradient you wish to compute.
The second is the list of variables used in defining the function. For example:
Out[66]= 2 x y3 , 3 x2 y2
x1 2 x2 3 x4 4
In[67]:= grad% , x1 , x2 , x3 , x4 )
x3 5
2 x1 x32 x44 3 x21 x22 x44 5 x21 x32 x44 4 x21 x32 x34
Out[67]= , , , !
x53 x53 x63 x53
You can evaluate the gradient at a specific point in the domain using replacement rules.
In[68]:= x f, y f s. x 0, y S!
Out[68]= 0, 2 S!
The following Manipulate will sketch a gradient vector directly on the ContourPlot for a function.
1 1
Initially it shows the gradient evaluated at the point - , 1. The tail of the gradient vector is a
2 2
Locator; you can simply click on the graphic to move it to a new position, or you can drag it
around. The geometric properties of the gradient quickly become apparent: it is perpendicular to the
level curve through its tail, and it points uphill.
In[69]:= Manipulate%Module%x, y ,
2 y2 0
ContourPlot%Æ,x x y, x, 1, 1, y, 1, 1 , Contours 20,
Epilog Dynamic%Arrow%
2
y2 2
y2
pt, pt y 2 Æx x, x 2 Æx y! s. x pt317, y pt327 !)!))),
pt, .5, .5 , Locator,
Appearance Graphics$Red, Disk#', ImageSize 5( )
6.2 Real-Valued Functions of Two or More Variables 283
Out[69]=
¿ There are several interesting features in this Manipulate. Notice that the first argument (the
thing we are manipulating) is a Module. Module is used to localize variables. In this case, the
variables x and y are insulated from any assignments made to them elsewhere in the session.
Module and other scoping commands are discussed in Section 8.6 on page 424. Secondly, note
that the Epilog to the ContourPlot is wrapped in Dynamic. While not strictly necessary, this
has the beneficial effect of forcing only the arrow to update as the Locator is moved, rather
than having the ContourPlot itself (which does not change) get re-rendered every time the
Locator is moved. This makes the action more “zippy.” For more information, search for
“Advanced Manipulate Functionality” in the Documentation Center and follow the link to the
tutorial of that name. Finally, note that we use the Appearance option to change the appear-
ance of the Locator from its default crosshair icon to a simple red dot. This option allows you
to make any Locator look exactly the way you like.
Given a function of two variables, there is a simple means for simultaneously plotting an array of its
gradient vectors over a rectangular domain, and for superimposing such a plot with a ContourPlot
of the function. See the subsection “Plotting a Two-Dimensional Vector Field” in Section 6.5, page
325, for a discussion of the GradientFieldPlot command.
You can take a directional derivative by taking the dot product of the gradient with a unit vector in
the indicated direction. Here, for example, is an expression representing the directional derivative of
¶ ¶
the function f ,x, y0 x2 y3 in the direction of the vector 3i j :
3, 1
In[70]:= grad$x2 y3 , x, y (.
Norm#3, 1'
3 x2 y2 2
Out[70]= 3 x y3
5
10
To evaluate the directional derivative at a specific point in the domain, use replacement rules:
284 Multivariable Calculus
In[71]:= s. x 2, y 3
2
Out[71]= 108
5
Optimization
There are numerous methods for finding extreme values of multivariate functions. It is certainly
possible to mimic the basic techniques presented in a standard calculus course, with Mathematica
doing the heavy lifting when the algebra gets tough. We outline such an approach in this section.
There are also the built-in commands Maximize, Minimize, NMaximize, NMinimize, FindMaxig
mum, and FindMinimum, which can be extremely useful, but which also have inherent
limitations. We’ll begin with these built-in commands, and then discuss the traditional approach
using critical points and second derivatives.
The commands Maximize, Minimize, NMaximize, and NMinimize (first introduced in Section 5.6
on page 212) all use the same syntax; understand one and you understand them all. In the most
simple setting, where your function is not overly complicated and happens to have a single extre-
mum in its largest natural domain, these commands make light work of optimization:
1
Out[72]= 32, x 2, y , z 5!!
2
If an extreme value does not exist, you can expect to see this sort of thing:
33 8
Out[73]= , x , y ,z !!
10 5
These commands attempt to find global extrema. They can be adapted to hunt for local extrema by
adding constraints. Simply use a list as the first argument, where the second member of the list is an
equation or inequality (or any logical combination of these):
Here the minimum occurs at a corner of the square region. Below we search in two concentric
circular regions centered at the origin. Since the same answer is reached in two different concentric
regions, we are assured that the minimum occurs in the interior of each region (not on the bound-
ary). We have found, or at least approximated, a local minimum for f :
Unfortunately, Minimize is unable to give us an exact numerical solution. Rather, it presents the
three numbers in the output as roots of sixth degree polynomials.
Out[78]= Root$76 902 125 319 355 960 Ó1 238 172 822 Ó12
46 171 432 Ó13 3 783 476 Ó14 2 441 664 Ó15 236 196 Ó16 &, 1(,
x Root$25 180 Ó1 92 Ó12 1080 Ó13 832 Ó14 1440 Ó15 1296 Ó16 &, 2(,
y Root$25 232 Ó12 288 Ó13 184 Ó14 576 Ó15 1296 Ó16 &, 1(
We’ll see shortly that traditional methods can be used to determine that the actual local minimum
125 25
occurs at - , 1. Our point here is to state plainly that while commands such as Minimize may
288 72
sound like a panacea for any optimization exercise, they can in fact be subtle to use and produce
output that is difficult to interpret. Worse yet, they can fail completely:
They also return only one extremum even in cases where there are two or more:
1 1 1
Out[80]= , x ,y !!
2
2 2
1 1
In[81]:= x
y s. x ,y !
2 2
1
Out[81]=
2
286 Multivariable Calculus
It is for these reasons that you must always be ready with plan B. Now don’t misunderstand us;
Minimize and NMinimize are powerful and versatile tools. In fact, they border on the amazing. But
they simply cannot be expected to work flawlessly in every situation; such is the variety and rich-
ness of the universe of mathematical functions. There are option settings for NMinimize that allow
you to specify the method it uses. Subtle details of this sort are essential if you plan to make exten-
sive use of these commands.
If your goal is to find all extrema for a differentiable function (as it often is in a calculus course),
your first line of defense in constructing plan B comes right out of your calculus textbook. The
critical points for a function are those points where the first partials are both zero (i.e., the gradient of
the function is the zero vector), or where one or both partials do not exist. If a function assumes a
relative minimum or maximum value in the interior of its domain, it does so at a critical point.
It is often possible to find critical points with Solve, NSolve, or Reduce. The setting here is just as it
was in Section 4.9, where we used these commands to solve systems of equations. Recall that Solve
and NSolve are designed primarily to solve polynomial equations, while Reduce can sometimes
solve more general classes of equations. Here’s an example where we use Solve to find the critical
points of a polynomial:
125 25
Out[83]= x 0, y 0 , x ,y !!
288 72
In any of these solving commands you may use as the first argument either a list of equations, or an
equation of lists. For instance, this input will also work:
125 25
Out[84]= x 0, y 0 , x ,y !!
288 72
You may be able to determine whether f has a relative minimum or maximum or saddle at a particu-
lar critical point in a purely algebraic fashion by examining the discriminant and the second partials
evaluated at this critical point. Recall that the discriminant of f is the expression
2
'f ,x,x f 0,y,y f 0 ,x,y f 0 .
The standard test to determine the status of the critical point ,x, y0 is as follows:
Let’s carry out this test for the two critical points found in our previous example.
2
In[85]:= +x,x f/,y,y f0 ,x,y f0 s. crPts ss N
The first critical point, +0, 0/, is therefore a saddle point, while the second is either a maximum or
minimum. Which is it?
Out[86]= 8.
The positive value indicates that there is upward concavity in the x direction at this point. Since this
point is an extreme value, it must be a minimum. A ContourPlot shows both critical points clearly,
confirming this analysis:
Out[87]=
In[88]:= f s. crPts
15 625
Out[88]= 0, !
62 208
In this example we used Solve to find the critical points, but Reduce could have been used instead:
125 4x
Out[89]= x m 0 «« x m && y m
288 5
A word about Reduce is in order. It is very convenient to use Reduce in cases where you are only
interested in real (as opposed to complex) solutions to equations; simply add the third argument
Reals. As this is usually the situation in calculus courses, Reduce may be your first choice as a
288 Multivariable Calculus
solver. On the flip side, Reduce does not (indeed, in general it cannot, as we will see in the next
example) return output in the form of replacement rules. And we like replacement rules. They are
enormously convenient when they are produced programmatically, so you do not have to type
them. In cases where Reduce produces reasonably simple output, a call to ToRules will convert the
4x
output into replacement rules. Just beware that an equation such as y m will be converted to the
5
4x
rule y , which means that replacements should be made with ReplaceRepeated (//.) rather
5
than ReplaceAll (/.):
In[90]:= ToRules#'
4x 125 4x
Out[90]= x 0, y !, x ,y !!
5 288 5
In[91]:= x, y s.
4x 125 4 x
Out[91]= 0, !, , !!
5 288 5
125 25
Out[92]= 0, 0, , !!
288 72
Here is a second example. We identify critical points using Reduce rather than Solve, as Solve
simply will not work in this case. It is important to point out something that is rarely emphasized in
calculus texts: the set of critical points may be far more complex than a few isolated points (like the
two critical points we found in the previous example). For instance:
1 S 4 S C#1'
x +S 4 S C#1'/ && y m ArcCos% ) 2 S C#2' ««
2 2x
S 4 S C#1' 1
y m ArcCos% ) 2 S C#2' «« x +S 4 S C#1'/ &&
2x 2
S 4 S C#1' S 4 S C#1'
y m ArcCos% ) 2 S C#2' «« y m ArcCos% ) 2 S C#2'
2x 2x
6.2 Real-Valued Functions of Two or More Variables 289
There are five solutions, and only the first and last are shown (since we wrapped the input above in
Short each of the middle three are indicated by <<1>>). Even the abbreviated output is a bit intimi-
dating. Note that there are two constants, C[1] and C[2], that are permitted to assume integer
values. Reduce has found an infinite family of points and curves, parameterized by these two
constants. If you are only concerned with critical points within a bounded domain the output can be
greatly simplified, often with such parameters removed. Below we include in the list of equations
the bounds on both x and y. The constants are no longer needed.
Okay, this is still rather intimidating. But be patient; the output rewards careful reading. Recall that
S
&& means “and” and || means “or.” The very last line shows two discrete critical points, at ,0, 0
2
S
and ,0, 0. Everything else shows a bounded domain on x, and y as a function of x on this domain.
2
In other words, the other critical points are comprised of curves.
Let’s embark on a brief visual investigation. In the following graphic, the solid mesh lines are curves
where the partial derivative with respect to x is zero, and dashed mesh lines are curves where the
partial derivative with respect to y is zero. Critical points are points where both partials are simultane-
ously zero. These can be discrete points (where the solid and dashed lines cross), or curves (where
they coincide). This function has both types.
290 Multivariable Calculus
In[98]:= Plot3D$Sin$x Cos$y((, x, 6, 6, y, 3, 3 , BoxRatios Automatic,
MeshFunctions Function$x, y , fx(, Function$x, y , fy( ,
MeshStyle Blue, Directive#Thick, Dotted', Mesh 0, 0, MaxRecursion 3,
Boxed False, Axes True, True, False, ViewPoint .1, 1, 3(
Out[98]=
Do you see the two discrete critical points that we identified earlier? They appear to be saddles. We
confirm this below:
2
In[99]:= +x,x f/,y,y f0 ,x,y f0 s. x 0, y S s 2 , x 0, y S s 2
We note that for this function, Maximize does not produce any output, while NMaximize reports,
as always, one maximum (even though there are in fact infinitely many on this domain). Clearly,
the approach we applied here using Reduce is far more comprehensive.
In cases where even Reduce cannot find a critical point, one has the commands FindMaximum
and FindMinimum. Like the command FindRoot (introduced in Section 4.7 on page 184), these are
your weapons of last resort. They require an initial guess for each variable, and using those as
starting values they hone in on a single extremum. Moreover, they are numerical tools; the solution
they provide is only approximate.
Despite these limitations FindMaximum and FindMinimum can be highly effective at refining an
approximate guess. They are also fast and extremely robust. Use them when other methods fail. One
simple means of using these commands is to start with a ContourPlot, and use it to identify a local
extremum. Then, using the approximate coordinates of the extremum as your initial guess, invoke
FindMaximum or FindMinimum. Here’s an example where we use this technique to approximate
some relative extrema for a rather nasty function:
6.2 Real-Valued Functions of Two or More Variables 291
In[100]:= Clear#f';
5x 3y
f ÆSin#x y' Cos% )Sin% );
y2 1 x2 1
ContourPlot$f, x, 2, 2, y, 2, 2 (
Out[102]=
There appears to be a tiny island near +1, 1/, suggesting that f assumes a relative maximum value
there. Now that we have it in our sights, let’s zero in on it:
Similarly, there appears to be a relative minimum near +1, 1/; let’s zero in on it:
Outstanding!
Constrained Optimization
The technique of Lagrange multipliers is easily implemented in Mathematica. Set things up so that
the function you wish to optimize is called f , while the constraint is of the form g 0. We wish to
solve the system ´ f O ´ g , for some real constant O, together with the constraint equation g 0.
This is easily accomplished using the grad command defined on page 282. Here’s a simple example:
maximize the quantity 4xy under the constraint that 4x2 y2 8.
This single Reduce input solves the system, as the three partial derivatives of the function
L,x, y, O0 f ,x, y0 Og,x, y0 are zero precisely when ´ f O ´ g and g 0. We next convert this
solution to replacement rules, and evaluate the function at the solution:
In[111]:= f s. sols
Note that the Maximize, Minimize, NMaximize, and NMinimize commands will do this all in one
go, but they will only find a single solution. If that’s all you need, there is no easier way to get there:
Regardless which approach is taken, a ContourPlot provides a visual verification. One could make a
ContourPlot of f , and a second ContourPlot with the first argument g m 0, then display them
together with Show. Below we take a different approach, making a single plot with a mesh line to
display the constraint curve. The solutions are shown as red dots:
Out[113]=
28
Out[114]=
9
x3 y 3
Out[115]= 5xy
9
In the examples above we integrated first with respect to x, then with respect to y. That is, the
variables are specified within Integrate in the same order that the integral signs are written in
standard mathematical notation. The palette version of the Integrate command makes the order of
integration more transparent. First type and highlight the function you wish to integrate, then push
the appropriate integration button on the BasicMathInput palette and fill in the placeholders for the
innermost integral, using the Í key to move from one placeholder to the next. Now highlight the
entire expression and push the integration button a second time, fill in the placeholders, and enter:
3 2
2 2
In[116]:= Ã Ã ,5 x y 0Å x Å y
1 0
28
Out[116]=
9
294 Multivariable Calculus
2 2
In[117]:= Ã .Ã ,5 x y 0Å x2Å y
x3 y 3
Out[117]= 5xy
9
2 4y2
In[118]:= Ã Ã ,5 x2 y2 0Å x Å y
2 4y2
52 S
Out[118]=
3
And here we integrate the function f ,x, y, z0 y z2 over the region bounded by a sphere of radius
two centered at the origin:
128 S
Out[119]=
15
This last integral may take a minute or so to evaluate. A more sensible approach, even with a tool as
powerful as Mathematica, is to use a spherical coordinate system. See the subsection “Integration in
Other Coordinate Systems” in Section 6.4, page 322, for details.
Finding Bounds of Integration and Plotting Regions in the Plane and in Space
While Mathematica makes the evaluation of most integrals a snap, you still have to set up those
integrals in the first place. And when the region over which the integration takes place is non-
rectangular, this can be a subtle and challenging enterprise in itself. However, if the region in
question is defined by one or more inequalities, the command CylindricalDecomposition will do
this work for you. For instance, to find the bounds used in the last example for integration over a
spherical region of radius 2 centered at the origin, one may simply do this:
Similarly, the circular region in the example preceding this one can be decomposed as follows:
Out[121]= 2 y 2 && 4 y2 x 4 y2
The second argument to CylindricalDecomposition is a list of the coordinate variables, and the
order in which they are listed is very important. It should match the order in which the integral
signs appear. To decompose complex regions, you may wish to experiment with the ordering to find
the one that leads to the most simple decomposition. Also, use strict inequalities when describing
regions of integration, as this will often simplify the output.
You can also make a plot of the region determined by your bounds of integration. This provides a
visual confirmation for your choice of bounds. One produces the plots using RegionPlot for planar
regions, and RegionPlot3D for regions in space. Here, for instance is the circular region used in the
double integral above. Note that the first argument uses the bounds of the inner integral, and is
presented as an inequality (it makes no difference whether strict or non-strict inequalities are used).
The bounds of the outer integral are given implicitly via the iterator for y:
Out[122]=
And here is a view of the volume that this double integral represents. We use Plot3D with both a
RegionFunction setting (to show the plot of the integrand over the circular region) and a Filling
setting (to show a translucent solid region under the graph of the integrand). Note also that Plotg
Range is needed to extend the image all the way down to the x-y plane.
296 Multivariable Calculus
In[123]:= Plot3D%5 x2 y2 , x, 2, 2, y, 2, 2 , Mesh None, PlotRange 0, 5,
Out[123]=
Out[124]=
Here the first argument to RegionPlot3D could be stated more simply as Norm[{x,y,z}] 2. We
stuck here with the inequalities suggested by the bounds of integration, precisely to test that these
bounds produce an appropriate image.
6.2 Real-Valued Functions of Two or More Variables 297
Below we construct multiple cut-away views of this solid ball, with MeshFunction and MeshShadg
ing settings applied to color the ball according the value of the integrand y z2 . If this function
gives the density of the ball at the point ,x, y, z0, for instance, then the triple integral gives the ball’s
mass. Note that the setting BoxRatios Automatic is needed to give all axes the same scale (by
default RegionPlot3D will scale the axes in order to create a cubical bounding box).
In[125]:= GraphicsRow$Table$RegionPlot3D$Norm$x, y, z ( 2,
x, 2, rightSide , y, 2, 2 , z, 2, 2, BoxRatios Automatic,
MeshFunctions Function$x, y, z , y z2 ( , Mesh 10,
MeshShading Table$ColorData$"TemperatureMap"(#k', k, 0, 1, .1(,
Lighting "Neutral", Axes False(, rightSide, 2, 1, 0 (, ImageSize 300(
Out[125]=
Exercises 6.2
1. In this exercise you will explore the ColorFunction option for Plot3D. ColorFunction may be
set to any pure function with three variables (one for each coordinate position). Pure functions
are discussed in Section 8.4. By default, each of the input values for this function are scaled from
the actual coordinate values to span the range from 0 to 1. In order to use the actual coordinate
values, the additional option setting ColorFunctionScaling False must be added. Moreover
the output of the ColorFunction must be a Hue, RGBColor, or other color directive (such as a
named gradient like ColorData["StarryNightColors"]). The inputs to functions such as Hue
should span the values from 0 to 1. In practice, this means that most “interesting” color func-
tions will have to be Rescaled before being suitable for input to Hue or whichever color render-
ing function you plan to use.
a. Make a Plot3D of the function Æsin+x y/ on the domain 2 x 2, 2 y 2 with the option
setting ColorFunction (#1&). Repeat for (#2&) and (#3&). Note that by setting an explicit
color function, the default Lighting setting switches to using white light only, so as not to
interfere with your choice of color.
2 2
b. Make a Plot3D of the function Æsin+x y/ ,x cos,x y00 ,y cos,x y00 on the domain 2 x 2,
2 y 2 with the option setting PlotRange All. Estimate the minimum and maximum
values obtained by the function on this domain.
298 Multivariable Calculus
c. Repeat the previous part, but this time plot the function
2 2
Rescale[ÆSin#x y' ,x Cos$x y(0 ,y Cos$x y(0 ,{0,4}]. What do you notice about its minimum
In[126]:= Plot3D%ÆSin#x y' , x, 2, 2, y, 2, 2 , ColorFunctionScaling False,
2 2
Rescale%ÆSin#x y' ,x Cos$x y(0 ,y Cos$x y(0 , 0, 4))), Mesh None)
Out[126]=
e. The following output wraps the color rendering function in Glow, which means that it will
not react with any Lighting. Can you see any difference from the last input?
In[127]:= Plot3D%ÆSin#x y' , x, 2, 2, y, 2, 2 , ColorFunctionScaling False,
2 2
Rescale%ÆSin#x y' ,x Cos$x y(0 ,y Cos$x y(0 , 0, 4))), Mesh None)
Out[127]=
2. Use TabView to construct a dynamic display of a Plot3D object like the one shown below where
MaxRecursion may be set to any of the values 0 to 3.
6.2 Real-Valued Functions of Two or More Variables 299
0 1 2 3
xy
3. Make a plot of the function f ,x, y0 over the annular domain .1 x2 y2 1. Add
x2 y2
x y2
Filling to the bottom of the bounding box. Repeat for f ,x, y0 . Comment on the behavior
x2 y2
4. Make two images side by side, one showing a ContourPlot of your favorite function, and the
other a Plot3D of that same function on the same domain. Use MeshFunctions to display level
curves in the Plot3D. Use a specific Range of values for the Contours settings on the Contourg
Plot, and use that same collection of values for Mesh settings on the Plot3D. This way you will
synchronize the level curves being shown in each plot. Use a ColorFunction or MeshShading to
apply "LakeColors" to your Plot3D.
5. Write a command called key that will make a graphical gradient key for a ContourPlot as shown
on page 272. It should have the syntax structure key[{min,max},contours], where min and max
denote the minimum and maximum function values in the plot, and contours is the number of
contour regions in the plot.
x0
y0
z z
0. y
7. Describe the set of critical points for the function f ,x, y0 sin,x2 y2 0 on the domain 2 x 2
and 1 y 1. Use Reduce with the second argument set to {y,x} and again with the second
argument set to {x,y}. Is one output easier to interpret?
a. Show that f has no critical points. Make a ContourPlot with MeshFunctions and Mesh
settings to display the curves where the partial derivative with respect to x is zero, and those
where the partial derivative with respect to y is zero. Confirm visually that these two sets of
curves never cross.
b. Show that for any direction measured by the polar angle T, and any real number r ! 0, the
function f has a point ,x0 , y0 0 in its domain where the directional derivative in the direction of
T exceeds r , and another point ,x1 , y1 0 where the directional derivative in the direction of T is
less than r . Essentially, the steepness of this function is unbounded in every direction, despite
being defined on the entire plane, and having no relative minima, maxima, or saddle points.
9. Explain how to use ContourPlot3D to view the graph of any real-valued function of two vari-
ables, such as f ,x, y0 2x y on the domain 1 x 1, 1 y 1. How does this differ from using
the Plot3D command to produce such a graph?
10. Maximize the quantity x1s3 y2s3 under the constraint that 40x 50y 10 000 .
11. Find all point(s) on the surface z x y closest to the point +0, 0, 3/. Make a ContourPlot3D of
this surface, colored (via MeshShading) according to how close points are to +0, 0, 3/.
12. Consider the function f ,x, y0 2 1 x2 defined over the unit disk in the x-y plane centered at
the origin.
a. Make a Plot3D of f over this circular region, and use Filling to display the solid under the
graph of f and above the x-y plane.
b. Find the volume of this solid.