Dat Chu
Dat Chu

Reputation: 11140

Keep numpy array operator in np.float32

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 conversion and telling numpy to do the work in float32?

Upvotes: 3

Views: 11860

Answers (1)

Robert Kern
Robert Kern

Reputation: 13430

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)

Upvotes: 5

Related Questions