13

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?

flodel
  • 87,577
  • 21
  • 185
  • 223
  • 2
    I guess it's because the result can lead to `Inf`?? `as.integer(Inf)` would result in `NA`. Ex: 2L ^ 10000L – Arun Jun 02 '13 at 22:07
  • 1
    While I like the selected answer, perhaps one could ask whether there's any advantage to having the actual code for exponentiation create yet another "corner case." Especially if either `R` code or the `unix` `pow` function which can be called uses logs to calculate exponents in the first place. – Carl Witthoft Jun 03 '13 at 01:02

4 Answers4

17

This covers the case when the exponent is negative.

Matthew Lundberg
  • 42,009
  • 6
  • 90
  • 112
Rob Lyndon
  • 12,089
  • 5
  • 49
  • 74
6

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.

Matthew Lundberg
  • 42,009
  • 6
  • 90
  • 112
  • interesting. I think I like Rob Lyndon's answer better ("the integers are not closed [mathematically] under the `^` operation"), but yours is reasonable ("the integers are not closed [computationally] under the `^` operation") -- but this gets tricky because one has to start deciding on mushy/pragmatic grounds ... – Ben Bolker Jun 02 '13 at 22:15
0

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.

itfeature.com
  • 380
  • 4
  • 16
0

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

MichaelChirico
  • 33,841
  • 14
  • 113
  • 198
Earl F Glynn
  • 375
  • 2
  • 7