Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to cast result of ceil to integer?

Tags:

c

floor

ceil

ceil function in C is declared as double ceil(double). Is it safe to cast return value of the function to int? I mean is there any guarantee that the following will never occur (the sample is just to illustrate of what I mean)?

double r = ceil(234235.53453);
// imagine r = 234235.9999999 due to round errors or
// due to the peculiarities of the machine arithmetics, etc.
int i = (int)r;
// i = 234235, but must be 234236

Of course, I know that the range of double is large than the range of int, so the cast may fail. My question is not about it, but about rounding errors or machine arithmetics side effects.

like image 894
Nick Avatar asked May 19 '16 12:05

Nick


2 Answers

A 64-bit double represents integers of up to 2 in power 53 exactly. Integers larger than that do not have any fractional part when represented as double.

In other words, you can safely cast the result of ceil or floor to an integer, as long as that integer can hold the value.

like image 106
Maxim Egorushkin Avatar answered Sep 21 '22 05:09

Maxim Egorushkin


Assuming the result of ceil fits in the range of int (or whatever the casted type may be), the cast is safe. Rounding errors only come into play when the number in question can't be expressed exactly in binary. For example, 0.5 can be expressed exactly as a binary number, but 0.1 cannot.

Since the result of ceil is a integer, it can be expressed exactly in binary so there is no rounding error, and is thus safe to cast.


You can tell if a number can be expressed as a terminating or non-terminating value by expressing the number as a reduced fraction and looking at the denominator. If the denominator contains only factors of the base in question, it can be expressed exactly, otherwise it is an infinitely repeating number.

Going back to the example of 0.5 and 0.1, the reduced fractional representation of these numbers is 1/2 and 1/10. Both of these numbers can be expressed exactly in decimal because both 2 and 10 contain only factors of 10. Only the first however can be expressed in binary because 10 has 5 as a factor, which is not a factor of 2.

In the case of integers, they can all be expressed as a fraction with a denominator of 1. And since 1 is a factor of all integers, any integer can be expressed exactly in any base (including 2).

like image 30
dbush Avatar answered Sep 20 '22 05:09

dbush