Floating Point Loop Control

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page

Answer:

  1. Will this new program compile?
    • Yes. The compiler will not complain about anything.
  2. Will it run?
    • Yes. It will run without any error messages.
  3. Is it correct?
    • No. There is an error which may be hard to find because the two loops are not self-contained.

Floating Point Loop Control

For counting loops it is best to use an integer for the loop control variable. However, it is legal to use a floating point control variable and to use fractional increments. The following program prints a table that displays x and ln(x) for values of x from 0.1 up to about 2.0:

class LogTable
{
  public static void main ( String[] args )
  {
    System.out.println( "x" + "/t ln(x)" );

    for ( double x = 0.1; x <= 2.0; x = x + 0.1 )
      System.out.println( x + "/t" + Math.log( x ) );
  } 
}

It compiles correctly, and runs. But its output is not pretty:

x                        ln(x)
0.1                     -2.3025850929940455
0.2                     -1.6094379124341003
0.30000000000000004     -1.203972804325936
0.4                     -0.916290731874155
0.5                     -0.6931471805599453
0.6                     -0.5108256237659907
0.7                     -0.35667494393873245
0.7999999999999999      -0.22314355131420985
0.8999999999999999      -0.1053605156578264
0.9999999999999999      -1.1102230246251565E-16
1.0999999999999999      0.09531017980432474
1.2                     0.1823215567939546
1.3                     0.26236426446749106
1.4000000000000001      0.336472236621213
1.5000000000000002      0.40546510810816455
1.6000000000000003      0.47000362924573574
1.7000000000000004      0.5306282510621706
1.8000000000000005      0.5877866649021193
1.9000000000000006      0.641853886172395

Remember (from a previous chapter) that floating point numbers are not always exact. In particular, 0.1 is always slightly wrong when represented using floating point, no matter how many bits are used. In the above program, errors in x accumulate, and x drifts away from the desired value.

Notice that the the loop does not end with x equal to 2.0, as you would expect. The loop condition is x <= 2.0, but x evidently overshoots the value 2.0 the last time it is incremented.

QUESTION 6:

Are integer numbers completely accurate?