24.6 Rational Numbers

Module: sage.rings.rational

Rational Numbers

Author Log:

TESTS:

sage: a = -2/3
sage: a == loads(dumps(a))
True

Module-level Functions

clear_mpz_globals( )

gmp_randrange( )

init_mpz_globals( )

make_rational( )

Make a rational number from s (a string in base 32)

Input:

s
- string in base 32
Output: Rational

sage: (-7/15).str(32)
'-7/f'
sage: sage.rings.rational.make_rational('-7/f')
-7/15

pyrex_rational_reconstruction( )

Find the rational reconstruction of a mod m, if it exists.

Input:

a
- Integer
m
- Integer
Output:
x
- rings.rational.Rational

sage: Integers(100)(2/3)
34
sage: sage.rings.rational.pyrex_rational_reconstruction(34, 100)
2/3

Class: int_to_Q

class int_to_Q

Special Functions: __init__,$ \,$ _repr_type

_repr_type( )

Return string that describes the type of morphism.

sage: sage.rings.rational.int_to_Q()._repr_type()
'Native'

Class: Rational

class Rational
A Rational number.

Rational numbers are implemented using the GMP C library.

sage: a = -2/3
sage: type(a)
<type 'sage.rings.rational.Rational'>
sage: parent(a)
Rational Field
sage: Rational('1/0')
Traceback (most recent call last):
...
TypeError: unable to convert 1/0 to a rational        
sage: Rational(1.5)
3/2
sage: Rational('9/6')
3/2
sage: Rational((2^99,2^100))
1/2
sage: Rational(("2", "10"), 16)
1/8
sage: Rational(QQbar(125/8).nth_root(3))
5/2
sage: Rational(AA(209735/343 - 17910/49*golden_ratio).nth_root(3) + 3*golden_ratio)
53/7

Conversion from PARI:

sage: Rational(pari('-939082/3992923'))
-939082/3992923

Functions: additive_order,$ \,$ ceil,$ \,$ charpoly,$ \,$ copy,$ \,$ denom,$ \,$ denominator,$ \,$ factor,$ \,$ floor,$ \,$ gamma,$ \,$ gcd,$ \,$ height,$ \,$ is_integral,$ \,$ is_one,$ \,$ is_square,$ \,$ lcm,$ \,$ list,$ \,$ minpoly,$ \,$ mod_ui,$ \,$ multiplicative_order,$ \,$ norm,$ \,$ nth_root,$ \,$ numer,$ \,$ numerator,$ \,$ period,$ \,$ round,$ \,$ sqrt,$ \,$ sqrt_approx,$ \,$ squarefree_part,$ \,$ str,$ \,$ trace,$ \,$ val_unit,$ \,$ valuation

additive_order( )

Return the additive order of self.

Output: integer or infinity

sage: QQ(0).additive_order()
1
sage: QQ(1).additive_order()
+Infinity

ceil( )

Return the ceiling of this rational number.

Output: Integer

If this rational number is an integer, this returns this number, otherwise it returns the floor of this number +1.

sage: n = 5/3; n.ceil()
2
sage: n = -17/19; n.ceil()
0
sage: n = -7/2; n.ceil()
-3
sage: n = 7/2; n.ceil()
4
sage: n = 10/2; n.ceil()
5

charpoly( )

Return the characteristic polynomial of this rational number. This will always be just var - self; this is really here so that code written for number fields won't crash when applied to rational numbers.

Input:

var
- a string
Output: Polynomial

sage: (1/3).charpoly('x')
 x - 1/3

Author: Craig Citro

copy( )

Return a copy of self.

Output: Rational

sage: a = -17/37
sage: a.copy() is a
False

Coercion does not make a new copy:

sage: QQ(a) is a
True

The constructor also makes a new copy:

sage: Rational(a) is a
False

denom( )

self.denom(): Return the denominator of this rational number.

sage: x = 5/13
sage: x.denom()
13
sage: x = -9/3
sage: x.denom()
1

denominator( )

self.denominator(): Return the denominator of this rational number.

sage: x = -5/11
sage: x.denominator()
11
sage: x = 9/3
sage: x.denominator()
1

factor( )

Return the factorization of this rational number.

