在 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
我希望两者都返回错误。
最佳答案
为什么使用“L”作为后缀?
我从未见过它被写下来,但我总结起来有两个原因:
后缀
"i"
这与 "I"
太相似了长整数可以取的值取决于字长。 R 本身不支持字长为 64 位的整数。 R 中的整数的字长为 32 位并带有符号,因此范围为
−2,147,483,648
至 2,147,483,647
.较大的值存储为 double
.This wiki page有关于常见数据类型、它们的常规名称和范围的更多信息。
还有来自
?integer
Note that current implementations of R use 32-bit integers for integer vectors, so the range of representable integers is restricted to about +/-2*10^9: doubles can hold much larger integers exactly.
为什么 1.0L 和 1.1L 返回不同的类型?
原因
1.0L
和 1.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;
}
}
关于r - 为什么 R 会使用 "L"后缀来表示整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24350733/