TestSum.java

Download TestSum.java

 1: // From Liang's "Intro to Java Programming", 11th ed, p. 180)
 2: // This demo shows some of the errors caused by using floats and doubles
 3: // in loops.
 4: //
 5: // Written 3/2017 by Wayne Pollock, Tampa Florida USA
 6: 
 7: public class TestSum {
 8:     public static void main ( String[] args ) {
 9:         System.out.println( "Sum 0.01..1.0 using floats "
10:             + "(should result in 50.50):" );
11:         floatTest();
12:         System.out.println( "\nSum 0.01..1.0 using doubles, the wrong way:" );
13:         doubleTestWrongWay();
14:         System.out.println( "\nSum 0.01..1.0 using doubles, a better way:" );
15:         doubleTestBetterWay();
16:         System.out.println( "\nSum 0.01..1.0 using ints and divide at the end, "
17:             + "the best way:" );
18:         intTest();
19:     }
20: 
21:     // This should only produce a small error:
22:     static void floatTest () {
23:         float sum = 0.0f;
24:         // Add 0.01 .. 1.0 to sum:
25:         for ( float i = 0.01f; i <= 1.0f; i += 0.01f )
26:             sum += i;
27:         System.out.println( "   Result: " + sum );
28:     }
29: 
30:     // This produces a large error!  The reason is that the loop executes
31:     // one less iteration; the final iteration has i at 1.00...something,
32:     // and since that is greater than 1.0, the loop terminates early:
33:     static void doubleTestWrongWay () {
34:         double sum = 0.0;
35:         for ( double i = 0.01; i <= 1.0; i += 0.01 )
36:             sum += i;
37:         System.out.println( "   Result: " + sum );
38:     }
39: 
40:     // Just don't use floating point as loop control variables:
41:     static void doubleTestBetterWay () {
42:         double sum = 0.0, increment = 0.01;
43:         for ( int i = 1; i <= 100; i += 1 ) {
44:             sum += increment;
45:             increment += 0.01;
46:         }
47:         System.out.println( "   Result: " + sum );
48:     }
49: 
50:     // Best way: don't use floating point at all:
51:     static void intTest () {
52:         int sum = 0;
53:         for (int i = 1; i <= 100; i += 1 )
54:             sum += i;
55:         System.out.println( "   Result: " + sum / 100.0 );
56:     }
57: }