Output: Factorization

sage: (-4/17).factor()
-1 * 2^2 * 17^-1

Trying to factor 0 gives an arithmetic error:

sage: (0/1).factor()
Traceback (most recent call last):
...
ArithmeticError: Prime factorization of 0 not defined.

floor( )

Return the floor of this rational number as an integer.

Output: Integer

sage: n = 5/3; n.floor()
1
sage: n = -17/19; n.floor()
-1
sage: n = -7/2; n.floor()
-4
sage: n = 7/2; n.floor()
3
sage: n = 10/2; n.floor()
5

gamma( )

Return the gamma function evaluated at self. This value is exact for integers and half-integers, otherwise a numerical approximation is returned.

sage: gamma(1/2)
sqrt(pi)
sage: gamma(7/2)
15*sqrt(pi)/8
sage: gamma(-3/2)
4*sqrt(pi)/3
sage: gamma(6/1)
120
sage: gamma(1/3)
2.67893853470775

This function accepts an optional precision argument:

sage: (1/3).gamma(prec=100)
2.6789385347077476336556929410
sage: (1/2).gamma(prec=100)
1.7724538509055160272981674833

gcd( )

Return the least common multiple of self and other.

One way to define this notion is the following:

Note that each rational positive rational number can be written as a product of primes with integer (positive or negative) powers in a unique way.

Then, the GCD of two rational numbers x,y can be defined by specifying that the exponent of every prime p in gcd(x,y) is the infimum of the exponents of p in x, and the exponent of p in y (The primes that does not appear in the decomposition of x or y are considered to have exponent zero).

This definition is consistent with the definition of the GCD in the rational integers. Our hopefully interesting notion of GCD for rational numbers is illustrated in the examples below.

sage: gcd(2/3,1/5)
1/15

This is consistent with the definition above, since:

$\displaystyle 2/3 = 2^1 * 3^{-1}*5^0
$

$\displaystyle 1/5 = 2^0 * 3^0 *5^{-1}
$

and hence,

$\displaystyle gcd(2/3,1/5)= 2^0*3^{-1}*5^{-1} = 1/15
$

sage: gcd(2/3,7/5)
1/15

In this example:

$\displaystyle 2/3 = 2^1*3^{-1}*5^0 * 7^0
$

$\displaystyle 7/5 = 2^0*3^0 *5^{-1} * 7^1
$

$\displaystyle gcd(2/3,7/5) = 2^0*3^{-1}*5^{-1}*7^0 = 1/15
$

sage: gcd(1/3,1/6)
1/6

In this example:

$\displaystyle 1/3 = 2^0*3^{-1}
$

$\displaystyle 1/6 = 2^{-1}*3^{-1}
$

$\displaystyle gcd(1/3,1/6)=2^{-1}*3^{-1}=1/6
$

sage: gcd(6/7,9/7)
3/7

In this example:

$\displaystyle 6/7 = 2^1*3^1*7^{-1}
$

$\displaystyle 9/7 = 2^0*3^2*7^{-1}
$

$\displaystyle gcd(6/7,9/7)=2^0*3^1*7^{-1}=3/7
$

height( )

The max absolute value of the numerator and denominator of self, as an Integer.

Output: Integer

sage: a = 2/3
sage: a.height()
3
sage: a = 34/3
sage: a.height()
34
sage: a = -97/4
sage: a.height()
97

Author: Naqi Jaffery (2006-03-05): examples

is_integral( )

Determine if a rational number is integral (i.e is in $ \mathbf{Z}$ ).

Output: bool

sage: QQ(1/2).is_integral()
False
sage: QQ(4/4).is_integral()
True

is_one( )

Determine if a rational number is one.

Output: bool

sage: QQ(1/2).is_one()
False
sage: QQ(4/4).is_one()
True

is_square( )

Return whether or not this rational number is a square.

Output: bool

sage: x = 9/4
sage: x.is_square()
True
sage: x = (7/53)^100
sage: x.is_square()
True
sage: x = 4/3
sage: x.is_square()
False
sage: x = -1/4
sage: x.is_square()
False

lcm( )

Return the least common multiple of self and other.

One way to define this notion is the following:

