Why does Math.ceil return a double?
Solution 1
The range of double
is greater than that of long
. For example:
double x = Long.MAX_VALUE;
x = x * 1000;
x = Math.ceil(x);
What would you expect the last line to do if Math.ceil
returned long
?
Note that at very large values (positive or negative) the numbers end up being distributed very sparsely - so the next integer greater than integer x
won't be x + 1
if you see what I mean.
Solution 2
A double can be larger than Long.MAX_VALUE
. If you call Math.ceil()
on such a value you would expect to return the same value. However if it returned a long, the value would be incorrect.
Related videos on Youtube
Comments
-
PengOne almost 2 years
When I call
Math.ceil(5.2)
the return is thedouble
6.0
. My natural inclination was to think thatMath.ceil(double a)
would return along
. From the documentation:ceil(double a)
Returns the smallest (closest to negative infinity)
double
value that is not less than the argument and is equal to a mathematical integer.But why return a
double
rather than along
when the result is an integer? I think understanding the reason behind it might help me understand Java a bit better. It also might help me figure out if I'll get myself into trouble by casting to along
, e.g. islong b = (long)Math.ceil(a);
always what I think it should be? I fear there could be some boundary cases that are problematic.
-
starblue almost 13 years
-
-
aalku almost 13 yearsI guess in your final sentence you are talking about a loose of precision but I think that does not depend on the high the number is but on the number of significant digits of it (in binary). I'll try to find an example.
-
Jon Skeet almost 13 years@user270349: The absolute gap between consecutive double values becomes larger as the value becomes larger. The number of significant digits represented remains the same (other than for subnormal numbers).
-
aalku almost 13 yearsExample:
2^60
can be represented as double while2^60 (+/-) 1
cannot -
aalku almost 13 yearsYou are right. An increment of one in the mantissa implies a much bigger number if the exponent is big, obvious.
-
Zoltán almost 10 yearsBut then why does
round
return along
? -
Tim Harper about 8 years^ Zoltán, exactly.
Math.round
returninglong
is inconsistent with the above reasoning. -
Ciprian Tomoiagă over 7 yearsthe
double
values that are larger thanLong.MAX_VALUE
may not be represented exactly, so thedouble
result ofceil(big_double)
will not bebig_double + 1
. So it's still incorrect... -
Vishy over 7 years@CiprianTomoiaga you are right that it won't be big_double +1 as this would be big_double. Any value which is too large to be represented as a
long
has no fractional part.