Libraries, clients, prin/

Similar documents
The Command Shell, Libraries and Clients, Formatted Printing. Fundamentals of Computer Science

2.2 Libraries and Clients

Sta$cs and forma.ng numbers

BASIC INPUT/OUTPUT. Fundamentals of Computer Science

CS 112 Introduction to Programming

Functions (or Static Methods) (Spring 2012)

Static methods. Not actually a valid Java static method. Fundamentals of Computer Science Keith Vertanen

2.1 Functions. x y. f (x, y, z) A Foundation for Programming. Functions (Static Methods)

1.1 Basic Programming Model 1.2 Data Abstrac9on

6. Functions and Libraries

6. Functions and Libraries

Classes and objects. Chapter 2: Head First Java: 2 nd Edi4on, K. Sierra, B. Bates

Condi(onals and Loops

COMPUTER SCIENCE. Computer Science. 5. Functions and Libraries. Computer Science. An Interdisciplinary Approach

JVM (java) compiler. A Java program is either a library of static methods (functions) or a data type definition

Modules and Clients 1 / 21

Objec+ves. Review. Basics of Java Syntax Java fundamentals. What are quali+es of good sooware? What is Java? How do you compile a Java program?

Primitive Data, Variables, and Expressions; Simple Conditional Execution

Outline. 1 Using Functions in Other Programs. 2 Modular Programming Abstractions. 3 Random Numbers. 4 List Processing. 5 Standard Statistics 1 / 21

Built-in data types. logical AND logical OR logical NOT &&! public static void main(string [] args)

Programming Language Basics

Built-in data types. public static void main(string [] args) logical AND logical OR logical NOT &&! Fundamentals of Computer Science

CSCI 135 Exam #1 Fundamentals of Computer Science I Fall 2012

Math Modeling in Java: An S-I Compartment Model

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

CMSC 150 INTRODUCTION TO COMPUTING LAB WEEK 3 STANDARD IO FORMATTING OUTPUT SCANNER REDIRECTING

Lecture 5: Methods CS2301

Performance. CSCI 135: Fundamentals of Computer Science Keith Vertanen. h"p://

CS110D: PROGRAMMING LANGUAGE I

COMP 110 Programming Exercise: Simulation of the Game of Craps

More on methods and variables. Fundamentals of Computer Science Keith Vertanen

1 class Lecture5 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

Conditionals, Loops, and Style. Control flow thus far. if statement. Control flow. Common branching statement Evaluate a boolean expression

Conditionals, Loops, and Style

A Foundation for Programming

Chapter 4 Classes in the Java Class Libraries

More on variables, arrays, debugging

CONDITIONAL EXECUTION

M e t h o d s a n d P a r a m e t e r s

COSC 243. Data Representation 3. Lecture 3 - Data Representation 3 1. COSC 243 (Computer Architecture)

History of Java. Java was originally developed by Sun Microsystems star:ng in This language was ini:ally called Oak Renamed Java in 1995

CCHAPTER SELECTION STATEMENTS HAPTER 3. Objectives

Introduction to Computer Science Unit 2. Notes

Topics. The Development Process

COS 126 Exam Review. Exams overview Example programming exam Example written exam questions (part 1)

2.1 Functions. f (x, y, z)

Nested Loops. A loop can be nested inside another loop.

printf( Please enter another number: ); scanf( %d, &num2);

Variables and data types

M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

A Founda4on for Programming

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

CS 139 Practice Midterm Questions #2

CHAPTER 7 OBJECTS AND CLASSES

A foundation for programming. Classes and objects. Overview. Java primitive types. Primitive types Creating your own data types

MODULE 02: BASIC COMPUTATION IN JAVA

Remedial Java - Excep0ons 3/09/17. (remedial) Java. Jars. Anastasia Bezerianos 1

Lec 3. Compilers, Debugging, Hello World, and Variables

Exercise (Revisited)

Midterm Examination (MTA)

STUDENT LESSON A7 Simple I/O

The Math Class. Using various math class methods. Formatting the values.

Basic Operations jgrasp debugger Writing Programs & Checkstyle

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

1001ICT Introduction To Programming Lecture Notes

Introduction to Programming Using Java (98-388)

Introduction to C An overview of the programming language C, syntax, data types and input/output

Topic 6: A Quick Intro To C. Reading. "goto Considered Harmful" History

Building Java Programs

Introduction to Computer Science Unit 2. Notes

CSCI 135 Exam #0 Fundamentals of Computer Science I Fall 2013

Topic 6: A Quick Intro To C

Pace University. Fundamental Concepts of CS121 1

DATA TYPES AND EXPRESSIONS

Review for Test 1 (Chapter 1-5)

Simple Java Reference

Inf1-OOP. Data Types. Defining Data Types in Java. type value set operations. Overview. Circle Class. Creating Data Types 1.

Formatting Output & Enumerated Types & Wrapper Classes

CSE 303 Lecture 8. Intro to C programming

Section 2.2 Your First Program in Java: Printing a Line of Text

Exercise. Write a program which allows the user to enter the math grades one by one (-1 to exit), and outputs a histogram.

Generic programming POLYMORPHISM 10/25/13

Chapter 5 C Functions

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

Functions. x y z. f (x, y, z) Take in input arguments (zero or more) Perform some computation - May have side-effects (such as drawing)

Variables, Types, Operations on Numbers

Chapter 5 Methods. public class FirstMethod { public static void main(string[] args) { double x= -2.0, y; for (int i = 1; i <= 5; i++ ) { y = f( x );

Programming Languages and Techniques (CIS120)

AP CS Unit 3: Control Structures Notes

Garbage collec,on Parameter passing in Java. Sept 21, 2016 Sprenkle - CSCI Assignment 2 Review. public Assign2(int par) { onevar = par; }

Getting started with Java

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++

Formatted Output Pearson Education, Inc. All rights reserved.

4. Java Project Design, Input Methods

Programming Languages and Techniques (CIS120)

Decisions: Logic Java Programming 2 Lesson 7

Transcription:

Libraries, clients, prin/ Fundamentals of Computer Science Keith Vertanen Copyright 2013

A founda8on for programming any program you might want to write objects func2ons and modules graphics, sound, and image I/O build bigger programs and reuse code h?p://www.flickr.com/photos/vermegrigio/5923415248/ arrays condi8onals and loops Math primi8ve data types text I/O assignment statements 2

Programs thus far Problems with one big main(): Doesn't scale to complex programs OOen find ourselves repea8ng similar code public class DiceRolling public static void main(string [] args) int rolls = 0; int sum = 0; int target = (int) (Math.random() * 12) + 2; "Repeated code is evil!" System.out.println("Rolling dice until I get " + target + "."); do int dice1 = (int) (Math.random() * 6) + 1; int dice2 = (int) (Math.random() * 6) + 1; sum = dice1 + dice2;... 3

Calling our new method Use handy new method in DiceRolling Add somewhere inside public class 's public class DiceRolling public static int getrandomnum(int start, int end) return (int) (Math.random() * (end - start + 1)) + start; public static void main(string [] args) int rolls = 0; int sum = 0; int target = getrandomnum(1, 12); System.out.println("Rolling dice until I get " + target + "."); do int dice1 = getrandomnum(1, 6); int dice2 = getrandomnum(1, 6); sum = dice1 + dice2;... 4

Calling our new method Alterna8ve: put method in new class Allows us to create a class with a bunch of helper methods (just like StdIn.java, StdDraw.java) public class RandomUtil // Return random integer in [start, end] inclusive public static int getrandomnum(int start, int end) return (int) (Math.random() * (end - start + 1)) + start; // Return random integer in [0, end] inclusive public static int getrandomnum(int end) return (int) (Math.random() * (end + 1)); getrandomint() is overloaded: Two methods with same name, but different signatures (e.g. different number of parameters) 5

Using our new class Put RandomUtil.java in same directory Methods qualified with RandomUtil. in front public class DiceRolling public static void main(string [] args) int rolls = 0; int sum = 0; int target = RandomUtil.getRandomNum(2, 12); System.out.println("Rolling dice until I get " + target + "."); do int dice1 = RandomUtil.getRandomNum(1, 6); int dice2 = RandomUtil.getRandomNum(1, 6); sum = dice1 + dice2; System.out.println(dice1 + " + " + dice2 + " = " + sum); rolls++; while (sum!= target); System.out.println("It took " + rolls + " rolls."); 6

Libraries Library A module whose methods are primarily intended for use by many other programs Client API Program that calls a library Applica8on Programming Interface Contract between client and implementa8on Implementa8on Program that implements the methods in an API 7

Random numbers 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. Jon von Neumann (lec), ENIAC (right) 8

9

"QRBG121 is a fast non- determinis8c random bit (number) generator whose randomness relies on intrinsic randomness of the quantum physical process of photonic emission in semiconductors and subsequent detec8on by photoelectric effect. In this process photons are detected at random, one by one independently of each other. Timing informa8on of detected photons is used to generate random binary digits - bits. The unique feature of this method is that it uses only one photon detector to produce both zeros and ones which results in a very small bias and high immunity to components varia8on and aging. Furthermore, detec8on of individual photons is made by a photomul8plier (PMT). Compared to solid state photon detectors the PMT's have dras8cally superior signal to noise performance and much lower probability of appearing of aoerpulses which could be a source of unwanted correla8ons." h?p://qrbg.irb.hr 10

Standard random Standard Random Library to generate pseudo- random numbers Applica8on Programming Interface (API): 11

Standard random, implementa8on 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() /* see Exercise 1.2.27 */ // gaussian with given mean and stddev public static double gaussian(double mean, double stddev) return mean + (stddev * gaussian()); 12

Unit tes8ng Include main() to test each library public static void main(string[] args) int N = Integer.parseInt(args[0]); if (args.length == 2) StdRandom.setSeed(Long.parseLong(args[1])); double[] t =.5,.3,.1,.1 ; StdOut.println("seed = " + StdRandom.getSeed()); 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.println(); % java StdRandom 5 seed = 1349544048443 72 34.23045 false 8.86067 10 47.24745 true 8.83698 65 35.25313 true 9.28941 17 34.37725 false 9.56543 52 90.80849 false 8.84883 % java StdRandom 5 seed = 1349544178256 18 23.68569 false 8.85914 71 70.97195 false 8.71287 17 93.72297 false 9.14421 24 93.54278 false 9.48963 41 52.23556 false 9.10782 These "random" numbers are the same as the first run! % java StdRandom 5 1349544048443 seed = 1349544048443 72 34.23045 false 8.86067 10 47.24745 true 8.83698 65 35.25313 true 9.28941 17 34.37725 false 9.56543 52 90.80849 false 8.84883 13

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); Use library name to invoke the method 14

Modular Programming Modular programming Divide program into self- contained pieces. Test each piece individually. Combine pieces to make program. Example: Flip N coins. How many heads? Read arguments from user. Flip one fair coin. Flip N fair coins and count number of heads. Repeat simula8on, coun8ng number of 8mes each outcome occurs. Plot histogram of empirical results. Compare with theore8cal predic8ons. 15

Bernoulli Trials 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; flip N fair coins; 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)]++; perform T trials of N coin flips each double[] normalized = new double[n+1]; for (int i = 0; i <= N; i++) normalized[i] = (double) freq[i] / T; StdStats.plotBars(normalized); plot histogram of number of heads 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); theore8cal predic8on 16

