为什么 NumPy int 不是 Python int 的实例,而 NumPy float 是 Python float 的实例? [英] Why is a NumPy int not an instance of a Python int, but a NumPy float is an instance of a Python float?

查看:30
本文介绍了为什么 NumPy int 不是 Python int 的实例,而 NumPy float 是 Python float 的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下事项:

<预><代码>>>>进口号码>>>导入 numpy>>>a = numpy.int_(0)>>>isinstance(a, int)错误的>>>isinstance(a, numbers.Integral)真的>>>b = numpy.float_(0)>>>isinstance(b, 浮动)真的>>>isinstance(b, numbers.Real)真的

NumPy 的 numpy.int_numpy.float_ 类型都在 Python 的 数字抽象基类层次结构,但我很奇怪np.int_ 对象不是内置的int 类,而np.float_ 对象 内置float 的实例类型.

为什么会这样?

解决方案

Python 整数可以是任意长度:type(10**1000) 仍然是 int,并且如果您输出它,将在您的屏幕上打印一个 1,然后打印出一千个零.

Numpy int64(这是我机器上的 int_ )是由 8 个字节(64 位)表示的整数,并且不能表示超出的任何内容.例如,np.int_(10)**1000 会给你一个错误的答案 - 但很快;).

因此,它们是不同种类的数字;将一个子类化为另一个子类与在 float 下子类化 int 一样有意义,这是我假设 numpy 人们认为的.最好将它们分开,这样就没有人会因为混淆它们是不明智的这一事实而感到困惑.

拆分是因为任意大小的整数很慢,而 numpy 试图通过坚持机器友好的类型来加速计算.

另一方面,浮点数是标准的 IEEE 浮点数,无论是在 Python 中还是在 numpy 中,我们的处理器都支持开箱即用.

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?

解决方案

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.

这篇关于为什么 NumPy int 不是 Python int 的实例,而 NumPy float 是 Python float 的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