Mathematica
Tutor
Part 7:
Functions
- Next we define a
function to assign the value 10 sin x to each x.
Enter
x=.
f[x_]:=10*Sin[x]
and then
f[1]
(Note the "_" (underscore) character which appears only on the
left of the second command, and the extra colon.) You may be
surprised to see
10
Sin[1]
rather than a
decimal approximation. To obtain a decimal approximation,
enter
N[10*Sin[1]]
The command "N" stands for "numerical value."
You should notice two
important things here:
- Functions that are
built into Mathematica always start with capital letters.
Functions that you define can start with either capital or
lower-case letters.
- The arguments of
functions in Mathematica are always enclosed in square
brackets, not parentheses as you might expect. Parentheses in
Mathematica are used only to indicate the grouping of
terms.
- To be sure that
the action of N is clear, enter
103751/2053
and then
N[103751/2053]
- An alternate way
of forcing Mathematica to return a decimal approximation
to f[1] is to enter
f[1.0]
- Note that
Mathematica distinguishes between a function and an
expression. Enter
g[x]=10*Sin[x]
Then enter
g[1]
followed by
g[x]
The symbols g[x] stand for the expression, not the
function. Try the same thing with
g[x]:=10*Sin[x]
(Colon, but no underscore.) You should get almost the same
results. Leaving out the underscore when you define a function is
a common source of problems when using Mathematica.
- Let's evaluate
f at pi/6. First, we need the value of pi.
Enter
Pi
Alter this line to read
N[Pi]
Now find a
decimal approximation to f(pi/6).
- Find a decimal
approximation to each of the following: f(2) and
f(pi/3).