Introduction to Functions

Math 213 - Math with Mathematica
Christopher Hanusa

Overview

In this tutorial, we ease into getting Mathematica to do what we want it to do, by creating user-defined functions.  We will visit a few sources along the way, which are useful for more than just learning about functions.

Wolfram’s “Fast Introduction”

Visit: http://www.wolfram.com/language/fast-introduction-for-programmers/function-definitions/
Complete the two sections on Function Definitions and Pure Functions.  Follow the tutorials, then answer the “Check your understanding” multiple choice quizzes at the bottom of the page.  If you are confused about an incorrect answer, then talk to your classmates or instructor.

Hazrat’s “Mathematica: A Problem-Centered Approach”

Visit: http://link.springer.com.queens.ezproxy.cuny.edu:2048/book/10.1007/978-1-84996-251-3  (If you are off-campus, you will have to log in using your QC library card.)
Download Chapter 2: Defining functions, and read Pages 19 through the top of 21 and then the bottom of Page 23 through Page 24.

1. Explore Problem 2.1 on page 21 (A worked example) by trying it in this notebook. What happens if you nest the f function more times?  What coefficients appear?  Do you see a pattern?

2. Complete Exercise 2.3 on page 24.  Write a sentence explaining what each command does.  You may want to experiment or use the Documentation Center.

Chapter 2 of Discovering Mathematics with Mathematica: The 3x+1 problem

Read page 19.
We will be investigating two more mathematical questions in Chapter 2.  The first question is that of the 3x+1 problem.  This problem is set up as follows.  Start with any integer.  At each step, look at the integer and determine if it is even or odd.  If the number is even, divide by 2.  If the number is odd, multiply by three and add 1.  What can we learn about this sequence?

We will learn how to program a function txp that does this calculation into Mathematica.  Before we get started, try by hand to understand how the function works by seeing what happens when you start with 2, 3, 5, or 6.
(Why did I not ask about 4?)

Important Concept: Q

The computer will need to determine if the number you give it is even or odd.  
Look at the top of page 20.  The function EvenQ is one of many Mathematica functions that ask a question (Q).  When you evaluate a number, EvenQ determines if the number is even or not.  Enter the next cell.

EvenQ[3]
EvenQ[4]
EvenQ[Sqrt[2]]

Go to the documentation center and search for `Q' and focus on the built-in commands that end in Q, especially on the second page of results.  You will get a good feel for all the sorts of questions you can ask Mathematica to determine if a variable satisfies a property or not.

Important Concept: If

The computer will not only need to be able to determine whether an input is even or odd, but will also need to be able to perform two different procedures depending on whether it is even or odd.  We will use the command If to do this.  The syntax for If is:

?If

That is, you type If[condition,expression1,expression2], and Mathematica will first check the condition.  If the condition is true, then it will do expression1; otherwise it will do expression2.
Evaluate the following cells and see if you understand what is going on.  If you don't, then ask a classmate and discuss.

If[True,3,5]

If[IntegerQ[Pi],4,100]

Table[If[PrimeQ[n],1,0],{n,1,10}]

Table[If[PrimeQ[n],Print[n]],{n,1,10}];

The txp function

On page 20, the function txp is defined, as well as the function tf which evaluates the function txp multiple times and outputs a list of the successive evaluations.  Define these functions in a new cell and try out a few values to confirm that they work well.

Concept Check: Complete Exercises 2.1 and 2.2 here.

3. Exercise 2.1

4. Exercise 2.2

Important Concept: While loops and negation (!)

Read through to the middle of page 21.  You will see that we will be replacing the function tf above by a function tg that only evaluates the function txp as many times as it takes to make it back to 1.  
To do this, you will be using a While loop.  The syntax for While is:

?While

That is, you type While[condition,expressions], and Mathematica will check the condition, and if it evaluates to True, it will evaluate the expressions.  One of the expressions will change variables in the condition.  Then While will check the condition again and evaluate the expressions and continue until the condition evaluates to False.  Also, just as == checks if two quantities are equal, != checks if two quantities are unequal.  Read each of the following cells and guess what you expect to see before evaluating them.

xx=7;
While[xx≥4,xx=xx-1;]
xx

yy=3;  
While[PrimeQ[yy],yy=yy+2;]
yy

zz=10;
L2 = {};  (* Define an empty list *)
While[zz!=19,L2=Append[L2,zz]; zz=zz+1;]  (* Append inserts an element into a list *)
L2

You will also see the ! operator when you wish verify the negative of a quantity.

!True

!False

Comprehension Question

5. What is does this code do?  Why does it do that?

aa=90;  
While[!PrimeQ[aa],aa=aa+1;]
aa

Important Concept: Module

When you are creating more complicated functions, you will need to use the Module function.

?Module

As you can see in the explanation of Module, it helps to quarantine the variables that you only use in this function.  This type of variables are called local variables.  As you can see in the following computation, even if i is defined outside the Module, you can use i inside without worrying about contamination.  It is good practice to define your functions in such a way that any variables you only use in your function are defined as local variables.

i=10;
Print["Outside Module, i is ",i]
Module[{i=20},Print["Inside Module, i is ",i]]
Print["Outside Module, i is ",i]

Comprehension Questions:

In this section we will see what we can do with the modified 3x+1 functions tg and th.

6. Define here the functions tg and th as included on page 21 of the book, and verify that they give the outputs you expect.  Which of the programs is faster?  Which do you prefer?

7. Complete Exercise 2.3.

8. Complete Exercise 2.4.

9. Complete Exercise 2.5.

10. Complete Exercise 2.6.

Introduction: The Digit Cube Sum problem for multiples of three.

The second problem that we investigate in Chapter 2 is the digit cube sum problem.  This problem is based upon another process that we iterate multiple times.  The idea is described at the top of page 23.  We will be implementing this problem with the function dcs.  As with the 3x+1 problem, start out working by hand, applying the digit cube sum process repeatedly to 156.

VICs: Very Important Concepts:  Apply and Map

We will want to cube each digit of n.  We first use the function IntegerDigits to break apart n into a list of its digits.

Digits=IntegerDigits[156]

Mathematica even knows what we mean when we cube a list.

Digits^3

Apply

But now we have to add the entries of the list.  We could do it manually, but we'd like Mathematica to do it automatically.  To do this, we'll use the Apply operator.  Ask for help to see the syntax:

?Apply

What Apply[function,list] does for us is to take the function and apply the function to the entire list.

Apply[Plus,Digits]

Apply[Times,Digits]

Map

A related command is the Map command.  Ask for help to see the syntax:

?Map

What Map[function,list] does for us is to take the function and apply the function to each entry of the list individually and return the results in a list.  So even if Mathematica weren't able to understand Digits^3, we could use Map to do the same thing.

Map[Function[x,x^3],Digits]

In fact, you will need to use Map when your functions are more complicated, such as the txp function from before.  You can see txp does not apply directly to a list, but you can use Map to apply it to each entry of the list.

txp[{2,3}]

Map[txp,Digits]

Putting it all together

So to get the computer to do the Digit Cube Sum calculations, we'll need to define the command dcs:

dcs[x_]:=Apply[Plus,(IntegerDigits[x])^3]

Verify that dcs works by iterating it, starting with 156.

Comprehension Questions

Use what you learned from the 3x+1 problem to create similar types of functions related to the digit cube sum problem.

11. Complete Exercise 2.9.

12. Complete Exercise 2.10.

13. Complete Exercise 2.11.