【问题标题】:Is it possible to convert an int to an array while using njit(numba)?使用 njit(numba) 时是否可以将 int 转换为数组?
【发布时间】:2021-03-08 18:40:57
【问题描述】:

我想知道在 numba 中使用 njit 时是否可以将 int 转换为数组?抱歉,如果这是一个简单的问题,我是图书馆的新手,希望了解更多信息。

我尝试了以下方法:

import numpy as np 
from numba import njit 

    @njit
    def top(f):
        if f =="TRUE":
             t = 0
             for i in range(10):
                  t = t+1
             t = np.array(t)
             return t
    
    top("TRUE") 

但得到以下错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3/dist-packages/numba/dispatcher.py", line 401, in _compile_for_args
    error_rewrite(e, 'typing')
  File "/usr/lib/python3/dist-packages/numba/dispatcher.py", line 344, in error_rewrite
    reraise(type(e), e, None)
  File "/usr/lib/python3/dist-packages/numba/six.py", line 668, in reraise
    raise value.with_traceback(tb)
numba.errors.TypingError: Failed in nopython mode pipeline (step: nopython frontend)
Cannot unify int64 and array(int64, 0d, C) for 't', defined at <stdin> (4)

File "<stdin>", line 4:
<source missing, REPL/exec in use?>

[1] During: typing of assignment at <stdin> (7)

File "<stdin>", line 7:
<source missing, REPL/exec in use?>

【问题讨论】:

  • 我认为问题在于t 在某一时刻是一个整数,后来是一个数组,因此它不知道如何为此生成正确的机器代码。但即便如此,为什么不把top的正文换成if f == "TRUE": return np.array(10)呢?
  • 使用不同的变量。

标签: python-3.x numpy numba


【解决方案1】:

您可能不应该在 numba 函数中更改变量的类型(类似于您无法在 C 函数中这样做的原因)。这似乎有效:

@njit
def top(f):
    if f =="TRUE":
        t = 0
        for i in range(10):
            t = t+1
        return np.array([t])

【讨论】:

    猜你喜欢
    • 2015-03-14
    • 1970-01-01
    • 1970-01-01
    • 2017-12-04
    • 1970-01-01
    • 2017-09-12
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多