Dependency Graph Modular programming Build rela8vely complicated program by combining several small, independent, modules. 17

Pre?y text formalng prinm- style formalng Common way to nicely format output Present in many programming languages Java, C++, Perl, PHP,... Use a special format language: Format string with special codes One or more variables get filled in In Java, used via: System.out.printf() output to standard out String.format() returns a forma?ed String 18

double d = 0.123456789; float f = 0.123456789f; Floa8ng- point formalng // %f code is used with double or float variables // %f defaults to rounding to 6 decimal places System.out.printf("d is about %f\n", d); System.out.printf("f is about %f\n", f); \n means line feed d is about 0.123457 f is about 0.123457 // Number of decimal places specified by.x // Output is rounded to that number of places System.out.printf("PI is about %.1f\n", Math.PI); System.out.printf("PI is about %.2f\n", Math.PI); System.out.printf("PI is about %.3f\n", Math.PI); System.out.printf("PI is about %.4f\n", Math.PI); // %e code outputs in scientific notation //.X specifies number of significant figures final double C = 299792458.0; System.out.printf("speed of light = %e\n", C); System.out.printf("speed of light = %.3e\n", C); PI is about 3.1 PI is about 3.14 PI is about 3.142 PI is about 3.1416 C = 2.99792e+08 C = 2.998e+08 19

