R在内部将数字视为双重?

问题描述 投票:2回答:2

R是否主要将数字视为双倍?

以下代码表明R将数字视为double。即使我将其设为整数,经过一些计算后它也很容易变为两倍。 (代码1)

此外,即使结果看起来像整数,在内部它也被视为double。 (代码2)

我的理解是对的吗?

代码1:

> typeof(5)
[1] "double"

> typeof( 5 / 1 )
[1] "double"

> typeof( as.integer(c(1,2,3)) )
[1] "integer"

> typeof( as.integer(c(1,2,3)) + 1 )
[1] "double"

> typeof( as.integer(c(1,2,3)) / 1 )
[1] "double"

代码2:

> 1 + 2 
[1] 3

> typeof( 1 + 2)
[1] "double"
r integer double
2个回答
1
投票

R以不同方式处理数字。在R中,整数和双精度浮点默认为32位版本。

正如安德烈所指出的,R中有两种不同类型的数字。

  1. 文字1L, 2L, 3L, ....,这相当于as.integer(1)
  2. 常规数字(1,2,3.4,任何数字真的)

以及他们复杂的同行。

文字本身就是整数

typeof(1)  #double
class(1)   #numeric
typeof(1L) #integer
class(1L)  #integer

很明确。但是,在计算时,如果计算的任何部分未存储为低于整数的低于或等于的类型,则它将自动转换为double:

typeof(1L + 1L)   #integer
typeof(1L + 1)    #double
typeof(1L + TRUE) #integer
typeof(1L * 3)    #double
typeof(1L * 3L)   #integer

但是应该注意,因为R运行32位变量,与python 3.x相比,它们的范围有限。然而,通过使用包为bit64的64位整数和Rmpfr,可以绕过32位变量(在大多数情况下!),它提供了任意浮点精度的接口(根据他们的文档)。


0
投票

要从一开始就将数字设为整数,请将L添加到它:

typeof(1L)
# [1] "integer"

使用32位整数有危险:

2e9L
# [1] 2000000000
2e9L + 2e9L
# [1] NA
# Warning message:
# In 2000000000L + 2000000000L : NAs produced by integer overflow
© www.soinside.com 2019 - 2024. All rights reserved.