Homework #5

A guided tour of functions in Mathematica

Double click on the little box to the right of this cell. This should 
"expand" this cell, and suddenly you will see lots more text appear 
before your eyes. You can "recontract" it all, at any time, by double 
clicking the mouse on the bracket on the right side that groups all these 
cells. (If you think you're familiar enough with Mma, you can just go 
ahead and do the problems, without reading the "hidden" parts of this 
notebook):

This notebook is just like any other saved notebook. You will see "In" 
and "Out" lines from things I have done. In places, I will tell you to 
change one of my "In" lines, re-evaluate it (shift return, as usual), and 
see what happens. I may ask you to insert comments (like this one!) 
explaining what's going on.

In the previous Mma hw's, you may have used an assignment  statement, 
like

f=x^4+3x^2

3*x^2 + x^4

Or something similar. From now on, "f" has been assigned to the 
expression x^4+3x^2. So, you can plot f, or integrate it, or whatever. 
Whenever you use f at any point, it replaces it with the expression:

f

3*x^2 + x^4

Integrate[f,{x,0,2}]

72/5

Which clearly can save some typing if you use an expression a few times.

Notice that f is not exactly a *function*, e.g. there's no easy way to 
evaluate f(2). ( Actually, last time, we did discover a sneaky way of 
finding f(2), by using the "at the point" command, /.)

f /. x->2

28

But this is not what we really want to do for a function. By the way, Mma will always retain this f, which can be a pain. We can clear definitions by:

Clear[f]

f

f

So, Mma has forgotten all about the definition.
Let's now make a real function. This is done with the :=  (colon equals)

Clear[cube];
cube[x_] := x^3

Note the syntax! There are two important features. First is that I use 
:=, not =. Second, notice the underscore character after the x on the 
left hand side. It's important! It tell Mma that this symbol is meant to 
be a *dummy variable*.( I begin with "Clear[cube]" just in case someone 
had been messing around and defined cube already, in some other way)

Following is the first of several problems. You can (should) do these assignments right here, in this notebook! Just click the mouse right below the problem, and do what I've suggested...

Problem number 1 (5 pts): 
Define a function "square" which yields x^2. But first, define it WITHOUT any underscore character after the argument, x. Then evaluate the expression square[x], and then square[y], and then square[3]. Do you see what has happened? Now go back, put that underscore character in where it belongs, and try evaluating the same 3 expressions. Write a short comment right below it explaining what  happened.

You should go ahead and put the mouse above this line, and then begin 
your work on the function. 

At this point, you have done some work, and you should probably save this notebook. Of course, you don't want to write over what I've done (what will the next student think?), so you should now do a "Save As". (Go into the "Notebook menu", that leads to the "Save As") You now have to tell the computer where to save this file - you're in the wrong directory! You have to work your way to your "home", and save it there under whatever title you like. You can do this by double clicking on the little picture of a house that  appears at the lower left corner of the "Save As" popup menu. 
Once you've done this, you never need to do any hunting (even if you have to leave and come back to continue), you have your own personal copy in your own home directory. Also, from now on, you don't have to do a "Save As",
you can just simple do a "Save". (You are now working on your own copy)

