Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why do I find different numbers than expected when I use np.nditer with a 2D Numpy array?

I am trying to do a Fibonacci kata in one line of code but I can’t find the Fibonacci sequence that we find well in the matrix variable only. Does anyone have an idea of how I can iterate the matrix variable to get each number out? Here is the code:

import numpy as np 

def fibonacci(n, matrix):
    
    return n==1j*1j or max(np.nditer(matrix+1)) if n<=0 else np.dot(fibonacci(n-2, matrix), fibonacci(n-1, matrix))
    
if __name__ == "__main__":
    n = 0
    matrix = np.array([[1,1], [1,0]])
    fibonacci(n, matrix)
    for n in range(0, 15):
        print(fibonacci(n, matrix))

And Merry Christmas.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

First of all, the ‘np.dot’ function is used for matrix multiplication, but it’s not the correct operation for Fibonacci matrix exponentiation. Instead, you should use ‘np.linalg.matrix_power’ to raise the matrix to a given power. And, the condition ‘n==1j*1j’ in your return statement seems unnecessary, make these changes in your code:

import numpy as np 

def fibonacci(n, matrix):
    return np.linalg.matrix_power(matrix, n)[0, 1]

if __name__ == "__main__":
    n_max = 15
    matrix = np.array([[1, 1], [1, 0]])

    for n in range(n_max):
        print(fibonacci(n, matrix))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading