ThomasMcLeod
ThomasMcLeod

Reputation: 7769

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.

Upvotes: 6

Views: 3455

Answers (5)

Stephen Canon
Stephen Canon

Reputation: 106167

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.

Upvotes: 3

ThomasMcLeod
ThomasMcLeod

Reputation: 7769

I see why ceil(-0.5) is returning -0.0. It's because for negative numbers, ceil is returning the integer part of the operand:

double af8IntPart;
double af8FracPart = modf(-0.5, & af8IntPart);
cout << af8IntPart;

The output here is "-0.0"

Upvotes: 0

Chris Morgan
Chris Morgan

Reputation: 2080

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.)

Upvotes: 3

Nate Koppenhaver
Nate Koppenhaver

Reputation: 1702

I can't say that I know that it is usual, but as for avoiding printing it, implement a check, something like this:

if(var == -0.0)
{
    var = 0.0;
}
// continue

Upvotes: 1

Jordonias
Jordonias

Reputation: 5848

Yes this is usual.

int number = (int) ceil(-0.5);

number will be 0

Upvotes: 0

Related Questions