Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added a new function to calculate nth fibonacci number using golden r… #222

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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