Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursion error in R (Fibonacci sequence)

Tags:

r

stdin

rscript

So I am trying to learn R on my own and am just working through the online tutorial. I am trying to code a recursive function that prints the first n terms of the Fibonacci sequence and can't get the code to run without the error:

Error in if (nterms <= 0) { : missing value where TRUE/FALSE needed

My code does ask me for input before entering the if else statement either which I think is odd as well. Below is my code any help is appreciated.

#Define the fibonacci sequence

recurse_fibonacci <- function(n) {
    # Define the initial two values of the sequence

    if (n <= 1){
        return(n)
    } else {

    # define the rest of the terms of the sequence using recursion
    return(recurse_fibonacci(n-1) + recurse_fibonacci(n-2))
    }
}

#Take input from the user
nterms = as.integer(readline(prompt="How many terms? "))

# check to see if the number of terms entered is valid
if(nterms <= 0) {
    print("please enter a positive integer")
} else {

    # This part actually calculates and displays the first n terms of the sequence
    print("Fibonacci Sequence: ")
    for(i in 0:(nterms - 1)){
        print(recurse_fibonacci(i))
    }
}
like image 476
apr92 Avatar asked Jun 01 '20 22:06

apr92


People also ask

How is recursion used in the Fibonacci sequence?

Recursion will happen till the bottom of each branch in the tree structure is reached with the resulting value of 1 or 0. During recursion these 1's and 0's are added till the value of the Fibonacci number is calculated and returned to the code which called the fibonacci method in the first place.

Is the Fibonacci sequence recursion?

The famous Fibonacci sequence. This famous sequence is recursive because each term after the second term is the sum of the previous two terms.

How do you do Fibonacci without recursion?

The logic of calculating nth Fibonacci number is implemented in this method and it does that without using recursion. It uses a simple for loop to iterate until the nth number and calculate Fibonacci number using the following formula : f(n) = f(n-1) + f(n-2);

What is the time complexity of recursion Fibonacci?

C program for The Fibonacci series can be found using the recursion method with time complexity of T(2^N) and space complexity of T(N).


2 Answers

This is a problem of readline in non-interactive mode. readline does not wait for a keypress and immediately executes the next instruction. The solution below is the solution posted in this other SO post.

I post below a complete answer, with the Fibonnaci numbers function a bit modified.

recurse_fibonacci <- function(n) {
  # Define the initial two values of the sequence
  if (n <= 1){
    n
  } else{
    # define the rest of the terms of the sequence using recursion
    Recall(n - 1) + Recall(n - 2)
  }
}

#Take input from the user
cat("How many terms?\n")
repeat{
  nterms <- scan("stdin", what = character(), n = 1)
  if(nchar(nterms) > 0) break
}
nterms <- as.integer(nterms)

# check to see if the number of terms entered is valid
if(nterms <= 0) {
  print("please enter a positive integer")
} else {
  # This part actually calculates and displays the first n terms of the sequence
  print("Fibonacci Sequence: ")
  for(i in 0:(nterms - 1)){
    print(recurse_fibonacci(i))
  }
}

This code is the contents of file fib.R. Running in a Ubuntu 20.04 terminal gives

rui@rui:~$ Rscript fib.R
How many terms?
8
Read 1 item
[1] "Fibonacci Sequence: "
[1] 0
[1] 1
[1] 1
[1] 2
[1] 3
[1] 5
[1] 8
[1] 13
rui@rui:~$
like image 157
Rui Barradas Avatar answered Oct 12 '22 05:10

Rui Barradas


To make it work with Rscript replace

nterms = as.integer(readline(prompt="How many terms? "))

with

cat ("How many terms?")
nterms = as.integer (readLines ("stdin", n = 1))

Then you can run it as Rscript fib.R, assuming that the code is in the file fib.R in the current working directory.

Otherwise, execute it with source ("fib.R") within an R shell.

Rscript does not operate in interactive mode and does not expect any input from the terminal. Check what interactive () returns in both the cases. Rscript will return FALSE as it is non-interactive, but the same function when run within an R shell (with source ()) it will be true.

?readline mentions that it cannot be used in non-interactive mode. Whereas readLines explicitely connect to stdin.

like image 2
phoxis Avatar answered Oct 12 '22 03:10

phoxis