Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ ceil and negative zero

On VC++ 2008, ceil(-0.5) is returning -0.0. Is this usual/expected behavior? What is the best practice to avoid printing a -0.0 to i/o streams.

like image 641
ThomasMcLeod Avatar asked May 13 '11 03:05

ThomasMcLeod


People also ask

What is the use of Ceil in C?

ceil function. (Ceiling) In the C Programming Language, the ceil function returns the smallest integer that is greater than or equal to x (ie: rounds up the nearest integer).

Is it possible to have a negative value of zero in C?

Still, for a real number ( float or double) in C, it’s theoretically possible to have a positive or negative value of zero. The question is whether the C language recognizes the difference. In the following code, I use the sign operator to compare the values zero, positive zero, and negative zero.

What is double Ceil () function in C?

The C library function double ceil(double x) returns the smallest integer value greater than or equal to x.

What does negative 0 mean in math?

Negatively signed zero echoes the mathematical analysis concept of approaching 0 from below as a one-sided limit, which may be denoted by x → 0−, x → 0−, or x → ↑0. The notation "−0" may be used informally to denote a small negative number that has been rounded to zero.


2 Answers

ceil in C++ comes from the C standard library.

The C standard says that if a platform implements IEEE-754 arithmetic, ceil( ) behaves as though its argument were rounded to integral according to the IEEE-754 roundTowardPositive rounding attribute. The IEEE-754 standard says (clause 6.3):

the sign of the result of conversions, the quantize operation, the roundToIntegral operations, and the roundToIntegralExact is the sign of the first or only operand.

So the sign of the result should always match the sign of the input. For inputs in the range (-1,0), this means that the result should be -0.0.

like image 150
Stephen Canon Avatar answered Sep 29 '22 23:09

Stephen Canon


This is correct behavior. See Unary Operator-() on zero values - c++ and http://en.wikipedia.org/wiki/Signed_zero

I am partial to doing a static_cast<int>(ceil(-0.5)); but I don't claim that is "best practice".

Edit: You could of course cast to whatever integral type was appropriate (uint64_t, long, etc.)

like image 21
Chris Morgan Avatar answered Sep 30 '22 00:09

Chris Morgan