|
There are usually many ways to attack a problem using Mathematica. As a case study, we consider the definition of a function f to calculate $n!$, the factorial of an integer $n$.
Notes:
- In each section, we use Clear[f] to remove the earlier definition of f.
- We use ?f to reveal each definition of f.
1. Set the name f equal to the built-in factorial function
- Clear[f]
- f = Factorial
- ?f
- f[5]
复制代码
2. Define the function f using the built-in factorial function !
- Clear[f]
- f[n_] := n!
- ?f
- f[5]
复制代码
3. Define f using a different built-in function, the gamma function
- Clear[f]
- f[n_] := Gamma[n + 1]
- ?f
- f[5]
复制代码
4. Define $n!$ as the product of integers up to $n$
- Clear[f]
- f[n_] := Product[i, {i, n}]
- ?f
- f[5]
复制代码
5. Define $n!$ recursively
The function is automatically called repeatedly since in appears on the right side of the equation definition. The value $n=1$ is a special case (and is necessary to stop the recursion!); it is given in a separate statement.
The semicolon separates two statements (and suppresses the output from the first).
- Clear[f]
- f[n_] := n f[n - 1]; f[1] = 1
- ?f
- f[5]
复制代码
6. Use an If statement to include the case $n=1$ in the recursive definition
We can read the definition as "If $n=1$, then $f[n]$ equals 1, else $f[ n]$ equals $n$ time $f[n-1]$."
Note the double equal signs == used to make comparisons.
- Clear[f]
- f[n_] := If[n == 1, 1, n f[n - 1]]
- ?f
- f[5]
复制代码
7. Write a little program using a Do loop
The local variable $t$ is declared in the first {}'s and initialized to 1. The Do loop runs through values of $i$ from 1 to $n$ and at each step multiplies the old value of $t$ by $i$ and sets this to be the new value of $t$. The final $t$ means to return the value of $t$ at the end.
- Clear[f]
- f[n_] := Module[{t = 1}, Do[t = t*i, {i, n}]; t]
- ?f
- f[5]
复制代码
8. Write a little C-style program using a For loop
The local variables are $t$ and $i$, and $t$ is initialized to 1. The For loop starts with $i=1$ and continues as long as $i$ is less than or equal to $n$. After each step, $i$ is increased by 1 (this is what i++ does), and the value of $t$ is multiplied by $i$ and then stored again in $t$ (this is what t*=i does). Finally, the value of $t$ is returned.
- Clear[f]
- f[n_] := Module[{t = 1, i}, For[i = 1, i <= n, i++, t *= i]; t]
- ?f
- f[5]
复制代码
9. Make a list of integers up to $n$, then use Apply and Times to multiply them
Note that we can use @@ as an operator instead of Apply in the usual function form.
- Clear[f]
- f[n_] := Apply[Times, Range[n]]
- ?f
- f[5]
复制代码
10. Make a list of integers up to $n$, then use Apply and Times to multiply them
- Clear[f]
- f[n_] := Fold[Times, 1, Range[n]]
- ?f
- f[5]
复制代码
11. For the experts!
Can you figure out how this works?
- Clear[f]
- f = If[#1 == 1, 1, #1 #0[#1 - 1]] &
- ?f
- f[5]
复制代码
12. Also for the experts!
Can you figure out how this works?
- Clear[f]
- f[n_] := Fold[#2[#1]&,1,Array[Function[t,# t]&,n]]
- ?f
- f[5]
复制代码 |
|