Skip to content

BUG: np.cov with rowvar=False returns the wrong shape for N=1 #27658

@jakevdp

Description

@jakevdp

Describe the issue:

For one observation of three variables, np.cov with rowvar=True returns the following:

>>> x = np.ones((3, 1))
>>> np.cov(x, ddof=0, rowvar=True)
array([[0., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.]])

For the same computation laid-out with rowvar=False, the return value is a scalar:

>>> np.cov(x.T, ddof=0, rowvar=False)
array(0.)

This should return a 3x3 matrix of zeros, same as the computation above.

The problem is the special-casing of X.shape[0] == 1 in this line, which seems aimed at handling the x.ndim == 1 case:

if not rowvar and X.shape[0] != 1:
X = X.T

It looks like this behavior was introduced in 959f36c, 19 years ago.

Python and NumPy Versions:

$ python -c "import sys, numpy; print(numpy.__version__); print(sys.version)"
2.1.1
3.12.3 (v3.12.3:f6650f9ad7, Apr  9 2024, 08:18:47) [Clang 13.0.0 (clang-1300.0.29.30)]

Runtime Environment:

$ python -c "import numpy; numpy.show_runtime()"
[{'numpy_version': '2.1.1',
  'python': '3.12.3 (v3.12.3:f6650f9ad7, Apr  9 2024, 08:18:47) [Clang 13.0.0 '
            '(clang-1300.0.29.30)]',
  'uname': uname_result(system='Darwin', node='jmdg-macbookpro.roam.internal', release='23.6.0', version='Darwin Kernel Version 23.6.0: Wed Jul 31 20:49:39 PDT 2024; root:xnu-10063.141.1.700.5~1/RELEASE_ARM64_T6000', machine='arm64')},
 {'simd_extensions': {'baseline': ['NEON', 'NEON_FP16', 'NEON_VFPV4', 'ASIMD'],
                      'found': ['ASIMDHP'],
                      'not_found': ['ASIMDFHM']}}]

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions