Yes. 1 + 1 is always exactly 2, with integers. (But you do need to worry about overflow when the operands get too big.)
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.3 -1.2039728043259361 0.4 -0.916290731874155 0.5 -0.6931471805599453 0.6 -0.5108256237659907 0.7 -0.35667494393873245 0.8 -0.2231435513142097 0.9 -0.10536051565782628 1.0 0.0 1.1 0.09531017980432493 1.2 0.1823215567939546 1.3 0.26236426446749106 1.4 0.33647223662121284 1.5 0.4054651081081644 1.6 0.4700036292457356 1.7 0.5306282510621704 1.8 0.5877866649021191 1.9 0.6418538861723947 2.0 0.6931471805599453
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).
Is 8 a power of two?