10

Consider the following:

>>> import numbers
>>> import numpy
>>> a = numpy.int_(0)
>>> isinstance(a, int)
False
>>> isinstance(a, numbers.Integral)
True
>>> b = numpy.float_(0)
>>> isinstance(b, float)
True
>>> isinstance(b, numbers.Real)
True

NumPy's numpy.int_ and numpy.float_ types are both in Python's numeric abstract base class hierarchy, but it is strange to me that a np.int_ object is not an instance of the built-in int class, while a np.float_ object is an instance of the built-in float type.

Why is this the case?

2 Answers 2

16

Python integers can be arbitrary length: type(10**1000) is still int, and will print out a one and then a thousand zeros on your screen if you output it.

Numpy int64 (which is what int_ is on my machine) are integers represented by 8 bytes (64 bits), and anything over that cannot be represented. For example, np.int_(10)**1000 will give you a wrong answer - but quickly ;).

Thus, they are different kinds of numbers; subclassing one under the other makes as much sense as subclassing int under float would, is what I assume numpy people thought. It is best to keep them separate, so that no-one is confused about the fact that it would be unwise to confuse them.

The split is done because arbitrary-size integers are slow, while numpy tries to speed up computation by sticking to machine-friendly types.

On the other hand, floating point is the standard IEEE floating point, both in Python and in numpy, supported out-of-the-box by our processors.

Sign up to request clarification or add additional context in comments.

Comments

2

Because numpy.int_() is actually 64-bit, and int can have an arbitrary size, it uses about 4 extra bytes for every 2^30 worth of bits you put in. int64 has constant size:

>>> import numpy as np
>>> a = np.int_(0)
>>> type(a)
<type 'numpy.int64'>
>>> b = 0
>>> type(b)
<type 'int'>

2 Comments

This doesn't answer my question. The type of a = np.float_(0) is numpy.float64, but it is still an instance of float. My question can be rephrased as "why is numpy.float64 a subclass of float but numpy.int64 is not a subclass of int?"
@ArtemMavrin int can have an arbitrary size, it uses about 4 extra bytes for every 2^30 worth of bits you put in. int64 has constant size.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.