Skip to content

Commit

Permalink
Added a new function to calculate nth fibonacci number using golden r… (
Browse files Browse the repository at this point in the history
#222)

* Added a new function to calculate nth fibonacci number using golden ratio, Closes:#221

Signed-off-by: Mukul Bindal <[email protected]>

* Added validation and doc string.

Signed-off-by: Mukul Bindal <[email protected]>

---------

Signed-off-by: Mukul Bindal <[email protected]>
Co-authored-by: Mukul Bindal <[email protected]>
  • Loading branch information
mukulbindal and Mukul Bindal authored Oct 16, 2024
1 parent 140737e commit 3e87bf9
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
22 changes: 22 additions & 0 deletions cereja/mathtools/_op.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
"least_common_multiple",
"degrees_to_radian",
"radian_to_degrees",
"nth_fibonacci_number",
]


Expand Down Expand Up @@ -130,3 +131,24 @@ def degrees_to_radian(val):

def radian_to_degrees(val):
return (val * 180.0) / math.pi


def nth_fibonacci_number(val:int) -> int:
"""
Calculates the nth fibonacci number using the golden ratio formula.
Args:
val(int): The index (val>0) of the Fibonacci number to calculate
Returns:
int: The nth Fibonacci number
Example:
>>> nth_fibonacci_number(10)
34
"""
if val < 1:
raise ValueError("val should be greater than 0")
val -= 1 # First Fibonacci number is 0
phi = (1 + 5**0.5) / 2
return round(phi**val / 5**0.5)
14 changes: 13 additions & 1 deletion tests/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
)
from cereja.utils import is_iterable, is_sequence, chunk
from cereja.array import prod
from cereja.mathtools import theta_angle
from cereja.mathtools import theta_angle, nth_fibonacci_number
from cereja.config.cj_types import Number
from cereja.mltools import Corpus
from cereja.mltools.pln import LanguageData
Expand Down Expand Up @@ -158,6 +158,18 @@ def test_matrix(self):
expected = Matrix([[1.0, 1.0, 1.0], [1.0, 1.0, 1.0]])
self.assertTrue((a / b) == expected)

def test_nth_fibonacci_number(self):
with self.assertRaises(ValueError):
nth_fibonacci_number(-1)
self.assertEqual(nth_fibonacci_number(1), 0)
self.assertEqual(nth_fibonacci_number(2), 1)
self.assertEqual(nth_fibonacci_number(3), 1)
self.assertEqual(nth_fibonacci_number(4), 2)
self.assertEqual(nth_fibonacci_number(5), 3)
self.assertEqual(nth_fibonacci_number(10), 34)
self.assertEqual(nth_fibonacci_number(12), 89)
self.assertEqual(nth_fibonacci_number(20), 4181)


class PathTest(unittest.TestCase):
def test_sanity(self):
Expand Down

0 comments on commit 3e87bf9

Please sign in to comment.