简体   繁体   English

计算的 Numpy 数组问题,int 类型,int32 与 int64

[英]Numpy Array Problem with Calculation, int type, int32 vs int64

I don't know why there is a discrepancy between the two lines of code below.我不知道为什么下面的两行代码之间存在差异。 The Numpy array (ie, "load_values") for some reason is slightly off in the calculation?由于某种原因,Numpy 数组(即“load_values”)在计算中略有偏差? When I replace the Numpy array index with the actual value that is stored (in this case, 1800), I get the correct answer.当我用存储的实际值(在本例中为 1800)替换 Numpy 数组索引时,我得到了正确答案。 Also, I replaced the Numpy array with a regular List and it also got the correct answer.另外,我用一个普通的 List 替换了 Numpy 数组,它也得到了正确的答案。 It's only when I use the Numpy array that I am getting the calculation slightly off.只有当我使用 Numpy 数组时,我的计算才会稍微偏离。 Any reason why this would be the case?为什么会出现这种情况? Is it obvious and I'm just not seeing it?是不是很明显而我只是没看到?

In [27]: alpha[3] + alpha[2] * 1800 + alpha[1] * (1800 ** 2) + alpha[0] * (1800 ** 3)

Out[27]: 1.2057057142857146

In [28]: alpha[3] + alpha[2] * load_values[2] + alpha[1] * (load_values[2] ** 2) + alpha[0] * (load_values[2] ** 3)

Out [28]: 1.2048772097918872

Edit: Here are the alpha and load_values:编辑:这里是 alpha 和 load_values:

In[54]: alpha

Out[54]: array([ 4.24382716e-13, -1.18055556e-09, -6.69194444e-04,  1.64000000e-03])

In[55]: load_values

Out[55]: array([ 600, 1200, 1800, 2400, 3000])

As mentioned in the comments, the root of the issue is an overflow when doing the operation: load_values[2] ** 3 .正如评论中提到的,问题的根源是执行操作时溢出: load_values[2] ** 3 The default int-type for numpy appears to be int32 while the standard python int appears to be at least the numpy.int64 equivalent. numpy的默认 int 类型似乎是int32而标准 python int似乎至少与numpy.int64等效。 You need to use int64 to properly compute your equation.您需要使用int64来正确计算您的方程。 This can be seen here:这可以在这里看到:

# load_values as int32 array (numpy default):
print(type(load_values[2]))  # <class 'numpy.int32'>
print(type(1800))            # <class 'int'>

answer_1 = 1800 ** 3
answer_2 = load_values[2] ** 3

print(answer_1)              # 5832000000
print(answer_2)              # 1537032704


# load_values as int64 array:
load_values = np.array(load_values, dtype=np.int64)

print(type(load_values[2]))  # <class 'numpy.int64'>
print(type(1800))            # <class 'int'>

answer_1 = 1800 ** 3
answer_2 = load_values[2] ** 3

print(answer_1)              # 5832000000
print(answer_2)              # 5832000000

I will leave the bit-by-bit analysis up to you.我会把一点一点的分析留给你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM