为什么R会使用"L"后缀来表示整数?

Sim*_*lon 32 parsing integer r semantics

在R中我们都知道,对于那些我们想要确保处理整数以使用"L"后缀来指定它的方式来说这很方便:

1L
# [1] 1
Run Code Online (Sandbox Code Playgroud)

如果我们没有明确告诉R我们想要一个整数,它会假设我们打算使用numeric数据类型......

str( 1 * 1 )
# num 1
str( 1L * 1L )
# int 1
Run Code Online (Sandbox Code Playgroud)

为什么"L"是首选后缀,为什么不是"我"呢?有历史原因吗?

另外,为什么R允许我做(有警告):

str(1.0L)
# int 1
# Warning message:
# integer literal 1.0L contains unnecessary decimal point 
Run Code Online (Sandbox Code Playgroud)

但不是..

str(1.1L)
# num 1.1
#Warning message:
#integer literal 1.1L contains decimal; using numeric value 
Run Code Online (Sandbox Code Playgroud)

我希望两者都返回一个错误.

Sim*_*lon 32

为什么"L"用作后缀?

我从来没有看到它写下来,但我理所当然地说明了两个原因:

  1. 因为R处理可以使用后缀指定的复数"i",这将太简单了"I"

  2. 因为R的整数是32位长整数,因此"L"似乎是引用此数据类型的合理简写.

长整数可以取的值取决于字大小.R本身不支持字长为64位的整数.R中的整数具有32位的字长并且是有符号的,因此具有范围 ?2,147,483,648to 2,147,483,647.较大的值存储为double.

此Wiki页面提供了有关常见数据类型,常规名称和范围的更多信息.

还来自 ?integer

注意,R的当前实现使用32位整数作为整数向量,因此可表示整数的范围被限制为大约+/- 2*10 ^ 9:双精度可以精确地保持更大的整数.


为什么1.0L和1.1L会返回不同的类型?

之所以1.0L1.1L将返回不同的数据类型,因为返回一个整数1.1会导致信息丢失,而对于1.0它不会(但你可能想知道你不再有一个浮点数字).深入了解词法分析器(/src/main/gram.c:4463-4485)是这段代码(函数的一部分NumericValue()),它实际上是int从一个double以ascii为后缀的输入创建一个数据类型"L":

/* Make certain that things are okay. */
if(c == 'L') {
double a = R_atof(yytext);
int b = (int) a;
/* We are asked to create an integer via the L, so we check that the
   double and int values are the same. If not, this is a problem and we
   will not lose information and so use the numeric value.
*/
if(a != (double) b) {
    if(GenerateCode) {
    if(seendot == 1 && seenexp == 0)
        warning(_("integer literal %s contains decimal; using numeric value"), yytext);
    else {
        /* hide the L for the warning message */
        *(yyp-2) = '\0';
        warning(_("non-integer value %s qualified with L; using numeric value"), yytext);
        *(yyp-2) = (char)c;
    }
    }
    asNumeric = 1;
    seenexp = 1;
}
}
Run Code Online (Sandbox Code Playgroud)

  • [r语言定义的相关部分](http://cran.r-project.org/doc/manuals/r-release/R-lang.html#Constants)似乎没有说任何更具启发性的内容 (3认同)
  • @ user1436187我不这么认为.我引用了"R 3.1.0".这些将是"双重"类型,如答案中所述.参见例如[**here**](http://r.789695.n4.nabble.com/Reading-64-bit-integers-tp3414704p3416388.html).整数使用长度为32位的C`int`类型.现在,使用`double`数据类型的双精度向量也可以表示整数. (2认同)

jxf*_*jxf 5

可能是因为R是用C编写的,而L在C中用于(长)整数