Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Cython doesn't magically let you do arithmetic at arbitrary precisions at the same speed as arithmetic with native machine types. If you need to support arbitrary precision calculations, you need use a datatype that supports them. In the easiest case, you could use Python's integers, but that has a speed overhead which you are probably trying to avoid. You'll likely need to use GMP/MPIR directly.

There is an example of creating a Cython file that uses GMP/MPIR directly in $SAGE_ROOT/examples/programming/sagex/factorial.spyx . This is mentioned in the Sage tutorial under the section Creating Compiled Code . After declaring the appropriate functions in the heading, it basically boils down to:

def factorial(int n):
    cdef mpz_t f
    cdef int i
    cdef char* s

    mpz_init(f)
    mpz_set_si(f, n)

    for i from 2 <= i <= n-1:
        mpz_mul_si(f, f, i)
    s = mpz_get_str(NULL, 32, f)

    r = int(s, 32)
    free(s)
    return r

Check the referenced file for the complete example.

It might be a nice feature or plugin to Cython where you could do "cdef mpz_t x" and have statements like "x+2" be converted into the appropriate GMP/MPIR function call. One could envision a similar thing for MPFR types. However, I do not know how feasible it would be to implement such a thing.