summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--doc/release/upcoming_changes/16841.change.rst19
-rw-r--r--numpy/core/function_base.py8
-rw-r--r--numpy/core/tests/test_function_base.py5
3 files changed, 32 insertions, 0 deletions
diff --git a/doc/release/upcoming_changes/16841.change.rst b/doc/release/upcoming_changes/16841.change.rst
new file mode 100644
index 000000000..d9499b6f4
--- /dev/null
+++ b/doc/release/upcoming_changes/16841.change.rst
@@ -0,0 +1,19 @@
+`np.linspace` on integers now use floor
+---------------------------------------
+When using a `int` dtype in `numpy.linspace`, previously float values would
+be rounded towards zero. Now `numpy.floor` is used instead, which rounds toward
+``-inf``. This changes the results for negative values. For example, the
+following would previously give::
+
+ >>> np.linspace(-3, 1, 8, dtype=int)
+ array([-3, -2, -1, -1, 0, 0, 0, 1])
+
+and now results in::
+
+ >>> np.linspace(-3, 1, 8, dtype=int)
+ array([-3, -3, -2, -2, -1, -1, 0, 1])
+
+The former result can still be obtained with::
+
+ >>> np.linspace(-3, 1, 8).astype(int)
+ array([-3, -2, -1, -1, 0, 0, 0, 1])
diff --git a/numpy/core/function_base.py b/numpy/core/function_base.py
index f57e95742..b2f17cfeb 100644
--- a/numpy/core/function_base.py
+++ b/numpy/core/function_base.py
@@ -34,6 +34,11 @@ def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None,
.. versionchanged:: 1.16.0
Non-scalar `start` and `stop` are now supported.
+ .. versionchanged:: 1.20.0
+ Values are rounded towards ``-inf`` instead of ``0`` when an
+ integer ``dtype`` is specified. The old behavior can
+ still be obtained with ``np.linspace(start, stop, num).astype(int)``
+
Parameters
----------
start : array_like
@@ -160,6 +165,9 @@ def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None,
if axis != 0:
y = _nx.moveaxis(y, 0, axis)
+
+ if _nx.issubdtype(dtype, _nx.integer):
+ _nx.floor(y, out=y)
if retstep:
return y.astype(dtype, copy=False), step
diff --git a/numpy/core/tests/test_function_base.py b/numpy/core/tests/test_function_base.py
index 62a9772c8..dad7a5883 100644
--- a/numpy/core/tests/test_function_base.py
+++ b/numpy/core/tests/test_function_base.py
@@ -402,3 +402,8 @@ class TestLinspace:
stop = array(2, dtype='O')
y = linspace(start, stop, 3)
assert_array_equal(y, array([1., 1.5, 2.]))
+
+ def test_round_negative(self):
+ y = linspace(-1, 3, num=8, dtype=int)
+ t = array([-1, -1, 0, 0, 1, 1, 2, 3], dtype=int)
+ assert_array_equal(y, t)