Fortunately, it is possible for a Mathematica user to define new functions.
This is one of the key things that makes Mathematica less like a calculator and more
like a programming language. It is also what will make you less like a
calculator user and more like a programmer.
Let's begin with a simple example. Suppose that you'd like to have a function
called square that takes a number as an argument and returns its square
as its result (by convention, internal Mathematica functions start with a capital letter,
while user defined functions start with a lower case letter.
Here's how to do that in Mathematica:
square[x_]:= x*x;
Now you can use the function square just as if it were built in. Here's
one example of its use; you should experiment with others.
square[5]
The definition of the square function may look funny to you. We are using
assignment to name the function square. The x_ symbol is what
tells Mathematica that we are defining a function of the variable x.
When you use a user-defined function, Mathematica takes the argument that you provide
(5 in the example above), substitutes it for the parameter (x) throughout the
body of the function (x*x), yielding an expression (5*5), which it then
evaluates as usual (producing 25 in the example above).
Try writing a function called cube that takes one argument and returns
its cube. Try it out to make sure it works. When you're done,
congratulations! Ð you've just written a program.
Now let's return to our original problem. We'd like to have a function called
compound that will calculate compound interest. So let's define one:
compound[p_, r_, n_] := p*(1+r)^n;
There's one extra complication here. The function compound takes three
arguments instead of one, which requires listing all three of the parameters
as shown. Now to calculate the consequences of investing $100 at .05 interest
for 50 years, we need only do:
compound[100, .05, 50]
See if you can use the compound function to answer the following
questions involving compound interest.
(1) If you invest $1000 at 6% interest right now, how much will it be worth
in 40 years?
(2) What if you invest it at 12% for 20 years?