[Python] complex type conversion errors in NumPy vs C complex.h library

Discussão em 'Python' iniciado por Stack, Fevereiro 4, 2025.

  1. Stack

    Stack Membro Participativo

    I have a large Python method that calculates a series of ndarray quantities of dtype=np.complex128. I have been experimenting with what speed increases are possible using Cython. In converting a Python method to Cython, there is the thought about using NumPy calculations vs using C libraries to do it. Exploring the latter, this is a watered-down Cython method for computing the complex exponential of an input NumPy array, x:

    import numpy as np
    cimport numpy as cnp
    cnp.import_array()

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

    DTYPEC = np.complex128
    ctypedef cnp.complex128_t DTYPEC_t

    cpdef cnp.ndarray[DTYPEC_t, ndim=1] stupid_exp(cnp.ndarray[DTYPEC_t, ndim=1] x):

    cdef int num_pts, j
    cdef double complex tmp

    num_pts = len(x)
    cdef cnp.ndarray[DTYPEC_t, ndim=1] result = np.zeros(num_pts, dtype=DTYPEC)

    for j in range(num_pts):
    result[j] = cexp(x[j])

    return result


    On my Windows 10 machine, compiled with Visual Studio 2022, the result[j] = cexp(x[j]) line creates a pair of errors:

    error C2440: 'function': cannot convert from '__pyx_t_double_complex' to '_Dcomplex'
    error C2440: '=': cannot convert from '_Dcomplex' to '__pyx_t_double_complex'


    This says that NumPy complex128 and C's double complex are not being seen as the same data type. A LLM suggested explicit type conversion:

    tmp = <double complex>x[j]
    tmp = cexp(tmp)
    result[j] = <DTYPEC_t>tmp


    but this doesn't fix the errors. Any thoughts about how I could get this simple code to compile correctly in Cython?

    Continue reading...

Compartilhe esta Página