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.

Slides:



Advertisements
Similar presentations
2.1 Program Construction In Java
Advertisements

Modular Programming With Functions
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Introduction to Computers and Programming Lecture 11: Introduction to Methods Professor: Evan Korth New York University.
Introduction to Computers and Programming Introduction to Methods in Java.
Chapter 6: User-Defined Functions I
Math class methods & User defined methods Introduction to Computers and Programming in JAVA: V
© 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.
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.
Chapter 6: User-Defined Functions I
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Introduction to Methods
CompSci 100E Gambler's Ruin  One approach. Monte Carlo simulation.  Flip digital coins and see what happens. o Pseudorandom number generation ojava.util.Random.
METHODS Introduction to Systems Programming - COMP 1005, 1405 Instructor : Behnam Hajian
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
Statistics for Engineer Week II and Week III: Random Variables and Probability Distribution.
Dale Roberts Procedural Programming using Java Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer and.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 6 Value- Returning Functions and Modules.
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.
1.1 Your First Program Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008 · October.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
CSE 131 Computer Science 1 Module 1: (basics of Java)
JAVA 0. HAFTA Algorithms FOURTH EDITION Robert Sedgewick and Kevin Wayne Princeton University.
Chapter 3: Developing Class Methods Object-Oriented Program Development Using Java: A Class-Centered Approach.
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.
2.1 Functions Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008 · October 21, 2015.
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.
Procedural programming in Java Methods, parameters and return values.
CompSci 100E 3.1 Random Walks “A drunk man wil l find his way home, but a drunk bird may get lost forever”  – Shizuo Kakutani Suppose you proceed randomly.
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.
EAS31116/B9036: Statistics in Earth & Atmospheric Sciences Lecture 3: Probability Distributions (cont’d) Instructor: Prof. Johnny Luo
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
2.2 Libraries and Clients Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008 · December.
CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © Your First Java.
Methods. Methods also known as functions or procedures. Methods are a way of capturing a sequence of computational steps into a reusable unit. Methods.
1 Chapter 6 Methods. 2 Motivation Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.
1.2 Built-in Types of Data Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008 · December.
CompSci 100e2.1 Today’s Topics l Reading:  Sedgewick & Wayne: , l Topics  APTs  Basic Collections: ArrayLists: the expandable array.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
2.1 Functions. Functions in Mathematics f x y z f (x, y, z) Domain Range.
Introduction to array: why use arrays ?. Motivational example Problem: Write a program that reads in and stores away 5 double numbers After reading in.
Chapter 3: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
CompSci 100e2.1 1 N-Body Simulation l Applications to astrophysics.  Orbits of solar system bodies.  Stellar dynamics at the galactic center.  Stellar.
CompSci 100E 4.1 Google’s PageRank web site xxx web site yyyy web site a b c d e f g web site pdq pdq.. web site yyyy web site a b c d e f g web site xxx.
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.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 24, 2009.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 6 Methods Dr. Musab Zghoul.
2.4 A Case Study: Percolation Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
Chapter 6: User-Defined Functions I
Function Call Trace public class Newton {
Chapter 6 Methods: A Deeper Look
Chapter 5 - Functions Outline 5.1 Introduction
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Exam 2 Review 1.
Chapter 6 Methods: A Deeper Look
MSIS 655 Advanced Business Applications Programming
Group Status Project Status.
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 6 Methods.
Chapter 5 Methods.
Topics Introduction to Value-returning Functions: Generating Random Numbers Writing Your Own Value-Returning Functions The math Module Storing Functions.
Introduction to Computer Science I.
1/2555 สมศักดิ์ ศิวดำรงพงศ์
Chapter 6: Methods CS1: Java Programming Colorado State University
Presentation transcript:

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 of code

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

4 Call by Value Functions provide a new way to control the flow of execution. Call by Reference - Arrays

5 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. 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); } two different variables with the same name i scope of c scope of epsilon scope of t

Implementing Mathematical Functions Gaussian Distribution

7 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  =

8 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; }

9 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

10 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 *

11 Building Functions Functions enable you to build a new layer of abstraction. n Takes you beyond pre-packaged libraries. n You build the tools you need by writing your own functions Process. n Step 1: identify a useful feature. n Step 2: implement it. n Step 3: use it in your program. n Step 3': re-use it in any of your programs.

2.2 Libraries and Clients Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008 · November 23, :11 tt

13 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. Link to JAVA Math API

Dr. Java Demo Creating a Library to Print Arrays Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008 · November 23, :11 tt

Key Points to Remember Create a class file with all your functions Use the standard Save -> Compile sequence This class file does NOT have a main() function Use the name of the class to invoke methods in that library Can do this from any Java program 15

Random Numbers Part of stdlib.jar 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. ” “

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

Statistics Part of stdlib.jar

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

Modular Programming

21 Modular Programming Coin Flipping 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? Distribution of these coin flips is the binomial distribution, which is approximated by the normal distribution where the PDF has mean N/2 and stddev sqrt(N)/2. n Read arguments from user. 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.

22 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

EXTRA SLIDES

24 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 Assignment 0 // gaussian with given mean and stddev public static double gaussian(double mean, double stddev) { return mean + (stddev * gaussian()); }... } Standard Random

25 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.