Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
358 views
in Technique[技术] by (71.8m points)

operators - Comparing float and double primitives in Java

I came across a strange corner of Java.(It seems strange to me)

double dd = 3.5;          
float ff = 3.5f;
System.out.println(dd==ff);   

o/p: true

double dd = 3.2;
float ff = 3.2f;
System.out.println(dd==ff);

o/p: false

I observed that if we compare any two values (a float and a double as I mentioned in the example) with .5 OR .0 like 3.5, 234.5, 645.0 then output is true i.e. two values are equal otherwise output is false though they are equals.

Even I tried to make method strictfp but no luck. Am I missing out on something.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Take a look at What every computer scientist should know about floating point numbers.

Squeezing infinitely many real numbers into a finite number of bits requires an approximate representation....

--- Edit to show what the above quote means ---

You shouldn't ever compare floats or doubles for equality; because, you can't really guarantee that the number you assign to the float or double is exact.

So

 float x = 3.2f;

doesn't result in a float with a value of 3.2. It results in a float with a value of 3.2 plus or minus some very small error. Say 3.19999999997f. Now it should be obvious why the comparison won't work.

To compare floats for equality sanely, you need to check if the value is "close enough" to the same value, like so

float error = 0.000001 * second;
if ((first >= second - error) || (first <= second + error)) {
   // close enough that we'll consider the two equal
   ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...