Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't floor return an integer? [duplicate]

Tags:

c++

c

Just now I stumbled upon the fact, that the C++ function floor returns the same type you pass to it, be it float, double or such.

According to this reference, the function returns a down rounded integral value. Why isn't this an integer?

like image 243
danijar Avatar asked Mar 11 '13 20:03

danijar


People also ask

Does floor return an integer?

floor() function returns the largest integer less than or equal to a given number.

Does Math floor return an integer?

Math. floor() function returns a double value equal to the nearest integer value, which is less than or equal to the double value passed to it as an argument.

Does Mathf round return an int?

Round(double) and Math. Round(decimal) will always return an integral value, these overloads still cannot return an integer value type.

Why does Java floor return double?

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.


1 Answers

Because an integral type can't necessarily hold the same integral values as a float or double.

int main(int argc, char *argv[]) {
    std::cout << floor(std::numeric_limits<float>::max()) << std::endl;
    std::cout << static_cast<long>(floor(std::numeric_limits<float>::max())) << ::endl;
}

outputs (on my x86_64 architecture)

3.40282e+38
-9223372036854775808

Additionally, floating-point values can hold NaN, +Inf, and -Inf, all of which are preserved by a floor() operation. None of these values can be represented with an integral type.

int main(int argc, char *argv[]) {
    std::cout << floor(std::numeric_limits<float>::quiet_NaN()) << std::endl;
    std::cout << floor(std::numeric_limits<float>::infinity()) << std::endl;
    std::cout << floor(-std::numeric_limits<float>::infinity()) << std::endl;
}

outputs

nan
inf
-inf
like image 80
Lily Ballard Avatar answered Oct 17 '22 23:10

Lily Ballard