More about the For Statement

This chapter discusses the 'for' loop in greater detail, as well as the scope of variables in the 'for' loop.

8. Nicer Table


Answer:

Yes: 2*2*2 == 8

Nicer Table

Here is the program again, this time with better accuracy because the divisor is 8, a power of two.

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

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

Here is its output:

               
x        ln(x)
0.125   -2.0794415416798357
0.25    -1.3862943611198906
0.375   -0.9808292530117262
0.5     -0.6931471805599453
0.625   -0.4700036292457356
0.75    -0.2876820724517809
0.875   -0.13353139262452263
1.0     0.0
1.125   0.11778303565638346
1.25    0.22314355131420976
1.375   0.3184537311185346
1.5     0.4054651081081644
1.625   0.4855078157817008
1.75    0.5596157879354227
1.875   0.6286086594223741
2.0     0.6931471805599453

This is our best table yet! Unfortunately, because of the awkward increment value (of 1/8) the table is inconvenient for human consumption. But computing a table of numbers for display purposes is rare. Usually the numbers computed in a loop are used by the program itself for some larger task, such as drawing a picture, or for an engineering computation, and there is no particular reason to use a step size of one tenth. No human will actually look at the numbers.


Question 8:

(Thought question: ) Binary-based floating point numbers have accuracy problems. So why not build
computers that use decimal-based floating point numbers?

Hint: chocolate-chip cookies are three for a dollar. How much is one cookie?