使用numpy求平方值可得出负数 [英] Using numpy to square value gives negative number

查看:593
本文介绍了使用numpy求平方值可得出负数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用numpy逐元素对数组进行平方.我注意到有些值显示为负数.平方值未接近最大int限制.有谁知道为什么会这样,我该如何解决?我宁愿避免使用for循环对每个元素进行平方运算,因为我的数据集很大.

I'm trying to use numpy to element-wise square an array. I've noticed that some of the values appear as negative numbers. The squared value isn't near the max int limit. Does anyone know why this is happening and how I could fix it? I'd rather avoid using a for loop to square an array element-wise, since my data set is quite large.

这是正在发生的事的一个例子:

Here's an example of what is happening:

import numpy as np

test = [1, 2, 47852]
sq = np.array(test)**2
print(sq)
print(47852*47852)

输出:

[1,4, -2005153392]
2289813904

推荐答案

这是因为NumPy不检查整数溢出-可能是因为这会减慢每个整数运算的速度,并且NumPy在设计时考虑了效率.因此,当您有一个由32位整数组成的数组并且结果不适合32位时,它仍会被解释为32位整数,从而给您带来奇怪的负结果.

This is because NumPy doesn't check for integer overflow - likely because that would slow down every integer operation, and NumPy is designed with efficiency in mind. So when you have an array of 32-bit integers and your result does not fit in 32 bits, it is still interpreted as 32-bit integer, giving you the strange negative result.

为避免这种情况,请牢记dtype,您需要安全地执行该操作,在这种情况下,'int64'就足够了.

To avoid this, you can be mindful of the dtype you need to perform the operation safely, in this case 'int64' would suffice.

>>> np.array(test, dtype='int64')**2
2289813904

您不会在Python int上看到相同的问题,因为Python会检查溢出并在必要时相应地调整为更大的数据类型.如果我还记得的话,邮件列表上有一个关于此的问题,并且答复是,如果在NumPy中执行相同操作,则对原子数组操作会有很大的性能影响.

You aren't seeing the same issue with Python int's because Python checks for overflow and adjusts accordingly to a larger data type if necessary. If I recall, there was a question about this on the mailing list and the response was that there would be a large performance implication on atomic array ops if the same were done in NumPy.

关于为什么,您的默认整数类型在64位系统上可能是32位,例如 Goyo在一个相关问题上回答了,默认整数np.int_类型与C long相同,后者与平台有关,但可以为32位.

As for why your default integer type may be 32-bit on a 64-bit system, as Goyo answered on a related question, the default integer np.int_ type is the same as C long, which is platform dependent but can be 32-bits.

这篇关于使用numpy求平方值可得出负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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