Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does casting to an int after std::floor guarantee the right result?

Tags:

c++

math

floor

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?

like image 546
Jesse Beder Avatar asked Mar 03 '09 08:03

Jesse Beder


People also ask

Is casting to INT the same as floor?

Casting to an int will truncate toward zero. floor() will truncate toward negative infinite. This will give you different values if bar were negative.

What does std :: floor do?

std::floor is meant to return an integer, and the cast is specified in terms of an integer value.


2 Answers

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.

like image 156
Jon Skeet Avatar answered Sep 30 '22 09:09

Jon Skeet


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.

like image 45
jalf Avatar answered Sep 30 '22 09:09

jalf