Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Convert from int to double and back in Cython

This is a really basic question, I'm sure, for cython types.

In the notebook, I have the following cell to compute a famous but totally inefficient $\pi(x)$ (prime counting function). It already is about 100 times faster than the equivalent in native Python.

Question: The result += (fact - j*int(floor(t))) line still is bright yellow. I don't know if there is any easy way to mix these types. The problem is I need for t to take two ints and make them something I can apply floor to, which appears to be a double. Then I need to make the floor an int again to multiply it by j. Any ideas? Again, I'm sure this is simple, but I haven't earned my Cython stripes yet.

%cython
cdef extern from "math.h":
    double floor(double x)

cdef int primeish(int n):
    cdef int fact
    cdef int result
    cdef int j
    cdef double t
    if n==1:
        return 0
    elif n==2:
        return 1
    elif n==3:
        return 2
    else:
        result = -1
        fact = 1
        for j in range(3,n+1):
            fact = fact*(j-2)
            t = fact/j
            result += (fact - j*int(floor(t)))
        return result