Skip to main content
 首页 » 编程设计

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

2024年12月31日14rubylouvre

我在尝试在 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 对文件进行 cythonize 时

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) 

这似乎是将 double 复合体返回到浮点复合体的问题。我试过将其显式转换为复杂的 float ,例如:

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

但这并没有什么不同。

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

请您参考如下方法:

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

为了避免它,您必须避免从 double 到 float 的转换,然后再返回。

例如:

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