gpt4 book ai didi

r - trunc() 和 as.integer() 有什么区别?

转载 作者:行者123 更新时间:2023-12-01 12:21:14 25 4
gpt4 key购买 nike

trunc()有什么区别和 as.integer() ?

为什么是 as.integer快点?谁能解释一下幕后发生了什么?

为什么trunc()返回类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) :

"trunc takes a single numeric argument x and returns a numeric vector containing the integers formed by truncating the values in x toward 0."


help(as.integer) :

"Non-integral numeric values are truncated towards zero (i.e., as.integer(x) equals trunc(x) there), [...]"



背景 :我正在编写函数来在不同的时间/日期表示之间进行转换,例如 120403 (hhmmss) -> 43443 (从 00:00:00 开始的秒数)性能才是最重要的。

注:本题与浮点运算无关
SessionInfo: R version 3.3.2, Windows 7 x64

最佳答案

在技​​术方面,这些功能有不同的目标。
trunc函数删除数字的小数部分。
as.integer函数将输入值转换为 32 位整数。

因此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

关于r - trunc() 和 as.integer() 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43894077/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com