Two Laptop Bag
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Float Calculations... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Float Calculations..." Watch "Float Calculations..." New topic

Float Calculations...

sonir shah
Ranch Hand

Joined: Nov 01, 2001
Posts: 435
The following code will print 'false'.
float f = 1.0F/3.0F;
System.out.println( (f * 3.0F) == 1.0F );
Options :
1) True
2) False
Answer : false..
I feel it should be true because when 1 is divided by 3 it gives 0.33333....i.e 0.334 and when we multiply 0.334 by 3.000 we get 1.002....i.e 1
Hence it should be true..
Any Comments???
R K Singh
Ranch Hand

Joined: Oct 15, 2001
Posts: 5382
float numbers are stored differently inside JVM so they lose some precision .. that's why it is not equal.

"Thanks to Indian media who has over the period of time swiped out intellectual taste from mass Indian population." - Chetan Parekh
Maulin Vasavada
Ranch Hand

Joined: Nov 04, 2001
Posts: 1873
but can we be sure of the answer "false"? because it's precision based and if we can't be sure of how much it would be exactly due to precision then we can't say "true" or "false".
how can we be sure?
R K Singh
Ranch Hand

Joined: Oct 15, 2001
Posts: 5382
Originally posted by Maulin, Vasavada:
how can we be sure?

I think we use strictfp for that only.
any expert comment plz .
[ January 20, 2002: Message edited by: ravish kumar ]
wood burning stoves
subject: Float Calculations...
It's not a secret anymore!