Lecture 16 Rational Numbers Last time 1 Aliasing and Mutability 2 Floating Point calculations Today 1 Example class development Rational Numbers CMSC 131 Fall 2007 Jan Plane adapted from Bonnie Dorr Definition of a Rational Number What is a rational number As a decimal it either terminates or repeats a pattern 1 75 0 242935353535 As a fraction it can be represented as a fraction of two integers CMSC 131 Fall 2007 Jan Plane adapted from Bonnie Dorr 1 Today we will start an extended example We will implement a class Rational for immutable rational numbers The class will include Constructors Arithmetic operations toString Comparisons equals compareTo CMSC 131 Fall 2007 Jan Plane adapted from Bonnie Dorr 2 Lowest Terms How do we represent the fraction 20 60 Reduce to lowest terms Given a fraction p q how do you put it into lowest terms Method Find greatest common divisor gcd of p q gcd of p q largest number that divides both p q Euclid s algorithm beyond scope of this lecture performs this if p q are both positive Replace p q by p gcd q gcd Example Consider 18 24 gcd of 18 and 24 is 6 So 18 24 18 6 24 6 3 4 CMSC 131 Fall 2007 Jan Plane adapted from Bonnie Dorr 3 Hints Come up with representative test cases Intertwine implementation and testing Rerun each test even ones for previously tested methods when you test Do constructors and getters first then test Implement related operations then test This is called regression testing Useful for detecting changes that may invalidate previous test results Easy to set up in Eclipse Use debugger to track down sources of errors in tests CMSC 131 Fall 2007 Jan Plane adapted from Bonnie Dorr 4 Rational Numbers continued Arithmetic Operations What you remember from middle high school p q s t p t q s q t We will focus on these two cases p q s t p s q t p q s t p q s t 1 p q q p p q s t p q t s p q 1 s t CMSC 131 Fall 2007 Jan Plane adapted from Bonnie Dorr 5 Comparisons p q s t if We will focus on this case p q s t are in lowest terms and p q and s t p q s t if p t q s CMSC 131 Fall 2007 Jan Plane adapted from Bonnie Dorr 6
View Full Document