开发者

Keep numpy array operator in np.float32

开发者 https://www.devze.com 2023-03-02 20:15 出处:网络
a = np.random.random((512,512,3)).astype(np.float32) b = np.ones((512,512,1), dtype=np.int32) c = a / b
a = np.random.random((512,512,3)).astype(np.float32)
b = np.ones((512,512,1), dtype=np.int32)
c = a / b
c.dtype

>> dtype('float64')

Dividing a float32 matrix by a int32 matrix gives a float64 matrix. Currently I have to do

return c.astype(np.float32)

This is extra work for the CPU. Is there a way for me to avoid the final conversi开发者_JAVA技巧on and telling numpy to do the work in float32?


You will have to use the out argument of np.divide().

[~/scratch]
|1> a = np.random.random((512,512,3)).astype(np.float32)

[~/scratch]
|2> b = np.ones((512,512,1), dtype=np.int32)

[~/scratch]
|3> c = np.empty_like(a)

[~/scratch]
|4> c = np.divide(a, b, c)

[~/scratch]
|5> c.dtype
dtype('float32')

In numpy 1.6, you will be able to do c = np.divide(a, b, dtype=np.float32)

0

精彩评论

暂无评论...
验证码 换一张
取 消