190 likes | 221 Views
2.1 Functions. Functions in Mathematics. x. f. y. f ( x, y, z ). z. Range. Domain. Functions in Computer Science. x. f. y. f ( x, y, z ). z. Output. Input. Algorithm. Allows you to clearly separate the tasks in a program. Enables reuse of code. Functions (Static Methods).
E N D
Functions in Mathematics x f y f (x, y, z) z Range Domain
Functions in Computer Science x f y f (x, y, z) z Output Input Algorithm • Allows you to clearly separate the tasks in a program. • Enables reuse of code
Functions (Static Methods) • Java function. • Takes zero or more input arguments. • Returns zero or one output value. • public static void main(String args[]) • 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(). • Princeton I/O libraries: StdIn.readInt(), StdDraw.line(), StdAudio.play(). • User-defined functions: main().
Writing Functions in Java • Java functions. Easy to write your own. f(x) = x output input 2.0 1.414213… Numerically Computing a Square-Root: Newton-Raphson Method
The Newton-Raphson Algorithm • To Compute Square Root of Positive Number c: • { • t = c; //initial estimate of square-root • while(square-root of c is not found) { • if(t == c/t) found square-root of x; • else t = Average of t and c/t; • } • }
Function to calculate Square Root using Newton-Raphson Method f(x) = x output input 2.0 1.414213…
Functions • Overloading: • Different argument types • Different number of arguments • Different return value is NOT overloading overloading multiple arguments
Flow of Control • Key point. Functions provide a new way to control the flow of execution.
Flow of Control • Key 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 calling code. • Control transfers back to the calling code. • Note. This is known as “pass/call by value.”
Can a Function Alter Its Arguments? • The short answer for Java: Only if the argument is an array! • (Later we’ll see that objects are like arrays in this way.) • Call by Value. • The argument-variable defined in the function signature is like a local variable inside the function. • A copy of the value of the actual argument is copied into the argument-variable when its called • Changes made to the argument-variable inside the function do not update anything back in the “caller”. • Call by Reference. • The argument-variable defined in the function signature refers to the same data variable that’s passed when the function is called. • Changes made to the argument-variable inside the function do update the variable in the “caller”.
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); } } } scope of c scope of epsilon scope of t two differentvariables withthe same name i
Why Are Functions An Important Concept / Technique? Good Software Design. • Problem-solving: from large problems to smaller sub-problems. • Easier to understand solutions to smaller sub-problems. • Easier to test smaller sub-problems. • We can re-use sub-problem solutions (functions). • 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); }
Function Challenge 1a • Q. What happens when you compile and run the following code? publicclass Cubes1 { public staticint 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)); } } % javac Cubes1.java % java Cubes1 6 1 1 2 8 3 27 4 64 5 125 6 216
Function Challenge 1b • Q. What happens when you compile and run the following code? publicclass Cubes2 { public staticint 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)); } } Compiler error: i is already defined
Function Challenge 1c • Q. What happens when you compile and run the following code? publicclass Cubes3 { public staticint 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)); } } Compiler error: missing return statement
Function Challenge 1d • Q. What happens when you compile and run the following code? publicclass Cubes4 { public staticint 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)); } } Correct: the i in cube() and the i in main() are different
Function Challenge 1e • Q. What happens when you compile and run the following code? publicclass Cubes5 { public staticint cube(int i) { returni * 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)); } } Correct and preferred style