DOC PREVIEW
UVA CS 101 - Recap of Functions

This preview shows page 1-2-24-25 out of 25 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 25 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 25 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 25 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 25 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 25 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

Recap of FunctionsFunctions in JavaAnatomy of a Java FunctionCall by ValueScopeImplementing Mathematical Functions Gaussian DistributionGaussian DistributionJava Function for (x)Gaussian Cumulative Distribution FunctionJava function for (z)Building Functions2.2 Libraries and ClientsLibrariesDr. Java Demo Creating a Library to Print ArraysKey Points to RememberRandom Numbers Part of stdlib.jarStandard RandomStatistics Part of stdlib.jarStandard StatisticsModular ProgrammingModular Programming Coin FlippingBernoulli TrialsEXTRA SLIDESSlide 24Slide 25Recap of FunctionsFunctions in Javafxyzf (x, y, z)InputOutputAlgorithm•Allows you to clearly separate the tasks in a program.•Enables reuse of code3Anatomy of a Java FunctionJava functions. Easy to write your own.f(x) = xinput2.0 1.414213…output4Call by ValueFunctions provide a new way to control the flow of execution.Call by Reference - Arrays5Scopepublic 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 differentvariables withthe same name iscope of cscope of epsilonscope of tImplementing Mathematical FunctionsGaussian Distribution7Gaussian 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.810601 1019122814378Java 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-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; }}9Gaussian 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)zTaylor series10Java 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 0.5 + sum * phi(z); } public static double Phi(double z, double mu, double sigma) { return Phi((z - mu) / sigma); } }accurate with absolute errorless than 8 * 10-1611Building FunctionsFunctions enable you to build a new layer of abstraction.Takes you beyond pre-packaged libraries.You build the tools you need by writing your own functionsProcess. Step 1: identify a useful feature.Step 2: implement it.Step 3: use it in your program.Step 3': re-use it in any of your programs.2.2 Libraries and ClientsIntroduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008 · 1/14/19 1/14/1913LibrariesLibrary. A module whose methods are primarily intended for useby many other programs.Client. Program that calls a library.API. Contract between client andimplementation.Implementation. Program thatimplements the methods in an API.Link toJAVAMath APIDr. Java DemoCreating a Library to Print ArraysIntroduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008 · 1/14/19 1/14/19Key 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 program15Random NumbersPart of stdlib.jarJon 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.”“17Standard RandomStandard random. Our library to generate pseudo-random numbers.StatisticsPart of stdlib.jar19Standard StatisticsEx. Library to compute statistics on an array of real numbers.mean sample varianceModular Programming21Modular ProgrammingCoin FlippingModular programming.Divide program into self-contained pieces.Test each piece individually.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.Read arguments from user.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.22public 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 Trialstheoretical predictionplot histogramof number of headsperform T trialsof N coin flips eachflip N fair coins;return # headsEXTRA SLIDES24public 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


View Full Document

UVA CS 101 - Recap of Functions

Documents in this Course
Classes

Classes

53 pages

Recursion

Recursion

15 pages

Iteration

Iteration

88 pages

PLEDGED

PLEDGED

6 pages

Objects

Objects

33 pages

PLEDGED

PLEDGED

11 pages

CS 101

CS 101

42 pages

Classes

Classes

83 pages

Iteration

Iteration

92 pages

Classes

Classes

186 pages

Classes

Classes

208 pages

Hardware

Hardware

21 pages

Arrays

Arrays

70 pages

Load more
Download Recap of 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 Recap of 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 Recap of 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?