FloatingLoop.java


Below is the syntax highlighted version of FloatingLoop.java from §9.1 Scientific Computation.



/******************************************************************************
 *  Compilation:  javac FloatingLoop.java
 *  Execution:    java FloatingLooop
 * 
 *  The first loop prints out 20,000,000 as expected. The second
 *  loop never terminates because of floating point precision.
 * 
 ******************************************************************************/

public class FloatingLoop {

    public static void main(String[] args) { 

        // using double
        int count1 = 0;
        for (double x = 0.0; x < 20000000.0; x = x + 1.0) {
            count1++;
        }
        StdOut.println(count1);

        // using float
        int count2 = 0;
        for (float x = 0.0f; x < 20000000.0f; x = x + 1.0f) {
            count2++;
        }
        StdOut.println(count2);


   }

}


Copyright © 2000–2017, Robert Sedgewick and Kevin Wayne.
Last updated: Fri Oct 20 14:12:12 EDT 2017.