I'm using python3 with numpy version 1.8.2 (same issue with numpy 1.10.4 and python2) and trying to do something very basic: multiplying two integers.
import numpy as np
a = 9223372036854775808
type(a)
b = np.int64(0)
type(b)
type(b*a)
The output is however:
builtins.int
numpy.int64
numpy.float64
So the multiplication of two integers returns a float! Is there any reasonable explanation for it?
Note that if I change to
a = 9223372036854775807
type(b*a)
returns
numpy.int64
And if I raise it to
a = 92233720368547758100
type(b*a)
returns (in python3)
builtins.int
and (in python2)
long
As I understand there must be some overflow, but why?
Actually it is very good observation and question. Here is the quick analogy:
import numpy as np
a = 9223372036854775808
Note that you are crossing the int limit, it is entering the long int range
awill produce output as9223372036854775808L
type(a)will produce output as<type 'long'>
In the below case, we are staying with in the int limit
a = 9223372036854775807
Here
areturns output as9223372036854775807type(a) returns output as
<type 'int'>
let us assume b = np.int64(1) for instance. I will explain in while why I took np.int64(1) instead of np.int64(0)
b*areturns9.2233720368547758e+18, as you see it is represented in decimals in Euler's form.
type(b*a)returnsnp.float64
Hence for the above reason, it is converted to float i.e., np.float(64). Eulers form of number always needs float/decimal points for its representation
Reason for considering b as np.int64(1): If it was np.int64(0), you will never notice the output as the result will be all 0s
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With