Skip to main content
 首页 » 编程设计

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

2025年05月04日62cyq1162

我正在编写一个程序,我想将数组中的每个数字(来自 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]) 
>>>