views:

737

answers:

4

I was just wondering...official javadoc says that it returns a double that is "equal to a mathematical integer", but then why shouldn't it return an int?

+13  A: 

According to the same javadoc:

If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument. Can't do that with an int.

The largest double value is also larger than the largest int, so it would have to be a long.

krosenvold
Guess it applies for .Net as well?
Ngu Soon Hui
+5  A: 

It's for precision. The double data-type has a 53 bit mantissa. Among other things that means that a double can represent all whole up to 2^53 without precision loss.

If you store such a large number in an integer you will get an overflow. Integers only have 32 bits.

Returning the integer as a double is the right thing to do here because it offers a much wider usefull number-range than a integer could.

Nils Pipenbrinck
It could return a long to cope with such values, of course. You'd still have to work out what to do with doubles > 2^63 though.
Jon Skeet
@Jon, true, but that would result in a performance impact (no conversion instruction from long to double in any instruction set that I'm aware of). I wonder what Math.floor does with doubles > 2^53 at the first place. Some results aren't representable.
Nils Pipenbrinck
But then, the pseudo-idiomatic form (int)Math.floor(foo), which appears also in the official javadoc is unsafe since the result may not fit into an int, am i right? And then again, which is a safe form to use Math.floor, since the result may not fit even into a long?
Raibaz
A: 

So that error and other non integer values can correctly cascade through a series of calculations.

For instance, if you feed Not a Number (NaN) into Math.floor, it'll pass it along.

If it returned integer it couldn't pass these status or errors along, and you could get bad results from an earlier calculation that look good but are wrong after further processing.

Adam Davis
+1  A: 

What would you want it to return if you gave it a double bigger than the largest int or long?

(Admittedly if it's bigger than the largest long the precision will be low anyway - it may not be the nearest theoretical integer - but even so...)

Jon Skeet