CMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)Lecture 16:Rational NumbersLast time:1.Aliasing and Mutability2.Floating Point calculationsToday:1.Example class development: Rational NumbersCMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)1Definition of a Rational NumberWhat is a rational number?As a decimal it either terminates or repeats a pattern:1.750.242935353535As a fraction, it can be represented as a fraction of two integers.CMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)2Today we will start an extended exampleWe will implement a class, Rational, for (immutable) rational numbersThe class will includeConstructorsArithmetic operations (+, -, *, /)toStringComparisons (equals, compareTo)CMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)3“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?MethodFind greatest common divisor (gcd) of p, qgcd of p, q: largest number that divides both p, qEuclid’s algorithm (beyond scope of this lecture) performs this if p, qare both positiveReplace p/q by (p/gcd) / (q/gcd)ExampleConsider 18/24gcd of 18 and 24 is 6So 18/24 = (18/6) / (24/6) = 3/4CMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)4HintsCome up with representative test casesIntertwine implementation and testingDo constructors and getters first, then testImplement “related operations”, then testRerun each test (even ones for previously tested methods) when you testThis is called regression testingUseful for detecting changes that may invalidate previous test results!Easy to set up in EclipseUse debugger to track down sources of errors in testsCMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)5Rational Numbers (continued): Arithmetic OperationsWhat you remember from middle / high schoolp/q + s/t = (p*t + q*s) / (q*t)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))We will focus on theseWe will focus on theseWe will focus on theseWe will focus on thesetwo cases.two cases.two cases.two cases.CMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)6Comparisonsp/q = s/t ifp/q, s/t are in lowest terms, andp = q and s = tp/q < s/t if p*t < q*sWe will focus on this case.We will focus on this case.We will focus on this case.We will focus on this
View Full Document