Chapter2.mws

Chapter 2: Plotting

Maple is a great tool for making plots. In this chapter we will learn how to make plots and then use them to review some important mathematical ideas that are important in physics.

Making x-y plots

Debugging

The simplest kind of plot is the 2-d, or x-y, plot and Maple does them with ease. Maple will plot both functions and expressions, but the syntax is different for each of these two data types. Here's a plot of the rational expression (x+1)/(x-1) from x = -5 to x = 0 . First we assign the rational expression to the variable g, then plot g. Note that g is an expression, not a function, so you can't use the notation g(x) to plot it.

> g:=(x+1)/(x-1);

g := (x+1)/(x-1)

> plot(g,x=-5..0);

[Maple Plot]

This same plot can be obtained using Maple's function notation, like this (I have purposely made the function have two arguments so you can see how to plot such a function)

> f:=(x,y)->(x+y)/(x-y);

f := proc (x, y) options operator, arrow; (x+y)/(x-...

To make a plot in x just give y a value through the argument list ( y = 1 reproduces the previous plot) and plot in x

> plot(f(x,1),x=-5..0);

[Maple Plot]

OK, now let's plot this same function over a larger range. Notice that you can just put the expression in the plot command line and skip the assignment of it to a variable if you want.

> plot((x+1)/(x-1),x=-5..5);

[Maple Plot]

Well, it's a plot, but perhaps not the one we wanted. The problem is that our function is singular at x = 1 , so Maple tried to give us its huge vertical range. We would probably rather not try to visualize infinity, so we would like to limit the vertical range. This is easy too.

> plot((x+1)/(x-1),x=-5..5,-5..5);

[Maple Plot]

Now this looks better, but the funny-looking vertical line at x = 1 looks wrong, and it is. Maple just connected the dots, including the jump from -infinity to infinity . To clean this up we have to work a little harder and give the plot command some options. There are many options you can specify and to become an expert plotter you have to be able to look them up and use them. You can find them by using

> ?plot[option]

and the one we need to make the plot above look better is the discont=true option, which tells Maple to look for discontinuities in our function and turn off dot-to-dot plotting.

> plot((x+1)/(x-1),x=-5..5,-5..5,discont=true);

[Maple Plot]

Now let's try something a little fancier; let's put two plots on the same frame and specify the two different colors we want to use to tell them apart. You can see what colors are available by using

> ?plot[colors]

Let's use the school colors of Brigham Young University, as far as they are translated correctly by Maple, and also will thicken the lines to make the colors stand out. (You might want to use thicker lines like this on a plot so that it would be of publication quality.)

> plot([(x+1)/(x-1),cos(x)],x=-5..5,-5..5,discont=true,color=[navy,tan],thickness=2);

[Maple Plot]

>

As you can see, the two functions are placed in a Maple list, which is a list of things separated by commas and contained within square brackets. Any options that apply separately to each plot are also specified in lists, as you can see in the color option. Warning: Maple does not always respect your color order. If you have lots of plots and lots of colors, Maple sometimes mixes the colors up.

I'll give you one more sample plot and then you will be off to the exercises. Suppose you wanted to make a plot of the motion of a damped harmonic oscillator, given by the formula exp(-t/100)*cos(t) from t = 0 to t = 600 . Since you now know how to plot you would just use

> plot(exp(-t/100)*cos(t),t=0..600);

[Maple Plot]

and you would be pretty sure that something had gone wrong. What went wrong is that Maple is not smart enough on its own to know how many points to plot; so when a function is wiggling like crazy, like this one is, it needs some help from you. You can fix it by using the numpoints option, like this

> plot(exp(-t/100)*cos(t),t=0..600,numpoints=400);

[Maple Plot]

One last, but very important, thing; you will often want to define your own expressions to plot using Maple's assign command ( := ), like this:

> F:=cos(omega*t)^3;

F := cos(omega*t)^3

Since it clearly depends on t we should be able to plot it

> plot(F,t=0..20);

[Maple Plot]

This blank plot is actually a Maple error message. The problem is that omega doesn't have a value yet, so there is no way Maple could plot it. But how are you supposed to know this? Try giving t a value and evaluating F.

> t:=7.;F;

t := 7.

cos(7.*omega)^3

The omega still sitting there is your clue; it needs a value. So let's assign it a value and try again.

> omega:=1.;plot(F,t=0..20);

omega := 1.

Error, (in plot) invalid arguments

What now!! The problem is subtle, and it will bite you often when you debug plots this way. Remember that we gave t a value of 7 so we could see what's wrong? Maple remembers this assignment and won't let us use t as a running variable in the plot. To fix it we have to undo the setting of t to 7 with the unassign command with 't' as its argument, then try it again.

> unassign('t');omega:=1;plot(F,t=0..20);

omega := 1

[Maple Plot]

or you could use the shorthand version of the unassign command like this

> t:='t';omega:=1;plot(F,t=0..20);

t := 't'

omega := 1

[Maple Plot]

>

The way to read this is "assign t to its own name, erasing any previous assignments."

Before we leave the introduction let's look at one more thing you will want to know so that you can make your plots look nice: lettering. To put labels on the axes of a plot you can use the labels option, like this: labels=["x","y"] . To put a title on use title="This is the title" . And if you want to put text in the figure somewhere, look up textplot in online help. Here's a plot illustrating these options.

> plot(sin(x^2),x=0..2*Pi,labels=["x","y(x)"],title=" sin(x^2) function");

[Maple Plot]

>

Notice that sin(x^2) didn't print in Maple's pretty math mode. I wish I knew how to make this happen in plots. But Greek letters are available, in a sort of limited form, by changing either the labelfont or the titlefont to SYMBOL, like this (I have purposely dumped the entire greek alphabet on the plot so you can see how they are coded)

> plot(sin(x^2),x=0..2*Pi,labels=["abcdefghijklmnopqrstuvwxyz","y(x)"],title="ABCDEFGHIJKLMNOPQRSTUVWXYZ",labelfont=[SYMBOL],titlefont=[SYMBOL]);

[Maple Plot]

>

Unfortunately, I can't tell you how to put labels and titles on that are mixtures of Roman and Greek letters. What Maple really needs is a text production capability like LaTex where full typesetting of text and equations is possible. Perhaps in a later version.

Ok, off to the exercises in the subsections below. Along the way you will learn some more plotting tricks.

Go to top of section

Basic function review

Debugging

In this section we will review the basic functions of mathematical physics by making plots.

Problem 2.1

Using a horizontal range of -2*Pi to 2*Pi and a vertical range of -2 to 2, plot the functions sin(x) , cos(x) , and tan(x) . Plot all three on the same plot by putting these three expressions in a list in the plot command line. Choose special colors for each one.

------------------------------------------------------------------------

Problem 2.2

Using a horizontal range of -3 to 3 and a vertical range of -3 to 3, plot the functions sinh(x) , exp(x)/2 , and -exp(-x)/2 . Choose special colors for each one and study the plot carefully so that you can remember how they relate. Now on another picture plot the functions exp(x)/2 and exp(-x)/2 together with cosh(x) . Finally, plot the functions sinh(x) , cosh(x) , and tanh(x) on the same picture and stare at them until you are sure you will remember what they look like.

------------------------------------------------------------------------

Problem 2.3

Verify by drawing the appropriate graphs that the following identities are true. (This is not the same as a proof, of course, but if you are a person who thinks visually, a graph is worth a thousand lemmas.)

exp(x)*exp(2*x) = exp(3*x) ; ln(x)+ln(2*x) = ln(2*x^2) ; 5*ln(x) = ln(x^5) . To avoid taking the logarithm of negative numbers make the plot only over positive values of x . Note: it will be easier to see that the two expressions are graphically equivalent if you plot them with different colors and thicknesses by using this option line in your plot command: color=[red,green],thickness=[2,10]

------------------------------------------------------------------------

Problem 2.4

Show by doing graphical experiments that the exponential function grows faster than any power of x and that the natural log function grows more slowly than any fractional power of x. Do this by choosing several fixed powers of x and then making plots over appropriately sized windows. Recall that if you leave the vertical scale out of the plot command, Maple will choose it appropriately. Note: when you do the exponential function you will probably run into a floating point error because you are trying to plot numbers that are too big. The standard way to avoid this problem is to plot the log of the functions instead. It is easier to tell how big the numbers are if you use the function log10(x). Second note: when you do the fractional power comparison you will have to use such big values of x that Maple will complain. So in place of x use log10(x), i.e., use x=10^t and make the plots versus t instead of x.

------------------------------------------------------------------------

Problem 2.5

Graphically verify the following trigonometric identities. Instead of overlaying two plots, plot the left-hand side minus the right-hand side. Comment on why you don't really get zero.

sin(2*x) = 2*sin(x)*cos(x) ; cos(2*x) = cos(x)^2-sin(x)^2 .

sin(x/2)^2 = (1-cos(x))/2 ; cos(x/2)^2 = (1+cos(x))/2

------------------------------------------------------------------------

Problem 2.6

Show graphically that when you add sin(x) and cos(x) together you just get another sinusoidal function with a new amplitude and phase shift. Make the plot by assigning the sum of these two functions to a Maple function F and then plotting F(x). From your graph find the new amplitude and the phase shift relative to the cosine function, i.e., find a formula for the addition of sine and cosine in the form A*cos(x-phi) .

------------------------------------------------------------------------

Go to top of section

Fourier analysis

Debugging

Later on you will learn some powerful techniques for solving partial differential equations using a technique called Fourier analysis , which is based on this powerful idea: you can make complicated functions by using infinite sums of simple ones. In the previous section you saw an example of this when you added cosine and sine to get a phase-shifted cosine. Here's another simple example that is important in physics. Add two cosine functions, but with different frequencies:

> f:=t-> cos(t)+cos(1.1*t);

f := proc (t) options operator, arrow; cos(t)+cos(1...

> plot(f(t),t=0..200*Pi,numpoints=1000);

[Maple Plot]

>

You have probably experienced this plot. Remember what the trumpets in junior high band sounded like: wah-wah-wah-wah. The annoying flutter of two inexperienced musicians trying to play the same note, but not quite succeeding, is called beats, and they are clearly illustrated by the plot above. The rapid oscillation is the note and the successive amplitude changes are the flutter.

Problem 2.7

Play with the graph of beats above and find the relation of the difference between the two frequencies ( omega[1] = 1 and omega[2] = 1.1 in the example above) to the wah-wah frequency, defined by f = 1/Tbeat , where Tbeat is the time between successive loud portions of the sound.

------------------------------------------------------------------------

Now let's illustrate Fourier's theorem. He showed that any periodic function could be represented by an infinite sum of sines and cosines having the same period as the function. In these sums the sines and cosine functions are multiplied by coefficients that usually get small as the sum index gets big. For instance, here's a sum of cosine functions with coefficients that fall off like 1/n coded using Maple's sum command.

> g:=x-> sum(cos(n*x)/n,n=1..100);

g := proc (x) options operator, arrow; sum(cos(n*x)...

There isn't any way you can get any insight into what this function looks like by staring at this sum, but Maple's plotting capability can show you exactly what is going on

> plot(g(x),x=0..6*Pi);

[Maple Plot]

>

Notice (i) that the function is periodic and (ii) that you probably couldn't have guessed that it was going to look like this. You can do some more examples in the problem below.

Problem 2.8

Consider the Fourier sum sum((-1)^n*cos((2*n-1)*t)/(2*n-1),n = 1 .. 100) . Plot it from t = 0 to t = 2*pi by assigning this sum to a Maple function. Now modify the sum so the factor in the denominator is squared, switch cosine to sine, and plot it again. Then change the factor in the denominator to be cubed and plot again. Then switch to the 4th power and plot again. This sequence illustrates a property of Fourier series which isn't in most math books. Functions which are discontinuous have Fourier series in which the terms go to zero like 1/n . (And at the discontinuities they have nasty wiggly features called the Gibbs phenomenon, which has someone's name attached to it because it had to be discovered the hard way, Maple plots having not yet been invented.) Functions which have discontinuous first derivatives fall off like 1/(n^2) . Functions which have discontinuous second derivatives fall off like 1/(n^3) . , etc.. And functions which have no discontinuities or discontinuous derivatives of any order have to fall off faster than any power of 1/n , which means they have to fall off exponentially in n , like exp(-n) , 1/cosh(n) , etc.. You will see Fourier series that fall off like this in Physics 441.

------------------------------------------------------------------------

Advanced topic: wave packets

Finally, we can use the idea of Fourier analysis to build wave packets and to examine the uncertainty principle. You probably think of the uncertainty principle only in terms of quantum mechanics, but it is really a result of Fourier analysis. But since Fourier analysis underlies all of quantum mechanics, it should be no surprise that this important physical principle turns out to be a mathematical result.

To build a wave packet we sum a whole bunch of cosines or sines with frequencies closely spaced around some central frequency. The result is a wave at the central frequency but it lives inside an envelope caused by the destructive interference of the neighboring waves. Here, I'll show you.

We'll use a Gaussian centered at omega = 4 as the distribution of frequencies in the packet

> A:=w-> exp(-(w-4)^2*20);

A := proc (w) options operator, arrow; exp(-20*(w-4...

Let's plot it so you can see the distribution of frequencies

> plot(A(w),w=0..5,labels=['w','A']);

[Maple Plot]

It is important to have a way of describing how wide this distribution is. A common term that you may have learned before is the Full Width at Half Maximum, or FWHM for short. This is the width in omega between the two points in the distribution A(omega) where A is one-half of its maximum. Look at the graph and roughly verify that the FWHM is given by Delta*omega = 2*sqrt(ln(2)/20) . Then do a little math and see that this formula is correct.

Now we will build a function of time which is made up of a superposition of waves with frequencies between omega = 3.5 and omega = 4.5 (frequencies outside of this range don't have enough amplitude to matter very much, according to the graph above).

> f:=t-> sum(cos((3.5+n/100)*t)*A(3.5+n/100),n=0..100);

f := proc (t) options operator, arrow; sum(cos((3.5...

Note that as n ranges from 0 to 100, the quantity 3.5+n/100 ranges from 3.5 to 4.5, just as desired for omega . Now we can plot the time signal and see what time function f(t) is produced by the frequency function A(omega) .

> plot(f(t),t=-50..50);

[Maple Plot]

>

So we see that a finite-width distribution of amplitudes in frequency space ( omega ) makes a finite-width distribution in time, which is exactly what a wave packet is. Now comes the uncertainty principle. This theorem says that the product of the width of the amplitude function A(omega) , which we call Delta*omega , and the width of the time signal Delta*t (the width of the wave packet plotted above) is no smaller than a number of order unity. In practice it is usually about equal to 5.5 if we measure the widths using the full-width at half-maximum. Or in symbols

5.5 <= Delta*omega*Delta*t

Problem 2.9

Verify the uncertainty principle given above for the graphs displayed. Then change the width of the amplitude function A(w) by changing the parameter 20 in the definition of A(w) to something else and making a new set of plots. Verify that the uncertainty relation holds for the new plots.

Go to top of section

Plotting data

Debugging

Maple is not really a very good way to do data analysis. You have learned, or will learn, some powerful ways to do data analysis when you study Labview in your physics lab courses or when you study Matlab in Physics 330. But you might want to import some data into Maple sometime and compare it with a formula that you have coded in Maple, so here's what you need to know.

Maple stores and plots data in matrix form. The way to read data in is to use readdata , like this

> d:=readdata("datafile", 2);

Error, (in readline) file or directory does not exist

where the 2 means that there are 2 columns of data in the file. If you execute this command you will get an error because you don't have a file called datafile in the directory you are working in. To fix this problem use Window's notepad editor to create a file called datafile that looks like this: (note that you can copy and paste this data into notepad)

0 1

1 1.5

2 1.9

3 2.6

4 3.7

5 5.4

6 7.3

7 10.4

8 14.2

9 20

10 29


After you have made this file and have properly saved it in the directory you are working in, try executing the command again......It failed again, didn't it? Part of the problem this time is that Notepad insists on putting a .txt extension on all of its files. So the readdata command needs to be changed to

> d:=readdata("datafile.txt",2);

Error, (in readline) file or directory does not exist

This still probably doesn't work if you are on a windows system. The problem now is that Maple is not looking for your file in the right directory. To fix this use the currentdir command like this:

> currentdir("c:\\Program Files\\Maple 6\\Users");

Error, (in currentdir) file or directory does not exist

or if you are running off the a: drive

> currentdir("a:");

Error, (in currentdir) file or directory does not exist

(Note that this change-directory command has the annoying feature in Windows that instead of echoing the new directory it echos the old one. To make sure you are where you want to be execute it twice.) Finally, this should work:

> d:=readdata("datafile.txt",2);

d := [[0., 1.], [1., 1.5], [2., 1.9], [3., 2.6], [4...

Now that the data is stored as a matrix Maple can plot it using the pointplot command, as shown below. But if you try to execute the pointplot command it will just print a pretty blue version of the command and ignore you. The problem is that the package that contains pointplot is so big that Maple doesn't load it unless it is needed, so you have to tell it that it's needed by using with(plots)

> with(plots):

> pointplot(d);

[Maple Plot]

>

Notice that the with(plots) command was terminated with a : instead of a ; . The : means to execute the command just like ; but to shut up about it. Try doing with(plots); and you will see what I mean. Whenever you want to execute a command and you are so confident that it will work that you don't need to see the output, use : . (You should never be this confident. Only use : after you have tested the command with ; first.) Now suppose we want to see how well this data is fit by the formula exp(x/3) . We simply assign the pointplot to one variable name and the formula plot to another, then display them together, like this (notice the colons at the end of the assign statements--it's better to have Maple shut up about what it is doing here.)

> p1:=pointplot(d):

> p2:=plot(exp(x/3),x=0..10):

> display({p1,p2});

[Maple Plot]

>

Maple's stats package does similar things, and will even do some fitting, but I don't think it's as good as Labview or Matlab.

Go to top of section

Parametric plots

Debugging

One of the best ways to make complicated plots is with a parametric representation. Consider, for example, the humble circle. The formula for it that you remember best is probably this one

x^2+y^2 = R^2 ,

but if you try to graph a circle with this formula you have to do it this way

y(x) = sqrt(R^2-x^2) and y(x) = -sqrt(R^2-x^2) . This requires two separate plots and the functions have infinite derivatives at x = R and x = -R ; it's just messy. But look how pretty the formulas for x and y on a circle look if you use a parametric representation:

x(s) = R*cos(s) ; y(s) = R*sin(s) ; s = 0 .. 2*pi .

Here are the Maple plot commands to do the plot of a circle both the y(x) way and the parametric way, with the parametric one at a smaller radius so you can see them both.

> with(plots):

> p1:=plot([sqrt(1-x^2),-sqrt(1-x^2)],x=-1..1):

> p2:=plot([ .8*cos(s),.8*sin(s),s=0..2*Pi]):

> display({p1,p2});

[Maple Plot]

Ok--they both look the same, but neither one looks like a circle. This is a common plotting problem in all computer programs: circles look like ellipses because the x and y axes have different scales. Maple has a particularly easy fix for this problem, which is that you just tell the plot command that you want the x and y axes contrained to be the same scale, like this

> display({p1,p2},scaling=constrained);

[Maple Plot]

>

You can explore some more ways of doing parametric plots in the problems below.

Problem 2.10

The classic conic sections all have parametric forms. Use the parametric plot command to sketch each of these curves using constrained scaling.

Ellipse: x(s) = 3*cos(s) ; y(s) = 1.3*sin(s) ; s = 0 .. 2*pi .

Hyperbola: x(s) = 3*cosh(s) ; y(s) = 1.3*sinh(s) ; s = -1.5 .. 1.5

(Once you draw this, figure out how to get the missing half of the picture.)

Parabola (rotated): x(s) = s*cos(phi)-s^2*sin(phi) ; y(s) = s^2*cos(phi)+s*sin(phi)

s = -3 .. 3 .

Try plotting this for several different angles. If you want to go a little crazy, try drawing a rotated parabola using the y(x) form.

---------------------------------------------------------------------

Problem 2.11

It is also possible to draw curves in polar coordinates. A simple example is the ellipse again, but this time with the origin at one focus of the ellipse. To make sense of this we need some relations from ellipse geometry. Suppose that the (x,y) form of the ellipse is as given above,

x(s) = a*cos(s) ; y(s) = b*sin(s) with b < a . Then the distance a is called the semi-major axis and the distance b is called the semi-minor axis. The eccentricity of the ellipse is defined to be e = sqrt(1-b^2/(a^2)) . It is zero for a circle and as it gets smaller the ellipse gets more and more squashed. The ellipse has two foci, one focus to the left of center along the long (semi-major) axis and the other to the right of center. The distance from the center of the ellipse to either focus is f = e*a . (Wait a sec--how come I am dragging you through this? What has this got to do with physics? Well, this is the language you will use in Physics 321 to describe the motion of planets around the sun, so stay with me, this is important.)

Draw an ellipse using an (x,y) parametrization which has the origin of coordinates at the right focus of the ellipse with a = 2 and b = 1 . (Use the standard parametrization given above, but subtract f from x(s) to shift it over.

Now, here's the point of this exercise. The parametric form of an ellipse with the origin of coordinates at the right focus in cylindrical coordinates (like you will use in Physics 321) is given by

r(phi) = a(1-e^2)/(1+e*cos(phi)) . Lay this cylindrical coordinate graph on top of the xy graph of the ellipse you just did and verify that they match. The form of a Maple parametric plot in cylindrical coordinates is plot([r(s),phi(s),s=s1..s2],coords=polar,options) . For example, to make a spiral you could use

> plot([s/10,s,s=0..16*Pi],coords=polar,scaling=constrained);

[Maple Plot]

>

Once you get the plots to agree you are finished; but try to remember that the form for an ellipse with long dimension 2*a , eccentricity e , and with the origin at one focus in cylindrical coordinates is

r(phi) = a*(1-e^2)/(1+e*cos(phi))

Ok-you won't remember this. But remember that you can come back here as a review when you get to planetary motion in Physics 321.

------------------------------------------------------------------------

Problem 2.12

Well, that was pretty bad. Here's one that's just for fun. In the polar plot command given below treat two numbers as adjustable, j and k, and just see what kinds of different pictures you can make. Fractional values of j are interesting if you use large values of k.

> j:=3;k:=2;

j := 3

k := 2

> plot([cos(j*s),s,s=0..k*Pi],coords=polar,scaling=constrained,axes=none);

[Maple Plot]

>

Go to top of section

Special functions

There are a bunch of functions you haven't encountered yet that are called special functions , meaning they are not like the simple sines, cosines, exponentials, logs, powers, and hyperbolic functions you can find on hand calculators. These are functions that arise in more advanced work in mathematical physics and you will work with them in Physics 318, 321, 441, 442, 451, and 452. You can see which functions Maple knows about by using ?inifcns . Let's get a head start on these functions by using Maple graphs to at least see what they look like. Each problem below introduces you to a different special function and asks you to get a feel for its properties by making graphs.

Problem 2.13: Legendre polynomials

Debugging

These functions show up when we do electrical and quantum mechanical problems in spherical coordinates. Their symbol is P[n](x) and they are simply polynomials in x . But they have very special properties on the interval [-1,1]. (i) For odd values of the integer index n they are odd and for even n they are even. (ii) P[n](1) = 1 and P[n](-1) = (-1)^n . (iii) They wiggle a lot, more and more as n gets bigger and bigger, but their magnitudes are always smaller than 1 inside the interval (-1,1). I have given you below a plot command that plots the first two on top of each other. Modify this command so that it plots the first 8 Legendre polynomials on top of each other.

You could type all 8 of them in, or you could use Maple's sequence command seq which works like this. Suppose you wanted to generate a sequence of the functions x^n from n=1..8. You would do this

> seq(x^n,n=1..8);

x, x^2, x^3, x^4, x^5, x^6, x^7, x^8

You can do this same kind of thing with P(n,x) in the plot command below.

> with(orthopoly);

[G, H, L, P, T, U]

> seq(P(n,x),n=0..8);

1, x, 3/2*x^2-1/2, 5/2*x^3-3/2*x, 35/8*x^4-15/4*x^2...
1, x, 3/2*x^2-1/2, 5/2*x^3-3/2*x, 35/8*x^4-15/4*x^2...

Put this sequence command properly into the following plot command so that a plot of all of these functions from n = 0 to n = 8 appears.

> plot(................,x=-1..1);

Error, `..` unexpected

Before we leave these functions I want you to see that there is something a little funny about this Maple function. If you type sin(x), exp(x), or any of the other functions we have already seen you get this

> sin(x);exp(x);

sin(x)

exp(x)

But look what you get if you type P(3,x)

> P(3,x);

5/2*x^3-3/2*x

>

You get a polynomial. All of the functions you get when you use with(orthopoly) work this way. This means that these functions are very different from the functions you are used to on a hand calculator. With a calculator you put in a number and you get a number back. With orthogonal polynomials you put in a variable and get a polynomial back. If you put a number in you get a number back, but the path to this number is indirect: first the polynomial is returned, then the number is put into the polynomial and evaluated. Maple does this on its own so it's invisible to you, but it is important to remember that this is how orthogonal polynomials work in Maple.

Go to top of section

Problem 2.14: Bessel functions

Debugging

These functions show up when we do electricity and thermal conduction problems in cylindrical geometry. There are 4 of them that are mostly commonly used: J[n](x) , Y[n](x) , I[n](x) , and K[n](x) and the Maple commands for them are BesselJ(n,x), BesselY(n,x), BesselI(n,x), and BesselK(n,x). The J's and Y's are sort of like cylindrical sines and cosines while the I's and K's are like cylindrical growing and dying exponentials. You also need to know that the Y's and the K's are singular at x = 0 so you have to be careful when making plots of them. You can control singularities by choosing the vertical range of the plot to be finite. The Maple command below plots the first two J's. I want you make the following plots: (a) Plot J[0](x) and Y[0](x) on one plot frame from x = 0 to x = 30 . Set numpoints large enough that you can see the logarithmic singularity of Y[0](x) near x = 0 . (b) Plot J[n](x) and Y[n](x) for n = 1 .. 4 with the J's on one plot frame and the Y's on another. Plot them from x = 0 to x = 30 . The sequence command seq will help you here. (c) Plot I[n](x) for n = 1 .. 4 all on one plot frame. Do it from x = 0 to x = 10 . (d) Plot K[n](x) from n = 1 .. 4 , all on one plot frame. Do it from x = 0 to x = 10 . Take a good look at these functions; they will show up later.

> plot([BesselJ(0,x),BesselJ(1,x)],x=0..50);

[Maple Plot]

>

Now use your graphs to answer the following questions.

1. (a) The J- and Y-Bessel functions look like sines and cosines after about x=10; what is the period of these almost periodic functions? (b) You will notice that their amplitudes are falling off at large x. The fall off factor is a power law, i.e., A/(x^p) . Find the value of p by plotting J[0](x) and A/(x^p) on the same plot and by adjusting A and p until the second function lines up with the top of the Bessel function wiggles.

2. The I- and K-Bessel functions look like exponentials ( exp(a*x) ) after about x=10. Find the approximate exponential function that fits them out there. You will have trouble doing this because in addition to the exp(a*x) -behavior these functions also have the same power-law drop-off factor A/(x^p) as the J's and Y's. So when you look for the exponential function that comes close to describing what they do, make your comparison plots between exponentials and I[n](x)*x^p and K[n](x)*x^p . You will also find it helpful to plot the logarithms of these functions instead of the functions themselves to handle their huge variation in magnitude. All you want to see is that the logarithms of the I[n](x)*x^p functions are parallel to each other and also parallel to the line y = a*x for the appropriate choice of a ; then do the same thing for the functions K[n](x)*x^p .

Go to top of section

Problem 2.15: The Gamma function

Debugging

The Gamma function is the analytic continuation onto the real number line of the factorial function for integers. The connection is

Gamma(n+1) = n! .

This function shows up in all kinds of places and it has rather surprising properties for negative values of its argument. All I want you to do is to plot it from -5..5 and verify that it has the correct values at positive integers, and then to marvel that a function that seems so simple on the positive half of the number line could be so messed up on the negative side. Maple's name for it is GAMMA(x) ;

Problem 2.16: Complete elliptic integrals

Debugging

The complete elliptic integral functions K(k) and E(k) are defined by the definite integrals

K(k) = int(1/sqrt(1-k^2*sin(phi)^2),phi = 0 .. Pi/2... ; E(k) = int(sqrt(1-k^2*sin(phi)^2),phi = 0 .. Pi/2)

The Maple names for these functions are EllipticK(k) and EllipticE(k) . These functions are usually used with k in the range 0..1, but they can be analytically continued into the entire complex plane. Both K(k) and E(k) are pi /2 for k=0. At the other end, k=1, K(k) is logarithmically singular and E(k) is 1. Plot both functions on the same plot over this range using numpoints=200 and 1000; I want you to see how weak a logarithmic singularity is. You should find that almost nothing happens as numpoints is changed, except that the vertical plotting range changes a little. To see why this plot behavior indicates a weak singularity, here's what such a pair of plots looks like for a strong singularity:

> plot(1/(1-x),x=0..1,numpoints=200);

[Maple Plot]

> plot(1/(1-x),x=0..1,numpoints=1000);

[Maple Plot]

>

Problem 2.17: The error function

Debugging

The error function erf(x) shows up all the time in probability theory and Maple calls it erf(x) . If you have a Gaussian probability distribution, proportional to exp(-x^2) , then the probability that the variable x lies between -infinity and z is proportional to

int(exp(-x^2),x = -infinity .. z) , which is just what the error function erf(z) involves. But for some reason a long time ago someone decided that the basic function erf should be defined as an integral starting at 0 instead of at -infinity , so they defined it this way:

erf(z) = 2*int(exp(-x^2),x = 0 .. z)/sqrt(pi) . The probability that a Gaussian variable lies between -infinity and z is given by (1+erf(z))/2 . Plot both erf(x) and (1+erf(x))/2 in the range -3..3.

Go to top of section

Animations

Debugging

Perhaps the coolest plots Maple can make are animations. Let's start with two simple wave examples. The formula for a traveling wave is y(x,t) = A*sin(k*x-omega*t) . Maple can show you that this formula travels with the animate command. First we will give A , k , and omega numerical values, then animate the function by plotting many plots in x at successive times, just like a movie. WARNING: when you execute this group of commands you will see a plot, but it will not be animated; it will just sit there. To make it move you have to click on it and then run it with the player controls that appear on the toolbar. When they come up, take a minute and check out what each one does.

> restart:with(plots):

> A:=1.5;k:=3*Pi/2.;omega:=Pi/2.;

> animate(A*cos(k*x-omega*t),x=0..20,t=0..20,numpoints=50,frames=10);

Warning, the name changecoords has been redefined

A := 1.5

k := 1.500000000*Pi

omega := .5000000000*Pi

[Maple Plot]

>

Problem 2.18

Modify the animate command above so that the function is smoother in x and so that it runs smoother in time as well by experimenting with the numpoints and frames settings. Show, using your animation, that the velocity at which the wavetops move (this velocity is called the phase velocity) is given by v[phi] = omega/k . Also show that changing the sign of k changes the direction the wave moves.

--------------------------------------------------------------------------------

Problem 2.19

Modify the animation above so that it plots a standing wave instead: y(x,t) = A*sin(k*x)*sin(omega*t) . Use a range in x so that the standing wave has 3 zeros between the endpoints and fixed ends as well.

--------------------------------------------------------------------------------

Problem 2.20

Show by making an animation that the sum of two waves of equal amplitude traveling in opposite directions is a standing wave.

--------------------------------------------------------------------------------

Advanced topic: wave packets

In addition to elementary wave properties, animation can also illustrate the more complex behavior of wave packets, including the concepts of group velocity and wave packet diffusion. The way to make a wave packet is to take a whole bunch of waves of the form A*sin(k*x-omega*t) with different k 's and add them together, as we did in the section of Fourier analysis when we discussed the uncertainty principle. We can do exactly the same thing here with k , using an amplitude function A(k) centered at k[0] with width Delta*k to make a wave packet in space with wavelength 2*Pi/k[0] and width Delta*x . But the new feature is that this packet moves, and in weird and strange ways. Its behavior is determined by the dispersion relation omega = omega(k) of the waves that are being added together. We will start with the simplest case and work our way up to some strange ones that are more than just mathematical curiosities. Every effect that will be shown in this section is physically realized in some kind of electromagnetic wave found in the plasmas that surround the sun and the planets of our solar system.

Suppose the dispersion relation is just the standard non-dispersive one that governs light and sound: omega = k*v , where v is the phase velocity of the waves. In this case every wave of the superposition moves at exactly the same speed, so every part of the wave packet moves at speed v , as shown in the example below.

Define the dispersion relation

> v:=1;w:=k->k*v;

v := 1

w := proc (k) options operator, arrow; k*v end proc...

Define the spectrum in k .

> ko:=1;A:=k-> exp(-(k-ko)^2*40);

ko := 1

A := proc (k) options operator, arrow; exp(-40*(k-k...

Now we will look at the wave packet at time t=0.

> f:=(x,t)-> sum(sin((ko-.5+n/40)*x-w(ko-.5+n/40)*t)*A(ko-.5+n/40),n=0..40);

f := proc (x, t) options operator, arrow; sum(sin((...

> with(plots):plot(f(x,0),x=-60..60);

[Maple Plot]

Now we are ready to make it move by using Maple's animation command.

> animate(f(x,t),x=-60..60,t=0..180,frames=80,numpoints=400,color=navy);

[Maple Plot]

>

Problem 2.21

If the dispersion relation is not just the linear function omega = k*v , then more interesting things can happen. The first of these is that the waves in the packet and the packet as a whole no longer move at the same velocity. Let's try a new dispersion relation using the form

omega = kv*(1+a*k/k[0]) . When you study Fourier analysis in more detail you will learn how to show that while the wave crests move at the phase velocity given by v[phase] = omega/k , the packet as a whole moves at the group velocity given by v[group] = d*omega/dk . (a) Find the phase and group velocities for the dispersion relation given in the introduction to this problem (Maple can help). Choose k = k[0] and obtain v[phi] and v[g] (the standard phase and group velocity notations) as functions of the parameter a . Modify the dispersion relation in the Maple execution groups given in the first part of the problem and run it again with a = 1 . Try to see the wave crests moving slower than the wave packet as a whole (you will see wavecrests moving backwards through the packet because the group velocity is bigger than the phase velocity). To see this you will have to slow the animation down using the controls on the toolbar. You may also want to put it into continuous play mode and adjust the simulation time so that it runs just long enough that the group velocity covers the distance from x=0 to x=60. Warning: this takes a while, so be patient. (b) Now for something really weird; choose a so that the group velocity is zero and run the animation again. The packet should sit still while the wave crests move through it.

--------------------------------------------------------------------------------

Problem 2.22

You may have noticed in part (b) of Problem 2.21 that although the packet didn't move much, it did change shape a little. The reason for this is that wave packets can also broaden in time via diffusion, just like a tiny hot spot in a piece of metal spreads out through thermal diffusion. The diffusion coefficient for wave packet broadening is proportional to the magnitude of the second derivative of the dispersion relation (with respect to k ). This means that if the dispersion relation has a non-zero second derivative, then the wave packet will spread in time. But to really see it you will need to run the simulation long enough that the effect starts to really matter. This run time is on the order of a few times the absolute value of 1/(w'' Delta k^2) in this problem, where Delta*k is the width of A(k) (use FWHM). Calculate w'' and verify that it is non-zero, then run the simulation for Problem 2.21 long enough that you can see the spreading.

--------------------------------------------------------------------------------

Problem 2.23

Invent a dispersion relation that has a positive phase velocity and a negative group velocity and verify that it works by modifying and running an animation.

Go to top of section

Visualizing vector fields

Debugging

Maple's fieldplot command allows you to visualize vector fields in two dimensions. Suppose, for instance, that you have a magnetic field given by the formulas B[x] = B[0]*y/a and B[y] = B[0]*x/a . To visualize the field lines we would do this (setting B[0] = 1 and a = 1 to make the numbers easy)

> restart;with(plots):

Warning, the name changecoords has been redefined

> fieldplot([y,x],x=-1..1,y=-1..1,grid=[20,20],color=red,arrows=SLIM);

[Maple Plot]

There is also a fieldplot3d command which works similarly in three dimensions; you can find out how it works with ?fieldplot3d.

>

Problem 2.24

(a) Use fieldplot to visualize the electric field of a line charge, given by E = lambda*(x*i+y*j)/(2*Pi*(x^2+y^2)) where i and j are the x and y unit vectors. (b) Use fieldplot to visualize the magnetic field of a long wire, given by B = mu[0]*I*(-y*i+x*j)/(2*Pi*(x^2+y^2)) . Experiment with different grid settings and choices for the arrows option (see ?fieldplot ). Note: don't use big numbers in the grid command. If you do, Maple will take forever and when it finishes you will be looking at a solid wall of color without any discernible arrows. I don't usually go above 30x30.

Go to top of section

3D-surface plots and contour plots

Debugging

To visualize 2-dimensional data in the form of a function f(x,y) Maple gives you two choices: (1) plot the function values as the height of a surface above the xy plane or (2) draw contours of constant f(x,y) in the xy plane. Which does a better job depends on the problem and on your tastes. Here is an example done both ways.

Consider the function f(x,y) = exp(-abs(x-sin(y)))*(1+.2*cos(x/2))*(1+.4/... , the "mountain range" function. (Don't worry about where this function came from. I just made it up because it looks cool, like a mountain range.) A three-dimensional surface plot is done with plot3d like this

> restart;

> f:=exp(-abs(x-sin(y)))*(1+.2*cos(x/2))*(1 + .4/(.3+y^2));

f := exp(-abs(x-sin(y)))*(1+.2*cos(1/2*x))*(1+.4/(....

> plot3d(f,x=-6..6,y=-6..6);

[Maple Plot]

This looks rather interesting, but the detail is too crude to really see what is going on, and we might want to use a different viewing angle too. These things are controlled with options which you can read about in ?plot3d[options] or you can just click on the figure and move the cursor while holding the left button down to cause the view to rotate. If you go into the Options menu on the toolbar and change the plot display from inline to window you will get a figure with its own set of tools that will let you change lots of things about the way it looks.

Here is an improved plot using options in the command line:

> plot3d(f,x=-6..6,y=-6..6,grid=[60,60],labels=["x","y","f"],orientation=[45,30],axes=boxed,shading=xy,view=0..3);

[Maple Plot]

>

As you can see the surface grid is controlled by the grid=[m,n] option, the labels on the axes are controlled by the labels option, and the viewing angle is controlled by orientation. A word of warning: the mathematicians who wrote Maple are used to having phi be the angle in spherical coordinates that comes down from the z-axis and theta be the azimuthal angle that winds around the z-axis in the xy plane. This is exactly backwards from the way we do it in physics. So to be consistent with the way we do spherical coordinates in physics, the form of the orientation option is orientation=[ phi, theta ] which is exactly backwards from what you will read in online help. In addition, the angle phi indicates the direction along which the viewer is sighting rather than the angular position of the viewer. This is weird enough that you will just have to experiment until you get what you want. The vertical size of the plotting box is controlled by the view=zmin..zmax option. Finally, the appearance of the plot is altered by the shading command which can be shading=z, shading=xy, shading=xyz, or a few other things found under ?plot3d . Experiment and see what looks best.

You can look at the same mountain with a contour, or topographic map, view like this (note that to use this command you have to to with(plots) first)

> restart;

> with(plots):

Warning, the name changecoords has been redefined

> f:=exp(-abs(x-sin(y)))*(1+.2*cos(x/2))*(1 + .4/(.3+y^2));

f := exp(-abs(-x+sin(y)))*(1+.2*cos(1/2*x))*(1+.4/(...

> contourplot(f,x=-6..6,y=-6..6,contours=40,grid=[30,30],coloring=[green,blue]);

[Maple Plot]

Note that the coloring=[green,blue] plots the low values of the function in green, the high values in blue, and in-between values in colors between green and blue. You can use any two Maple colors you want in this option (see ?plot[colors] )

> ?plot[colors]

>

Look more carefully at this contour plot and compare it with the 3d mountain picture--in Maple 6 they don't look like the same objects. This is a bug in the original release of Maple 6. Even their examples in ?plots[contourplot] don't work right. But if you have Maple 6.01, or later, this bug has been fixed and contour plotting is done right.

Go to top of section

Go to top of chapter