






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
An introduction to java functions, their usage, and the flow of control. It covers topics such as static methods, scope, and examples of function overloading and multiple arguments. The document also includes challenges to test your understanding of java functions.
Typology: Slides
1 / 12
This page cannot be seen from the preview
Don't miss anything!







Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008 · February 22, 2009 3:08 AM 2
build bigger programs and reuse code
4
Java function. Takes zero or more input arguments. Returns one output value. Side effects (e.g., output to standard draw). 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(). more general than mathematical functions
5
Java functions. Easy to write your own. f ( x ) = √ x input
output 6
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. Best practice: declare variables to limit their scope. public class Newton { public static double sqrt(double c) { double epsilon = 1e-15; if (c < 0 ) return Double.NaN; double t = c; while (Math.abs(t - c/t) > epsilon * t) t = (c/t + t) / 2.0; return t; } public static void main(String[] args) { double[] a = new double[args.length]; for (int i = 0 ; i < args.length; i++) a[i] = Double.parseDouble(args[i]); for (int i = 0 ; i < a.length; i++) { double x = sqrt(a[i]); StdOut.println(x); } } } scope of i scope of c scope of epsilon scope of t scope of another^ scope of^ a variable i 7
Key point. Functions provide a new way to control the flow of execution. 8
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. Note. This is known as “pass by value.”
13
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)); } } 14
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)); } } Gaussian Distribution 16
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.
"( x ) = (^12) # e $^ x^ (^2) / 2 601 810 1019 1228 1437
= " (^) ( x^ % #^ μ) / # docsity.com
17
Mathematical functions. Use built-in functions when possible; build your own when not available. 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 public class Gaussian { 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; } }
(^2) / 2 ! " ( x , μ, # ) = " (^) ( x^ $ #^ μ) / # 18
Goal. Compute Gaussian cdf Φ(z). Challenge. No "closed form" expression and not in Java library. Bottom line. 1,000 years of mathematical formulas at your fingertips. Φ(z) z
(^2) / 2 Taylor series 19
accurate with absolute error less than 8 * 10- !
20
Q. NCAA requires at least 820 for Division I athletes. What fraction of test takers in 2000 do not qualify? A. Φ(820, μ, σ) ≈ 0.17051. [approximately 17%] 601 810 1019 1228 1437 area = 0. 820
docsity.com
25
Sampling. Represent curve by sampling it at regular intervals. audio CD ! y ( i ) = sin 2 "^ #^ i^ #^440 44 , 100
26
Musical tone. Create a music tone of a given frequency and duration. Remark. Can use arrays as function return value and/or argument.
y ( i ) = sin 2 "^ #^ i^ #^ hz 44 , 100
27
Standard audio. Library for playing digital audio. Concert A. Play concert A for 1.5 seconds using StdAudio.
28
Concert A with harmonics. Obtain richer sound by adding tones one octave above and below concert A. 880 Hz 220 Hz 440 Hz
29
public class PlayThatTune { // 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 } 30
Play that tune. Read in pitches and durations from standard input, and play using standard audio.
31 2.2 Libraries and Clients Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008 · February 22, 2009 3:09 AM
6 public class StdRandom { ... public static void main(String[] args) { int N = Integer.parseInt(args[ 0 ]); double[] t = {. 5 ,. 3 ,. 1 ,. 1 }; for (int i = 0 ; i < N; i++) { StdOut.printf(" %2d " , uniform( 100 )); StdOut.printf("%8.5f ", uniform(10.0, 99.0)); StdOut.printf("%5b " , bernoulli(. 5 )); StdOut.printf("%7.5f ", gaussian(9.0,. 2 )); StdOut.printf("%2d " , discrete(t)); StdOut.println(); } } } % java StdRandom 5 61 21.76541 true 9.30910 0 57 43.64327 false 9.42369 3 31 30.86201 true 9.06366 0 92 39.59314 true 9.00896 0 36 28.27256 false 8.66800 1
Unit test. Include main() to test each library. 7
public class RandomPoints { public static void main(String args[]) { int N = Integer.parseInt(args[ 0 ]); for (int i = 0 ; i < N; i++) { double x = StdRandom.gaussian(0.5, 0.2); double y = StdRandom.gaussian(0.5, 0.2); StdDraw.point(x, y); } } } % javac RandomPoints.java % java RandomPoints 10000 use library name to invoke method Statistics 9
Ex. Library to compute statistics on an array of real numbers. mean sample variance
10
Ex. Library to compute statistics on an array of real numbers. Modular Programming 12
Modular programming. Divide program into self-contained pieces. Test each piece individually. Combine pieces to make program. Ex. Flip N coins. How many heads? Read arguments from user. Flip one fair coin. Flip N fair coins and count number of heads. Repeat simulation, counting number of times each outcome occurs. Plot histogram of empirical results. Compare with theoretical predictions. 13 public class Bernoulli { public static int binomial(int N) { int heads = 0 ; for (int j = 0 ; j < N; j++) if (StdRandom.bernoulli(0.5)) heads++; return heads; } public static void main(String[] args) { int N = Integer.parseInt(args[ 0 ]); int T = Integer.parseInt(args[ 1 ]); int[] freq = new int[N+ 1 ]; for (int i = 0 ; i < T; i++) freq[binomial(N)]++; double[] normalized = new double[N+ 1 ]; for (int i = 0 ; i <= N; i++) normalized[i] = (double) freq[i] / T; StdStats.plotBars(normalized); double mean = N / 2.0, stddev = Math.sqrt(N) / 2.0; double[] phi = new double[N+ 1 ]; for (int i = 0 ; i <= N; i++) phi[i] = Gaussian.phi(i, mean, stddev); StdStats.plotLines(phi); } }
theoretical prediction plot histogram of number of heads perform T trials of N coin flips each flip N fair coins; return # heads