Name: nt126004 Date: 08/31/2001
Multiple platforms/versions. Here are two:
Win2K:
java version "1.3.1"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.3.1-b24)
Java HotSpot(TM) Client VM (build 1.3.1-b24, mixed mode)
Solaris : SunOS 5.7 Generic_106541-10 sun4u sparc SUNW,Ultra-4
java version "1.2.1"
Solaris VM (build Solaris_JDK_1.2.1_03a, native threads, sunwjit)
public class FloatTest
{
public static void main(String[] args)
{
float f = 16777216;
float f1 = f + 1;
if (f1 == f)
System.out.println("Wrong answer but it shows "+f1);
else
System.out.println("Good answer");
f1 = f + 2;
if (f1 == f)
System.out.println("Wrong answer");
else
System.out.println("Good answer which is correct");
}
}
produces:
$ java FloatTest
Wrong answer but it shows
Good answer which is correct
Even more insiduous than the previous example, every increment with a factor
of 4 fails. Here's the class:
import java.text.*;
public class FloatTest2
{
public static void main(String[] args)
{
float f = 16777216;
while (f < Float.MAX_VALUE)
{
float f1 = f + 1;
if (f1 == f)
{
System.out.println("Wrong answer but it shows: " +
NumberFormat.getInstance().format(f) + " + 1 =" +
NumberFormat.getInstance().format(f1));
f = f + 2;
}
else
f++;
}
}
}
produces (probably upto Float.MAX_VALUE):
Wrong answer but it shows: 16,777,216 + 1 =16,777,216
Wrong answer but it shows: 16,777,220 + 1 =16,777,220
Wrong answer but it shows: 16,777,224 + 1 =16,777,224
Wrong answer but it shows: 16,777,228 + 1 =16,777,228
(Review ID: 131174)
======================================================================