首页 > 解决方案 > int64 数组和 int 的总和是否应该通过 int64 类型检查?

问题描述

我似乎偶然发现了一些奇怪的代码行为,并且不确定这是预期的还是错误的。当我添加一个从时间对象派生的 int 时,对 int64 的类型检查失败。

我可以将其缩小为将浮点数乘以时间对象:

import numpy, time

# base check works
ts = numpy.arange(10, dtype=numpy.int64)

print(type(ts[0]), " and should be numpy.int64 : ",  end = "")
if isinstance(ts[0], numpy.int64) : print("Check OK!")
else : print("Check FAILED!")

# time object works
ts = numpy.arange(10, dtype=numpy.int64) + int(round(time.time()))

print(type(ts[0]), " and should be numpy.int64 : ",  end = "")
if isinstance(ts[0], numpy.int64) : print("Check OK!")
else : print("Check FAILED!")

# float itself works
ts = numpy.arange(10, dtype=numpy.int64) + numpy.int64(round(1e9))

print(type(ts[0]), " and should be numpy.int64 : ",  end = "")
if isinstance(ts[0], numpy.int64) : print("Check OK!")
else : print("Check FAILED!")


# for some reason the multiplication of both does not work
ts = numpy.arange(10, dtype=numpy.int64) + int(round(time.time()*1e9))

print(type(ts[0]), " and should be numpy.int64 : ",  end = "")
if isinstance(ts[0], numpy.int64) : print("Check OK!")
else : print("Check FAILED!")

我的输出是:

<class 'numpy.int64'>  and should be numpy.int64 : Check OK!  
<class 'numpy.int64'>  and should be numpy.int64 : Check OK!     
<class 'numpy.int64'>  and should be numpy.int64 : Check OK! 
<class 'numpy.int64'>  and should be numpy.int64 : Check FAILED!  

上面的第一个检查应该正常工作,因为据我了解, ts 的 dtype 应该保持 int64 (很明显)。

然而,最后一次检查失败,即使 dtype 被指示为 int64。我不懂为什么。

我用 numpy1.16.4 在 python3.6.8 上运行代码。这台机器是 64 位的,所以自然的 int 也应该是 64 位的,但无论哪种方式,这都不重要,因为我在 numpy 数组(AFAIK)中专门声明了 int64。

我实际上有 3 台不同的机器,使用不同的 python 版本(python 3.5.3 和 numpy 1.16.2)和(3.6.8 和 1.16.2)产生相同的失败检查。其中一个甚至不是我自己设置的,而是一个托管系统。我相信这与我的本地安装无关。

标签: pythonnumpy

解决方案


推荐阅读