Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the default return type of `ceiling` and `floor` numeric?

Why are the following all "numeric"?

class(ceiling(3))
class(ceiling(3L))
class(ceiling(3.1))
class(floor(2))
class(floor(2L))
class(floor(2.1))

This seems like one arithmetic operation where the result is unambiguously an integer (unlike, say, exponentiation), regardless of inputs (it's an error to pass a complex number).

I tried poking around for an answer related in the underlying C code but didn't really get anywhere.

I also learned that, while "%/%"(x,y) should also always be an integer, the class of the results depends on the input types, e.g. 5%/%2, 6%/%2 and 6%/%2L are all numeric, but 5L%/%2L and 6L%/%2L are both integer (something about this is mentioned in ?Arithmetic); this doesn't really make sense to me either, but at least it's documented.

Is there a simple reason for returning numeric objects from ceiling and floor? If it were about inefficiency due to re-casting (which seems may be the case for integer division), I would expect class(ceiling(3L)) to be "integer", so what's going on?

like image 877
MichaelChirico Avatar asked Aug 19 '15 20:08

MichaelChirico


1 Answers

I don't know if this is why ceiling was designed to return numeric, but the following example shows the limitations ceiling would have if it actually returned an integer:

options(digits = 15)
.Machine$integer.max + 1.4
#[1] 2147483648.4

ceiling(.Machine$integer.max + 1.4)
#[1] 2147483649

as.integer(ceiling(.Machine$integer.max + 1.4))
#[1] NA
#Warning message:
#NAs introduced by coercion 

That said, there is no good reason that I see why ceiling doesn't return an integer when given an integer input.

like image 113
eddi Avatar answered Sep 19 '22 00:09

eddi