permaculture playing cards
The moose likes Java in General and the fly likes Floating  Confusion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Floating  Confusion" Watch "Floating  Confusion" New topic

Floating Confusion

Talib Jockey

Joined: Aug 06, 2003
Posts: 22
Hi All,

I have a confusion...

The following code snippet prints "true"

float f = 1.0F/3.0F;
System.out.println( (f * 3.0F) == 1.0F );

whereas the following prints "false"

double d = 1.0F/3.0F;
System.out.println( (d * 3.0F) == 1.0F );

How is it possible, the value of 1/3 cannot be precisely stored by either variable type. Then why does double return false?

Am I missing something?


SCJP 1.4 - 97%<br />SCWCD 1.4 - In Progress
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2398
Remember that an implict conversion to double is taking place.

Consider this code.

The output is

Talib Jockey

Joined: Aug 06, 2003
Posts: 22
Thanks bro..but its kindda wierd!!
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
(Not an Advanced question at all)

Testing for equality, with floating point, is almost always wrong. It is an inexact data type, so exact equality test generally does not do what you want.

Therefore you have two mistakes: -
  • using float constants (F suffix) with double type
  • worrying about exact equality tests in floating-point

  • [ September 25, 2006: Message edited by: Peter Chase ]

    Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
    I agree. Here's the link:
    subject: Floating Confusion
    It's not a secret anymore!