[Cython] Cython and complex floats

Dag Sverre Seljebotn dagss at student.matnat.uio.no
Fri Aug 1 09:27:16 CEST 2008


Stefan Behnel wrote:
> 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.

Thanks. Buffers support more types though (Zf, Zd and Zg, ie complex 
float, complex double, complex long double), so I'm not sure how useful 
this would be.

> 
> 
>> 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?

The idea is getting the data out of the buffer for numeric calculations. 
In the buffer it is stored as two floats (of whatever size), not as a 
Python object, so that's what the buffer "contains". I could add 
syntactic sugar to wrap it in Python objects but that would defeat the 
purpose of buffers as you would loose speed (just use a memoryview then).

(Note that buffers support structs, I would just support structs first 
and then map "Zf" to "ff").

The idea was that I would initially just map "Zx" to "a struct of two x" 
and let the user deal with it. It is not a long-term solution, but 
perhaps we can get a user-base without it first.

Of course, if I go with 2) or 3), any complex native type will coerce to 
the Python complex object (perhaps with a need for explicit cast to go 
down from long double).

-- 
Dag Sverre


More information about the Cython-dev mailing list