python - 如何将数组中的每个元素与大数相乘而不会出现 OverflowError : Python int too large to convert to C long?

标签 python arrays for-loop numpy

我正在编写一个程序,我想将数组中的每个数字(来自 numpy)与一个大数字(1.692287392646066e+41)相乘,我这样做是这样的:

x = array([ 16,  18,  19,  15,  27,  26,  13,  34,  38,  36,  43,  42,  48,
    50,  55,  57,  70,  67,  65,  85,  99,  94,  90, 112, 126, 130,
   142, 120])
weight = 1.692287392646066e+41

x[:] = [i*weight for i in x]

但随后我收到错误“OverflowError:Python int 太大而无法转换为 C long”。奇怪的是,在 for 循环外乘以数字似乎可行:

In [1]: x[0]*weight
Out[1]: 2.7076598282337055e+42

我的问题是,有什么方法可以让我在 for 循环中执行此操作,因为我事先不知道我的数组有多长? (我知道它有 1 行。)

最佳答案

python 而不是 numpy 中进行乘法是没有意义的。 numpy 不仅速度更快,而且效果更好。

您正在尝试创建一个 python 列表,然后尝试将其复制到 numpy 数组 元素中。

只是使用

x = x * weight

你很好。

EOL 怀疑这行得通,所以这是我刚刚在我的计算机上所做的:

$ python
Python 2.7.3 (default, Dec 18 2014, 19:03:52)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from numpy import array
>>> x = array([ 16,  18,  19,  15,  27,  26,  13,  34,  38,  36,  43,  42,  48,
...     50,  55,  57,  70,  67,  65,  85,  99,  94,  90, 112, 126, 130,
...    142, 120])
>>> weight = 1.692287392646066e+41
>>> x = x * weight
>>> x
array([  2.70765983e+42,   3.04611731e+42,   3.21534605e+42,
         2.53843109e+42,   4.56917596e+42,   4.39994722e+42,
         2.19997361e+42,   5.75377713e+42,   6.43069209e+42,
         6.09223461e+42,   7.27683579e+42,   7.10760705e+42,
         8.12297948e+42,   8.46143696e+42,   9.30758066e+42,
         9.64603814e+42,   1.18460117e+43,   1.13383255e+43,
         1.09998681e+43,   1.43844428e+43,   1.67536452e+43,
         1.59075015e+43,   1.52305865e+43,   1.89536188e+43,
         2.13228211e+43,   2.19997361e+43,   2.40304810e+43,
         2.03074487e+43])
>>>

关于python - 如何将数组中的每个元素与大数相乘而不会出现 OverflowError : Python int too large to convert to C long?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29628410/

相关文章:

java - 我的任务输出错误,无法解决

javascript - 如何在 JS 中以 1 秒的延迟逐行制作循环日志

python - Twisted 试验、PYTHONPATH 和 sys.path

C++ 意外的数组输出

java - 将数组添加到 ArrayList

php - 获取 ID 数组,然后通过这些 ID 查询不同的帖子类型

javascript - 循环返回两个数组

python - 接听 twilio 电话时收到通知

python - 如何将整数添加到字符串中?

python - easy_install最新版本github