Note that each rational positive rational number can be written as a product of primes with integer (positive or negative) powers in a unique way.

Then, the LCM of two rational numbers x,y can be defined by specifying that the exponent of every prime p in lcm(x,y) is the supremum of the exponents of p in x, and the exponent of p in y (The primes that does not appear in the decomposition of x or y are considered to have exponent zero).

This definition is consistent with the definition of the LCM in the rational integers. Our hopefully interesting notion of LCM for rational numbers is illustrated in the examples below.

sage: lcm(2/3,1/5)
2

This is consistent with the definition above, since:

$\displaystyle 2/3 = 2^1 * 3^{-1}*5^0
$

$\displaystyle 1/5 = 2^0 * 3^0 *5^{-1}
$

and hence,

$\displaystyle lcm(2/3,1/5)= 2^1*3^0*5^0 = 2.
$

sage: lcm(2/3,7/5)
14

In this example:

$\displaystyle 2/3 = 2^1*3^{-1}*5^0 * 7^0
$

$\displaystyle 7/5 = 2^0*3^0 *5^{-1} * 7^1
$

$\displaystyle lcm(2/3,7/5) = 2^1*3^0*5^0*7^1 = 14
$

sage: lcm(1/3,1/5)
1

In this example:

$\displaystyle 1/3 = 3^{-1}*5^0
$

$\displaystyle 1/5 = 3^0 * 5^{-1}
$

$\displaystyle lcm(1/3,1/5)=3^0*5^0=1
$

sage: lcm(1/3,1/6)
1/3

In this example:

$\displaystyle 1/3 = 2^0*3^{-1}
$

$\displaystyle 1/6 = 2^{-1}*3^{-1}
$

$\displaystyle lcm(1/3,1/6)=2^0*3^{-1}=1/3
$

list( )

Return a list with the rational element in it, to be compatible with the method for number fields.

Output:

list
- the list [self]

sage: m = 5/3
sage: m.list()
[5/3]

minpoly( )

Return the minimal polynomial of this rational number. This will always be just x - self; this is really here so that code written for number fields won't crash when applied to rational numbers.

Input:

var
- a string
Output: Polynomial

sage: (1/3).minpoly('x')
 x - 1/3

Author: Craig Citro

mod_ui( )

Return the remainder upon division of self by the unsigned long integer n.

Input:

n
- an unsigned long integer
Output: integer

sage: (-4/17).mod_ui(3)
1
sage: (-4/17).mod_ui(17)
Traceback (most recent call last):
...
ArithmeticError: The inverse of 0 modulo 17 is not defined.

multiplicative_order( )

Return the multiplicative order of self.

Output: Integer of infinity

sage: QQ(1).multiplicative_order()
1
sage: QQ('1/-1').multiplicative_order()
2
sage: QQ(0).multiplicative_order()
+Infinity
sage: QQ('2/3').multiplicative_order()
+Infinity
sage: QQ('1/2').multiplicative_order()
+Infinity

norm( )

Returns the norm from Q to Q of x (which is just x). This was added for compatibility with NumberFields.

Output:

Rational
- reference to self

sage: (1/3).norm()
 1/3

Author: Craig Citro

nth_root( )

Computes the nth root of self, or raises a ValueError if self is not a perfect nth power.

Input:

n
- integer (must fit in C int type)

Author: David Harvey (2006-09-15)

sage: (25/4).nth_root(2)
5/2
sage: (125/8).nth_root(3)
5/2
sage: (-125/8).nth_root(3)
-5/2
sage: (25/4).nth_root(-2)
2/5

sage: (9/2).nth_root(2)
Traceback (most recent call last):
...
ValueError: not a perfect nth power

sage: (-25/4).nth_root(2)
Traceback (most recent call last):
...
ValueError: cannot take even root of negative number

numer( )

Return the numerator of this rational number.

sage: x = -5/11
sage: x.numer()
-5

numerator( )

Return the numerator of this rational number.

sage: x = 5/11
sage: x.numerator()
5

sage: x = 9/3
sage: x.numerator()
3

period( )

Return the period of the repeating part of the decimal expansion of this rational number.

