[Cython] Cython and complex floats

Stefan Behnel stefan_ml at behnel.de
Fri Aug 1 06:41:13 CEST 2008


Hi,

Dag Sverre Seljebotn wrote:
> Buffers and Python has the complex datatype, while I'm reasonably sure I 
> haven't found anything about it in Cython (?).

You can use Python's complex types in Cython by simply declaring them as an
extension type:

    cdef extern from "complexobject.h":

        struct Py_complex:
            double real
            double imag

        ctypedef class __builtin__.complex [object PyComplexObject]:
            cdef Py_complex cval

    # A function which uses the above type
    def spam(complex c):
        print "Real:", c.cval.real
        print "Imag:", c.cval.imag

That's already done in Cython/Includes/python2.5.pxd.


> 1) Complex numbers can be pulled out into a struct consisting of two 
> floats. Like this:
> 
> cdef struct cdouble:
>    double real
>    double imag
> 
> def f(object[cdouble] buf):
>    ...

I'm not sure we need such syntactic sugar. All you gain is one ".cval" less.

Or do I misunderstand your proposal here?


> Operations on the fields must happen manually.
> 
> 2) In addition, Cython gets support for the C99 "complex" float modifier.
> 
> def complex double sum(object[complex double] buf):
>    cdef complex double result = 0 + 0j
>    ...
> 
> Here, operations between complex datatypes are done natively by the 
> compiler. However the code generated is illegal on non-C99-compilers.

I think it's fine for a specific feature to break compiler compatibility as
long as it is clearly stated in the docs and it does not impact code that does
not use it.

Stefan



More information about the Cython-dev mailing list