Question

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?

Was it helpful?

Solution

This covers the case when the exponent is negative.

OTHER TIPS

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.

Its simple adding, subtracting, and multiplying two integers results in integer. while dividing or performing exponentiation results in number with/without decimal that why shown numeric instead of integer.

Is it possible a^b was implemented as something like exp(b * log(a))?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top