# rational numbers with cython

I want to work efficiently with rational numbers under the context %cython but I dont 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 close merge delete

1

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

( 2016-04-20 12:11:11 -0600 )edit

I re-edited with an example. Thanks.

( 2016-04-20 12:41:05 -0600 )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.

( 2016-04-20 17:51:37 -0600 )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.

( 2016-04-20 17:52:30 -0600 )edit