2.1 Functions. f x y z f (x, y, z) 3 Functions (Static Methods) Java function. n Takes zero or more input arguments. n Returns one output value. Applications.

Slides:



Advertisements
Similar presentations
2.1 Program Construction In Java
Advertisements

Modular Programming With Functions
Probability Distributions CSLU 2850.Lo1 Spring 2008 Cameron McInally Fordham University May contain work from the Creative Commons.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Chapter 5 Methods to our madness. Review Identifiers are names used for variables, constants, methods, classes, and packages. Must start with a letter,
Methods Liang, Chapter 4. What is a method? A method is a way of running an ‘encapsulated’ series of commands. System.out.println(“ Whazzup ”); JOptionPane.showMessageDialog(null,
Introduction to Computers and Programming Introduction to Methods in Java.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
Classes, methods, and conditional statements We’re past the basics. These are the roots.
COMP 14 Introduction to Programming Mr. Joshua Stough February 28, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
CS 201 Functions Debzani Deb.
Probability Distributions Random Variables: Finite and Continuous A review MAT174, Spring 2004.
1 Chapter 5 Methods. 2 Introducing Methods A method is a collection of statements that are grouped together to perform an operation.
Lecture 5: Modular Programming (functions – part 1 BJ Furman 27FEB2012.
CompSci 100E Gambler's Ruin  One approach. Monte Carlo simulation.  Flip digital coins and see what happens. o Pseudorandom number generation ojava.util.Random.
10/25: Methods & templates Return to concepts: methods Math class methods 1 st Program of the day About DrawLine.java modifications Method definitions.
METHODS Introduction to Systems Programming - COMP 1005, 1405 Instructor : Behnam Hajian
Statistics for Data Miners: Part I (continued) S.T. Balke.
Sullivan – Fundamentals of Statistics – 2 nd Edition – Chapter 11 Section 1 – Slide 1 of 34 Chapter 11 Section 1 Random Variables.
The Rectangle Method. Introduction Definite integral (High School material): A definite integral a ∫ b f(x) dx is the integral of a function f(x) with.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
Ch4 Data Types Every value has a type associated with it. The computer needs to know how much memory to allocate. Every value is either a primitive type.
CSE 131 Computer Science 1 Module 1: (basics of Java)
2.1 Functions Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008 · October 21, 2015.
Introduction to Behavioral Statistics Probability, The Binomial Distribution and the Normal Curve.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Methods (a.k.a. Functions)
Working with arrays (we will use an array of double as example)
First Programs CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Lecture 5 Methods. Sometimes we want to perform the same sequence of operations multiple times in a program. While loops allow us to do this, they are.
2.1 Functions Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008 · 9/10/08 9/10/08.
CompSci 100E Functions (Static Methods)  Java function.  Takes zero or more input arguments.  Returns one output value.  Applications.  Scientists.
Recap of Functions. Functions in Java f x y z f (x, y, z) Input Output Algorithm Allows you to clearly separate the tasks in a program. Enables reuse.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
Essential Statistics Chapter 91 Introducing Probability.
2.2 Libraries and Clients Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008 · December.
Chapter 10 Introducing Probability BPS - 5th Ed. Chapter 101.
Chapter 3 Top-Down Design with Functions Part II J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National.
Random Variable The outcome of an experiment need not be a number, for example, the outcome when a coin is tossed can be 'heads' or 'tails'. However, we.
Computer simulation Sep. 9, QUIZ 2 Determine whether the following experiments have discrete or continuous out comes A fair die is tossed and the.
The Math Class Methods Utilizing the Important Math Operations of Java!
CS-I MidTerm Review Hao Jiang Computer Science Department Boston College.
CompSci 100e2.1 Today’s Topics l Reading:  Sedgewick & Wayne: , l Topics  APTs  Basic Collections: ArrayLists: the expandable array.
2.1 Functions. Functions in Mathematics f x y z f (x, y, z) Domain Range.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
Probability Theory Modelling random phenomena. Permutations the number of ways that you can order n objects is: n! = n(n-1)(n-2)(n-3)…(3)(2)(1) Definition:
Simple algorithms on an array - compute sum and min.
1 Chapter 10 Probability. Chapter 102 Idea of Probability u Probability is the science of chance behavior u Chance behavior is unpredictable in the short.
CSE 1030: Implementing Static Features Mark Shtern.
int [] scores = new int [10];
Chapter 8: Probability: The Mathematics of Chance Probability Models and Rules 1 Probability Theory  The mathematical description of randomness.  Companies.
Lecture 6: Methods MIT-AITI Kenya © 2005 MIT-Africa Internet Technology Initiative In this lecture, you will learn… What a method is Why we use.
Programming Fundamentals Enumerations and Functions.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 24, 2009.
2.4 A Case Study: Percolation Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008.
The normal approximation for probability histograms.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 6 Methods.
13-5 The Normal Distribution
Chapter 6: Methods CS1: Java Programming Colorado State University
Chapter 5 - Functions Outline 5.1 Introduction
Functions Declarations CSCI 230
Week 9 – Audio Processing
Data types, assignment statements, and math functions allow you to compute You write a sequence of statements that tell the computer what needs to be done.
Chapter 5 Methods.
AP Statistics Chapter 16 Notes.
Introduction to Computer Science I.
Chapter 6: Methods CS1: Java Programming Colorado State University
Presentation transcript:

2.1 Functions

f x y z f (x, y, z)

3 Functions (Static Methods) Java function. n Takes zero or more input arguments. n Returns one output value. Applications. n Scientists use mathematical functions to calculate formulas. n Programmers use functions to build modular programs. n 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().

4 Anatomy of a Java Function Java functions. Easy to write your own. f(x) =  x input … output

5 Functions overloading multiple arguments

6 Flow of Control Flow of control. Functions provide a new way to control the flow of execution of a program. "pass-by-value"

Demo Use the Debugger to step through a program like Coupon.java (p. 197) n See how StepOver and StepInto are different 7

8 Why Are Functions An Important Concept / Technique? Good Software Design. n Problem-solving: from large problems to smaller sub-problems. n Easier to understand solutions to smaller sub-problems. n Easier to test smaller sub-problems. n We can re-use sub-problem solutions (functions). n Hide details from rest of design. (Example: sqrt. Do we care how it’s done inside function?) Abstraction. Reducing or factoring out details so that one can focus on a few important concepts // Two functions for getting random values // between 0 and N-1 public static int randomVal (int N) { return (int) (Math.random() * N); } // between a and b, i.e. in range [a,b) public static double randomVal(double a, double b) { return a + Math.random() * (b-a); }

9 Functions: An Example of the Concept of Abstraction An important concept in computing: Abstraction n Reducing or factoring out details so that one can focus on a few important concepts at a time n Often we give an abstraction a name. n Giving something a name is an important part of abstraction – I can refer to it. We understand it. We agree on it. – Often in a programming language, we can design code using the abstraction-name StdDraw.setPenColor(StdDraw.BLACK); StdDraw.filledCircle(rx, ry, radius); java.util.Arrays.sort(intArray); java.util.Arrays.equals(array1, array2);

10

11 Scope Scope. Set of statements that can refer to that name. n Scope of a variable defined within a block is limited to the statements in that block. n Best practice: declare variables to limit their scope. public class Scope { 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)); } two variables named i are independent % java Scope including function block

