Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Float vs Double

Is there ever a case where a comparison (equals()) between two floating point values would return false if you compare them as DOUBLE but return true if you compare them as FLOAT?

I'm writing some procedure, as part of my group project, to compare two numeric values of any given types. There're 4 types I'd have to deal with altogether : double, float, int and long. So I'd like to group double and float into one function, that is, I'd just cast any float to double and do the comparison.

Would this lead to any incorrect results?

Thanks.

like image 338
user113454 Avatar asked Apr 10 '12 04:04

user113454


1 Answers

If you're converting doubles to floats and the difference between them is beyond the precision of the float type, you can run into trouble.

For example, say you have the two double values:

9.876543210
9.876543211

and that the precision of a float was only six decimal digits. That would mean that both float values would be 9.87654, hence equal, even though the double values themselves are not equal.

However, if you're talking about floats being cast to doubles, then identical floats should give you identical doubles. If the floats are different, the extra precision will ensure the doubles are distinct as well.

like image 119
paxdiablo Avatar answered Oct 01 '22 02:10

paxdiablo