DOC PREVIEW
Princeton COS 126 - Functions

This preview shows page 1-2-3 out of 9 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 9 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 9 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 9 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 9 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

2.1 Functionsfxyzf (x, y, z)A Foundation for Programmingobjectsfunctions and modulesgraphics, sound, and image I/Oarraysconditionals and loopsMath text I/Oassignment statementsprimitive data typesany program you might want to writebuild bigger programsand reuse codeFunctions (Static Methods)Java function.•Takes zero or more input arguments.•Returns zero or one output value.•May cause 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 thanmathematical functionsAnatomy of a Java FunctionJava functions. Easy to write your own.f(x) = !xinput2.0 1.414213…outputpublic class Gambler { public static void main(String[] args) { int stake = Integer.parseInt(args[0]); int goal = Integer.parseInt(args[1]); int trials = Integer.parseInt(args[2]); . . . . . .} Mumbojumbo Demystification, Part 2Flow of ControlKey point. Functions provide a new way to control the flow of execution.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); } }}Flow of ControlKey point. Functions provide a new way to control the flow of execution.Summary of 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 the calling code.•Control transfers back to the calling code.Note. This technique (standard in Java) is known as “pass by value”. other languages may use different methodsScopeScope (of a name). The code that can refer to that name.Def. A variable’s scope is code following the declaration in its block.Best practice: declare variables so as 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++) System.out.println(sqrt(a[i])); }}two different variableswith the same name ieach with two lines of scopescope of cscope of epsilonscope of tscope of aFunction Call Tracepublic 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++) System.out.println(sqrt(a[i])); }}Functions Challenge 1What 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)); }}Functions Challenge 2What 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)); }}Functions Challenge 3What 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)); }}Functions Challenge 4What 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)); }}Functions Challenge 5What 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)); }}Example: Gaussian DistributionGaussian DistributionStandard Gaussian distribution.•"Bell curve."•Basis of most statistical analysis in social and physical sciences.Ex. 2000 SAT scores follow a Gaussian distribution withmean µ = 1019, stddev " = 209.! "(x) =12#e$ x2/ 2810601 101912281437 ! "(x,µ,#) =1#2$e%(x%µ)2/ 2#2 = "x %µ#( )/#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 oruser-definedpublic 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; }}! "(x) =12#e$ x2/ 2! "(x,µ,#) = "x $µ#( )/#Gaussian Cumulative Distribution FunctionGoal. 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! "(x) =12#e$ x2/ 2Taylor seriesJava function for $(z)public class Gaussian{


View Full Document

Princeton COS 126 - Functions

Download Functions
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Functions and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Functions 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?