Can a Function Alter Its Arguments? The short answer for Java: Only if the argument is an array! n (Later we’ll see that objects are like arrays in this way.) Call by Value. n The argument-variable defined in the function signature is like a local variable inside the function. n A copy of the value of the actual argument is copied into the argument-variable when its called n Changes made to the argument-variable inside the function do not update anything back in the “caller”. Call by Reference.. n The argument-variable defined in the function signature refers to the same data variable that’s passed when the function is called. n Changes made to the argument-variable inside the function do update the variable in the “caller”. 12

Gaussian Distribution

14 Gaussian Distribution Standard Gaussian distribution. n "Bell curve." n Basis of most statistical analysis in social and physical sciences. Ex SAT scores follow a Gaussian distribution with mean  = 1019, stddev  =

15 Java Function for  (x) 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; }

16 Gaussian Cumulative Distribution Function 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 Taylor series

17 Java function for  (z) public class Gaussian { public static double phi(double x) // as before public static double Phi(double z) { if (z < -8.0) return 0.0; if (z > 8.0) return 1.0; double sum = 0.0, term = z; for (int i = 3; sum + term != sum; i += 2) { sum = sum + term; term = term * z * z / i; } return sum * phi(z); } public static double Phi(double z, double mu, double sigma) { return Phi((z - mu) / sigma); } accurate with absolute error less than 8 *

Comment on Good Coding Style n Our textbook author’s are not following good coding style with these function names! – Phi() and phi() only differ by case of first letter – Easily mis-read or mis-typed – Industry-accepted Java convention is that all function (method) names start with lower-case n So: don’t do this at home! n Better name? – phiCDF() // phi cumulative distribution function – phiCumulative() // ?? – ??? 18

19 SAT Scores Q. NCAA requires at least 820 for Division I athletes. What fraction of test takers in 2000 do not qualify? A.  (820, ,  )  [approximately 17%] area = double fraction = Gaussian.Phi(820, 1019, 209);

20 Tout le monde y croit cependent, car les expérimenteurs s'imaginent que c'est un théorem de mathématiques, et les mathématiciens que c'est un fait expérimental. Everybody believes in the exponential law of errors: the experimenters, because they think it can be proved by mathematics; and the mathematicians, because they believe it has been established by observation. - M. Lippman in a letter to H. Poincaré Gaussian Distribution Q. Why relevant in mathematics? A. Central limit theorem: under very general conditions, average of a set of variables tends to the Gaussian distribution. Q. Why relevant in the sciences? A. Models a wide range of natural phenomena and random processes. n Weights of humans, heights of trees in a forest. n SAT scores, investment returns. Caveat.

21 Building Functions Functions enable you to build a new layer of abstraction. n Takes you beyond pre-packaged libraries. You build the tools you need: Gaussian.phi(), … Process. n Step 1: identify a useful feature. n Step 2: implement it. n Step 3: use it. n Step 3': re-use it in any of your programs.

2.2 Libraries and Clients

23 Libraries Library. A module whose methods are primarily intended for use by many other programs. Client. Program that calls a library. API. Contract between client and implementation. Implementation. Program that implements the methods in an API.

Random Numbers Jon von Neumann (left), ENIAC (right) The generation of random numbers is far too important to leave to chance. Anyone who considers arithmetical methods of producing random digits is, of course, in a state of sin. ” “

25 Standard Random Standard random. Our library to generate pseudo-random numbers.

26 public class StdRandom { // between a and b public static double uniform(double a, double b) { return a + Math.random() * (b-a); } // between 0 and N-1 public static int uniform(int N) { return (int) (Math.random() * N); } // true with probability p public static boolean bernoulli(double p) { return Math.random() < p; } // gaussian with mean = 0, stddev = 1 public static double gaussian() // recall lab work // gaussian with given mean and stddev public static double gaussian(double mean, double stddev) { return mean + (stddev * gaussian()); }... } Standard Random

27 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 true false true true false Unit Testing Unit test. Include main() to test each library.

28 Using a Library 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 use library name to invoke method

29 Using a Library To use the standard random library: Put a copy of StdRandom.java in current directory. n Write a client program that uses it. public class LoadedDie { public static void main(String args[]) { int N = Integer.parseInt(args[0]); double[] p = { 0,.1,.1,.1,.1,.1,.5 }; for (int i = 0; i < N; i++) { int die = StdRandom.discrete(p); System.out.print(die + " "); } % javac LoadedDie.java % java LoadedDie % chance of 6, 10% chance of 1-5 automatically compiles StdRandom.java if needed

Statistics

31 Standard Statistics Ex. Library to compute statistics on an array of real numbers. meansample variance

32 public class StdStats { public static double max(double[] a) { double max = Double.NEGATIVE_INFINITY; for (int i = 0; i < a.length; i++) if (a[i] > max) max = a[i]; return max; } public static double mean(double[] a) { double sum = 0.0; for (int i = 0; i < a.length; i++) sum = sum + a[i]; return sum / a.length; } public static double stddev(double[] a) // see text } Standard Statistics Ex. Library to compute statistics on an array of real numbers.

Modular Programming

34 Modular Programming Modular programming. n Divide program into self-contained pieces. n Test each piece individually. n Combine pieces to make program. Ex. Flip N coins. How many heads? n Read arguments from user. n Flip one fair coin. n Flip N fair coins and count number of heads. n Repeat simulation, counting number of times each outcome occurs. n Plot histogram of empirical results. n Compare with theoretical predictions.

35 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); } Bernoulli Trials theoretical prediction plot histogram of number of heads perform T trials of N coin flips each flip N fair coins; return # heads

36 Dependency Graph Modular programming. Build relatively complicated program by combining several small, independent, modules.

37 Libraries Why use libraries? n Makes code easier to understand. n Makes code easier to debug. n Makes code easier to maintain and improve. n Makes code easier to reuse.

38

Digital Audio

40 Crash Course in Sound Sound. Perception of the vibration of molecules in our eardrums. Concert A. Sine wave, scaled to oscillated at 440Hz. Other notes. 12 notes on chromatic scale, divided logarithmically. frequency

41 Digital Audio Sampling. Represent curve by sampling it at regular intervals. audio CD

42 Musical Tone Function Musical tone. Create a music tone of a given frequency and duration. Remark. Can use arrays as function return value and/or argument. public static double[] tone(double hz, double seconds) { int SAMPLES_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); } return a; }

43 Digital Audio in Java Standard audio. Library for playing digital audio. Concert A. Play concert A for 1.5 seconds using StdAudio. double[] a = tone(440, 1.5); StdAudio.play(a);

44 Harmonics Concert A with harmonics. Obtain richer sound by adding tones one octave above and below concert A. 880 Hz 220 Hz 440 Hz

45 Harmonics 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 = * 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 }

46 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); }

47

Unused slides follow 48

49 Discrete Distribution Discrete distribution. Given an array of weights (that sum to 1), choose an index at random with probability equal to its weight. public static int discrete(double[] p) { // check that weights are nonnegative and sum to 1 double r = Math.random(); double sum = 0.0; for (int i = 0; i < p.length; i++) { sum = sum + p[i]; if (sum >= r) return i; } return -1; } something went wrong p = { 0,.1,.1,.1,.1,.1,.5 }