Prepare: Functions in Mathematica

MATH 242 Modern Computational Mathematics

Run the following code before class on Wednesday, February 11. Then answer the preparation question for February 11 on Moodle.

Here is how to code the function f(x)=(x^2) in Mathematica.

f[x_]:=x^2

Note the underscore following the x inside of the square brackets: this tells Mathematica that the x is a placeholder for anything value that you put into the function.
Also note the := operator, which indicates a delayed assignment statement. This means that we don’t want to evaluate (x^2) using the current value of x, but we want to evaluate (x^2) each time f[x] is called.

We can plot the function like this:

Plot[f[x],{x,-1,1}]

Let's use our function to make a list of squares. Recall that Table creates a list.

squares=Table[f[n],{n,3,20}]

We can also define functions with more than one variable. Here is g(x,n)=(x^n).

g[x_,n_]:=x^n

To try this out, let’s make a of functions, each with a different exponent. Note that we don’t have to use the variable n for the exponent; the following code uses k instead.

functions=Table[g[x,k],{k,1,10}]

Now plot our list of functions:

Plot[functions,{x,0,1},PlotRange->{{0,1},{0,1}}]