Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在R中查找整数中最低有效位的最快/最有效方法是什么?_R_Optimization_Bit Manipulation_Bitwise Operators - Fatal编程技术网

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

在R中查找整数中最低有效位的最快/最有效方法是什么?,r,optimization,bit-manipulation,bitwise-operators,R,Optimization,Bit Manipulation,Bitwise Operators,对于R,我的问题类似于、、和。我需要找到R中整数中最低有效集位的位置。提出的解决方案如下: unlist(lapply(x, function(z) min(which(as.integer(intToBits(z)) == 1))-1)) 有更有效的方法吗?以下方法速度更快: f <- function(x){ log2(bitwAnd(x,-x)) } f tests sum(f(tests)=g(tests))#只是为了检查 [1] 1000 >微基准(f(测试),g(测试)

对于R,我的问题类似于、、和。我需要找到R中整数中最低有效集位的位置。提出的解决方案如下:

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

有更有效的方法吗?

以下方法速度更快:

f <- function(x){
  log2(bitwAnd(x,-x))
}
f tests sum(f(tests)=g(tests))#只是为了检查
[1] 1000
>微基准(f(测试),g(测试))
单位:微秒
expr最小lq平均uq最大neval
f(测试)38.435 40.5515 45.82673 42.667 45.1355 146.337 100
g(测试)1985.940 2083.9680 2530.79036 2131.218 2287.4280 11749.204 100

< p>如果你有长向量,想进入C++,那么下面的代码可能会帮助你(与<代码> Rcpp < /Cord>和<代码> FFS/COD>函数从<代码>字符串.H < /C> >:


此外,在GCC中,还有
\uuu内置的ffs()
函数。我想知道C++的方法是否更好。很高兴看到它被确认(+1)。
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
#include <Rcpp.h>
#include <strings.h>
using namespace Rcpp;

// [[Rcpp::export]]
Rcpp::IntegerVector lsb(const IntegerVector x)
{
  IntegerVector res(x.size());
  std::transform(x.begin(), x.end(), res.begin(), ffs);
  return(res-1);  # To start from 0
}
> x <- floor(runif(10000,1,2^31))
> microbenchmark::microbenchmark(f(x), g(x), lsb(x))
Unit: microseconds
   expr       min         lq        mean    median         uq       max neval
   f(x)   121.771   129.6360   168.91273   133.241   151.0110  1294.667   100
   g(x) 36165.757 40508.1740 50371.45183 42608.686 60460.5270 94664.255   100
 lsb(x)    25.767    26.8015    34.58856    33.035    35.2385   156.852   100