/* --- CSU213 Spring 2006 Lecture Notes --------- Copyright 2006 Viera K. Proulx Comparing doubles. ------------------ Often we need to design methods that produce values of the type 'double'. In order to make examples, we need to be able to deteremine whether two 'double' values represent the same information (at least as far as we are concerned). We decide that it is sufficient if the difference between the two values is less than 0.0001. The Java expression that computes the difference between two 'doubles' can be written as: Math.abs(value1 - value2) That means, we can define (in our Examples class) the method sameDoubles, which determines whether two double values are sufficiently close for our purpose, and use it to define test cases that involve 'doubles': // determine whether the two given double values are the same within 0.001 boolean sameDoubles(value1, value2){...} Examples illustrate the use: sameDoubles(5.0, 4.9999) -> true sameDoubles(3.33333, 10.0/3) --> true sameDoubles(2.0, 2.001) --> false The template consists of the two parameters for the method, and the body is simply return Math.abs(value1 - value2) < 0.0001; */ class Examples { Examples() {} // determine whether the two given double values are the same within 0.001 boolean sameDoubles(double value1, double value2){ return Math.abs(value1 - value2) < 0.0001; } boolean test(){ return this.sameDoubles(5.0, 4.9999) == true && this.sameDoubles(3.33333, 10.0/3) == true && this.sameDoubles(2.0, 2.001) == false; } } /* Note: If we do not know beforehand what is the desired limit on the acceptable difference between the two 'double' values, we can supply the limit as an additional parameter to the method. The purpose and the header would then become // determine whether the difference between two given double values // is within the given limit (epsilon) boolean sameDoubles(double value1, double value2, double epsilon){...} We leave it to the reader to complete the design of this method. */