Search code examples
pythonnumpynumpy-2.x

numpy numbers output with type cast around them, which is a bug in my program


I am casting a python tuple to a numpy array, using a quaternion function, and then casting the returning numpy array back to a tuple. Here, start_pos is a tuple (0,0,0). The second tuple goes into a list.

current_pos = np.array(start_pos)
current_quaternion = Quaternion.from_axis_angle(np.array([0,0,1]), math.radians(rotation))
vertices.append(tuple(current_pos))

This used to work on my last laptop, but now, when I run my source code the output of tuple(current_pos) looks like (np.int64(0), np.int64(0), np.int64(0))

This doesn't work for me because vertices needs to be written to a file, and the format needs raw numbers like 0.4999238475781956, not np.float64(0.4999238475781956).

Previously, the same source code output the correct thing after tuple(current_pos). It output raw numbers. When I imported my files into the new laptop and installed python and numpy, something changed to cause this issue.

  • Python version: 3.12.4 (tags/v3.12.4:8e8a4ba, Jun 6 2024, 19:30:16) [MSC v.1940 64 bit (AMD64)]
  • NumPy version: 2.0.1

with start_pos = (0,0,0), I expected a tuple of 3 raw numbers, as floats, to be appended to a list vertices. Instead, vertices looks like:

[(np.int64(0), np.int64(0), np.int64(0)),
 (np.float64(0.0), np.float64(0.0), np.float64(1.0)),
 (np.float64(0.4999238475781956), np.float64(0.008726203218641754), np.float64(1.8660254037844388)),
 (np.float64(0.0), np.float64(0.0), np.float64(2.0))]

Solution

  • I'm guessing the difference is that you were originally on Numpy 1.2x and updated to numpy 2.0. As per the release notes, there has been a change to how floats are now represented. The release notes mention this may be an issue when outputting to a file. You don't show how you are printing to a file and haven't explained why you are using tuples rather than a 2D array, so my suggestions will be limited.

    If you want to keep your current code, convert the numpy array to a Python list of floats when creating your tuple.

    vertices.append(tuple(current_pos.tolist()))
    

    Or, you can downgrade numpy to 1.2x or do what the documentation says for using the legacy representation, i.e. add np.set_printoptions(legacy="1.25") after your imports.