从带有地图的类方法调用NumPy时发生Python错误 [英] Python error when calling NumPy from class method with map
问题描述
以下代码抛出错误:
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'
代码:
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)
我相信我犯了一个严重的错误,因为Python似乎将NumPy中的'np'解释为整数,但是我不知道为什么.
I believe I made a serious mistake, because it seems like Python interprets the 'np' from NumPy as an integer, but I have no glimpse why that is.
推荐答案
我将尝试为已经给出的答案添加精确答案. numpy.sqrt
有一些math.sqrt
没有的限制.
I'll try to add a precise answer to those that have already been given. numpy.sqrt
has some limitations that math.sqrt
doesn't have.
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))
返回(使用Python 3.5):
returns (with 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'
实际上,2 ** 64
等于18,446,744,073,709,551,616
,并且根据C数据类型(版本C99)的标准,long long unsigned integer
类型至少包含0
和18,446,744,073,709,551,615
之间的范围.
In fact, 2 ** 64
is equal to 18,446,744,073,709,551,616
and, according to the standard of C data types (version C99), the long long unsigned integer
type contains at least the range between 0
and 18,446,744,073,709,551,615
included.
出现AttributeError
的原因是,numpy
看到了一个不知道如何处理的类型(转换为C数据类型后),默认情况下是在对象上调用sqrt
方法(但是不会) t存在).如果我们使用浮点数而不是整数,那么所有内容都将使用numpy
:
The AttributeError
occurs because numpy
, seeing a type that it doesn't know how to handle (after conversion to C data type), defaults to calling the sqrt
method on the object (but that doesn't exist). If we use floats instead of integers then everything will work using numpy
:
import numpy # version 1.13.3
print(numpy.sqrt(float(2 ** 64)))
返回:
4294967296.0
因此,也可以在代码中将calc = np.sqrt(food ** 5)
替换为calc = np.sqrt(float(food ** 5))
,而不是用math.sqrt
替换numpy.sqrt
.
So instead of replacing numpy.sqrt
by math.sqrt
, you can alternatively replace calc = np.sqrt(food ** 5)
by calc = np.sqrt(float(food ** 5))
in your code.
我希望这个错误现在对您更有意义.
I hope this error will make more sense to you now.
这篇关于从带有地图的类方法调用NumPy时发生Python错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!