Fibonacci Numbers In R

Hi. This page is about creating a function which would extract Fibonacci numbers in R.

(This function can also be coded in other programming languages such as Python and C++. )

 


A Function Which Extracts A Fibonacci Number In R

My main objective for this function is to have the function output the n-th Fibonacci number in a Fibonacci sequence.

Remember that the Fibonacci sequence starts with 1 and 1 as follows:

    \[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...\]

(An alternate version of the Fibonacci sequence has the sequence starting at 0 and 1.)

If n = 5, the fifth Fibonacci number in the above sequence would be 5.

 


Before introducing the Fibonacci function, I have included a brief review of functions in R, if-else statements in R and for-loops in R.

Functions In R

Recall that a function in R follows this format.

To use the function, the function_name along with the argument(s) needs to be declared. An example of a function call would be something like:

 

If-Else Statements In R

In this Fibonacci function, I use an if-else statement for dealing with cases. I want the user of the function to put in whole numbers that are at least 1.

In R, the if-else statement follows a format which looks something like this:

For Loops In R

For loops is a compact way to repeatedly run lines of code while changing variable values. The for-loop format in R would look something like:

A simple example of a for loop in printing numbers from 1 to 10.

 

 

The Fibonacci Function In R

The code for the Fibonacci function can be found below. The user puts in a single argument which should be a positive whole number (integer) that is at least 1 or greater. In the function, the if-else statement deals with cases for numbers less than 1 and for non-whole numbers (by making sure the fractional part of the number is 0).

Since the Fibonacci sequence relies on the previous two numbers in the sequence (with 1 and 1 as the first two numbers), a for loop is used here. The n-th Fibonacci number in the sequence is represented by fibonacci_vect[n] which is used in the paste0() string concatenation function.

 

 


Test Cases

To make sure that the function works and is error free, some testing is required. I want to test cases where the numbers in the function call are negative, 1, 2, and numbers with a fractional part (non-whole numbers).

 

 


References

https://stackoverflow.com/questions/3476782/check-if-the-number-is-integer

https://www.programiz.com/r-programming/if-else-statement

Leave a Reply