Yes. 1 + 1 is always exactly 2, with integers.
Often a program uses an
integer loop control variable
which is used to compute a floating point x
for every iteration of the loop:
class LogTable { public static void main ( String[] args ) { System.out.println( "x" + "\t ln(x)" ); for ( int j = 1; j <= 20; j++ ) { double x = j/10.0 ; System.out.println( x + "\t" + Math.log( x ) ); } } }
This is not without problems,
but at least the errors in x
are not accumulating.
Here is the output:
x ln(x) 0.1 -2.3025850929940455 0.2 -1.6094379124341003 0.30000000000000004 -1.203972804325936 0.4 -0.916290731874155 0.5 -0.6931471805599453 0.6000000000000001 -0.5108256237659905 0.7000000000000001 -0.3566749439387323 0.8 -0.2231435513142097 0.9 -0.10536051565782628 1.0 0.0 1.1 0.09531017980432493 1.2000000000000002 0.1823215567939548 1.3 0.26236426446749106 1.4000000000000001 0.336472236621213 1.5 0.4054651081081644 1.6 0.47000362924573563 1.7000000000000002 0.5306282510621705 1.8 0.5877866649021191 1.9000000000000001 0.6418538861723948 2.0 0.6931471805599453
The new problem is that the result of dividing j
by 10.0
is not completely accuracy.
However, dividing an integer by a power of two,
is accurate (as long as the result is not too small).