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

自闭症网瘾萝莉.ら 提交于 2019-12-08 14:57:52

问题


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?


回答1:


This covers the case when the exponent is negative.




回答2:


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.




回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/16887763/why-does-a-b-return-a-numeric-when-both-a-and-b-are-integers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!