What is the difference between np.float64 and np.double?

会有一股神秘感。 提交于 2020-05-26 19:30:47

问题


I tried running the following code to find out the difference between float64 and double in numpy. The result is interesting as type double takes almost double the time compared with time taken for multiplication with float64. Need some light on this.

import time
import numpy as np

datalen = 100000
times = 10000

a = np.random.rand(datalen)
b = np.random.rand(datalen)

da = np.float64(a)
db = np.float64(a)

dda = np.double(a)
ddb = np.double(b)

tic = time.time()
for k in range(times):
    dd = dda * ddb
toc = time.time()
print (toc - tic), 'time taken for double'

tic = time.time()
for k in range(times):
    d = da * db
toc = time.time()
print (toc - tic), 'time taken for float64'

回答1:


I think you're comparing apples with oranges.

The first bench is basically a * b but the second a * a.

I suspect much less cache misses for the latter.




回答2:


import numpy as np
np.double is np.float64 # returns True

In theory both should be same.




回答3:


Many array operations are typically limited only by the time it takes to load the array elements from the RAM into your cache.

So you'd expect the operation to be faster if the size of each value is smaller or you don't need to load so many elements into your cache.

That's why your timings were different: np.float64 and np.double don't actually make copies, so in the first case the arrays are identical while they are not in the second case:

>>> da is db
True

>>> dda is ddb
False

So the first case can be optimized because you don't need to load values from two arrays but only from one. Thus doubling the bandwith.

However there's another thing to consider: np.float64 and np.double should be identical on most machines but that's not garantueed. np.float64 is a fixed-sized float value (always 64bit) while np.double depends on the machine and/or compiler. On most machines doubles are 64bit but that's not always garantueed! So you might have speed differences if your double and float64 are of different widths:

>>> np.double(10).itemsize
8
>>> np.float64(10).itemsize
8
>>> np.float64 is np.double
True


来源:https://stackoverflow.com/questions/43679734/what-is-the-difference-between-np-float64-and-np-double

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!