tags:

views:

971

answers:

5

I'd like a floor function with the syntax

int floor(double x);

but std::floor returns a double. Is

static_cast <int> (std::floor(x));

guaranteed to give me the correct integer, or could I have an off-by-one problem? It seems to work, but I'd like to know for sure.

For bonus points, why the heck does std::floor return a double in the first place?

+8  A: 

The range of double is way greater than the range of 32 or 64 bit integers, which is why std::floor returns a double. Casting to int should be fine so long as it's within the appropriate range - but be aware that a double can't represent all 64 bit integers exactly, so you may also end up with errors when you go beyond the point at which the accuracy of double is such that the difference between two consecutive doubles is greater than 1.

Jon Skeet
So if it's in the right range, the cast is fine? Where does it say (something that implies) this in the spec?
Jesse Beder
Well, there are two operations here: std::floor, and the cast. std::floor is meant to return an integer, and the cast is specified in terms of an integer value. So long as std::floor returns a value which genuinely is an exact integer, I can't see how it would make sense for it to fail.
Jon Skeet
How would floor ever return something that's not an exact integer? For small doubles (epsilon << 1), all integral values can be represented, including floor(x). For big doubles (epsilon >> 1), only integral values can be represented, so floor(x)==x.
MSalters
+4  A: 
static_cast <int> (std::floor(x));

does pretty much what you want, yes. It gives you the nearest integer, rounded towards -infinity. At least as long as your input is in the range representable by ints. I'm not sure what you mean by 'adding .5 and whatnot, but it won't have the same effect

And std::floor returns a double because that's the most general. Sometimes you might want to round off a float or double, but preserve the type. That is, round 1.3f to 1.0f, rather than to 1.

That'd be hard to do if std::floor returned an int. (or at least you'd have an extra unnecessary cast in there slowing things down).

If floor only performs the rounding itself, without changing the type, you can cast that to int if/when you need to.

Another reason is that the range of doubles is far greater than that of ints. It may not be possible to round all doubles to ints.

jalf
floor() rounds towards -infinity, not zero: See http://www.cplusplus.com/reference/clibrary/cmath/floor.html
George V. Reilly
doh, you're right of course. Fixed.
jalf
+1  A: 

If you want to deal with various numeric conditions and want to handle different types of conversions in a controlled way, then maybe you should look at the Boost.NumericConversion. This library allows to handle weird cases (like out-of-range, rounding, ranges, etc.)

Here is the example from the documentation:

#include <cassert>
#include <boost/numeric/conversion/converter.hpp>

int main() {

    typedef boost::numeric::converter<int,double> Double2Int ;

    int x = Double2Int::convert(2.0);
    assert ( x == 2 );

    int y = Double2Int()(3.14); // As a function object.
    assert ( y == 3 ) ; // The default rounding is trunc.

    try
    {
        double m = boost::numeric::bounds<double>::highest();
        int z = Double2Int::convert(m); // By default throws positive_overflow()
    }
    catch ( boost::numeric::positive_overflow const& )
    {
    }

    return 0;
}
Anonymous
A: 

Most of the standard math library uses doubles but provides float versions as well. std::floorf() is the single precision version of std::floor() if you'd prefer not to use doubles.

Edit: I've removed part of my previous answer. I had stated that the floor was redundant when casting to int, but I forgot that this is only true for positive floating point numbers.

Dan Olson
A: 

The C++ standard says (4.9.1):

"An rvalue of a floating point type can be converted to an rvalue of an integer type. The conversion truncates; that is, the fractional part is discarded. The behavior is undefined if the truncated value cannot be represented in the destination type".

So if you are converting a double to an int, the number is within the range of int and the required rounding-up is toward zero, then it is enough to simply cast the number to int:

(int)x;

Michal Czardybon
Truncation of the fraction part is not floor - the result is different for negative numbers.
Suma
I have clearly written "So if ... the required rounding-up is toward zero" to distinguish this case from "rounding-up toward -infinity". Floor is rounding toward -infinity, truncation - toward zero.
Michal Czardybon