Defining Functions and Choosing Variable Names

In this notebook (and accompanying video) we will discuss how to define functions and variables while avoiding common errors.

Example: Recall that the volume of a box is V = l*w*h, where l, w, and h are the length, width, and height of the box respectively.  Note then that V = V(l,w,h).  Let’s try to define our function:

Clear[V,l,w,h];

V[l_,w_,h_]:=lwh;

V[10,5,7]

53

5*3

So what went wrong? The variables are what went wrong.  Mathematica things that ‘lwh’ is a single variable, not the product of three variables.  Thus, when we try to evaluate V(10,5,7) there is nothing to plug in for the three variables that V is supposedly a function of.  We can correct this:

Clear[V]

V[l_,w_,h_]:=l*w*h;

V[10,5,7]

We do not have to define variables as single letters, and in some instances, it might make more sense to use longer names for the variables.  For instance, we know volume = length*width*height, so we can literally define the function exactly as given:

volume[length_, width_, height_]:= length*width*height;

volume[10,5,7]

volume[l,w,h]

volume[2,6,r]

V[2,6,r]

Solve[V[l,w,h]==v,l]

Solve[volume[a1,a2,a3]==t,a2]

c

Why might we want to define a function with a longer name?  You will see that many of the functions in the text are related to cost (C), number of a species (N), interest earned (I) and so forth...  For example, in Mathematica, N, C, I and E are all reserved objects (see the constants notebook and corresponding video).

I

I

(I^2)

E

N[%]

C[

N[

If we want to define functions involving many of these variables, we should use LOWER CASE letters....

N[c_,e_]:= c+e

n[c_,e_]:=c+e

n[c,e]

n[12,5]

n[-4,9]

Remember that Mathematica always starts off its commands with capital letters, so you should be reasonably safe by using lowercase letters in your definitions.  If you want to use capital letters, then use more than one letter for the variable name...  For instance, the following is simply a formula (made up of course) which involved three dependent variables, which correlate to interest, principle, and time of loan.  As such, the variables are clear in their definition:

NumPay[int_, princ_, time_]:=princ*E^(int*time);

NumPay[0.05,10000,12]