How do I do a repeat structure function on R?

Asked

Viewed 40 times

1

I’m trying this way:

 H <- function(n) {

   for (i in 1:length(n))
   {
   x <- 0
   a <- 2
   b <- 3
   func = x + a/b
   a+2
   b+2
   return(func)
   }
 }

Does anyone know how to solve?

1 answer

4

Here are five ways to solve the problem.

1. With cycle while

H1 <- function(n){
  numer <- 2L
  denom <- 3L
  termos <- 0L
  total <- 0L
  while(termos < n){
    total <- total + numer/denom
    numer <- numer + 2L
    denom <- denom + 2L
    termos <- termos + 1L
  }
  total
}
H1(4)
#[1] 3.212698

2. With cycle for

H2 <- function(n){
  total <- 0
  for(i in seq_len(n)){
    total <- total + 2*i/(2*i + 1L)
  }
  total
}
H2(4)
#[1] 3.212698

3. With cycle *apply.

H3 <- function(n){
  x <- sapply(seq_len(n), function(i) 2*i/(2*i + 1L))
  sum(x)
}
H3(4)
#[1] 3.212698

4. Vectorized

This is the best, most correct way since R is a vector language. First it creates two vectors, one of even numbers (the numerators of the fractions) and the other of odd numbers (the denominators). Then, with a single instruction, calculate all fractions and sum the results. Since this is the last instruction, it will be the function output value.

H <- function(n){
  pares <- seq(2, by = 2, length.out = n)
  impares <- seq(3, by = 2, length.out = n)
  sum(pares/impares)
}
H(4)
#[1] 3.212698

5. Another vector function.

And now in one line.

H <- function(n) sum(2*seq_len(n)/(2*seq_len(n) + 1))
H(4)
#[1] 3.212698

Browser other questions tagged

You are not signed in. Login or sign up in order to post.