File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

weird behavior

 
Rishi Kumar
Greenhorn
Posts: 19
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why these two statements give different result?
System.out.println(4.3 - 2.3);
2.0
System.out.println(4.3f - 2.3f);
2.0000002
I mean why there is .0000002
Can anyone explain?
Thank You
Rishi
 
Colin Kenworthy
Ranch Hand
Posts: 88
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well they are not the same expressions.
4.3 - 2.3 is promoted to double and so is calculated as 4.3d - 2.3d
float and double arithmetic is full of tiny inaccuracies due to the way the numbers are stored internally and limiting precision.
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just to precise what Colin just said, 4.3 - 2.3 is not promoted to double since the expression already is of type double. If one specifies a floating point number without appending "f" directly after that number then the type defaults to double.
So 4.3 (as well as 4.3d) is of type double and 4.3f is of type float.
------------------
Valentin Crettaz
Sun Certified Programmer for Java 2 Platform
 
Rishi Kumar
Greenhorn
Posts: 19
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Colin Kenworthy:
Well they are not the same expressions.
4.3 - 2.3 is promoted to double and so is calculated as 4.3d - 2.3d
float and double arithmetic is full of tiny inaccuracies due to the way the numbers are stored internally and limiting precision.

Thanks for the answer,
I have checked double always give precise answer but if you have substraction with float it does not. The inaccuracies are only in float, I think.
Any comment?
Rishi
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, beware. Double is more precise than float. But it is subject to the same type of imprecisions that you have seen using floats! The imprecisions are just smaller in magnitude.
In particular, there is no guarantee that a given integer number can be represented precisely using a float or double.
- Peter
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic