[英]What is the difference between trunc() and as.integer()?
What is the difference between trunc()
and as.integer()
? trunc()
和as.integer()
什么as.integer()
?
Why is as.integer
faster? 为什么as.integer
更快? Can anyone explain a bit what goes on behind the curtain? 任何人都可以解释幕后发生的事情吗?
Why does trunc()
return class double
instead of integer
? 为什么trunc()
返回class double
而不是integer
?
x <- c(-3.2, -1.8, 2.3, 1.5, 1.500000001, -1.499999999)
trunc(x)
[1] -3 -1 2 1 1 -1
as.integer(x)
[1] -3 -1 2 1 1 -1
all.equal(trunc(x), as.integer(x))
[1] TRUE
sapply(list(trunc(x), as.integer(x)), typeof)
[1] "double" "integer"
library(microbenchmark)
x <- sample(seq(-5, 5, by = 0.001), size = 1e4, replace = TRUE)
microbenchmark(floor(x), trunc(x), as.integer(x), times = 1e4)
# I included floor() as well just to see the performance difference
Unit: microseconds
expr min lq mean median uq max neval
floor(x) 96.185 97.651 126.02124 98.237 99.411 67892.004 10000
trunc(x) 56.596 57.476 71.33856 57.770 58.649 2704.607 10000
as.integer(x) 16.422 16.715 23.26488 17.009 18.475 2828.064 10000
help(trunc)
: help(trunc)
:
"trunc takes a single numeric argument x and returns a numeric vector containing the integers formed by truncating the values in x toward 0." “trunc采用单个数字参数x并返回一个数字向量,其中包含通过将x中的值截断为0而形成的整数。”
help(as.integer)
: help(as.integer)
:
"Non-integral numeric values are truncated towards zero (ie, as.integer(x) equals trunc(x) there), [...]" “非整数数值被截断为零(即as.integer(x)等于trunc(x)那里),[...]”
Background : I'm writing functions to translate between different time/date representation, such as 120403 (hhmmss) -> 43443
(seconds since 00:00:00) Performance is all that matters. 背景 :我正在编写函数来在不同的时间/日期表示之间进行转换,例如120403 (hhmmss) -> 43443
(自00:00:00以来的秒数)性能非常重要。
Note: this question has nothing to do with floating point arithmetic 注意:这个问题与浮点运算无关
SessionInfo: R version 3.3.2, Windows 7 x64
On the technical side, these functions have different goals. 在技术方面,这些功能有不同的目标。
The trunc
function removes the fractional part of numbers. trunc
函数删除数字的小数部分。
The as.integer
function converts the input values into 32-bit integers. as.integer
函数将输入值转换为32位整数。
Thus as.integer
would overflow on large numbers (over 2^31): 因此as.integer
将大量溢出(超过2 ^ 31):
x = 9876543210.5
sprintf("%15f", x)
# [1] "9876543210.500000"
sprintf("%15f", trunc(x))
# [1] "9876543210.000000"
as.integer(x)
# [1] NA
Values in your vector
is already numeric
. vector
值已经是numeric
。
as.integer
is used to convert data to numeric
: as.integer
用于将数据转换为numeric
:
as.integer("3.55")
# [1] 3
trunc("3.55")
# Error in trunc("3.55") : non-numeric argument to mathematical function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.