ALGORITHM: When a rational number $ n/d$ with $ (n,d)==1$ is expanded, the period begins after $ s$ terms and has length $ t$ , where $ s$ and $ t$ are the smallest numbers satisfying $ 10^s=10^(s+t) (mod d)$ . When $ d$ is coprime to 10, this becomes a purely periodic decimal with $ 10^t=1 (mod d)$ . (Lehmer 1941 and Mathworld).

sage: (1/7).period()
6
sage: RR(1/7)
0.142857142857143
sage: (1/8).period()
1
sage: RR(1/8)
0.125000000000000
sage: RR(1/6)
0.166666666666667
sage: (1/6).period()
1
sage: x = 333/106
sage: x.period()
13
sage: RealField(200)(x)
3.1415094339622641509433962264150943396226415094339622641509

round( )

Returns the nearest integer to self.

Input:

self
- a rational number
mode
- a rounding mode for half integers: 'toward' (default) rounds toward zero 'away' rounds away from zero 'up' rounds up 'down' rounds down 'even' rounds toward the even integer 'odd' rounds toward the odd integer
Output: Integer

sage: n = 4/3; n.round()
1
sage: n = -17/4; n.round()
-4
sage: n = -5/2; n.round()
-2
sage: n.round("away")
-3
sage: n.round("up")
-2
sage: n.round("down")
-3
sage: n.round("even")
-2
sage: n.round("odd")
-3

sqrt( )

The square root function.

Input:

prec
- integer (default: None): if None, returns an exact square root; otherwise returns a numerical square root if necessary, to the given bits of precision.
extend
- bool (default: True); if True, return a square root in an extension ring, if necessary. Otherwise, raise a ValueError if the square is not in the base ring.
all
- bool (default: False); if True, return all square roots of self, instead of just one.

sage: x = 25/9
sage: x.sqrt()
5/3
sage: x = 64/4
sage: x.sqrt()
4
sage: x = 100/1
sage: x.sqrt()
10
sage: x.sqrt(all=True)
[10, -10]
sage: x = 81/5
sage: x.sqrt()
9/sqrt(5)
sage: x = -81/3
sage: x.sqrt()
3*sqrt(3)*I

sage: n = 2/3
sage: n.sqrt()
sqrt(2)/sqrt(3)
sage: n.sqrt(prec=10)
0.82
sage: n.sqrt(prec=100)
0.81649658092772603273242802490
sage: n.sqrt(prec=100)^2
0.66666666666666666666666666667
sage: n.sqrt(prec=53, all=True)
[0.816496580927726, -0.816496580927726]
sage: n.sqrt(extend=False, all=True)
Traceback (most recent call last):
...
ValueError: square root of 2/3 not a rational number
sage: sqrt(-2/3, all=True)
[sqrt(2)*I/sqrt(3), -sqrt(2)*I/sqrt(3)]
sage: sqrt(-2/3, prec=53)
0.816496580927726*I
sage: sqrt(-2/3, prec=53, all=True)
[0.816496580927726*I, -0.816496580927726*I]

Author: Naqi Jaffery (2006-03-05): some examples

sqrt_approx( )

Return numerical approximation with given number of bits of precision to this rational number. If all is given, return both approximations.

Input:

prec
- integer
all
- bool

sage: (5/3).sqrt_approx()
1.29099444873581
sage: (990829038092384908234098239048230984/4).sqrt_approx()
4.9770197862083713747374920870362581922510725585130996993055116540856385e17
sage: (5/3).sqrt_approx(prec=200)
1.2909944487358056283930884665941332036109739017638636088625
sage: (9/4).sqrt_approx()        
3/2

squarefree_part( )

Return the square free part of $ x$ , i.e., an integer z such that $ x = z y^2$ , for a perfect square $ y^2$ .

sage: a = 1/2
sage: a.squarefree_part()
2
sage: b = a/a.squarefree_part()
sage: b, b.is_square()
(1/4, True)
sage: a = 24/5
sage: a.squarefree_part()
30

str( )

Input:

base
- integer (default: 10); base must be between 2 and 36.

Output: string

sage: (-4/17).str()
'-4/17'
sage: (-4/17).str(2)
'-100/10001'

Note that the base must be at most 36.

