Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy.int64 times int -> numpy.float64

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?

like image 603
Daniele Bigoni Avatar asked Mar 10 '16 22:03

Daniele Bigoni


1 Answers

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

a will produce output as 9223372036854775808L

type(a) will produce output as <type 'long'>

In the below case, we are staying with in the int limit

a = 9223372036854775807

Here a returns output as 9223372036854775807

type(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*a returns 9.2233720368547758e+18, as you see it is represented in decimals in Euler's form.

type(b*a) returns np.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

like image 80
be_good_do_good Avatar answered Oct 20 '22 15:10

be_good_do_good