From 3e87bf980fbdb29c3776cf3a54ede9ce4e22f5c0 Mon Sep 17 00:00:00 2001 From: Mukul Bindal <48384048+mukulbindal@users.noreply.github.com> Date: Wed, 16 Oct 2024 19:07:00 +0530 Subject: [PATCH] =?UTF-8?q?Added=20a=20new=20function=20to=20calculate=20n?= =?UTF-8?q?th=20fibonacci=20number=20using=20golden=20r=E2=80=A6=20(#222)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Added a new function to calculate nth fibonacci number using golden ratio, Closes:#221 Signed-off-by: Mukul Bindal * Added validation and doc string. Signed-off-by: Mukul Bindal --------- Signed-off-by: Mukul Bindal Co-authored-by: Mukul Bindal --- cereja/mathtools/_op.py | 22 ++++++++++++++++++++++ tests/tests.py | 14 +++++++++++++- 2 files changed, 35 insertions(+), 1 deletion(-) 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):