Skip to content

Instantly share code, notes, and snippets.

@richfitz
Last active December 16, 2015 12:19
Show Gist options
  • Save richfitz/5433804 to your computer and use it in GitHub Desktop.
Save richfitz/5433804 to your computer and use it in GitHub Desktop.
Faster version of 1-(prod(1-x))
#include <vector>
// [[Rcpp::export]]
double or_cpp(std::vector<double> x) {
double tot = 1.0;
for ( size_t i = 0; i < x.size(); i++ )
tot *= (1 - x[i]);
return 1 - tot;
}
/*
## Benchmarking:
library(Rcpp)
library(rbenchmark)
sourceCpp("or.cpp")
f <- function(n) {
set.seed(1)
x <- runif(n, 0, .1)
or <- function(x) 1-(prod(1-x))
gc()
res <- benchmark(or(x), or_cpp(x), replications=500, order=NULL)
res$relative[[2]] / res$relative[[1]]
}
## Surprising behaviour -- R is about the same as C++ until very
## large sample sizes, where R starts killing C++; probably switching
## to a different algorithm?
n <- round(10^(seq(1, 5, length=21)))
r <- sapply(n, f)
plot(r ~ n, log="x")
abline(h=1, lty=3)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment