Why does Math.floor return a double?

The official Javadoc says that Math.floor() returns a double value equal to a "mathematical integer", but then why not return an int ?

+87
java math types
04 Feb '09 at 15:47
source share
6 answers

According to the same Javadoc:

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

The largest value of type double also greater than the largest value of type int , so it must be long .

+72
Feb 04 '09 at 15:49
source share

This is for accuracy. The dual data type has 53 bit mantissa. Incidentally, this means that the double can represent all integers up to 2 ^ 53 without loss of accuracy.

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

Returning an integer as a double is what you need to do here because it offers a much wider useful range of numbers than an integer.

+14
Feb 04 '09 at 15:53
source share

Others told you why, I am going to tell you how to round if you want to do this. If you are going to use only positive numbers, you can use this statement:

 int a=(int) 1.5; 

However (int) is always rounded to 0. Thus, if you want to make a negative number:

 int a=(int) -1.5; //Equal to -1 

In my case, I did not want to do this. I used the following code for rounding, and it seems to handle all extreme cases well:

 private static long floor(double a) { return (int) Math.floor(a); } 
+6
Oct 10 '13 at 23:17
source share

What would you like it to return if you gave it a double size larger than the largest int or long?

(Admittedly, if it is greater than the longest, the accuracy will be low anyway - it may not be the nearest theoretical whole, but even so ...)

+3
Feb 04 '09 at 15:53
source share

Thus, an error and other non-integer values ​​can be correctly cascaded using a series of calculations.

For example, if you submit Not Not Number (NaN) to Math.floor, it will pass it.

If he returns an integer, he will not be able to pass these states or errors together, and you may get bad results from earlier calculations that look good but are erroneous after further processing.

-Adam

0
Feb 04 '09 at 15:53
source share

Just as in Java there is integer and floating point division, there are full and floating ways to create a floor:

 double f = Math.floor(x); 

or

 int k = (int) x; 

but you always need to be careful when using arithmetic gender with finite precision: your calculation of x may lead to something like 1.99999999 that will overlap to 1, not 2 in both forms. There are many algorithms that must circumvent this limitation in order to avoid incorrect results for some input values.

0
Sep 11 '13 at 15:10
source share



All Articles