diff --git a/cereja/mathtools/_op.py b/cereja/mathtools/_op.py index b39ebc1..31bac82 100644 --- a/cereja/mathtools/_op.py +++ b/cereja/mathtools/_op.py @@ -39,6 +39,7 @@ "least_common_multiple", "degrees_to_radian", "radian_to_degrees", + "nth_fibonacci_number", ] @@ -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) \ No newline at end of file diff --git a/tests/tests.py b/tests/tests.py index 6223a19..96a5535 100644 --- a/tests/tests.py +++ b/tests/tests.py @@ -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 @@ -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):