Skip to content

np.nan astype np.int32 gives -2147483648 #13101

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
kkonevets opened this issue Mar 7, 2019 · 6 comments
Closed

np.nan astype np.int32 gives -2147483648 #13101

kkonevets opened this issue Mar 7, 2019 · 6 comments

Comments

@kkonevets
Copy link

Converting nan to int32 succeeds

Reproducing code example:

import numpy as np
np.array([np.nan]).astype(np.int32) 

outputs
array([-2147483648], dtype=int32)

Error message:

Numpy/Python version information:

np.version == '1.16.1'

@eric-wieser
Copy link
Member

Emitting a RuntimeWarning would probably be a good idea here

@kkonevets
Copy link
Author

kkonevets commented Mar 7, 2019

Emitting a RuntimeWarning would probably be a good idea here

My suggestion is to convert np.nan to np.nan as with float32

np.array([np.nan]).astype(np.float32) 

outputs

array([nan], dtype=float32)

@eric-wieser
Copy link
Member

Integers can't store nan though? That's like saying np.array(2).astype(bool) should give 2.

@mxt3
Copy link

mxt3 commented Dec 7, 2020

I've just ran into this. So nan is converted tot the smallest 32bit signed integer. I don't know if this is deliberate, but this behavior coincidentally suits my needs.

However, it does not seem to be a very deliberate design, because np.int32(np.nan) throws a ValueError.

It feel it should be documented, at the least, under the form of a warning or deliberate design.

@seberg
Copy link
Member

seberg commented Dec 7, 2020

@mxt3 note that NumPy currently returns whatever (int32)NaN returns in C, and that is unfortunately "undefined", I think. IIRC, there are machines where you may get a different result unfortunately, e.g. 0 (there should be an issue about that open somewhere).

@seberg
Copy link
Member

seberg commented Jun 14, 2022

This will now give a RuntimeWarning on main (will be a while until a release with it). There is another issue about this open at gh-14412, which I will keep open as a point for discussing whether more than a warning (settable using np.errstate(invalid="raise"/"ignore") would be a nice further step.

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

4 participants