R为什么会使用“ L”后缀表示整数?

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

在R中,我们都知道在那些时候我们想确保我们正在处理一个使用"L"后缀指定它的整数,这很方便:

1L
# [1] 1

如果我们不明确告诉R我们想要一个整数,它将假定我们打算使用numeric数据类型...

str( 1 * 1 )
# num 1
str( 1L * 1L )
# int 1

为什么“ L”是首选的后缀,为什么不选择“ I”?有历史原因吗?

此外,R为什么允许我这样做(带有警告):

str(1.0L)
# int 1
# Warning message:
# integer literal 1.0L contains unnecessary decimal point 

但不是..

str(1.1L)
# num 1.1
#Warning message:
#integer literal 1.1L contains decimal; using numeric value 

我希望两个都返回一个错误。

r parsing integer semantics
2个回答
32
投票

为什么将“ L”用作后缀?

我从来没有看过它,但是我归纳为两个原因:

  1. 因为R处理的复数可以使用后缀"i",对于"I"

  2. 来说太相似了
  3. 因为R的整数是32位长的整数,因此“ L”似乎是引用此数据类型的明智捷径。

长整数可以取的值取决于单词的大小。 R本机不支持字长为64位的整数。 R中的整数的字长为32位,并且有符号,因此范围为−2,147,483,6482,147,483,647。较大的值存储为double

[This wiki page具有有关常见数据类型,其常规名称和范围的更多信息。

也来自?integer

注意,R的当前实现将32位整数用于整数矢量,因此可表示整数的范围限制为大约+/- 2 * 10 ^ 9:双精度数可以精确地容纳更大的整数。


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

1.0L1.1L返回不同数据类型的原因是因为为1.1返回整数将导致信息丢失,而对于1.0则不会(但是您可能想知道不再具有浮点数字)。该代码(是/src/main/gram.c:4463-4485的一部分)深深地嵌入了词法分析器(NumericValue())中,该代码实际上是通过以[ASCII] int为后缀的double输入创建"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;
}
}

0
投票

for:为常量显式创建一个整数值

© www.soinside.com 2019 - 2024. All rights reserved.