Skip to content

matmul @ of boolean arrays gives inconsistent results #14439

Closed

Description

@winsm

Since the matrix A is its own square, the loop below should be infinite, but it terminates after 8 iterations. If A = A.dot(A) is used in place of A = A @ A, the loop is infinite as expected.

Reproducing code example:

import numpy as np

A = M = np.array([[ True, False],[True,True]])
i = 0
while (A == M).all():
    i += 1
    print(i, "A == M")
    A = A @ A
print(A)

# 1 A == M
# 2 A == M
# 3 A == M
# 4 A == M
# 5 A == M
# 6 A == M
# 7 A == M
# 8 A == M
# [[ True False]
#  [False  True]]

Numpy/Python version information:

1.16.0rc1 3.7.2 (default, Jan 3 2019, 02:55:40)
[GCC 8.2.0]

Activity

  1. WarrenWeckesser commented on Sep 6, 2019

    @WarrenWeckesser
    Member

    It looks like the multiplication is being performed with the underlying integer data (i.e. False = 0, True = 1), and the resulting underlying values are not converted back to 0 and 1 afterwards. Eventually an underlying integer value overflows. This snippets prints A.view(np.int8) to show what is going on with the underlying data:

    A = M = np.array([[ True, False],[True,True]])
    i = 0
    while (A == M).all():
        i += 1
        A = A @ A
        print("A:\n", A.view(np.int8))
    
    A:
     [[1 0]
     [2 1]]
    A:
     [[1 0]
     [4 1]]
    A:
     [[1 0]
     [8 1]]
    A:
     [[ 1  0]
     [16  1]]
    A:
     [[ 1  0]
     [32  1]]
    A:
     [[ 1  0]
     [64  1]]
    A:
     [[   1    0]
     [-128    1]]
    A:
     [[1 0]
     [0 1]]
    
  2. seberg commented on Sep 8, 2019

    @seberg
    Member

    Hmmm, this seems like a bug. Matmul should probably conform with dot, or possibly upcast to long or intp.

  3. charris commented on Sep 8, 2019

    @charris
    Member

    The dot behavior was discussed long ago, turned out that boolean matrix multiplication was useful for some subjects, so we should keep it.

  4. added
    09 - Backport-Candidate
    on Sep 8, 2019
  5. added this to the 1.16.6 milestone on Sep 8, 2019
  6. removed
    09 - Backport-Candidate
    on Jul 19, 2020
  7. removed this from the 1.16.6 milestone on Jul 19, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions