nicolaspanel / numjs

Like NumPy, in JavaScript

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Behavior not the same: numjs.slice v.s. python array[1::2]

huan opened this issue · comments

NumJs:

> a = nj.array([1,2,3,4,5,6])
array([ 1, 2, 3, 4, 5, 6])
> a.slice([null, null, 2])
array([ 1, 3, 5])
> a.slice([1, null, 2])
array([ 1])

Python:

>>> a = [1,2,3,4,5,6]
>>> a[::2]
[1, 3, 5]
>>> a[1::2]
[2, 4, 6]

Numjs: > a.slice([1, null, 2]): array([ 1])
Python: >>> a[1::2]: [2, 4, 6]

Which as a.slice([1, null, 2]) in numjs behavior is not right.


UPDATE: I can use the following syntax to get the right slice. Does that be designed, or a bug?

> a.slice([1, 6, 2])
array([ 2, 4, 6])

Definitely a bug. Thanks for for the issue, I will take a look ASAP.

I added some tests and played with it, but I still not made the trick.

diff --git a/src/ndarray.js b/src/ndarray.js
index 52c38d4..e4bf2f2 100644
--- a/src/ndarray.js
+++ b/src/ndarray.js
@@ -122,14 +122,14 @@ NdArray.prototype.slice = function () {
       step[i] = 1;
     } else {
       // assume it is an array
-      var start = (arg[0] < 0) ? arg[0] + tShape[i] : arg[0];
-      var end = (arg[1] < 0) ? arg[1] + tShape[i] : arg[1];
+      var start = (arg[0] < 0) ? arg[0] + tShape[i] + 1 : arg[0];
+      var end = arg[1] === null ? arg[0] < 0 ? 0 : tShape[i] : (arg[1] < 0) ? arg[1] + tShape[i] : arg[1];
       lo[i] = end ? start : 0;
       hi[i] = end ? end - start : start;
       step[i] = arg[2] || 1;
     }
   }
-

fixed in numjs#0.14.1

Awesome, thanks!

commented

The bug still exists