![](/img/trans.png)
[英]Numba - memory address of argument (numpy array) from inside jitted function
[英]How can I cast a float numpy array value to an int inside of a numba jitted function in nopython mode
在一个numba jitted nopython函数内部,我需要使用另一个数组内部的值对一个数组进行索引。 这两个数组都是numpy数组浮点数。
例如
@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])或index [i] .astype(“ int”)。
我该怎么做呢?
至少使用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.]
如果您真的不能使用int(indices[i])
(它既适用于JoshAdel,也适用于我),则应该可以使用math.trunc
或math.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
四舍五入为负值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.