[Cython] Cython and complex floats

Robert Bradshaw robertwb at math.washington.edu
Fri Aug 1 07:03:12 CEST 2008


On Jul 31, 2008, at 9:41 PM, 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.
>
>
>> 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?

I think the point is to operate on complex numbers without the object  
baggage (the same way one can operate on C doubles). I'm not sure  
what the best long term option is (out of the 3 you proposed) but 1  
seems reasonable for now--it will be quite a bit of work to fully  
support complexes via macros (especially when evaluating mixed  
expressions) but should probably eventually be done.

>
>
>> 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
>
> _______________________________________________
> Cython-dev mailing list
> Cython-dev at codespeak.net
> http://codespeak.net/mailman/listinfo/cython-dev



More information about the Cython-dev mailing list