sage: (-4/17).str(40)
Traceback (most recent call last):
...
ValueError: base (=40) must be between 2 and 36
sage: (-4/17).str(1)
Traceback (most recent call last):
...
ValueError: base (=1) must be between 2 and 36

trace( )

Returns the trace from Q to Q of x (which is just x). This was added for compatibility with NumberFields.

Output:

Rational
- reference to self

sage: (1/3).trace()
 1/3

Author: Craig Citro

val_unit( )

Returns a pair: the p-adic valuation of self, and the p-adic unit of self, as a Rational.

We do not require the p be prime, but it must be at least 2. For more documentation see Integer.val_unit

Input:

p
- a prime
Output:
int
- the p-adic valuation of this rational
Rational
- p-adic unit part of self

sage: (-4/17).val_unit(2)
(2, -1/17)
sage: (-4/17).val_unit(17)
(-1, -4)
sage: (0/1).val_unit(17)
(+Infinity, 1)

Author: David Roe (4/12/07)

valuation( )

Return the largest power of p that divides self.

Input:

p
- a prime number

sage: x = -5/9
sage: x.valuation(5)
1
sage: x.valuation(3)
-2
sage: x.valuation(2)
0

Some edge cases:

sage: (0/1).valuation(4)
+Infinity
sage: (7/16).valuation(4)
-2

Special Functions: __abs__,$ \,$ __eq__,$ \,$ __float__,$ \,$ __ge__,$ \,$ __getitem__,$ \,$ __gt__,$ \,$ __index__,$ \,$ __init__,$ \,$ __int__,$ \,$ __invert__,$ \,$ __le__,$ \,$ __long__,$ \,$ __lshift__,$ \,$ __lt__,$ \,$ __mod__,$ \,$ __ne__,$ \,$ __neg__,$ \,$ __pos__,$ \,$ __pow__,$ \,$ __reduce__,$ \,$ __repr__,$ \,$ __rlshift__,$ \,$ __rmod__,$ \,$ __rpow__,$ \,$ __rrshift__,$ \,$ __rshift__,$ \,$ __set_value,$ \,$ _gcd,$ \,$ _im_gens_,$ \,$ _integer_,$ \,$ _interface_init_,$ \,$ _latex_,$ \,$ _lcm,$ \,$ _mathml_,$ \,$ _pari_,$ \,$ _reduce_set

__abs__( )

Return the absolute value of this rational number.

Output: Rational

sage: (-4/17).__abs__()
4/17
sage: abs(-4/17)
4/17

__float__( )

Return floating point approximation to self as a Python float.

Output: float

sage: (-4/17).__float__()
-0.23529411764705882
sage: float(-4/17)
-0.23529411764705882

__getitem__( )

Return n-th element of self, viewed as a list. This is for consistency with how number field elements work.

Input:

n
- an integer (error if not 0 or -1)

Output: Rational

sage: (-4/17)[0]
-4/17
sage: (-4/17)[1]
Traceback (most recent call last):
...
IndexError: index n (=1) out of range; it must be 0        
sage: (-4/17)[-1]   # indexing from the right
-4/17

__index__( )

Needed so integers can be used as list indices.

sage: v = [1,2,3,4,5]
sage: v[3/1]
4
sage: v[3/2]
Traceback (most recent call last):
...
TypeError: rational is not an integer

__int__( )

Return coercion of self to Python int.

