GeeCON Prague 2014*
The moose likes Beginning Java and the fly likes weird behavior Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "weird behavior " Watch "weird behavior " New topic
Author

weird behavior

Rishi Kumar
Greenhorn

Joined: Mar 28, 2001
Posts: 19
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

Rishi Kumar,SCJP SCJD SCWCD
Colin Kenworthy
Ranch Hand

Joined: Aug 06, 2001
Posts: 88
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

Joined: Aug 26, 2001
Posts: 7610
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


SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
Rishi Kumar
Greenhorn

Joined: Mar 28, 2001
Posts: 19
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

Joined: Apr 20, 2000
Posts: 3252
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
 
GeeCON Prague 2014
 
subject: weird behavior