Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does `a ^ b` return a numeric when both `a` and `b` are integers?

Given two integers:

a <- 1L
b <- 1L

As I would expect, adding, subtracting, or multiplying them also gives an integer:

class(a + b)
# [1] "integer"
class(a - b)
# [1] "integer"
class(a * b)
# [1] "integer"

But dividing them gives a numeric:

class(a / b)
# [1] "numeric"

I think I can understand why: because other combinations of integers (e.g. a <- 2L and b <- 3L) would return a numeric, it is the more general thing to do to always return a numeric.

Now onto exponentiation:

class(a ^ b)
# [1] "numeric"

This one is a bit of a surprise to me. Can anyone explain why it was designed this way?

like image 908
flodel Avatar asked Jun 02 '13 22:06

flodel


2 Answers

This covers the case when the exponent is negative.

like image 110
Rob Lyndon Avatar answered Oct 07 '22 18:10

Rob Lyndon


Consider ^ as a family of functions, f(a)(b) = a^b. For a=2, the domain for which this returns integer is limited to the values [0,62] (assuming 64-bit signed integers). That is a very small subset of the valid inputs. The domain only gets smaller as a increases.

like image 30
Matthew Lundberg Avatar answered Oct 07 '22 17:10

Matthew Lundberg