Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

== operator..

 
suresh seeram
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello frineds,
Can any one explain the the result..
public class Test041
{
static double d;
static float f;
public static void main(String args[])
{
compare(Long.MAX_VALUE, Long.MAX_VALUE );
compare(Integer.MAX_VALUE, Integer.MAX_VALUE );
compare(Character.MAX_VALUE, Character.MAX_VALUE);
compare(Short.MAX_VALUE, Short.MAX_VALUE );
compare(Byte.MAX_VALUE, Byte.MAX_VALUE );
}
static void compare(double d, float f)
{
if (f == d) System.out.print(" equal" );
else System.out.print(" unequal");
}
}
result:
equal unqequal equal equal equal
thanks in advance
regards,
Suresh
 
Manfred Leonhardt
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Suresh,
Welcome to the world or IEEE 754. the primitive type double is not the same as float in this world. Let the JLS Spec illuminate you (Section 5.1.2):

Conversion of an int or a long value to float, or of a long value to double, may result in loss of precision-that is, the result may lose some of the least significant bits of the value. In this case, the resulting floating-point value will be a correctly rounded version of the integer value, using IEEE 754 round-to-nearest mode.

Regards,
Manfred.
 
Bill Krieger
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Interesting. I would have expected "unequal unequal equal equal equal". When the Long.MAX_VALUE is converted to double, some precision is lost. When the Long.MAX_VALUE is converted to float, even more bits of precision are lost. When the float version is converted to double for the comparison, is the extra precision just accidently coming out equal?
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
With this line:
System.out.println("d= " + d +
"\n" + "f= " + f + "\n" + "(double)f: " + (double)f);
we can see the following output:
d= 9.223372036854776E18
f= 9.223372E18
(double)f: 9.223372036854776E18
equal
d= 2.147483647E9
f= 2.14748365E9
(double)f: 2.147483648E9
unequal
d= 65535.0
f= 65535.0
(double)f: 65535.0
equal
d= 32767.0
f= 32767.0
(double)f: 32767.0
equal
d= 127.0
f= 127.0
(double)f: 127.0
equal
Also if we add:
compare(5555555555L, 5555555555L);
the output:
d= 5.555555555E9
f= 5.5555553E9
(double)f: 5.555555328E9
unequal
I would say that comparing floating point numbers with == is very risky. I think it's better to establish the precission that is going to be meaningfull for our comparision before doing the actual comparision. Maybe rounding...
Please correct or confirm.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic