Home > Software design >  Why does np.linalg.solve give me an error when trying to solve a 16x16 system of equations?
Why does np.linalg.solve give me an error when trying to solve a 16x16 system of equations?

Time:12-22

I'm creating an nxn matrix with the largest value being n**n. np.linalg.solve works when n < 16, but for n >= 16, it gives an error:

numpy.core._exceptions.UFuncTypeError: Cannot cast ufunc 'solve1' input 0 from dtype('O') to dtype('float64') with casting rule 'same_kind'

Here's my code:

import numpy as np

def fib_to(n):
    if n==0: return [0]
    fibs = [0, 1]
    for i in range(2, n 1):
        fibs.append(fibs[-1]   fibs[-2])
    return fibs

def get_nth_matrix(n):
    coeficients = [[i**j for j in range(n, -1, -1)] for i in range(n 1)]
    augment = fib_to(n)
    return coeficients, augment

print(np.linalg.solve(*get_nth_matrix(16)))

I also noticed that doing np.linalg.cond on the matrix had the same problem. It worked for values up to 15, but gave a division by 0 error when n was 16 or greater

CodePudding user response:

The list of lists returned by get_nth_matrix(16) contains integers that are too large to fit into numpy integer types. When you use np.linalg.solve() this list of lists gets converted into a numpy array, but because of this size issue, it produces an array of python objects. The error occurs since np.linalg.solve() can't handle this type of an array. You can replace the last line of get_nth_matrix() with

return np.array(coeficients, dtype=float), augment

to fix this - at least for the values that will not overflow the float type.

  • Related