Field \(\QQ\) of Rational Numbers

The class RationalField represents the field \(\QQ\) of (arbitrary precision) rational numbers. Each rational number is an instance of the class Rational.

Interactively, an instance of RationalField is available as QQ:

sage: QQ
Rational Field

Values of various types can be converted to rational numbers by using the __call__ method of RationalField (that is, by treating QQ as a function).

sage: RealField(9).pi()
3.1
sage: QQ(RealField(9).pi())
22/7
sage: QQ(RealField().pi())
245850922/78256779
sage: QQ(35)
35
sage: QQ('12/347')
12/347
sage: QQ(exp(pi*I))
-1
sage: x = polygen(ZZ)
sage: QQ((3*x)/(4*x))
3/4

AUTHORS:

  • Niles Johnson (2010-08): trac ticket #3893: random_element() should pass on *args and **kwds.
  • Travis Scrimshaw (2012-10-18): Added additional docstrings for full coverage. Removed duplicates of discriminant() and signature().
  • Anna Haensch (2018-03): Added function quadratic_defect()
sage.rings.rational_field.RationalField

The class RationalField represents the field \(\QQ\) of rational numbers.

EXAMPLES:

sage: a = long(901824309821093821093812093810928309183091832091)
sage: b = QQ(a); b
901824309821093821093812093810928309183091832091
sage: QQ(b)
901824309821093821093812093810928309183091832091
sage: QQ(int(93820984323))
93820984323
sage: QQ(ZZ(901824309821093821093812093810928309183091832091))
901824309821093821093812093810928309183091832091
sage: QQ('-930482/9320842317')
-930482/9320842317
sage: QQ((-930482, 9320842317))
-930482/9320842317
sage: QQ([9320842317])
9320842317
sage: QQ(pari(39029384023840928309482842098430284398243982394))
39029384023840928309482842098430284398243982394
sage: QQ('sage')
Traceback (most recent call last):
...
TypeError: unable to convert 'sage' to a rational
sage: QQ(u'-5/7')
-5/7

Conversion from the reals to the rationals is done by default using continued fractions.

sage: QQ(RR(3929329/32))
3929329/32
sage: QQ(-RR(3929329/32))
-3929329/32
sage: QQ(RR(1/7)) - 1/7
0

If you specify an optional second base argument, then the string representation of the float is used.

sage: QQ(23.2, 2)
6530219459687219/281474976710656
sage: 6530219459687219.0/281474976710656
23.20000000000000
sage: a = 23.2; a
23.2000000000000
sage: QQ(a, 10)
116/5

Here’s a nice example involving elliptic curves:

sage: E = EllipticCurve('11a')
sage: L = E.lseries().at1(300)[0]; L
0.2538418608559106843377589233...
sage: O = E.period_lattice().omega(); O
1.26920930427955
sage: t = L/O; t
0.200000000000000
sage: QQ(RealField(45)(t))
1/5
sage.rings.rational_field.frac(n, d)

Return the fraction n/d.

EXAMPLES:

sage: from sage.rings.rational_field import frac
sage: frac(1,2)
1/2
sage.rings.rational_field.is_RationalField(x)

Check to see if x is the rational field.

EXAMPLES:

sage: from sage.rings.rational_field import is_RationalField as is_RF
sage: is_RF(QQ)
True
sage: is_RF(ZZ)
False