This takes the floor of self if self has a denominator (which is consistent with Python's long(floats)).

sage: int(7/3)
2
sage: int(-7/3)
-3

__invert__( )

Return the multiplicative inverse of this rational number.

Output: Rational

sage: (-4/17).__invert__()
-17/4
sage: ~(-4/17)
-17/4

__long__( )

Return coercion of self to Python long.

This takes the floor of self if self has a denominator (which is consistent with Python's long(floats)).

sage: long(7/3)
2L
sage: long(-7/3)
-3L

__lshift__( )

Left shift operator x « y.

Input:

x, y
- integer or rational
Output: Rational

sage: (2/3).__lshift__(4/1)
32/3
sage: (2/3).__lshift__(4/7)
Traceback (most recent call last):
...
ValueError: denominator must be 1
sage: (2).__lshift__(4/1)
32
sage: (2/3).__lshift__(4)
32/3
sage: (2/3) << (4/1)
32/3

__mod__( )

Return the remainder of division of self by other, where other is coerced to an integer

Input:

other
- object that coerces to an integer.
Output: integer

sage: (-4/17).__mod__(3/1)
1

__neg__( )

Return the negative of this rational number.

Output: Rational

sage: (-4/17).__neg__()
4/17
sage: - (-4/17)
4/17

__pos__( )

Return this rational number.

Output: Rational

sage: (-4/17).__pos__()
-4/17
sage: +(-4/17)
-4/17

__reduce__( )

Used in pickling rational numbers.

sage: a = 3/5
sage: a.__reduce__()
(<built-in function make_rational>, ('3/5',))

__repr__( )

Return string representation of this rational number.

sage: a = -17/37; a.__repr__()
'-17/37'

__rshift__( )

Right shift operator x « y.

Input:

x, y
- integer or rational
Output: Rational

sage: (2/3).__rshift__(4/1)
1/24
sage: (2/3).__rshift__(4/7)
Traceback (most recent call last):
...
ValueError: denominator must be 1
sage: (2).__rshift__(4/1)
0
sage: (2/1).__rshift__(4)
1/8
sage: (2/1) >>(4/1)
1/8

__set_value( )

Set the value of this rational number. This function handles numerous cases.

Input:

x
- object
base
- positive integer

sage: a = 3/5
sage: a.__set_value('-h/3ki', 32); a
-17/3730

_gcd( )

Returns the least common multiple, in the rational numbers, of self and other. This function returns either 0 or 1 (as a rational number).

Input:

other
- Rational
Output:
Rational
- 0 or 1

sage: (2/3)._gcd(3/5)
1
sage: (0/1)._gcd(0/1)
0

_im_gens_( )

Return the image of self under the homomorphism from the rational field to codomain. This always just returns self coerced into the codomain.

Input:

codomain
- object (usually a ring)
im_gens
- list of elements of codomain

sage: a = -17/37
sage: a._im_gens_(QQ, [1/1])
-17/37

_integer_( )

Return self coerced to an integer. Of course this rational number have a denominator of 1.

Output: Integer

sage: (-4/17)._integer_()
Traceback (most recent call last):
...
TypeError: no coercion of this rational to integer
sage: (-4/1)._integer_()
-4

_interface_init_( )

Return representation of this rational suitable for coercing into most any computer algebra system.

Output: string

sage: (2/3)._interface_init_()
'2/3'        
sage: kash(3/1).Type()              # optional
elt-fld^rat
sage: magma(3/1).Type()             # optional
FldRatElt

_latex_( )

Return Latex representation of this rational number.

sage: a = -17/37
sage: a._latex_()
'-\frac{17}{37}'

_lcm( )

Returns the least common multiple, in the rational numbers, of self and other. This function returns either 0 or 1 (as a rational number).

Input:

other
- Rational
Output:
Rational
- 0 or 1

sage: (2/3)._lcm(3/5)
1
sage: (0/1)._lcm(0/1)
0
sage: type((2/3)._lcm(3/5))
<type 'sage.rings.rational.Rational'>

_mathml_( )

Return mathml representation of this rational number.

sage: a = -17/37; a._mathml_()
'<mo>-</mo><mfrac><mrow><mn>17</mn></mrow><mrow><mn>37</mn></mrow></mfrac>'

_pari_( )

Return this rational coerced into the PARI C library.

Output: pari gen

sage: (-9/17)._pari_()
-9/17

_reduce_set( )

Used in setting a rational number when unpickling. Do not call this from external code since it violates immutability.

Input:

s
- string representation of rational in base 32

sage: a = -17/3730; _, (s,) = a.__reduce__(); s
'-h/3ki'
sage: b = 2/3; b._reduce_set('-h/3ki'); b
-17/3730

Class: Z_to_Q

class Z_to_Q

Special Functions: __init__,$ \,$ _repr_type

_repr_type( )

Return string that describes the type of morphism.

sage: sage.rings.rational.Z_to_Q()._repr_type()
'Natural'

See About this document... for information on suggesting changes.