The function of summing harmonic series in R

I am trying to write a function that takes a positive real number and continues to add members of the harmonic series until the total sum exceeds the original argument. I need my function to display the total number of series terms that have been added.

Here is my code:

harmonic<-function(n){
  x<-c(0,1)
  while (length(x) < n) {
    position <- length(x)
    new <- 1/(x[position] + x[position-1])
    x <- c(x,new)
  }
  return(x)
}

I apologize for the errors in my code, unfortunately, I only worked with R for a month, and this is the first time I use a while loop, and I could not find any useful information.

Thank you, I am very grateful for your help.

+4
source share
2 answers

, maths.stackexchange: https://math.stackexchange.com/q/496116
, . emptor.

harmsum.cnt <- function(x,tol=1e-09) {
  em.cons <- 0.577215664901533
  difffun  <- function(x,n) x - (log(n) + em.cons + 1/(2*n) - 1/(12*n^2))
  ceiling(uniroot(difffun, c(1, 1e10), tol = tol, x = x)$root)
}

, :

harmsum.cnt(7)
#[1] 616

harmsum.cnt(15)
#[1] 1835421

:

tail(cumsum(1/1:616),1); tail(cumsum(1/1:615),1)
#7.001274
#6.999651

dput(tail(cumsum(1/1:1835421),1)); dput(tail(cumsum(1/1:1835420),1))
#15.0000003782678
#14.9999998334336
+1

, . , , , , .

-, - memoise , .

-, () , , . N (N + 1): 2N . parallel, .

-, , .Machine$double.eps 1/n , gmp Rmpfr, .

, , ,

 mylimit <- [pick a value]
        harmsum<-0 
        for(k in 1:N){
     harmsum <- harmsum + 1/k
    if (harmsum >= mylimit) break
    }

( while)

+1

All Articles