0

I want to calculate the quotients of a Fibonacci series, such that:

enter image description here

I have created a function to calculate the Fbonacci series, and is ok, but i'm having troubles calculating the quotients. This is my function:

fibonacci <- function(n){
  numbers <- numeric(n)
  numbers[1] <- 1
  numbers[2] <- 1
  for (i in 3:n)  
    numbers[i] <- numbers[i-1]+numbers[i-2]
  return(numbers)
}

This will calculate the Fibonacci sequence. This is what i have tried to calculate the quotients:

fibonacci_q <- function(n){
  numbers <- numeric(n)
  numbers[1] <- 1
  numbers[2] <- 1
  for (i in 3:n)  
    numbers[i] <- numbers[i-1]+numbers[i-2]
  return(numbers/numbers[i-1])
}

This not working properly, it returns really small numbers, and i'm not getting the same results displayed in the table above. Can someone explain me what i'm i doing wrong and how to fix it please?

Thank you very much in advance

Miguel 2488
  • 1,410
  • 1
  • 20
  • 41

1 Answers1

1

Currently, you are dividing all numbers with n-1th number. Your function is giving you values

fibonacci_q(10)
#[1] 0.0294 0.0294 0.0588 0.0882 0.1471 0.2353 0.3824 0.6176 1.0000 1.6176

which is equal to

fibonacci(10)/34
#[1] 0.0294 0.0294 0.0588 0.0882 0.1471 0.2353 0.3824 0.6176 1.0000 1.6176

why 34? because it is 9th number in fibonacci(10) sequence (which is n-1th number).

You need to change the function to

fibonacci_q <- function(n){
   numbers <- numeric(n)
   numbers[1] <- 1
   numbers[2] <- 1
   for (i in 3:n)  
     numbers[i] <- numbers[i-1]+numbers[i-2]
  return(c(NA, numbers[-1]/numbers[-length(numbers)]))
}

fibonacci_q(10)
# [1]   NA 1.00 2.00 1.50 1.67 1.60 1.62 1.62 1.62 1.62

which is now equal to

c(NA, fibonacci(10)[-1]/fibonacci(10)[-10])
#[1]   NA 1.00 2.00 1.50 1.67 1.60 1.62 1.62 1.62 1.62
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • damn, i was stuck in that. So basically, you remove the first element from the vector of numbers. But later, what is the `numbers[-length(numbers)` doing?? – Miguel 2488 May 04 '19 at 15:33
  • @Miguel2488 it removes the last number from the vector of numbers. So basically, 2nd number gets divided by 1st, 3rd by 2nd and nth number by n-1 th number. – Ronak Shah May 04 '19 at 15:37
  • ahh so this equivalent to `numbers[i-1]`?? – Miguel 2488 May 04 '19 at 15:38
  • 1
    nope. Check `a <- 1:10;n <- 10;`. Now see the difference between `a[n-1]` and `a[-n]`. – Ronak Shah May 04 '19 at 15:40
  • aahh i see whats happening, i was substracting 1 to each element in the vector but the way to do was to just remove the last element so the numbers would be divided by the previous number at each time, is that? – Miguel 2488 May 04 '19 at 15:42
  • 1
    Thank you very much for yor help!! I understood it well now – Miguel 2488 May 04 '19 at 15:44