I am a novice in R, and so what seemed to work fine in C and Python, surprisingly breaks down in R. I am trying to calculate the product of the first 1000 Fibonacci numbers. Here is the full code:
#PRRODUCT OF FIBONACCI NUMBERS
Fibonacci<-rep(0, 1000)
Fibonacci[0]<-1
Fibonacci[1]<-1
Product<-1
for (i in 2:1000)
{
Fibonacci[i]<-(Fibonacci[i-1])+(Fibonacci[i-2])
Product<-Fibonacci[i]*Product
}
Fibonacci[1000]
Product
This returns the following error:
Error in Fibonacci[i] <- (Fibonacci[X - 1]) + (Fibonacci[X - 2]) :
replacement has length zero
I am inclined to think I have misunderstood operating with different elements of an array (perhaps the i-2 in the vector description is not correct), but I haven't found anything over the past hour and a half which would have helped me correct it. So, any insights into the cause of the problem would be most appreciated.
Thank you in advance.
Arrays in R are 1-based.
Fibonacci[1]<-1
Fibonacci[2]<-1
Product<-1
for (i in 3:1000)
{
(the remainder as in your question)
The problem is Fibonacci[0]
which is a 0-length numeric. When i = 2
, this expression has a right hand side of numeric(0)
:
Fibonacci[i]<-(Fibonacci[i-1])+(Fibonacci[i-2])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With