Do this now!  CHECK that a file has appeared in your home directory with
the name you chose. (You can get to your home by bringing up the "Workspace"
(just click on it, its still sitting in the background behind Mathematica), and in 
the upper left corner is a picture of a house, double click there and you're home. 
Do you see the newly saved file there? You can come back to Mathematica by clicking on any piece of the window, which is now behind the workspace.

For instructions that will make the next problem (number 2) easier, 
double click on the box on the right of this cell. (As before, if you are 
familiar enough with Mma to go ahead, you can skip this and just do the 
next problem!)

Your function can be much more complicated than a simple expression. It 
can also span several lines (Mma generally ignores carriage returns!) It 
can have multiple arguments. For example, I can write a "dot product" 
function like this, remembering that a[[1]] gives the first component of 
a vector:

mydot[a_,b_] := (
(* I can stick comments in! Mma always ignores
    everything between matching parenthesis, if 
    they have a star immediately after/before 
    like this:  *)
	  a[[1]]*b[[1]] +a[[2]]*b[[2]] 
                )

The parenthesis at the start and end weren't needed, I just put them 
there to guide the eye.

vec1 = {1,2};
vec2 = {3,1};
mydot[vec1,vec2]

mydot[vec1,{2,4}]

Study the function, be sure you understand how it worked. It's really 
still just a one liner- I just added more lines of comments!  Feel free 
to go up and try it out, but first evaluate the expression "mydot" (if 
you don't, Mma won't yet know about it - even though it *looks* like it, 
Mma hasn't evaulated any expressions in this notebook since you got 
started!)  What happens if you give it an argument that's not a vector? 
What about if you give it a vector with 3 components? (Clearly we could 
do a lot to improve this function!) 

Here's a function that is truly more than one line, switching from polar  
components to Cartesian:

mypolar[r_,theta_] := (
	x=r Cos[theta];
	y=r Sin[theta];
	{x,y}
	)

mypolar[1,Pi/4]

Notice some features of mypolar. I used dummy variables r and theta (I 
could have called them anything at all) I used dummy variables x and y, 
and unfortunately, these leave behind hints of themselves. Look, I 
assigned a value to x inside the function, but Mma never forgets...

x

That's probably not the best example of "programming style", but it 
worked. There are ways around this, if you're interested. Look up 
"Block[...]" in Blachman, or Wolfram. 

The last line of the function "mypolar" output a vector {x,y}, and so the 
RESULT of this function is now a vector! For example, recall that "mydot" 
expects to be fed two vectors. I can just as well feed it "mypolar" as 
one (or both) of these vectors!:

mydot[{0,Sqrt[2]} , mypolar[1,Pi/4] ]

Do you see what I just did? I dotted the vector (0,sqrt[2]) with the 
vector (1/sqrt2,1/sqrt2)

Problem 2 (10 pts): Write a function called curl[f_] that takes the curl of a 
given vector force field, f={fx,fy,fz}. It should output a vector. Test 
your function on at least three different force fields, choosing 
carefully some that have curl=0, and some that don't. (Don't use any 
built in Mma functions to take the curl for you!)

For some extra hints, double click on the little box at the right of this 
line

There are many different ways of giving Mma a force field f. As a 
specific example, you might just use "f = {x,-y,0}", or you might want to 
get more general and make f a function, "f[x_,y_,z_] := {x,-y,0}". Choose what's easiest for this problem. Your solution depends on which of these choices you're going to make, though. If you choose the latter, you might like to know the syntax for accessing on of the compontents of the function! It looks like this:

f[x_,y_,z_] := {x,-y,0}

f[x,y,z][[2]]

f[a,b,c]

f[a,b,c][[2]]

So you see, f can take any (dummy arguments), and the [[2]] returns the second compenent

Clear[f]

Don't forget that, to take the partial derivative of a function with 
respect to x, you would use the command D[expression,x]  If f is a 
function, rather than an expression, it's a bit trickier: So e.g

Clear[x,y];
D[x+y,x]

That's just the partial of (x+y) with respect to x...

Clear[f];
f=x+y;
D[f,x]

This still behaves in the simple way you would expect. But, if f is a 
function, life is a bit more complicated:

Clear[f];
f[x_,y_] := x+y;
D[f,x]

You see, this failed! What I need to do in this case was be explicit 
about the arguments to f:

D[f[x,y],x]

One last hint: If you write a function (e.g. curl), and it doesn't work, 
you can type ?curl, and ??curl, and Mma will give you some information about what *it* thinks you've defined. Sometimes (rarely) this can be useful for eliminating syntax errors...

You should go ahead and put the mouse above this line, and then begin 
your work on the function. 

Please don't forget to SAVE now and again, it's really painful if the 
machine crashes when you haven't saved 15 minutes worth of work (let 
alone many hours!!!)

