diff --git a/mpmath/matrices/matrices.py b/mpmath/matrices/matrices.py index b5ef40f4..44b75b8e 100644 --- a/mpmath/matrices/matrices.py +++ b/mpmath/matrices/matrices.py @@ -205,9 +205,15 @@ class _matrix(object): ['2.0', '3.0']]) Of course you can perform matrix multiplication, if the dimensions are - compatible:: + compatible, using ``@`` (for Python >= 3.5) or ``*``. For clarity, ``@`` is + recommended (`PEP 465 `), because + the meaning of ``*`` is different in many other Python libraries such as NumPy. - >>> A * B + >>> A @ B # doctest:+SKIP + matrix( + [['8.0', '22.0'], + ['14.0', '48.0']]) + >>> A * B # same as A @ B matrix( [['8.0', '22.0'], ['14.0', '48.0']]) @@ -215,6 +221,10 @@ class _matrix(object): matrix( [['2.0']]) + .. + COMMENT: TODO: the above "doctest:+SKIP" may be removed as soon as we + have dropped support for Python 3.4 and below. + You can raise powers of square matrices:: >>> A**2 @@ -233,6 +243,8 @@ class _matrix(object): [['1.0', '1.0842021724855e-19'], ['-2.16840434497101e-19', '1.0']]) + + Matrix transposition is straightforward:: >>> A = ones(2, 3) @@ -592,6 +604,9 @@ class _matrix(object): new[i, j] = other * self[i, j] return new + def __matmul__(self, other): + return self.__mul__(other) + def __rmul__(self, other): # assume other is scalar and thus commutative if isinstance(other, self.ctx.matrix): diff --git a/mpmath/tests/test_matrices.py b/mpmath/tests/test_matrices.py index 25fdd697..04452031 100644 --- a/mpmath/tests/test_matrices.py +++ b/mpmath/tests/test_matrices.py @@ -1,4 +1,5 @@ import pytest +import sys from mpmath import * def test_matrix_basic(): @@ -48,6 +49,19 @@ def test_matrix_basic(): assert A9 != A10 assert nstr(A9) +def test_matmul(): + """ + Test the PEP465 "@" matrix multiplication syntax. + To avoid syntax errors when importing this file in Python 3.4 and below, we have to use exec() - sorry for that. + """ + # TODO remove exec() wrapper as soon as we drop support for Python <= 3.4 + if sys.hexversion < 0x30500f0: + # we are on Python < 3.5 + pytest.skip("'@' (__matmul__) is only supported in Python 3.5 or newer") + A4 = matrix([[1, 2, 3], [4, 5, 6]]) + A5 = matrix([[6, -1], [3, 2], [0, -3]]) + exec("assert A4 @ A5 == A4 * A5") + def test_matrix_slices(): A = matrix([ [1, 2, 3], [4, 5 ,6],