似乎从int数组中减去float32数字会导致默认情况下导致float64数组.有没有办法绕过这个并获得float32作为结果的数据类型?
numpy.subtract不允许指定dtype参数.
实现这一点的唯一方法是将int数组转换为float32之前,实际上减去了两个似乎相当慢的float32数组.这是应该的方式吗?
示例代码:
import time import numpy as np if __name__ == '__main__': # some int32 array a = np.arange(1e7) print('a.dtype={}'.format(a.dtype)) # int32 # subtraction with a python float t0 = time.clock() b = a - 5.5 t1 = time.clock() print('b.dtype={}, took {}s'.format(b.dtype, t1 - t0)) # float64 # a numpy float32 c = np.array(5.5, dtype=np.float32) print('c.dtype={}'.format(c.dtype)) # float32 # subtraction with the numpy float32 t0 = time.clock() d = a - c t1 = time.clock() print('d.dtype={}, took {}s'.format(d.dtype, t1 - t0)) # float64! why not float32 # convert the int32 to float32 e = a.astype(dtype=np.float32) print('e.dtype={}'.format(e.dtype)) # float32 # subtract two float32 array t0 = time.clock() e = a.astype(dtype=np.float32) f = e - c t1 = time.clock() print('f.dtype={}, took {}s'.format(f.dtype, t1 - t0)) # float32 (finally)
版画
a.dtype=float64 b.dtype=float64, took 0.0229595559008s c.dtype=float32 d.dtype=float64, took 0.0223958136306s e.dtype=float32 f.dtype=float32, took 0.0334388477586s
手动转换为float32之前似乎比自动转换为float64慢.
作为ufunc,np.subtract
接受几个未在其主文档页面上列出的关键字参数.其中一个是dtype,所以你可以这么说,np.subtract(a, b, dtype='float32')
并且:实现你想要的结果.
如果它在将来有用,np.promote_types
会告诉你两个dtypes都可以安全地投射的最小dtype,并np.result_type
告诉你dtype Numpy的投射规则默认会产生.