从带有map的类方法调用NumPy时出现Python错误

Ma *_*Tze 16 python numpy

以下代码抛出了错误:

Traceback (most recent call last):
  File "", line 25, in <module>
    sol = anna.main()
  File "", line 17, in main
    sol = list(map(self.eat, self.mice))
  File "", line 12, in eat
    calc = np.sqrt((food ** 5))
AttributeError: 'int' object has no attribute 'sqrt'
Run Code Online (Sandbox Code Playgroud)

码:

import numpy as np
#import time

class anaconda():

    def __init__(self):
        self.mice = range(10000)

    def eat(self, food):
        calc = np.sqrt((food ** 5))
        return calc

    def main(self):

        sol = list(map(self.eat, self.mice))
        return sol


if __name__ == '__main__':
    #start = time.time()
    anna = anaconda()
    sol = anna.main()
    print(len(sol))
    #print(time.time() - start)
Run Code Online (Sandbox Code Playgroud)

我相信我犯了一个严重错误,因为似乎Python将NumPy中的'np'解释为整数,但我没有看到为什么会这样.

Fla*_*bes 13

我会尝试为那些已经给出的答案添加一个精确的答案.numpy.sqrt有一些math.sqrt没有的限制.

import math
import numpy  # version 1.13.3

print(math.sqrt(2 ** 64 - 1))
print(numpy.sqrt(2 ** 64 - 1))

print(math.sqrt(2 ** 64))
print(numpy.sqrt(2 ** 64))
Run Code Online (Sandbox Code Playgroud)

返回(使用Python 3.5):

4294967296.0
4294967296.0
4294967296.0
Traceback (most recent call last):
  File "main.py", line 8, in <module>
    print(numpy.sqrt(2 ** 64))
AttributeError: 'int' object has no attribute 'sqrt'
Run Code Online (Sandbox Code Playgroud)

实际上,2 ** 64等于18,446,744,073,709,551,616和,根据C数据类型(版本C99)的标准,long long unsigned integer类型至少包含介于018,446,744,073,709,551,615包含的范围.

AttributeError发生这种情况是因为numpy,看到它不知道如何处理的类型(转换为C数据类型后),默认调用sqrt对象上的方法(但不存在).如果我们使用浮点数而不是整数,那么一切都可以使用numpy:

import numpy  # version 1.13.3

print(numpy.sqrt(float(2 ** 64)))
Run Code Online (Sandbox Code Playgroud)

收益:

4294967296.0
Run Code Online (Sandbox Code Playgroud)

因此,而不是取代numpy.sqrtmath.sqrt,则还可以取代calc = np.sqrt(food ** 5)通过calc = np.sqrt(float(food ** 5))在你的代码.

我希望这个错误现在对你更有意义.