Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does math.infinity turn to a big negative integer when overwriting in some cases?

Tags:

python

numpy

I want to overwrite some array values for a min-finding algorithm. For these examples, I want the values of the first row to be replaced by math.inf.

It works fine in example c, but I don't understand what happens in a and b:

import numpy as np
import math

a = np.repeat(0, 9).reshape((3, 3))
a[0, :] = np.ones((3,)) * math.inf
print(a)

b = np.arange(9).reshape((3, 3))
b[0, :] = np.ones((3,)) * math.inf
print(b)

c = np.empty((3, 3))
c[0, :] = np.ones((3,)) * math.inf
print(c)

Output: shows infinity as the row entry in example c, but -9223372036854775808 in example a and b.

enter image description here

Why does the existing output have an influence when I overwrite it?

like image 298
Yuvraj Avatar asked Jan 23 '21 10:01

Yuvraj


Video Answer


1 Answers

The integer literal arguments to repeat and arange cause the returned arrays to have an integer type. The empty does not have a similar literal argument and has a dtype argument instead, which defaults to a float type.

See the 0.0 and 9.0 below:

import numpy as np
import math

a = np.repeat(0.0, 9).reshape((3, 3))
a[0, :] = np.ones((3,)) * math.inf
print(a)

b = np.arange(9.0).reshape((3, 3))
b[0, :] = np.ones((3,)) * math.inf
print(b)
[[inf inf inf]
 [ 0.  0.  0.]
 [ 0.  0.  0.]]
[[inf inf inf]
 [ 3.  4.  5.]
 [ 6.  7.  8.]]

As to why -9223372036854775808:

The float to integer conversion uses the cvttsd2si instruction which returns 1 followed by 63 zeros to signify error:

If a converted result exceeds the range limits of signed quadword integer (in 64-bit mode and REX.W/VEX.W/EVEX.W = 1), the floating-point invalid exception is raised, and if this exception is masked, the indefinite integer value (80000000_00000000H) is returned.

which if interpreted as a 2's complement integer, corresponds to -2^63 = -9223372036854775808.

like image 130
mkayaalp Avatar answered Oct 14 '22 01:10

mkayaalp