Next: Precision in measures Up: Unit 04 Previous: Solution for the class

## Precision in the representation: rounding errors

Not all numbers between -3.4028235 . 10+38 and +3.4028235 . 10+38 can be represented as a float (similar considerations hold for double).

This aspect is shown in the picture below: the closer we are to zero, the closer to each other are the numbers that can be represented (depicted by the vertical lines); the more we move away from zero the wider from each other are the numbers that can be represented.

Example: The number that is nearest to +3.4028235 . 10+38 and that can be represented as a float is +3.4028234 . 10+38.

This leads to approximations due to rounding errors in computing the values of expressions.

Example:

float x = 1222333444.0f;
System.out.println("x   = " + x);
x += 1.0;
System.out.println("x+1 = " + x);

prints
x   = 1.222333444E9;
x+1 = 1.222333444E9;

while
int j = 1222333444;
System.out.println("j   = " + j);
j += 1;
System.out.println("j+1 = " + j);

prints
j   = 1222333444;
j+1 = 1222333445;


Next: Precision in measures Up: Unit 04 Previous: Solution for the class