2

I want to convert the return type of np.inf to int, by default it returns float type.

I have tried the followings, but both give erros.

int(np.inf)

OverflowError: cannot convert float infinity to integer

(np.inf).astype(int64)

AttributeError: 'float' object has no attribute 'astype'

Ali Khan
  • 143
  • 1
  • 4
  • 9
  • 1
    inf and nan are part of the floating point standard IEEE 754. Integer types typically have no way to represent these special case values and only can represent numeric values within their given range ([wikipedia source](https://en.wikipedia.org/wiki/NaN#Integer_NaN)). You will need to choose how to handle these cases on your own (like assigning nan's to 0 and inf to -1 etc.) – Aaron Jun 28 '19 at 18:31
  • 1
    Possible duplicate of [Represent infinity as an integer in Python 2.7](https://stackoverflow.com/questions/40445920/represent-infinity-as-an-integer-in-python-2-7) – Aaron Jun 28 '19 at 18:40

2 Answers2

5

Unfortunately as the comments suggest no there isn't, but if you know the integer type you want, you can use np.iinfo and pick max or min

np.iinfo(np.int32).max  # ---- 2147483647

np.iinfo(np.int32).min  # ---- -2147483648

np.iinfo(np.int64).max  # ---- 9223372036854775807

np.iinfo(np.int64).min  # ---- -9223372036854775808
NaN
  • 2,212
  • 2
  • 18
  • 23
1

There is a standard for floating point numbers: "IEEE 754" (it is not specific to python). This standard reserves some special bytes sequences for +/-Infinity and NaN. For integer such special values are not reserved so it is impossible to have an int infinity.

I have done some experimenting: you can do np.array([np.inf]).astype(int)[0] this will give you -9223372036854775808 (-(2 ** 64)/2). np.array([np.nan]).astype(int)[0] also produces the same value.

grabantot
  • 2,111
  • 20
  • 31