2016-03-17 65 views
2

在numba jitted nopython函數內部,我需要使用另一個數組內的值對數組進行索引。這兩個數組都是numpy數組浮點數。如何在nopython模式下將浮點numpy數組值賦給numba jitted函數內的一個int

例如

@numba.jit("void(f8[:], f8[:], f8[:])", nopython=True) 
def need_a_cast(sources, indices, destinations): 
    for i in range(indices.size): 
     destinations[i] = sources[indices[i]] 

我的代碼是不同的,但是讓我們假設問題是這個愚蠢的例子(即,我不能有一個int類型的索引)可重複的。 AFAIK,我不能在nopython jit函數中使用int(indices [i])和indices [i] .astype(「int」)。

我該怎麼做?

回答

2

使用numba 0.24至少,你可以做一個簡單的轉換:

import numpy as np 
import numba as nb 

@nb.jit(nopython=True) 
def need_a_cast(sources, indices, destinations): 
    for i in range(indices.size): 
     destinations[i] = sources[int(indices[i])] 

sources = np.arange(10, dtype=np.float64) 
indices = np.arange(10, dtype=np.float64) 
np.random.shuffle(indices) 
destinations = np.empty_like(sources) 

print indices 
need_a_cast(sources, indices, destinations) 
print destinations 

# Result 
# [ 3. 2. 8. 1. 5. 6. 9. 4. 0. 7.] 
# [ 3. 2. 8. 1. 5. 6. 9. 4. 0. 7.] 
2

如果你真的不能使用int(indices[i])(它爲JoshAdel,也爲我),你應該能夠解決它與math.truncmath.floor

import math 

... 

destinations[i] = sources[math.trunc(indices[i])] # truncate (py2 and py3) 
destinations[i] = sources[math.floor(indices[i])] # round down (only py3) 

math.floor僅適用於Python3據我知道,因爲它返回一個Python2 float。但另一方面math.trunc四捨五入爲負值。

相關問題