R中整数计算期间从整数到数字的自动转换?
以下是两个片段:R中整数计算期间从整数到数字的自动转换?,r,types,type-conversion,R,Types,Type Conversion,以下是两个片段: a = 1:1000000; res = as.integer(0); class(res) system.time(for (e in a) res = res + e ^ 2) class(res) ########################### fn1 <- function (N) { for(i in 1:N) { y <- i*i } } print (fn1(1000000)) 我的问题是:res为什么从“整数”变为“数字
a = 1:1000000; res = as.integer(0);
class(res)
system.time(for (e in a) res = res + e ^ 2)
class(res)
###########################
fn1 <- function (N)
{
for(i in 1:N) {
y <- i*i
}
}
print (fn1(1000000))
我的问题是:
res
为什么从“整数”变为“数字”?因为幂运算^
以双精度返回浮点数
typeof( (2L) ^ 2 )
#[1] "double"
typeof( (2L) ^ (2L) )
#[1] "double"
如果您确实想在整数溢出实验中使用它,请使用
res = res + as.integer(e ^ 2)
您是否已获得R文档
?“^”
(或?算术
):
如果两个参数都是integer类型,则/
和^
的结果类型是数字,而对于其他运算符,它是整数(溢出,发生在+/-(2^31-1)
,返回为NA_integer,并带有警告)。来自帮助(“^”)
:如果两个参数都是integer类型,/and^的结果类型为数字,而对于其他运算符,则为整数(溢出发生在+/-(2^31-1),返回为NA_integer_uu,并带有警告)。
res = res + as.integer(e ^ 2)