Cython 将 double 复合体返回到 float 复合体会导致表达式不在纯 C 中

Cython returning a double complex to a float complex causes the expression not to be in pure C

我在 Cython 中尝试使用 complex64_t 时遇到问题。这是我简单的 cython 示例。

cimport numpy as cnp

cdef extern from "complex.h":
    double complex cexp(double complex)

cpdef example():
    cdef float b = 2.0
    cdef cnp.complex64_t temp1
    cdef cnp.complex128_t temp2

    temp1 = cexp(1j * b)
    temp2 = cexp(1j * b)

当我使用以下 setup.py

对文件进行 cython 化时
from distutils.core import setup
from Cython.Build import cythonize
from distutils.extension import Extension
import numpy as np


ext_modules = [
    Extension(
        "bug_example",
        ["bug_example.pyx"],
        include_dirs=[np.get_include()],
    )
]


setup(
    name='bug_example',
    ext_modules=cythonize(ext_modules, annotate=True,
                          compiler_directives={'boundscheck': False})
)

一切编译都没有问题,但我在包含

的行上变成黄色(不是纯 C)
temp1 = cexp(1j * b)

但不在

temp2 = cexp(1j * b)

这似乎是将双精度复合体返回到浮点复合体的问题。我试过将它显式转换为复杂的浮点数,如:

temp1 = <float complex>(cexp(1j * b))

但这没有什么不同。

有人可以帮我修复我的代码,使带有 temp1 的行不再是黄色的,而是纯 C 代码。这将允许我在 cython 中使用 openmp。

黄色是由于 __Pyx_CREAL__Pyx_CIMAG 造成的,这应该不是问题,但谁知道呢...

为了避免它,您必须避免从 doublefloat 的转换。

例如:

cimport numpy as cnp

#take the float version (cexpf) instead of double-version (cexp)
cdef extern from "complex.h":
     float complex cexpf(float complex)

#1j maps to double complex, so create a float version
cdef float complex float_1j = 1j

cpdef example():
    cdef float b_float = 2.0                              #use float not double
    cdef cnp.complex64_t temp1 = cexpf(float_1j*b_float)  #everything is float