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–2022, Robert Sedgewick and Kevin Wayne.
Last updated: Thu Aug 11 10:33:43 EDT 2022.