How to do it...

In this example, we provide a demonstration of the Numba compiler using the @guvectorize annotation.

The task to execute is matrix multiplication:

  1. Import guvectorize from the numba library and the numpy module:
from numba import guvectorize 
import numpy as np 
  1. Using the @guvectorize decorator, we define the matmul function, which will perform the matrix multiplication task:
@guvectorize(['void(int64[:,:], int64[:,:], int64[:,:])'], 
             '(m,n),(n,p)->(m,p)') 
def matmul(A, B, C): 
    m, n = A.shape 
    n, p = B.shape 
    for i in range(m): 
        for j in range(p): 
            C[i, j] = 0 
            for k in range(n): 
                C[i, j] += A[i, k] * B[k, j] 
  1. The input matrices are 10 × 10 in size, while the elements are integers:
dim = 10 
A = np.random.randint(dim,size=(dim, dim)) 
B = np.random.randint(dim,size=(dim, dim)) 
  1. Finally, we call the matmul function on the previously defined input matrices:
C = matmul(A, B) 
  1. We print the input matrices and the resulting matrix:
print("INPUT MATRIX A") 
print(":
%s" % A) 
print("INPUT MATRIX B") 
print(":
%s" % B) 
print("RESULT MATRIX C = A*B") 
print(":
%s" % C) 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.23.176