gpt4 book ai didi

r - 在R中找到整数中最低有效位的最快/最有效方法是什么?

转载 作者:行者123 更新时间:2023-12-03 16:25:05 24 4
gpt4 key购买 nike

我有类似 What's the fastest method to return the position of the least significant bit set in an integer in Python 3? 的问题, finding the first set bit in a binary number , 和 Position of least significant bit that is set对于R。我需要找到R中整数中最低有效位的位置。Spätzle提出的解决方案是以下内容:

unlist(lapply(x, function(z) min(which(as.integer(intToBits(z)) == 1))-1))

有没有更有效的方法?

最佳答案

下面的要快得多:

f <- function(x){
log2(bitwAnd(x,-x))
}

比较:

g <- function(x){
unlist(lapply(x, function(z) min(which(as.integer(intToBits(z)) == 1))-1))
}

快速测试:

> library(microbenchmark)
> tests <- floor(runif(1000,1,2^31))
> sum(f(tests) == g(tests)) #just to check
[1] 1000
> microbenchmark(f(tests),g(tests))
Unit: microseconds
expr min lq mean median uq max neval
f(tests) 38.435 40.5515 45.82673 42.667 45.1355 146.337 100
g(tests) 1985.940 2083.9680 2530.79036 2131.218 2287.4280 11749.204 100

关于r - 在R中找到整数中最低有效位的最快/最有效方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54267291/

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