rational numbers with cython

asked 2016-04-20 17:07:20 +0100

rafarob32 gravatar image

updated 2016-04-20 21:42:23 +0100

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:

  %cython

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

rational_partitions(10)
edit retag flag offensive close merge delete

Comments

1

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 19:11:11 +0100 )edit

I re-edited with an example. Thanks.

rafarob32 gravatar imagerafarob32 ( 2016-04-20 19:41:05 +0100 )edit
1

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-21 00:51:37 +0100 )edit
2

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-21 00:52:30 +0100 )edit

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

slelievre gravatar imageslelievre ( 2016-04-21 11:14:19 +0100 )edit