fmpq – rational numbers

class flint.fmpq(p=None, q=None)

The fmpq type represents multiprecision rational numbers.

>>> fmpq(1,7) + fmpq(50,51)
401/357
static bernoulli(ulong n, bool cache=False)

Returns the Bernoulli number \(B_n\) as an fmpq.

>>> [fmpq.bernoulli(n) for n in range(8)]
[1, -1/2, 1/6, 0, -1/30, 0, 1/42, 0]
>>> fmpq.bernoulli(50)
495057205241079648212477525/66

If cache is set to True, all the Bernoulli numbers up to n are computed and cached for fast subsequent retrieval. This feature should be used with caution if n is large. Calling ctx.cleanup() frees cached Bernoulli numbers.

denom(self)

Returns the denominator of self as an fmpz.

static harmonic(ulong n)

Returns the harmonic number \(H_n\) as an fmpq.

>>> [fmpq.harmonic(n) for n in range(6)]
[0, 1, 3/2, 11/6, 25/12, 137/60]
>>> fmpq.harmonic(50)
13943237577224054960759/3099044504245996706400
next(s, bool signed=True, bool minimal=True)

Returns the next rational number after s as ordered by minimal height (if minimal is True) or following the Calkin-Wilf sequence (if minimal is False). If signed is set to False, only the nonnegative rational numbers are considered.

>>> fmpq(23456789,98765432).next()
-23456789/98765432
>>> fmpq(23456789,98765432).next(signed=False)
98765432/23456789
>>> fmpq(23456789,98765432).next(signed=False, minimal=False)
98765432/75308643
>>> a, b, c, d = [fmpq(0)], [fmpq(0)], [fmpq(0)], [fmpq(0)]
>>> for i in range(20):
...     a.append(a[-1].next())
...     b.append(b[-1].next(signed=False))
...     c.append(c[-1].next(minimal=False))
...     d.append(d[-1].next(signed=False, minimal=False))
... 
>>> a
[0, 1, -1, 1/2, -1/2, 2, -2, 1/3, -1/3, 3, -3, 2/3, -2/3, 3/2, -3/2, 1/4, -1/4, 4, -4, 3/4, -3/4]
>>> b
[0, 1, 1/2, 2, 1/3, 3, 2/3, 3/2, 1/4, 4, 3/4, 4/3, 1/5, 5, 2/5, 5/2, 3/5, 5/3, 4/5, 5/4, 1/6]
>>> c
[0, 1, -1, 1/2, -1/2, 2, -2, 1/3, -1/3, 3/2, -3/2, 2/3, -2/3, 3, -3, 1/4, -1/4, 4/3, -4/3, 3/5, -3/5]
>>> d
[0, 1, 1/2, 2, 1/3, 3/2, 2/3, 3, 1/4, 4/3, 3/5, 5/2, 2/5, 5/3, 3/4, 4, 1/5, 5/4, 4/7, 7/3, 3/8]
numer(self)

Returns the numerator of self as an fmpz.

p

fmpq.numer(self)

Returns the numerator of self as an fmpz.

q

fmpq.denom(self)

Returns the denominator of self as an fmpz.

repr(self)
str(self, **kwargs)

Converts self to a string, forwarding optional keyword arguments to fmpz.str().

>>> fmpq.bernoulli(12).str()
'-691/2730'
>>> fmpq.bernoulli(100).str(base=2, condense=10)
'-110001110{...257 digits...}0011011111/1000001000110010'