Integer formalng // %d code is for integer values, int or long // Multiple % codes can be used in a single printf() long power = 1; for (int i = 0; i < 8; i++) System.out.printf("%d = 2^%d\n", power, i); power = power * 2; You can have mul8ple % codes that are filled in by a list of parameters to prinm() // A number after the % indicates the minimum width // Good for making a nice looking tables of values power = 1; for (int i = 0; i < 8; i++) System.out.printf("%5d = 2^%d\n", power, i); power = power * 2; Minimum width of this field in the output. Java will pad with whitespace to reach this width (but can exceed this width if necessary). 1 = 2^0 2 = 2^1 4 = 2^2 8 = 2^3 16 = 2^4 32 = 2^5 64 = 2^6 128 = 2^7 1 = 2^0 2 = 2^1 4 = 2^2 8 = 2^3 16 = 2^4 32 = 2^5 64 = 2^6 128 = 2^7 20

Flags // Same table, but left justify the first field power = 1; for (int i = 0; i < 8; i++) System.out.printf("%- 5d = 2^%d\n", power, i); power = power * 2; - flag causes this field to be leo jus8fied 1 = 2^0 2 = 2^1 4 = 2^2 8 = 2^3 16 = 2^4 32 = 2^5 64 = 2^6 128 = 2^7 // Use commas when displaying numbers power = 1; for (int i = 0; i < 17; i++) System.out.printf("%,5d = 2^%d\n", power, i); power = power * 2;, flag causes commas between groups of 3 digits 1 = 2^0 2 = 2^1 4 = 2^2 8 = 2^3 16 = 2^4 32 = 2^5 64 = 2^6 128 = 2^7 256 = 2^8 512 = 2^9 1,024 = 2^10 2,048 = 2^11 4,096 = 2^12 8,192 = 2^13 16,384 = 2^14 32,768 = 2^15 65,536 = 2^16 21

