Skip to content

Bug in reshape for 0-stride arrays #380

Closed
@dhirschfeld

Description

@dhirschfeld

The following test fails as reported on the ML:
http://thread.gmane.org/gmane.comp.python.numeric.general/51227/focus=51240

x = array([5])
y = np.lib.stride_tricks.as_strided(x, shape=(10,), strides=(0,))
z = y.reshape([10,1])
assert np.all(z == 5) # FAIL!

In the same thread Sebastian Berg has proposed the following patch:

+++ b/numpy/core/src/multiarray/shape.c
@@ -273,21 +273,21 @@ PyArray_Newshape(PyArrayObject *self, PyArray_Dims
*newdims,
          * appropriate value to preserve contiguousness
          */
         if (order == NPY_FORTRANORDER) {
-            if (strides[0] == 0) {
+            if ((strides[0] == 0) && (dimensions[0] == 1)) {
                 strides[0] = PyArray_DESCR(self)->elsize;
             }
             for (i = 1; i < ndim; i++) {
-                if (strides[i] == 0) {
+                if ((strides[i] == 0) && (dimensions[i] == 1)) {
                     strides[i] = strides[i-1] * dimensions[i-1];
                 }
             }
         }
         else {
-            if (strides[ndim-1] == 0) {
+            if ((strides[ndim-1] == 0) && (dimensions[ndim-1] == 1)) {
                 strides[ndim-1] = PyArray_DESCR(self)->elsize;
             }
             for (i = ndim - 2; i > -1; i--) {
-                if (strides[i] == 0) {
+                if ((strides[i] == 0) && (dimensions[i] == 1)) {
                     strides[i] = strides[i+1] * dimensions[i+1];
                 }
             }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions