Search code examples
rfunctionfractions

Function for sum of fractions in R


I want to write a function to sum fractions. x is the numerator and n the maximum of x. I want to sum all fractions of x/c if c = x+1 and stop if c == y.

For example, if x = 1 and y = 4

1/1 + 1/2 + 1/3 + 1/4 = 2.083333

Or, if x = 2 and y = 5

2/1 + 2/2 + 2/3 + 2/4 + 2/5 = 4.566667

I tried a while loop but I think that's not even close:

score <- function(x, y){
  while (c < y){
    c <- x/1
    c <- x/c+1
  }
}

Solution

  • Edit: Avoid loops in R when possible.

    f <- function(x,y) x * sum(1/(1:y))