21 Function
21 Function
1 Functions
Copyright 20022010
2/17/11 9:58 PM
2.1 Functions
x
y
z
f (x, y, z)
any program you might want to write objects functions and modules graphics, sound, and image I/O arrays conditionals and loops Math primitive data types text I/O assignment statements
3
Applications. Scientists use mathematical functions to calculate formulas. Programmers use functions to build modular programs. You use functions for both.
Examples. Built-in functions: Math.random(), Math.abs(), Integer.parseInt(). Our I/O libraries: StdIn.readInt(), StdDraw.line(), StdAudio.play(). User-defined functions: main().
2.0
input
f(x) = x
output
1.414213
Flow of Control
Key point. Functions provide a new way to control the flow of execution.
Flow of Control
Key point. Functions provide a new way to control the flow of execution. What happens when a function is called: Control transfers to the function code. Argument variables are assigned the values given in the call. Function code is executed. Return value is assigned in place of the function name in calling code. Control transfers back to the calling code.
Scope
Scope (of a name). The code that can refer to that name. Ex. A variable's scope is code following the declaration in the block.
Function Challenge 1a
Q. What happens when you compile and run the following code?
public class Cubes1 { public static int cube(int i) { int j = i * i * i; return j; } public static void main(String[] args) { int N = Integer.parseInt(args[0]); for (int i = 1; i <= N; i++) StdOut.println(i + " " + cube(i)); } } % % 1 2 3 4 5 6 javac Cubes1.java java Cubes1 6 1 8 27 64 125 216
9
Function Challenge 1b
Q. What happens when you compile and run the following code?
public class Cubes2 { public static int cube(int i) { int i = i * i * i; return i; } public static void main(String[] args) { int N = Integer.parseInt(args[0]); for (int i = 1; i <= N; i++) StdOut.println(i + " " + cube(i)); } }
10
Function Challenge 1c
Q. What happens when you compile and run the following code?
public class Cubes3 { public static int cube(int i) { i = i * i * i; } public static void main(String[] args) { int N = Integer.parseInt(args[0]); for (int i = 1; i <= N; i++) StdOut.println(i + " " + cube(i)); } }
11
Function Challenge 1d
Q. What happens when you compile and run the following code?
public class Cubes4 { public static int cube(int i) { i = i * i * i; return i; } public static void main(String[] args) { int N = Integer.parseInt(args[0]); for (int i = 1; i <= N; i++) StdOut.println(i + " " + cube(i)); } }
12
Function Challenge 1e
Q. What happens when you compile and run the following code?
public class Cubes5 { public static int cube(int i) { return i * i * i; } public static void main(String[] args) { int N = Integer.parseInt(args[0]); for (int i = 1; i <= N; i++) StdOut.println(i + " " + cube(i)); } }
13
Gaussian Distribution
Gaussian Distribution
Standard Gaussian distribution. "Bell curve." Basis of most statistical analysis in social and physical sciences.
Ex. 2000 SAT scores follow a Gaussian distribution with mean = 1019, stddev = 209.
601
810
( x) =
1 2
e x
/2
( x , , ) =
1 2
e ( x )
/ 2 2
( )/
x
15
( x) =
1 2
e x
/2
public static double phi(double x) { return Math.exp(-x*x / 2) / Math.sqrt(2 * Math.PI); } public static double phi(double x, double mu, double sigma) { return phi((x - mu) / sigma) / sigma; } ( x, , ) = ( x ) /
Overloading. Functions with different signatures are different. Multiple arguments. Functions can take any number of arguments. Calling other functions. Functions can call other functions.
library or user-defined
16
( x) =
(z)
1 2
e x
/2
z
Taylor series
SAT Scores
Q. NCAA requires at least 820 for Division I athletes. What fraction of test takers in 2000 do not qualify? A. (820, 1019, 209) 0.17051. [approximately 17%]
area = 0.17
601
810
19
Gaussian Distribution
Q. Why relevant in mathematics? A. Central limit theorem: under very general conditions, average of a set of random variables tends to the Gaussian distribution. Q. Why relevant in the sciences? A. Models a wide range of natural phenomena and random processes. Weights of humans, heights of trees in a forest. SAT scores, investment returns.
Caveat.
Tout Everybody le monde believes y croit incependent, the exponential car les law exprimenteurs of errors: thes'imaginent experimenters, because que c'est they think un it thorem can be proved de mathmatiques, by mathematics; et les and mathmaticiens the mathematicians, que because c'est believe they un fait exprimental. it has been established
by observation.
M. Lippman in a letter to H. Poincar
20
Building Functions
Functions enable you to build a new layer of abstraction. Takes you beyond pre-packaged libraries. You build the tools you need: Gaussian.phi(),
Process. Step 1: identify a useful feature. Step 2: implement it. Step 3: use it.
21
Digital Audio
23
Digital Audio
Sampling. Represent curve by sampling it at regular intervals.
audio CD
24
public static double[] tone(double hz, double seconds) { int SAMPLE_RATE = 44100; int N = (int) (seconds * SAMPLE_RATE); double[] a = new double[N+1]; for (int i = 0; i <= N; i++) { a[i] = Math.sin(2 * Math.PI * i * hz / SAMPLE_RATE); } 2 i hz return a; y(i) = sin } 44,100
25
26
Harmonics
Concert A with harmonics. Obtain richer sound by adding tones one octave above and below concert A.
880 Hz 220 Hz 440 Hz
27
Harmonics
public class PlayThatTuneDeluxe { // return weighted sum of two arrays public static double[] sum(double[] a, double[] b, double awt, double bwt) { double[] c = new double[a.length]; for (int i = 0; i < a.length; i++) c[i] = a[i]*awt + b[i]*bwt; return c; } // return a note of given pitch and duration public static double[] note(int pitch, double duration) { double hz = 440.0 * Math.pow(2, pitch / 12.0); double[] a = tone(1.0 * hz, duration); double[] hi = tone(2.0 * hz, duration); double[] lo = tone(0.5 * hz, duration); double[] h = sum(hi, lo, .5, .5); return sum(a, h, .5, .5); } public static double[] tone(double hz, double t) // see previous slide public static void main(String[] args) // see next slide }
28
Harmonics
Play that tune. Read in pitches and durations from standard input, and play using standard audio.
public static void main(String[] args) { while (!StdIn.isEmpty()) { int pitch = StdIn.readInt(); double duration = StdIn.readDouble(); double[] a = note(pitch, duration); StdAudio.play(a); } }
29
30