Skip to content

Bug in np.histogram when min == max and values are >= 2**53 #8627

Open

Description

@astrofrog

The following call to histogram fails:

In [5]: np.histogram([2**53])
/Users/tom/miniconda3/envs/dev/lib/python3.6/site-packages/numpy/lib/function_base.py:566: RuntimeWarning: divide by zero encountered in double_scalars
  norm = bins / (mx - mn)
/Users/tom/miniconda3/envs/dev/lib/python3.6/site-packages/numpy/lib/function_base.py:591: RuntimeWarning: invalid value encountered in multiply
  tmp_a *= norm
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-5-41f77d7d86af> in <module>()
----> 1 np.histogram([2**53])

/Users/tom/miniconda3/envs/dev/lib/python3.6/site-packages/numpy/lib/function_base.py in histogram(a, bins, range, normed, weights, density)
    598             # The index computation is not guaranteed to give exactly
    599             # consistent results within ~1 ULP of the bin edges.
--> 600             decrement = tmp_a_data < bin_edges[indices]
    601             indices[decrement] -= 1
    602             # The last bin includes the right edge. The other bins do not.

IndexError: index -9223372036854775808 is out of bounds for axis 1 with size 11

whereas this succeeds:

In [6]: np.histogram([2**53-1])
Out[6]: 
(array([0, 0, 0, 0, 0, 0, 1, 0, 0, 0]),
 array([  9.00719925e+15,   9.00719925e+15,   9.00719925e+15,
          9.00719925e+15,   9.00719925e+15,   9.00719925e+15,
          9.00719925e+15,   9.00719925e+15,   9.00719925e+15,
          9.00719925e+15,   9.00719925e+15]))

The threshold for triggering the bug appears to be 2**53, but this only happens when the min of the array is the same as the max:

In [7]: np.histogram([2**53, 2**53])
/Users/tom/miniconda3/envs/dev/lib/python3.6/site-packages/numpy/lib/function_base.py:566: RuntimeWarning: divide by zero encountered in double_scalars
  norm = bins / (mx - mn)
/Users/tom/miniconda3/envs/dev/lib/python3.6/site-packages/numpy/lib/function_base.py:591: RuntimeWarning: invalid value encountered in multiply
  tmp_a *= norm
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-7-f74f7a6cf401> in <module>()
----> 1 np.histogram([2**53, 2**53])

/Users/tom/miniconda3/envs/dev/lib/python3.6/site-packages/numpy/lib/function_base.py in histogram(a, bins, range, normed, weights, density)
    598             # The index computation is not guaranteed to give exactly
    599             # consistent results within ~1 ULP of the bin edges.
--> 600             decrement = tmp_a_data < bin_edges[indices]
    601             indices[decrement] -= 1
    602             # The last bin includes the right edge. The other bins do not.

IndexError: index -9223372036854775808 is out of bounds for axis 1 with size 11

When the min and the max are different, things are fine:

