如何在nopython mod中将float numpy数组值强制转换为numba jitted函数内部的int

2024-10-06 12:25:52 发布

您现在位置:Python中文网/ 问答频道 /正文

在numba jitted nopython函数中,我需要用另一个数组中的值索引一个数组。两个数组都是numpy数组float。在

例如

@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类型的索引)。另外,我不能在nopythonjit函数内部使用int(index[i])或index[i].astype(“int”)。在

我该怎么做?在


Tags: 函数numpyindex数组floatjitintsources
2条回答

如果您真的不能使用int(indices[i])(它对JoshAdel和我都有效),那么您应该可以使用math.trunc或{}来解决它:

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则取整为负值。在

至少使用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.]

相关问题 更多 >