Hojin Cho
Hojin Cho

Reputation: 466

How to properly convert between types in Cython?

I have a function which looks like

cdef double __test_func(double x, double y, double z):
    return (x-y)/((2*x-y)*y)**(0.5*z)
def test_func(x, y, z):
    return __test_func(<double>x, <double>y, <double>z)

What I want to do is to use this test_func in python without regarding whether I typed a dot or not like a real python function. The <double> part is what I wrote after reading the Cython guide, but honestly I am not sure if I did right, especially when they called it "type casting". Because, if I recall correctly, type casting isn't exactly the same thing as type conversion.

And as I suspected, this is not a great idea. This function works somehow as I wrote. But, if I were to type the arguments of the python wrapper,

ctypedef fused Numeric:
    char
    short
    int
    long
    long long
    float
    double
    long double
cdef double __test_func(double x, double y, double z):
    return (x-y)/((2*x-y)*y)**(0.5*z)
def test_func(Numeric x, Numeric y, Numeric z):
    return __test_func(<double>x, <double>y, <double>z)

and after compiling and loading it in a python shell, if I give the argument x as something integer, for instance, x=100, then it gets horribly wrong and gives completely different result to when I give x=100., as if I did the type casting in C.

So, how do I ensure the type conversion is done correctly in cython files? Specifically, how do I convert it to double-precision floating point (64bit floating point)? I know in python it is synonymous to float, but given it is cython, I am not entirely sure what precision float(x) would end up.

Upvotes: 1

Views: 55

Answers (0)

Related Questions