Problem 3 (10 pts): Write a function called cons[f_] that tests whether a given vector force field, f={fx,fy,fz} is conservative. Have it print 
"conservative" if the answer is yes, and "non-conservative" if not. Test 
your function on at least three different force fields, choosing 
carefully so that both positive and negative results are demonstrated.

For some extra hints, double click on the little box at the right of this line.

Hint: You may want to use what you did for problem 2 here! (How does 
having the curl help you?)

Hint 2: At least for my solution, I needed to know about the "syntactic 
equality tester" === (or inequality tester =!= ) (see Blachman, p 150). 
The test you may have used before, ==, tests for mathematical equality. 
Mma doesn't know what to respond if you type "x == 0" if x is a general 
symbol with no specific value assigned. 
So, e.g. syntactic test "{0,0,0} === {0,0,0}" will generate True, 
"{xy, z+x^2, yz} === {0,0,0}" will give False, while the mathematical test "{xy,z+x^2,yz} == {0,0,0}" will leave Mma confused and spluttering if it doesn't know what x,y, or z are yet... (The triple === will always give you just True or False, and it's only true if the expressions are identical, so I think that's what you need here)

Hint 3: See the comments for problem 2 about how to define f. Your 
solution depends on which of these choices you're going to make.

Hint 4: Other useful functions for this question might include "If[...]" 
(Blachman p 185-186) and "Print" (Blackman p. 184). 
For more info on "If" and "Print", double click on the box to the right!

Here's an example of the If statement, and the Print statement

myabs[x_] := If[x<0,Print["Abs(",x,") = ",-x],
                    Print["Abs(",x,") = ",x]]

myabs[2]

myabs[-3]

You can always type ?If to learn more about it, and ??If to learn still 
more!

You should go ahead and put the mouse above this line, and then begin your work on the function. 

Please don't forget to SAVE now and again.

Problem 4 (5 pts): Armed with what you have learned, here's the grand 
finale! Design a function phi[f_] in Mma that will take your given force 
field, f={fx,fy,fz}, and return for you the scalar function v(x,y,z) such 
that  grad v = f. You might like to return an error message if the function f is not conservative (since in that case, there is no unique single valued 
scalar function v.)  Test your function out on the same force fields you 
tried in the previous problem, and one or two more in addition. (Make the 
new ones as complicated as you like, but conservative! )

For some hints, double click on the box on the right

Hint 1: As above, you may choose how to input f as you like. It might not 
be the same as what you chose before, which may require a little extra 
work for you, but now you know how you should have done things in the 
first place!

Hint 2: Think about how you go about finding the scalar function v, given 
its gradient. Recall, in class (or Boas, around p. 261-262) we showed 
that v(x',y',z') is the line integral of f.dr, integrated from 0 to 
(x',y',z') where I have (arbitrarily) chosen v(0,0,0) = 0.  

You may find this problem a little challenging, but it turns out that 
there is a reasonably straightforward solution. Have fun!

You should do your work right above this spot. Once again, SAVE 
periodically while you're working! (This last one is a bit more 
challenging, but the final solution can be really quite reasonable. Enjoy!)

When you're done, you should print out your own work, but to save some trees, there's no need to print out all my yacking (especially all the stuff  I originally had hidden!). I only want to see what YOU did.  If you don't know how to do this, click on the box on the right...

The easiest way will be just to "double click" on the appropriate brackets on 
the right, to REcontract all my excess prose, just like it was when you 
started. Then, when you print your notebook, the hidden text should not 
print out.  

(Another way is to really CHOP out all unneeded text of mine: select a cell bracket on the right by clicking on it, then use the "Cut" function under edit (there's a keyboard shortcut for this too, command x) You can also "sweep across text" with the mouse, making it turn highlighted, and again cut it 
out the same way.)

 Be sure to save BEFORE you start cutting! That way, if you accidentally 
cut out some of *your own* work, you can quite without saving, and in 
that way restore it. By the way, you do have one chance to re-paste cut 
text (under edit), but if you cut out a second thing, the first is forever gone!