Mathematical Applications · BE5B15MAA · Topic 10 of 13
Functions in Mathematica: piecewise functions, overloaded functions, tracing the evaluation
Week 10. One symbol can have several definitions; conditions pick between them and Trace shows what happened.
Key ideas
Conditions and piecewise definitions
A condition /; restricts a rule: f[x_]:=x/;x<=1 and f[x_]:=2−x^2/;x>1 make a piecewise function. Which[x<1,x,x>=1,2−x^2] and Piecewise do the same in one expression. Conditional rules can also call themselves, for example to extend a function periodically: f[x_]:=f[x−2]/;x>1.
Overloaded definitions
Several definitions of f can coexist. They differ by the number of arguments (f[x_] and f[x_,y_]), by a list pattern (f[{x_,y_}]), by a type (f[x_Integer]) or by a literal (f[1]). Mathematica tries the more specific definitions first, and keeps the order of definition among definitions it cannot rank.
Tracing and memoization
Trace[a[3]] lists the steps of an evaluation. The recursive definition a[n_]:=n*a[n−1] with a[0]:=1 recomputes everything on every call and may hit $RecursionLimit; a[n_]:=a[n]=n*a[n−1] stores each value the first time it is computed (memoization), so Timing[Table[a[i],{i,1050}]] becomes fast.
In one line: Order your definitions from specific to general, and memoize a recursion with f[n_]:=f[n]=....
Sources
Written by Ucenly. Based on the BE5B15MAA course materials:
- Course card BE5B15MAA (Bílá kniha), p. 1
- Seminar notebook, state of 28 Mar 2019 (seminar2832019.nb), text extract, p. 1
- Seminar 1 notebook, 21 Feb 2019 (seminar1_21_02_19.nb), text extract, p. 1
- Introduction to Wolfram Mathematica (Intro_Wm.nb inside Intro_WM.rar), text extract, p. 1
- Lecture notebook 2017 (englMAA2017-1.nb), text extract, p. 1