Numpy: Using round() leads to TypeError on some systems (but not all)

Created on 13 Nov 2020  路  1Comment  路  Source: numpy/numpy

Performing round() without the round function's ndigits argument on a calculation that involves a random number generated by numpy random() should return an int. However on _some_ systems (in this case, macOS) this seems to result in a numpy.float64 which then leads to a TypeError. On a different system (Win10 and Win10/WSL Ubuntu), the code runs without any issues.

I would expect an error to be raised on all systems or on no system.

Reproducing code example:

Creating a list of randomized shades of a color (hex):

import numpy as np
N = 1000
y = np.random.random(size=N) * 100
colors = ["#%02x%02x%02x" % (255, round(value * 255 / 100), 255) for value in y]

Error message:

Error message on macOS (@bryevdv):

TypeError                                 Traceback (most recent call last)
<ipython-input-6-e848e8d9e2df> in <module>
----> 1 colors = ["#%02x%02x%02x" % (255, round(value * 255 / 100), 255) for value in y]

<ipython-input-6-e848e8d9e2df> in <listcomp>(.0)
----> 1 colors = ["#%02x%02x%02x" % (255, round(value * 255 / 100), 255) for value in y]

TypeError: %x format: an integer is required, not numpy.float64

No error is raised on Win10 (Python 3.8.6) and Win10/WSL Ubuntu (4.19.128-microsoft-standard, Python 3.8.5)

NumPy/Python version information:

Win 10: 1.19.2 3.8.6 | packaged by conda-forge | (default, Oct 7 2020, 18:22:52) [MSC v.1916 64 bit (AMD64)]
Win10/WSL Ubuntu: 1.19.2 3.8.5 (default, Jul 28 2020, 12:59:40)

Most helpful comment

We fixed/changed this in NumPy 1.19.x, if your code targets older versions as well, you will have to add an additional int() call or similar.

>All comments

We fixed/changed this in NumPy 1.19.x, if your code targets older versions as well, you will have to add an additional int() call or similar.

Was this page helpful?
0 / 5 - 0 ratings