The following code throws me the error:
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'
Code:
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)
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.
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))
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'
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.
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)))
returns:
4294967296.0
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.
As others have noticed, this boils down to the fact that np.sqrt(7131 ** 5) works but np.sqrt(7132 ** 5) returns an error:
import numpy as np
print(np.sqrt(7131 ** 5))
print(np.sqrt(7132 ** 5))
# 4294138928.9
Traceback (most recent call last):
File "main.py", line 4, in <module>
print(np.sqrt(7132 ** 5))
AttributeError: 'int' object has no attribute 'sqrt'
Since np.sqrt docs don't mention any bounds on the argument, I'd consider this a numpy bug.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With