8000 Allow random.choice from empty array when size=0 · Issue #8311 · numpy/numpy · GitHub
[go: up one dir, main page]

Skip to content

Allow random.choice from empty array when size=0 #8311

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
werenike opened this issue Nov 24, 2016 · 2 comments
Closed

Allow random.choice from empty array when size=0 #8311

werenike opened this issue Nov 24, 2016 · 2 comments

Comments

@werenike
Copy link
Contributor
werenike commented Nov 24, 2016

This piece of code:

np.random.choice([],size=0)

Generates this error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "mtrand.pyx", line 1397, in mtrand.RandomState.choice (numpy/random/mtrand/mtrand.c:15499)
ValueError: a must be non-empty

This error makes sense when size>0, but when size=0, random.choice could simply return []. This would be useful when the a and size parameters are variable. Right now this situation requires an additional check:

if size > 0:
  result = np.random.choice(a,size)
else:
  result = np.array([])

Would it be a good idea to simply return an empty array when size=0? This is my first issue so I hope this is the right way to address this.

I created a simple patch that implements this: 57ab0728d4cf73c1f4b3af2450fe603bf8670b75

I'm using Python 3.5.2 with numpy 1.11.2.

Edit: My implementation returns an empty slice from the original array. My thinking was that this would assign the correct base to the resulting array, but on second thought this is not what happens with random.choice normally, so I think returning np.array([]) would be better.

@eric-wieser
Copy link
Member

You should probably promote this to a PR, and add a test with it

@anntzer
Copy link
Contributor
anntzer commented Dec 20, 2016

You probably want to return an array of the same dtype of the input choices (if it is already an ndarray itself), too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants
0