rational numbers with cython

asked 2016-04-20 10:07:20 -0500

rafarob32 gravatar image

updated 2016-04-20 14:42:23 -0500

I want to work efficiently with rational numbers under the context %cython but I don`t know how. Can anyone suggest any ideas? Thank you.

An example:


    def rational_partitions(n):
        sol = [i/n for i in range(n)]
        for a in sol[0:-1]:
            for b in sol[1:]:
                while abs(b-a)/k>1/n:
                    k += 1
        return sol

edit retag flag offensive close merge delete



Can you say a bit more about what you want to do? Or give some Sage code that you would like to cythonize?

slelievre gravatar imageslelievre ( 2016-04-20 12:11:11 -0500 )edit

I re-edited with an example. Thanks.

rafarob32 gravatar imagerafarob32 ( 2016-04-20 12:41:05 -0500 )edit

Note that cython does provide a limited "machine integer" type in the form of C int or C long, which behave different from python ints and sage Integers in that they silently overflow rather than use multiprecision arithmetic. Cython does NOT provide such a type for rational arithmetic because C does not provide it. When you do arithmetic with rational numbers, overflow happens remarkably easily, so having fixed bitlength rational numbers would probably not have much use anyway.

nbruin gravatar imagenbruin ( 2016-04-20 17:51:37 -0500 )edit

If you're finding that the python wrappers are causing undue speed loss, you can look in sage/rings/rational.pyx and sage/rings/rational.pyx and see how much can be gained from interfacing at the C-level. Surprisingly few routines are mentioned in the pxd, but the cdef mpq_t value attribute allows you to use the super-optimized gmp mpq routines to compute with rational numbers.

nbruin gravatar imagenbruin ( 2016-04-20 17:52:30 -0500 )edit

@nbruin: you could turn both of your comments into an answer.

slelievre gravatar imageslelievre ( 2016-04-21 04:14:19 -0500 )edit