The IEEE 754 representation has round off errors
|
Example: 0.2(10) = 0.001100110011001100110011...
0.2 *2 ------- 0 0.4 *2 ------- 0 0.8 *2 ------- 1 1.6 --> 0.6 *2 ------- 1 1.2 --> 0.2 *2 ------- 0 0.4 *2 ------- 0 0.8 *2 ------- 1 1.6 --> 0.6 *2 ------- 1 1.2 --> 0.2 and so on (repeats !) |
Note:
|
Example:
1/7 = 0.14265714265714.... |
Consider this Java program: /home/cs255001/demo/java/FloatError.java
public class FloatError { public static void main(String[] arg) { float f1, f2; f1 = 0.2f + 0.2f + 0.2f + 0.2f + 0.2f + 0.2f + 0.2f + 0.2f + 0.2f + 0.2f; f2 = 2.0f; if ( f1 == f2 ) { System.out.println ("f1 == f2"); } else { System.out.println ("f1 != f2"); } } } |
What will this program print ?
Solution:
public class FloatError
{
public static void main(String[] arg)
{
float f1, f2;
f1 = 0.2f + 0.2f + 0.2f + 0.2f + 0.2f
+ 0.2f + 0.2f + 0.2f + 0.2f + 0.2f;
f2 = 2.0f;
if ( Math.abs(f1 - f2) < EPSILON )
{
System.out.println ("f1 == f2");
}
else
{
System.out.println ("f1 != f2");
}
}
}
|