user16461886
user16461886

Reputation:

Does anyone know how I can make my code run faster?

I am trying to calculate Sigma(n=0 to infinity) (−1)^n/(n + 1) as accurately as possible. But my code takes forever and I am not able to see whether my answer is right. Does anyone know how I can make my code faster? The sum is supposed to converge to log(2). My idea is that f(n) will eventually become a very small number (less than 2^-52) and a time would come when R would consider sum = sum + f(n) and that's when I'd want the code to stop running. But clearly, that doesn't seem to work and my code takes forever to run and at least to me, it doesn't seem to ever stop.

f <- function(n) 
  return(((-1)^(n))/(n+1))


s <- function(f){
  sum <- 0
  n <- 0
  while(sum != sum + f(n)) {
    sum <- sum + f(n)
    n <- n + 1
  }
  return(c(sum, n))
}

s(f)

Upvotes: 0

Views: 283

Answers (1)

Arnaud Feldmann
Arnaud Feldmann

Reputation: 765

library(Rcpp)
cppFunction("
List s(int max_iter) {
  double sum = 0;
  double sum_prec=NA_REAL;
  double n = 0;
  for (;sum != sum_prec && n < max_iter;n++) {
    sum_prec = sum;
    sum+=pow(-1,n)/(n+1);
  }
  return  List::create( 
   _[\"sum\"]  = sum, 
   _[\"iterations\"]  = n, 
   _[\"precision\"] = sum-sum_prec
 ) ;
}")
test <- s(100000000)
test

When you use a huge number of subsequent iterations you know that R is not appropriated. However C++ functions are very easy to use within R. You can do something like that by example. The function needs a max of iterations and returns a list with your sum, the number of iterations and the precision.

EDIT : By precision I only do sum-sum_prec so this is not the real interval.

EDIT 2 : I let the sum != sum_prec for the example but if you don't have a supercomputer you're not supposed to see the end lol

EDIT 3 :

Typically, a fast R base solution would be something like :

base_sol <- function(n_iter) {
  v <- seq_len(n_iter)
  v <- (-1L)^(v-1L)/v
  list(
    sum = sum(v),
    iterations = n_iter,
    precision = v[length(v)]
  )
}

Which is only 1.5 times slower than c++, which is pretty fast for an interpreted language, but has the con of loading every member of the sum in ram (but then, R is made for stats not for calculating things at 2^-52)

Upvotes: 3

Related Questions