-
-
Notifications
You must be signed in to change notification settings - Fork 48.7k
feat: Implemented Matrix Exponentiation Method #11636
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
Closed
Closed
Changes from 22 commits
Commits
Show all changes
27 commits
Select commit
Hold shift + click to select a range
f5211cc
feat: add Matrix Exponentiation method
Acuspeedster 95421d7
feat: added new function matrix exponetiation method
Acuspeedster adf10bf
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] ba1cbc6
feat: This function uses the tail-recursive form of the Euclidean alg…
Acuspeedster fd37108
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 50fd058
reduced the number of characters per line in the comments
Acuspeedster d6fec67
Merge branch 'branch1' of https://github.com/Acuspeedster/Python into…
Acuspeedster ede7215
removed unwanted code
Acuspeedster 0f939a8
feat: Implemented a new function to swaap numbers without dummy variable
Acuspeedster 5dc67f8
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] b581cf5
removed previos code
Acuspeedster 3ad4b6a
removed the previous code
Acuspeedster 31c5645
Done with the required changes
Acuspeedster 6ee1a40
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] e48a3f3
Done with the required changes
Acuspeedster 8085e66
Merge branch 'branch1' of https://github.com/Acuspeedster/Python into…
Acuspeedster f82bd8c
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 8bf1389
Done with the required changes
Acuspeedster 7860646
Merge branch 'branch1' of https://github.com/Acuspeedster/Python into…
Acuspeedster 9ffd634
Done with the required changes
Acuspeedster 4e2456f
Done with the required changes
Acuspeedster 07ed6b9
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 955c792
Update maths/fibonacci.py
Acuspeedster 70dd92d
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 1909143
Done with the required changes
Acuspeedster 6cc39c0
Merge branch 'branch1' of https://github.com/Acuspeedster/Python into…
Acuspeedster b7db4ca
Done with the required changes
Acuspeedster File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -7,6 +7,8 @@ | |
|
||
NOTE 2: the Binet's formula function is much more limited in the size of inputs | ||
that it can handle due to the size limitations of Python floats | ||
NOTE 3: the matrix function is the fastest and most memory efficient for large n | ||
|
||
|
||
See benchmark numbers in __main__ for performance comparisons/ | ||
https://en.wikipedia.org/wiki/Fibonacci_number for more information | ||
|
@@ -17,6 +19,9 @@ | |
from math import sqrt | ||
from time import time | ||
|
||
import numpy as np | ||
from numpy import ndarray | ||
|
||
|
||
def time_func(func, *args, **kwargs): | ||
""" | ||
|
@@ -230,6 +235,79 @@ def fib_binet(n: int) -> list[int]: | |
return [round(phi**i / sqrt_5) for i in range(n + 1)] | ||
|
||
|
||
def matrix_mult_np(a, b): | ||
""" | ||
Multiplies two matrices using numpy's dot product. | ||
|
||
Args: | ||
a: First matrix as a numpy array | ||
b: Second matrix as a numpy array | ||
|
||
Returns: | ||
The product of matrices a and b. | ||
""" | ||
return np.dot(a, b) | ||
|
||
|
||
def matrix_pow_np(m: ndarray, power: int) -> ndarray: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Could we have unit tests for this function as well? |
||
""" | ||
Raises a matrix to the power of 'power' using binary exponentiation. | ||
|
||
Args: | ||
m: Matrix as a numpy array. | ||
power: The power to which the matrix is to be raised. | ||
|
||
Returns: | ||
The matrix raised to the power. | ||
""" | ||
result = np.array([[1, 0], [0, 1]], dtype=int) # Identity matrix | ||
base = m | ||
while power: | ||
if power % 2 == 1: | ||
result = np.dot(result, base) | ||
base = np.dot(base, base) | ||
power //= 2 | ||
return result | ||
|
||
|
||
def fib_matrix_np(n: int) -> int: | ||
""" | ||
Calculates the n-th Fibonacci number using matrix exponentiation. | ||
https://www.nayuki.io/page/fast-fibonacci-algorithms#:~:text= | ||
Summary:%20The%20two%20fast%20Fibonacci%20algorithms%20are%20matrix | ||
|
||
Args: | ||
n: Fibonacci sequence index | ||
|
||
Returns: | ||
The n-th Fibonacci number. | ||
|
||
Raises: | ||
ValueError: If n is negative. | ||
|
||
>>> fib_matrix_np(0) | ||
0 | ||
>>> fib_matrix_np(1) | ||
1 | ||
>>> fib_matrix_np(5) | ||
5 | ||
>>> fib_matrix_np(10) | ||
55 | ||
>>> fib_matrix_np(-1) | ||
Traceback (most recent call last): | ||
... | ||
ValueError: n is negative | ||
""" | ||
if n < 0: | ||
raise ValueError("n is negative") | ||
if n == 0: | ||
return 0 | ||
|
||
m = np.array([[1, 1], [1, 0]], dtype=int) | ||
result = matrix_pow_np(m, n - 1) | ||
return int(result[0, 0]) | ||
|
||
|
||
if __name__ == "__main__": | ||
from doctest import testmod | ||
|
||
|
@@ -242,3 +320,4 @@ def fib_binet(n: int) -> list[int]: | |
time_func(fib_memoization, num) # 0.0100 ms | ||
time_func(fib_recursive_cached, num) # 0.0153 ms | ||
time_func(fib_recursive, num) # 257.0910 ms | ||
time_func(fib_matrix_np, num) # 0.0000 ms |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.