Operator @ in python? what does?

Question:

I have been programming for years in python but now i was reading a program to do linnear regression and i found this.

    if X.ndim == 1:
        X = X[:, None]
    d = X - self.mean
    precision = np.linalg.inv(self.var)
    return (
        np.exp(-0.5 * np.sum(d @ precision * d, axis=-1))
        * np.sqrt(np.linalg.det(precision))
        / np.power(2 * np.pi, 0.5 * self.ndim))

what does the @ in this code?

Asked By: user2636742

||

Answers:

It’s the matrix multiplication operator as described in PEP-465 and first made available in Python 3.5.

Answered By: paxdiablo

If @ is mentioned in the middle of the statement then it’s a matrix multiplication.

Example:

class Mat(list):
def __matmul__(self, B):
    A = self
    return Mat([[sum(A[i][k]*B[k][j] for k in range(len(B)))
                for j in range(len(B[0])) ] for i in range(len(A))])

A = Mat([[2,3],[7,5]])
B = Mat([[4,8],[3,6]])

print(A @ B)

Output:

[[17, 34], [43, 86]]

Cheers!!!

Answered By: DRV
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.