SNU IDB Lab. 1 Great Ideas of CS with Java Part 1 WWW & Computer programming in the language Java Ch 1: The World Wide Web Ch 2: Watch out: Here comes Java Ch 3: Numerical computation & Function Ch 4: Subroutines & Databases Ch 5: Graphics Ch 6: Simulation Ch 7: Software engineering Part 2 Understanding what a computer is and how it works Ch 8: Machine architecture Ch 9: Language translation Ch 10: Virtual Environment for Computing Ch 11: Security, Privacy, and Wishful thinking Ch 12: Computer Communication Part 3 Advanced topics Ch 13: Program Execution Time Ch 14: Parallel Computation Ch 15: Noncomputability Ch 16: Artificial intelligence
SNU IDB Lab. 2 Ch 3. Numerical Computation and the Study of Functions Copyright © SNU IDB Lab.
SNU IDB Lab. 3 Table of contents Let’s Calculate Some Numbers Some Simple Calculations Looping and a Study of Functions Storing Information in Arrays Simple Statistics Program Design Putting Things on Array Summary
SNU IDB Lab. 4 Number crunching example Many situations like below Yearly bank interest rate: 5% & Your asset: $10000 You want to know how much you would earn after 20 years? Two obvious solutions Do it yourself using a calculator 20 times Write a program and let a machine find the answer. Solving optimization problems Find the best value for a parameter in some situation
SNU IDB Lab. 5 Figure 3.1 1,000 square cm of tin: How to make a largest possible cylindrical can? Solving optimization problems: Find the best value for a parameter in some situation Number crunching example
SNU IDB Lab. 6 Basic Java Facts: Variables and Data Types An object stores its state in variables (data member) Definition: A variable is an item of data named by an identifiervariable Variable declaration To give a variable a type and a name type variable-name (ex. Int varx) The Java programming language has two categories of data types: primitive and reference. reference A variable of primitive type contains a single value of the appropriate size and format for its type a number, a character, or a boolean value. For example an integer value is 32 bits of data in a format known as two's complement the value of a character is 16 bits of data formatted as a Unicode character
SNU IDB Lab. 7 Primitive Data Types in Java
SNU IDB Lab. 8 Basic Java Fact: Primitive Data Types You can put a literal primitive value directly in your code. For example int anInt = 4; A series of digits with no decimal point is typed as an integer You can specify a long integer by putting an 'L' or 'l' after the number 'L' is preferred as it cannot be confused with the digit '1 ‘ : (ex) 8864L A series of digits with a decimal point is of type float You can specify a float by putting an 'f' or 'F' after the number: (ex) 87.14F A literal character value is any single Unicode character between single quote marks (ex) ‘greeting’ The two boolean literals true and false
SNU IDB Lab. 9 Basic Java Fact: Reference Data Types Arrays, classes, and interfaces are reference typesreference The value of a reference type variable is a reference to the value or set of values represented by the variable A reference to the value == an address of the value A reference is called a pointer, or a memory address in other languages. The Java programming language does not support the explicit use of addresses like other languages do So, there is no pointer in Java Java use the variable's name instead. Int[] SampleArray;
SNU IDB Lab. 10 Basic Java Fact: “Final” Variables You can declare a variable in any scope to be finalfinal The value of a final variable cannot change after it has been initialized Such variables are similar to constants in other programming languages To declare a final variable, use the final keyword in the variable declaration before the type: final int aFinalVar = 0; You may defer initialization of a final local variable. Declare and initialize it later, like this: final int blankfinalsample;... blankfinalsample = 0; A final local variable that has been declared but not yet initialized is called a blank final.
SNU IDB Lab. 11 Java Fact on Floating Point Data Types Limitations of “int” data type 32bit (two’s complement) Minimum and maximum of int (-2,147,483,648 ~~ 2,147,483,647) “long” data type extends the range Cannot take on fractional values like The solution is using real numbers. Real numbers are specified with floating point ( 부동소수점 ) data type In Java, there are two data types in this category (float and double) float is single-precision floating point ( 단정도 실수 ) double is double-precision floating point ( 배정도 실수 ) FP(Floating Point) data type represents numbers in two parts significant digits and an exponent 177 might be represented as 1.77 * 10 2 in float data type
SNU IDB Lab. 12 Roundoff error in floating point numbers Even if we are using “double” data type, the following things still can happen! 64 bit representation is not enough for some cases An infinite decimal expansion: …… will not fit in a computer register Instead, will be stored More than 17 digit decimal number: is approximated by the computer to There are some tricks for the above cases, but,,,,,,,,, import java.math.BigDecimal (or import.java.math.BigInteger) BigDecimal bignum = new BigDecimal(" ")
SNU IDB Lab. 13 ErrorDemo program: a program for reading a number and printing the same number (1) Import awb.*; Import java.awt.*; Import java.awt.event.*; Public class ErrorDemo extends java.applet.Applet implements ActionListener { double data, extra; DoubleField dataF, extraF; Button b1; Public void init () { dataF = new DoubleField(20); dataF.setLabel(“Data”); extraF = new DoubleField(20); extraF.setLabel(“Extra”); b1 = new Button(“Compute”); b1.addActionListener(this); add(dataF); add(extraF); dataF.setDouble(0); extraF.setDouble(0); }
SNU IDB Lab. 14 ErrorDemo program: a program for reading a number and printing the same number (2) Public void actionPerformed(ActionEvent event) { object cause = event.getSource(); if (cause = b1) { data = dataF.getDouble(); extra = extraF.getDouble(); data = data + extra; data = data – extra; dataF.setDouble(data); }
SNU IDB Lab. 15 Result of the ErrorDemo program (p Table 3.1) data(Input)extra(Input)data(Output)
SNU IDB Lab. 16 Table of contents Let’s Calculate Some Numbers Some Simple Calculations Looping and a Study of Functions Storing Information in Arrays Simple Statistics Program Design Putting Things on Array Summary
SNU IDB Lab. 17 Two Special Classes for easy-handling Numbers only for this textbook (See appendix) ** These classes enable you to read and write int and double numbers easily in applets without having to deal with additional Java syntax. ** Put these into awb directory under your public html directory and then use the import awb.* command at the top of each program public class IntField extends TextField { public IntField(); public IntField(int size); public void setInt(int number); public int getInt(); } public class DoubleField extends TextField { public DoubleField(); public DoubleField(int size); public void setDouble(double num); public double getDouble(); }
SNU IDB Lab. 18 Calculating Cylinder Volume User puts values for radius and length of a cylinder Using DoubleField in example of calculating cylinder volume CylVol.java.java
SNU IDB Lab. 19 import awb.*; import java.awt.*; import java.awt.event.*; public class Numbers extends java.applet.Applet implements ActionListener { TextField instruct, result, mRadius, mLength; DoubleField gRadius, gLength; Button bCompute; double radius, length, cylVol, pi= ; public void init () { instruct = new TextField(72); instruct.setText("Please enter radius and length below."); mRadius = new TextField(9); mRadius.setText("radius:"); mLength = new TextField(9); mLength.setText("length:"); gRadius = new DoubleField(10); gLength = new DoubleField(10); result = new TextField(72); result.setText("The volume of the cylinder is: " + cylVol); bCompute = new Button("Compute"); bCompute.addActionListener(this); add(instruct) ; add(mRadius) ; add(gRadius) ; add(mLength) ; add(gLength) ; add(bCompute) ; add(result) ; } public void actionPerformed(ActionEvent event) { Object cause = event.getSource(); if (cause == bCompute) { length = gLength.getDouble(); radius = gRadius.getDouble(); cylVol = pi * radius * radius * length; result.setText("The volume of the cylinder is: " + cylVol); } CylVol.java
SNU IDB Lab. 20 Installment-based Purchase Calculation Suppose you are going to buy a car on the installment plan You want to know monthly payments by clicking a button Variables: principal, rate, payment, balance ButCompound.java Iteration by Button Pushing Often need to repeat a calculation with minor changes Sometimes refine previous solution Sometimes calculate successive values in series Can do this under control of a button
SNU IDB Lab. 21 import awb.*; import java.awt.*; import java.awt.event.*; public class ButCompound extends java.applet.Applet implements ActionListener { TextField mInstruct, mBalance; DoubleField gRate, gPrinc, gPay; IntField gMonths; Button bStart, bNextInstallment; double rate, princ, pay, balance; int months; public void init() { mInstruct = new TextField(80); mInstruct.setText("Enter principal, rate, payment, " + "then press Start"); gPrinc = new DoubleField(10); gRate = new DoubleField(10); gPay = new DoubleField(10); mBalance = new TextField(80); bStart = new Button("Start"); bNextInstallment = new Button("Next Installment"); bStart.addActionListener(this); bNextInstallment.addActionListener(this); add(mInstruct); add(gPrinc); add(gRate); add(gPay); add(bStart); add(bNextInstallment); add(mBalance); } public void actionPerformed(ActionEvent event) { Object cause = event.getSource(); if (cause == bStart) { princ = gPrinc.getDouble(); rate = gRate.getDouble()/12; pay = gPay.getDouble(); months = 0; balance = princ; mInstruct.setText("Press Next Installment for next Balance"); mBalance.setText("After " + months + " months at " + 100*rate*12 + "% and payments of " + pay + " the balance is " + balance); } if (cause == bNextInstallment) { months = months + 1; balance = balance*(1.0 + rate) - pay; mBalance.setText("After " + months + " months at " + 100*rate*12 + "% and payments of " + pay + " the balance is " + balance); } ButCompound.java
SNU IDB Lab. 22 Table of contents Let’s calculate some numbers Some Calculations Looping and a Study of Functions Storing Information in Arrays Simple Statistics Program Design Putting Things on Array Summary
SNU IDB Lab. 23 Java Control Flow Statements
SNU IDB Lab. 24 The Looping statements You use a while or do-while or for statement to continually execute a block of statements while a condition remains true.while The general syntax of the while statement is: while (expression) { statement(s) } Example: int sum = 0; int k = 0; while (k < 100) { k = k + 1; sum = sum + k; }
SNU IDB Lab. 25 The Looping Statements The general syntax of the do - while : do { statement(s) } while (expression); The for statement provides a compact way to iterate over a range of values. The general form of the for statement: for (initialization; termination; increment) { statement(s) }
SNU IDB Lab. 26 Searching the best value: CylinderVolumeMax Figure 3.1 1,000 square cm of tin: How to make a largest possible cylindrical can? Find such radius Find such volume
SNU IDB Lab. 27 Searching the best value: CylinderVolumeMax Volume V = Pi * r * r * h Area A = 2 * Pi * r * r + 2 * Pi * r * h = 1000 If we remove h from V V = 500 * r - Pi * r * r * r Start with r =1 cm Keep going by increasing r by 1 until V becomes maximum
SNU IDB Lab. 28 Figure 3.4
SNU IDB Lab. 29 Figure 3.5
SNU IDB Lab. 30 Figure 3.6
SNU IDB Lab. 31 CylinderVolumeMax Algorithm Set r at some starting value. Decide how much r should be increased each cycle Mostly given by the user Algorithm Initialize previous V at zero. Find V. Repeat the following: (1) if V < previousV, stop loop (2) increase r by some amount (3) save V in a place called “previousV”. (4) find V After looping, Previous V is supposed to have Max Volume
SNU IDB Lab. 32 import awb.*; import java.awt.*; import java.awt.event.*; public class CylinderVolumeMax extends java.applet.Applet implements ActionListener { double r, previousV, increase, V; DoubleField rF, increaseF, VF; Button b1; public void init () { rf = new DoubleField(20); rf.setLabel( “ Radius ” ); increaseF = new DoubleField(20); increaseF.setLabel( “ increase ” ); b1 = new Button( “ Compute ” ); b1.addActionListener(20); add(rF) ; add(increaseF) ; add(b1) ; add(VF) ; rF.setDouble(1.0); increaseF.setDouble(0.01); } CylinderVolumeMax.Java
SNU IDB Lab. 33 Pubic void actionPerformed(ActionEvent event) { Object cause = event.getSource(); if (cause == b1) { r = rF.getDouble(); increase = increaseF.getDouble(); previousV = 0; V = 500 * r – * r * r * r; while(V >= previousV) { r += increase; previousV = V; V = 500 * r – * r * r * r; } VF.setDouble(previousV); } CylinderVolumeMax.Java
SNU IDB Lab. 34 One last thing to consider in searching the best value! Local-Maxima Loophole
SNU IDB Lab. 35 Computing Interests CompInterest.java Wild Card Bonus (WCB-1)! Submit 5 page report explaining the following code Diamond.java Another Looping examples
SNU IDB Lab. 36 import awb.*; import java.awt.*; import java.awt.event.*; public class CompInterest extends java.applet.Applet implements ActionListener { TextField mInstruct, mBalance; DoubleField gRate, gPrinc, gPay; Button bCompute; IntField gMonths; double rate, princ, pay, balance; int months, k; public void init() { mInstruct = new TextField(80); mInstruct.setText("Enter principal, rate, payment, " + "#months; then press 'Compute'"); gPrinc = new DoubleField(10); gRate = new DoubleField(10); gPay = new DoubleField(10); gMonths = new IntField(10); bCompute = new Button("Compute"); mBalance = new TextField(80); bCompute.addActionListener(this); add(mInstruct); add(gPrinc); add(gRate); add(gPay); add(gMonths); add(bCompute); add(mBalance); } public void actionPerformed(ActionEvent event) { Object cause = event.getSource(); if (cause == bCompute) { princ = gPrinc.getDouble(); rate = gRate.getDouble()/12; pay = gPay.getDouble(); months = gMonths.getInt(); balance = princ; k = 0; while (k < months) { balance = balance*(1.0 + rate) - pay; k = k + 1; } mBalance.setText("After " + months + " months at " + 100*rate*12 + "% and payments of " + pay + " the balance is " + balance); } CompInterest.java
SNU IDB Lab. 37 import java.awt.*; import java.awt.event.*; public class Diamond extends java.applet.Applet implements ActionListener { TextField tf; TextArea ta; Button bDraw; String stars = "*******************"; String spaces = " "; int k; public void init() { tf = new TextField("Hello "); ta = new TextArea(22, 20); ta.setFont(new Font("Monospaced", Font.BOLD, 12)); bDraw = new Button("Draw"); bDraw.addActionListener(this); add(tf); add(bDraw); add(ta); } public void actionPerformed(ActionEvent event) { Object cause = event.getSource(); if (cause == bDraw) { tf.setText("Goodbye"); k = 0; while (k < 10) { ta.append(spaces.substring(0,10-k) + stars.substring(0,2*k+1)+"\n"); k = k + 1; } k = 1; while (k < 10) { ta.append(spaces.substring(0,1+k) + stars.substring(0,19-2*k)+"\n"); k = k + 1; } Diamond.java
SNU IDB Lab. 38 Table of contents Let’s calculate some numbers Some Calculations Looping and a Study of Functions Storing Information in Arrays Simple Statistics Program Design Putting Things on Array Summary
SNU IDB Lab. 39 Concept of Array Holds multiple values of the same type Aggregate Data Types: set, bag, list Deal with items of same type The length of an array is established when the array is created (at runtime) After creation, an array is a fixed-length structure
SNU IDB Lab. 40 Motivations of Arrays Analogies mailboxes in Post Office CD rack with slots Advantages Simplifies naming of similar objects Allows use of loops Useful for statistical problems and numerical problems The most fundament data structure in computer science for constructing other advanced data structures Many other kinds of data structures are built by “Array” List Matrix Stack Queue Binary Tree And so on
SNU IDB Lab. 41 Declaring an Array in Java int[] anArray; anArray = new int[10]; = int anArray[]; anArray = new int[10]; int anArray[10]; =
SNU IDB Lab. 42 Creating and using an Array To get the size of an array, you write arrayname.length This is a member-variable. Not a function (not length() ) ! int[] anArray; // declare an array of integers anArray = new int[10];// create an array of integers // assign a value to each array element for (int i = 0; i < anArray.length; i++) { anArray[i] = i; }
SNU IDB Lab. 43 Some more on Array shortcut syntax for creating and initializing an array. boolean[] answers = { true, false, true, true, false }; int[] primeNumsBelowTen = { 2, 3, 5, 7 }; Setting up an array Declaration: double weights[ ]; Definition: weights = new double[50]; Or Combined: double weights[ ] = new double[50];
SNU IDB Lab. 44 int num[ ] = new int[6]; ?????? num[1] = 21; num[5] = 13; ?21???13 Array Creation and Use int k = 2; while(k<6) { num[k] = k*k; k = k+1; } ? ** Real Array Example Hotel.javaHotel.java: A hotel has room[500] which are all “0” in the beginning. If a guest registers a particular room P, the value of room[p] is changed to the number of guests. Whenever a new guest registers a room, the message about the room occupancy comes up.
SNU IDB Lab. 45 import awb.*; import java.awt.*; import java.awt.event.*; public class Hotel extends java.applet.Applet implements ActionListener { TextField mInstruct, mHotelCensus; IntField gRoomNo, gNoGuests; Button bRegister; int k=0, totGuests = 0, noOccupied = 0, roomNo, noGuests; int room[]; public void init() { room = new int[500]; k = 0; while (k < 500) { room[k] = 0; k = k + 1; } mInstruct = new TextField(60); mInstruct.setText("Enter room number, number of guests, "+ "then press Register"); gRoomNo = new IntField(6); gNoGuests = new IntField(6); bRegister = new Button("Register"); mHotelCensus = new TextField(60); bRegister.addActionListener(this); add(mInstruct); add(gRoomNo); add(gNoGuests); add(bRegister); add(mHotelCensus); } public void actionPerformed(ActionEvent event) { Object cause = event.getSource(); if (cause == bRegister) { roomNo = gRoomNo.getInt(); noGuests = gNoGuests.getInt(); if (room[roomNo] != 0) { mHotelCensus.setText("That room is occupied!"); } else { room[roomNo] = noGuests; totGuests = totGuests + noGuests; noOccupied = noOccupied + 1; mHotelCensus.setText("There are " + totGuests + " occupying " + noOccupied + " rooms."); } Hotel.java
SNU IDB Lab. 46 Table of contents Let’s calculate some numbers Some Calculations Looping and a Study of Functions Storing Information in Arrays Simple Statistics Program Design Putting Things on Array Summary
SNU IDB Lab. 47 Simple Statistics Program Design Algorithms for Maximum, Minimum, and Mean in the context of array Array Statistics Example ArrayStats.java Wild Card Bonus (WCB-2) Submit a 5 page report explaining ArrayStats.Java
SNU IDB Lab. 48 import awb.*; import java.awt.*; import java.awt.event.*; public class ArrayStats extends java.applet.Applet implements ActionListener { TextField mInstruct, mAnswer; IntField iCount; double list[]; Button bStore, bShow, bExtremes, bMean, bClear; int count, nextFree, nextUse; double mean(double[] list, int size) { int k = 0; double sum = 0.0; while (k < size) { sum = sum + list[k]; k = k + 1; } return sum/size; } double max(double[] list, int size) { int k = 1; double largest = list[0]; while (k < size) { if (list[k] > largest) { largest = list[k]; } k = k + 1; } return largest; } double min(double[] list, int size) { int k = 1; double smallest = list[0]; while (k < size) { if (list[k] < smallest) { smallest = list[k]; } k = k + 1; } return smallest; } public void init() { list = new double[100]; mInstruct = new TextField(70); mAnswer = new TextField(70); mInstruct.setText("Enter Value, then press Store button"); iCount = new IntField(10); bStore = new Button("Store"); bShow = new Button("Show"); bExtremes = new Button("Extremes"); bMean = new Button("Mean"); bClear = new Button("Clear"); nextFree = 0; nextUse = 0; bStore.addActionListener(this); bShow.addActionListener(this); bExtremes.addActionListener(this); bMean.addActionListener(this); bClear.addActionListener(this); add(mInstruct); add(iCount); add(bStore);
SNU IDB Lab. 49 add(bShow); add(bExtremes); add(bMean); add(bClear); add(mAnswer); } public void actionPerformed(ActionEvent event) { int value, total;; Object cause = event.getSource(); if (cause == bStore) { value = iCount.getInt(); list[nextFree] = value; nextFree = nextFree + 1; iCount.setInt(); // clear IntField } if (cause == bShow) { mAnswer.setText("The value in element "+nextUse+" is "+ list[nextUse]); nextUse = (nextUse + 1)% nextFree; } if (cause == bExtremes) { mAnswer.setText("The largest data item is " + max(list, nextFree) + " and the smallest data item is " + min(list, nextFree)); } if (cause == bMean) { mAnswer.setText("The average is " + mean(list, nextFree)); } if (cause == bClear) { nextUse = 0; nextFree = 0; mAnswer.setText("The old data has been cleared out"); } ArrayStats.java (cont’d)
SNU IDB Lab. 50 Table of contents Let’s calculate some numbers Some Calculations Looping and a Study of Functions Storing Information in Arrays Simple Statistics Program Design Putting Things on Array Summary
SNU IDB Lab. 51 Advanced discussion: Putting things in an Array The question of whether there are enough bins to hold all the elements of a set of objects If we can succeed with a set, the set is countable If countable computable solvable decidable What about the set of positive numbers What about the set of positive and negative integers ????? An unending chain of bins than extends off into infinity
SNU IDB Lab. 52 Advanced discussion: Uncomputability Let’s consider: the functions that input a positive integer and yields a positive integer cannot be put in a row No matter how one tries to squeeze them all into bins, there will always be huge numbers more that will not fit The notion of uncountable set This is an important property with great implications for computer science uncomputability
SNU IDB Lab. 53 Figure 3.9 Let’s call the function that accept positive numbers as input and yield positive integers as output PIPO type function Let’s assume the set of PIPO type functions is countable If the assumption is true, all PIPO type functions would be put into bins successfully That means no left-overs. But …..
SNU IDB Lab. 54 Figure 3.10 ** However, Consider the new function constructed as in Figure 3.10 ** The new function is definitely different from existing functions and definitely PIPO type function ** But it was not in the bin! ** The set of PIPO type functions is uncountable! ** The notion of uncountable set leads to uncomputability! (chap 15)
SNU IDB Lab. 55 Table of contents Let’s Calculate some Numbers Some Calculations Looping and a Study of Functions Storing Information in Arrays Simple Statistics Program Design Putting Things on Array Summary
SNU IDB Lab. 56 Summary This chapter has discussed many aspects of numerical computation We covered many Java constructs through sample programs “Integers” are not adequate for general numerical computation Even “Double” data type has round-off errors Looping programs are frequent Arrays were useful Putting things into an array is simple job but can lead to a discussion of uncomputability
SNU IDB Lab. 57 Ch3: Mumerical Computation & Function Textbook Review Time