This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Float Calculations...

 
sonir shah
Ranch Hand
Posts: 435
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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???
Sonir
 
R K Singh
Ranch Hand
Posts: 5384
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
float numbers are stored differently inside JVM so they lose some precision .. that's why it is not equal.
CMIW
HTH
 
Maulin Vasavada
Ranch Hand
Posts: 1873
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
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?
regards
maulin.
 
R K Singh
Ranch Hand
Posts: 5384
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Maulin, Vasavada:
how can we be sure?

I think we use strictfp for that only.
any expert comment plz .
CMIW
[ January 20, 2002: Message edited by: ravish kumar ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic