Skip to content

Could random.hypergeometric() be made to match behavior of random.binomial() when sample or n = 0? #9237

Closed

Description

@wmatern

I am trying to implement a multidimensional hypergeometric distribution. My algorithm would be made simpler if np.random.hypergeometric() returned zeros when sample=0, just like the np.random.binomial() does when n = 0 (instead of throwing an ValueError). Note that the binomial is often used as an approximation to the hypergeometric so getting the same behavior when swapping one for the other may be advantageous.

In particular:
np.random.binomial(0,.5)
Returns
0

whereas:
np.random.hypergeometric(1,1,0)
Returns
... ValueError: nsample < 1

I think it would be a matter of 3 changes to the code base:

  1. change Line 4254-5 of master/numpy/random/mtrand/mtrand.pyx to:
    if lnsample < 0: raise ValueError("nsample < 0")

  2. Move line 794 of master/numpy/random/mtrand/distributions.c to line 791.

  3. Add if(sample == 0) Z = 0 to rk_hypergeometric_hrua in master/numpy/random/mtrand/distributions.c --- though there might be another way to avoid an if but I don't understand how the code works well enough.

Also, as a new user, please let me know if there is a better way to ask for this change.

Thank you

-Will

Activity

  1. bashtage commented on Jun 12, 2017

    @bashtage
    Contributor

    See #8056 -- this is tagged for inclusion in 1.14.

  2. WarrenWeckesser commented on Jun 16, 2017

    @WarrenWeckesser
    Member

    This seems reasonable, but I would think so, given that my implementation of multivariate_hypergeometric in #8056 behaves this way, e.g.:

    In [5]: np.random.multivariate_hypergeometric([5, 10, 15], 0)
    Out[5]: array([0, 0, 0])
    
  3. bashtage commented on Apr 11, 2019

    @bashtage
    Contributor

    xref #13163 . This is fixed in the randomgen branch (subject to pending PR mattip#8)

  4. mattip commented on May 29, 2019

    @mattip
    Member

    Closing. Verified that np.random.Generator().hypergeometric(1,1,0) returns 0. Please reopen if I misunderstood.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions