numpy错误:电源中遇到无效值 [英] Numpy error: invalid value encountered in power

查看:407
本文介绍了numpy错误:电源中遇到无效值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

import numpy

def numpysum(n):
   a = numpy.arange(n) ** 2
   b = numpy.arange(n) ** 3
   c = a + b
   return c


size = 3000
c = numpysum(size)

运行时出现错误:

D:\ Work \ programming \ python \ test_1 \ src \ test1_numpy.py:6:RuntimeWarning:电源遇到无效值 b = numpy.arange(n)** 3

D:\Work\programming\python\test_1\src\test1_numpy.py:6: RuntimeWarning: invalid value encountered in power b = numpy.arange(n) ** 3

请注意,以下numpyless函数可以正常工作:

Note that the following numpyless function works fine:

def pythonsum(n):
   a = list(range(n))
   b = list(range(n))
   c = []
   for i in range(len(a)):
      a[i] = i ** 2
      b[i] = i ** 3
      c.append(a[i] + b[i])
   return c

我想这是因为我试图筹集大量资金以支持三.除了处理浮点数外,我还能做什么?

I guess it happens because I try to raise a large number to power three. What can I do, beside working with floating point numbers?

我正在使用Python 3.2.

I am working with Python 3.2.

推荐答案

numpy实际上正在为此上寻找您.与标准Python不同,其整数运算不适用于任意精度的对象.我猜您正在运行32位python,因为相同的操作对我而言不会溢出:

numpy is actually looking out for you on this one. Unlke in standard Python, its integer operations don't work on arbitrary-precision objects. I'd guess you were running a 32-bit python, because the same operations don't overflow for me:

>>> sys.maxsize
9223372036854775807
>>> size = 3000
>>> c = numpysum(size)
>>>

但是他们最终会.甚至更容易了解您是否手动控制类型的大小:

but they will eventually. Even easier to see if you control the size of the type manually:

>>> numpy.arange(10, dtype=numpy.int8)**10
__main__:1: RuntimeWarning: invalid value encountered in power
array([  0,   1,   0, -87,   0,  -7,   0, -15,   0,   0], dtype=int8)
>>> numpy.arange(10, dtype=numpy.int16)**10
array([     0,      1,   1024,  -6487,      0,    761, -23552,  15089,
            0,      0], dtype=int16)
>>> numpy.arange(10, dtype=numpy.int32)**10
array([          0,           1,        1024,       59049,     1048576,
           9765625,    60466176,   282475249,  1073741824, -2147483648], dtype=int32)
>>> numpy.arange(10, dtype=numpy.int64)**10
array([         0,          1,       1024,      59049,    1048576,
          9765625,   60466176,  282475249, 1073741824, 3486784401])

随着位数的增加,情况会有所改善.如果您确实希望对Python任意大小的整数执行numpy数组操作,则可以将dtype设置为object:

where things improve as the number of bits increases. If you really want numpy array operations on Python arbitrary-size integers, you can set dtype to object:

>>> numpy.arange(10, dtype=object)**20
array([0, 1, 1048576, 3486784401, 1099511627776, 95367431640625,
       3656158440062976, 79792266297612001, 1152921504606846976,
       12157665459056928801], dtype=object)

这篇关于numpy错误:电源中遇到无效值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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