2

I have to inverse my matrix. But I am getting an error. How to solve it?

@njit
def inv():
    x = [[1,2],[9,0]]
    inverted = np.linalg.inv(x)
    return x
inv()

TypingError: Failed in nopython mode pipeline (step: nopython frontend)
No implementation of function Function(<function inv at 0x7f1ce02abb90>) found for signature:

inv(list(list(int64)<iv=None>)<iv=None>)

There are 2 candidate implementations:
- Of which 2 did not match due to:
Overload in function 'inv_impl': File: numba/np/linalg.py: Line 833.
With argument(s): '(list(list(int64)<iv=None>)<iv=None>)':
Rejected as the implementation raised a specific error:
TypingError: np.linalg.inv() only supported for array types
raised from /opt/conda/envs/rapids/lib/python3.7/site-packages/numba/np/linalg.py:767

During: resolving callee type: Function(<function inv at 0x7f1ce02abb90>)
During: typing of call at (4)


File "", line 4:
def inv():


x = [[1,2],[9,0]]
inverted = np.linalg.inv(x)

1 Answers1

4

You need to provide a np.array of float or complex dtype, not some list with int:

from numba import jit
import numpy as np  

@jit(nopython=True)
def inv():
    x = np.array([[1,2],[9,0]], dtype=np.float64) # explicitly specify float64 dtype
    # x = np.array([[1.,2.],[9.,0.]]) # or just add floating points
    inverted = np.linalg.inv(x)
    return x
inv()

see the linear algebra supported numpy features in numba.

Yacola
  • 2,873
  • 1
  • 10
  • 27
  • Yeah, I know it works, when I send from outside. But I need that it should work from the inside. So that's why I put the matrix inside the function. numpy array doesn't work inside the jit function. How to do it from inside? – Nurislom Rakhmatullaev Feb 15 '21 at 06:24
  • Just initialize `x` exactly as I did from inside the function, you need to use `float64` dtype. See the edited answer. – Yacola Feb 15 '21 at 12:01
  • Very interesting. Why it doesn't work with integers? – Nurislom Rakhmatullaev Feb 15 '21 at 15:18
  • 1
    I am not sure exactly why, but my guess is that usually `numpy` is much more flexible than `numba` and will automatically cast `int` to `float64` internally when calling `inv`, you can check the source to be sure. My advice to you is the following: when mixing `numba` and `numpy`, always strictly refer to the link I gave you in the answer above, this page provides all the informations you need to make `njit`ted functions run :) – Yacola Feb 15 '21 at 23:35