In [8]: np.histogram([2**53, 2**54])
Out[8]: 
(array([1, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
 array([  9.00719925e+15,   9.90791918e+15,   1.08086391e+16,
          1.17093590e+16,   1.26100790e+16,   1.35107989e+16,
          1.44115188e+16,   1.53122387e+16,   1.62129587e+16,
          1.71136786e+16,   1.80143985e+16]))

Activity

  1. charris commented on Feb 17, 2017

    @charris
    Member

    Is this a regression? I'm going to make a list of reported histogram issues and see if they can get fixed before the 1.12.1 release.

  2. astrofrog commented on Feb 17, 2017

    @astrofrog
    ContributorAuthor

    This is present in Numpy 1.11 too and there is also an issue in 1.10 but the error is different

  3. charris commented on Feb 17, 2017

    @charris
    Member

    OK, thanks for checking. I rather expected that as the problem seems to be floating point granularity.

  4. mirca commented on Feb 18, 2017

    @mirca
    Contributor

    A possible fix maybe would involve casting mn and mx to np.float128?

  5. njsmith commented on Feb 18, 2017

    @njsmith
    Member
  6. polwel commented on May 30, 2018

    @polwel

    I get a similar error message for different input.

    In[34]: sys.version
    Out[34]: '3.6.5 |Anaconda, Inc.| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit (AMD64)]'
    In[35]: np.__version__
    Out[35]: '1.14.3'
    In[36]: np.histogram([1e-317, 0])
    C:\Users\welterp\AppData\Local\Continuum\miniconda3\envs\qs3\lib\site-packages\numpy\lib\function_base.py:766: RuntimeWarning: overflow encountered in double_scalars
      norm = n_equal_bins / (last_edge - first_edge)
    C:\Users\welterp\AppData\Local\Continuum\miniconda3\envs\qs3\lib\site-packages\numpy\lib\function_base.py:788: RuntimeWarning: invalid value encountered in multiply
      tmp_a *= norm
    Traceback (most recent call last):
      File "C:\Users\welterp\AppData\Local\Continuum\miniconda3\envs\qs3\lib\site-packages\IPython\core\interactiveshell.py", line 2963, in run_code
        exec(code_obj, self.user_global_ns, self.user_ns)
      File "<ipython-input-36-813036c82db0>", line 1, in <module>
        np.histogram([1e-317, 0])
      File "C:\Users\welterp\AppData\Local\Continuum\miniconda3\envs\qs3\lib\site-packages\numpy\lib\function_base.py", line 797, in histogram
        decrement = tmp_a_data < bin_edges[indices]
    IndexError: index -9223372036854775808 is out of bounds for axis 1 with size 11
    

    Since my example requires a number only representable in double precision, I thought that some unsafe cast was to blame. Not sure how its related to the original issue. NVM, the error message says right there what's going on: norm = n_equal_bins / (last_edge - first_edge) evaluates to inf, and it goes downhill from there.

  7. eric-wieser commented on Aug 19, 2018

    @eric-wieser
    Member

    I think the fix here is just to disable the uniform-bins fast-path for large integers.

    I don't know how you can lerp 64-bit integers without overflow - the formula we're using of

    index = floor((data - first) / (last - first) * n_bins)
    

    either:

    • overflows (if the multiplication is done first)
    • causes precision loss due to conversion to float64 (if the division is done first)

    I suspect interp has similar problems.

    Some interesting related remarks about lerp here

  8. sanjok-bless commented on Nov 1, 2018

    @sanjok-bless

    I have the same issue with a big double number, reproducible code:

    double_numbers = np.array([1e20] * 20)
    np.histogram(double_numbers, bins=100)

    I get an error:

    IndexError                                Traceback (most recent call last)
    <ipython-input-2-51958daa5f2c> in <module>()
          1 double_numbers = np.array([1e20] * 20)
    ----> 2 np.histogram(double_numbers, bins=100)
    
    /home/oleksandr/.pyenv/versions/2.7.8/envs/dr2.7.8/lib/python2.7/site-packages/numpy/lib/histograms.pyc in histogram(a, bins, range, normed, weights, density)
        764             # The index computation is not guaranteed to give exactly
        765             # consistent results within ~1 ULP of the bin edges.
    --> 766             decrement = tmp_a < bin_edges[indices]
        767             indices[decrement] -= 1
        768             # The last bin includes the right edge. The other bins do not.
    
    IndexError: index -9223372036854775808 is out of bounds for axis 1 with size 101

    I use numpy 1.15.1 and see the bug exists at least from 1.10 version. Are there any plans to fix this?

  9. added a commit that references this issue on Dec 21, 2018
  10. collinmccarthy commented on May 14, 2020

    @collinmccarthy

    I'm getting this same error with the following:
    np.histogram(np.nan_to_num(np.inf))

    This makes it difficult to create a histogram when some values are +/- infinity, which happens a lot when logging gradient information in deep learning frameworks like PyTorch and Tensorflow.

    Are there still plans to fix this issue? If not what should I set these large values to (sometimes they're in 32 or 64-bit arrays) to avoid this? Thank you.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions