Truncation and casting to ceiling with double overlap

When executed std::ceil

on a double value, the value is rounded to an integer. So 3.3 becomes 4.0. Which can be dropped or truncated to int

. That will "cut off" the part after the decimal point. So:

int foo = (int)std::ceil(3.3);

      

So at first glance this will store 4 in foo. However, double is a floating point value. So it can be either 4.000000001

or 3.999999999

. The latter would be truncated to 3.

But in practice I have never seen this behavior. Is it safe to assume that any implementation will return 4? Or it only does IEEE-754

. Or was I just lucky?

+3


source to share


2 answers


Rounding (or overlapping) a double will always, always, always be accurate.

For floating point numbers below 2 ^ (m + 1), where m is the number of mantissal bits, all integers have exact representations, so the result can be accurately represented.



For floating point numbers above 2 ^ (m + 1) ... they are already integers. Makes sense if you think about it: there are not enough mantissal bits to stretch to the right of the decimal point. So again the rounding / ceiling is more accurate.

+5


source


ceil

in C ++ behaves the same as in C where the standard says

The ceil functions evaluate the smallest integer value at least x.



The result ceil

is always a floating point integer; however, truncation can result in an integral type overflow.

In your particular case it std::ceil(3.3)

should be exactly 4.0

, since it is "smallest integer value not less" 3.3

.

0


source







All Articles