2017-01-16 57 views
1

它似乎從int數組中減去float32數字默認情況下會生成float64數組。有沒有辦法繞過這一點,並獲得float32作爲結果的數據類型?如何爲NumPy中的算術運算指定結果數據類型?

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慢。

回答

5

作爲ufunc,np.subtract接受several keyword arguments未列在其主文檔頁面上。其中之一就是dtype,所以你可以這樣做,例如:np.subtract(a, b, dtype='float32')並達到你想要的結果。

如果將來有用,np.promote_types會告訴你兩個dtypes都可以安全投射的最小dtype,並且np.result_type會告訴你dtype Numpy的投射規則默認會產生。

+0

嘗試這是字面上我的第一個想法,我想我已經嘗試過。但似乎我沒有。還要感謝promote_types和result_type。 – Trilarion