Text formalng // Characters can be output with %c, strings using %s String name = "Bill"; char grade = 'B'; System.out.printf("%s got a %c in the class.\n", name, grade); Bill got a B in the class. // This prints the same thing without using printf System.out.println(name + " got a " + grade + " in the class."); An equivalent way to print the same thing out using good old println(). 22

Crea8ng forma?ed strings Forma?ed String crea8on You don't always want to immediately print forma?ed text to standard output Save in a String variable for later use // Formatted Strings can be created using format() String lines = ""; for (int i = 0; i < 4; i++) lines += String.format("Random number %d = %.2f\n", i, Math.random()); System.out.print(lines); Random number 0 = 0.54 Random number 1 = 0.50 Random number 2 = 0.39 Random number 3 = 0.64 23

The format specifier Which argument to use in this slow (not as commonly used). Minimum number of character used, but if number is longer it won't get cut off %[argument number][flags][width][.precision]type Special formalng op8ons like inser8ng commas, making leo jus8fied, etc. Sets the number of decimal places, don't forget the. Type is only required part of specifier. "d" for an integer, "f" for a floa8ng- point number. %[argument number][flags][width][.precision]type printf("%,6.1f", 42.0); 24

prinm gone wild Format string specifies: Number of variables to fill in Type of those variables Make sure format string agrees with arguments aoerwards Run8me error otherwise Compiler / Eclipse won't protect you // Runtime error %f expects a floating- point argument System.out.printf("crash %f\n", 1); // Runtime error, %d expects an integer argument System.out.printf("crash %d\n", 1.23); // Runtime error, not enough arguments System.out.printf("crash %d %d\n", 2); 25

prinm puzzler Code System.out.printf("%f", 4242.00); System.out.printf("%d", 4242); System.out.printf("%.2f", 4242.0); System.out.printf("%.3e", (double) 4242); System.out.printf("%,d", 4242); Le:er E A B C D Le:er Output A 4242 B 4242.00 C 4.242e+03 D 4,242 E 4242.000000 Code # System.out.printf("%d%d", 42, 42); 2 System.out.printf("%d+%d", 42, 42); 1 System.out.printf("%d %d", 42); 5 System.out.printf("%8d", 42); 3 System.out.printf("%- 8d", 42); 4 System.out.printf("%d", 42.0); 5 # Output 1 42+42 2 4242 3 42 4 42 5 runtime error 26

Summary Libraries Collec8on of useful methods for use by clients Implements a specific API Why? Makes code easier to understand Makes code easier to debug Makes code easier to maintain and improve Makes code easier to reuse Formalng output printf() method First parameter: specifies output format using % codes Variable number of other parameters Must match number and types of "slots" in the format specifier 27