Allow linspace and logspace with steps=1 and start != end like numpy (#14748)
authorJan Schlüter <github@jan-schlueter.de>
Thu, 6 Dec 2018 17:29:01 +0000 (09:29 -0800)
committerFacebook Github Bot <facebook-github-bot@users.noreply.github.com>
Thu, 6 Dec 2018 17:30:55 +0000 (09:30 -0800)
commit1c8d41a08d30185109a506fd984210ec130ae213
tree0e91641db3e3c3b9b7218c608e1e7acc48cc1f0e
parentd2fdc33411a3ffeb0575604d60014869869c5653
Allow linspace and logspace with steps=1 and start != end like numpy (#14748)

Summary:
`torch.linspace(0, 1, 1)` fails with `RuntimeError: invalid argument 3: invalid number of points at ../aten/src/TH/generic/THTensorMoreMath.cpp:2119`, while `np.linspace(0, 1, 1)` works fine.
Looking at the code, there is even a comment by gchanan asking: "NumPy allows you to pass different points even if n <= 1 -- should we?"
I would say "yes". Currently, I would need to handle the case of `steps == 1` or `steps == 0` separately, making sure to change the `end` when calling `torch.linspace`. This is impractical. If we support `start != end`, there are two possibilities for the result: Either we ensure the first value in the resulting sequence always equals `start`, or we ensure the last value in the resulting sequence always equals `end`. Numpy chose the former, which also allows it to support a boolean `endpoint` flag. I'd say we should follow numpy.

This PR adapts `linspace` and `logspace` to mimic the behavior of numpy, adapts the tests accordingly, and extends the docstrings to make clear what happens when passing `steps=1`.

If you decide against this PR, the error message should become explicit about what I did wrong, and the documentation should be extended to mention this restriction.
Pull Request resolved: https://github.com/pytorch/pytorch/pull/14748

Differential Revision: D13356136

Pulled By: ezyang

fbshipit-source-id: db85b8f0a98a5e24b3acd766132ab71c91794a82
aten/src/TH/generic/THTensorMoreMath.cpp
aten/src/THC/generic/THCTensorMath.cu
test/test_torch.py
torch/_torch_docs.py