source: sage/rings/rational_field.py @ 6140:2fb4b1da68ab

Revision 6140:2fb4b1da68ab, 11.7 KB checked in by William Stein <wstein@…>, 6 years ago (diff)

Working on improving basic structure of number fields.

Line 
1r"""
2Field $\Q$ of Rational Numbers.
3
4The class \class{RationalField} represents the field $\Q$ of
5(arbitrary precision) rational numbers.  Each rational number is an
6instance of the class \class{Rational}.
7
8TEST:
9   sage: Q = RationalField()
10   sage: Q == loads(dumps(Q))
11   True
12
13"""
14
15import random
16import field
17import ring
18import sage.rings.rational
19import sage.structure.factorization
20import infinity
21
22ZZ = None
23
24from sage.structure.parent_gens import ParentWithGens
25import sage.rings.number_field.number_field_base as number_field_base
26
27
28_obj = {}
29class _uniq(object):
30    def __new__(cls):
31        if _obj.has_key(0):
32            return _obj[0]
33        O = number_field_base.NumberField.__new__(cls)
34        _obj[0] = O
35        return O
36
37class RationalField(_uniq, number_field_base.NumberField):
38    r"""
39    The class \class{RationalField} represents the field $\Q$ of
40    rational numbers.
41    """
42    def __init__(self):
43        """
44        We create the rational numbers $\\Q$, and call a few functions:
45       
46            sage: Q = RationalField(); Q
47            Rational Field
48            sage: Q.characteristic()
49            0
50            sage: Q.is_field()
51            True
52            sage: Q.zeta()
53            -1
54
55        We next illustrate arithmetic in $\\Q$.
56       
57            sage: Q('49/7')
58            7
59            sage: type(Q('49/7'))
60            <type 'sage.rings.rational.Rational'>
61            sage: a = Q('19/374'); b = Q('17/371'); print a, b
62            19/374 17/371
63            sage: a + b
64            13407/138754
65            sage: b + a
66            13407/138754
67            sage: a * b
68            19/8162
69            sage: b * a
70            19/8162
71            sage: a - b
72            691/138754
73            sage: b - a
74            -691/138754
75            sage: a / b
76            7049/6358
77            sage: b / a
78            6358/7049
79            sage: b < a
80            True
81            sage: a < b
82            False
83
84        Next finally illustrate arithmetic with automatic coercion.
85        The types that coerce into the rational field include
86        \\code{str, int, long, Integer}.
87       
88            sage: a + Q('17/371')
89            13407/138754
90            sage: a * 374
91            19
92            sage: 374 * a
93            19
94            sage: a/19
95            1/374
96            sage: a + 1
97            393/374
98
99        TESTS:
100            sage: QQ.variable_name()
101            'x'
102            sage: QQ.variable_names()
103            ('x',)
104        """
105        ParentWithGens.__init__(self, self)
106        self._assign_names(('x',),normalize=False)
107
108    def __hash__(self):
109        return -11115808
110 
111    def _repr_(self):
112        return "Rational Field"
113   
114    def _latex_(self):
115        return "\\mathbf{Q}"
116
117    def __len__(self):
118        raise TypeError, 'len() of unsized object'
119
120    def __call__(self, x, base=0):
121        """
122        Coerce x into the field of rational numbers.
123
124        EXAMPLES:
125            sage: a = long(901824309821093821093812093810928309183091832091)
126            sage: b = QQ(a); b
127            901824309821093821093812093810928309183091832091
128            sage: QQ(b)
129            901824309821093821093812093810928309183091832091
130            sage: QQ(int(93820984323))
131            93820984323
132            sage: QQ(ZZ(901824309821093821093812093810928309183091832091))
133            901824309821093821093812093810928309183091832091
134            sage: QQ('-930482/9320842317')
135            -930482/9320842317
136            sage: QQ((-930482, 9320842317))
137            -930482/9320842317
138            sage: QQ([9320842317])
139            9320842317
140            sage: QQ(pari(39029384023840928309482842098430284398243982394))
141            39029384023840928309482842098430284398243982394
142            sage: QQ('sage')
143            Traceback (most recent call last):
144            ...
145            TypeError: unable to convert sage to a rational
146
147        Coercion from the reals to the rational is done by default
148        using continued fractions.
149       
150            sage: QQ(RR(3929329/32))
151            3929329/32
152            sage: QQ(-RR(3929329/32))
153            -3929329/32
154            sage: QQ(RR(1/7)) - 1/7
155            0
156
157        If you specify an optional second base argument, then
158        the string representation of the float is used.
159            sage: QQ(23.2, 2)
160            6530219459687219/281474976710656
161            sage: 6530219459687219.0/281474976710656
162            23.199999999999999
163            sage: a = 23.2; a
164            23.2000000000000
165            sage: QQ(a, 10)
166            116/5
167
168        Here's a nice example involving elliptic curves:
169            sage: E = EllipticCurve('11a')
170            sage: L = E.Lseries_at1(300)[0]; L
171            0.253841860855911
172            sage: O = E.omega(); O
173            1.269209304279553421688794616754547305219492241830608667967136921230408338613     # 32-bit
174            1.26920930427955342168879461675454730521949224183060866796713692123040833861277772269036230592151260731164529627832128743728170032847684397649271401057075        # 64-bit
175            sage: t = L/O; t
176            0.200000000000000
177            sage: QQ(RealField(45)(t))
178            1/5
179        """
180        if isinstance(x, sage.rings.rational.Rational):
181            return x
182        return sage.rings.rational.Rational(x, base)
183       
184    def construction(self):
185        from sage.categories.pushout import FractionField
186        import integer_ring
187        return FractionField(), integer_ring.ZZ
188       
189    def completion(self, p, prec, extras = {}):
190        if p == infinity.Infinity:
191            from sage.rings.real_mpfr import create_RealField
192            return create_RealField(prec, **extras)
193        else:
194            from sage.rings.padics.factory import Qp
195            return Qp(p, prec, **extras)
196
197    def _coerce_impl(self, x):
198        if isinstance(x, (int, long, sage.rings.integer.Integer,
199                          sage.rings.rational.Rational)):
200            return self(x)
201        raise TypeError, 'no implicit coercion of element to the rational numbers'
202       
203    def coerce_map_from_impl(self, S):
204        global ZZ
205        if ZZ is None:
206            import integer_ring
207            ZZ = integer_ring.ZZ
208        if S is ZZ:
209            return sage.rings.rational.Z_to_Q()
210        else:
211            return field.Field.coerce_map_from_impl(self, S)
212
213    def _is_valid_homomorphism_(self, codomain, im_gens):
214        try:
215            return im_gens[0] == codomain._coerce_(self.gen(0))
216        except TypeError:
217            return False
218
219    def __iter__(self):
220        r"""
221        Creates an iterator that generates the rational numbers without
222        repetition. It uses the sequence defined by $a_0=0$ and
223        $a_{n+1}=\frac{1}{2\lfloor a_n\rfloor+1-a_n}$ and generates the
224        sequence $$a_0,a_1,-a_1,a_2,-a_2,\ldots$$
225
226        EXAMPLES:
227
228        This example creates a list consisting of the first 10 terms
229        generated by this function.
230
231            sage: import itertools
232            sage: [a for a in itertools.islice(Rationals(),10)]
233            [0, 1, -1, 1/2, -1/2, 2, -2, 1/3, -1/3, 3/2]
234
235        NOTES:
236            A proof of the correctness of this formula is attributed to
237            Sam Vandervelde and Don Zagier [A002487], but a better
238            reference for the origin of this formula would be welcome.
239
240            REFERENCES:
241                 [A002487] Sloane's OLEIS,
242                 http://www.research.att.com/~njas/sequences/A002487
243
244        AUTHORS:
245            - Nils Bruin (2007-02-20)
246        """
247
248        from sage.rings.arith import integer_floor as floor
249
250        n=self(0)
251        yield n
252        while True:
253          n=1/(2*floor(n)+1-n)
254          yield n
255          yield -n
256
257    def complex_embedding(self, prec=53):
258        import complex_field
259        CC = complex_field.ComplexField(prec)
260        return self.hom([CC(1)])
261
262    def gens(self):
263        return (self(1), )
264
265    def gen(self, n=0):
266        if n == 0:
267            return self(1)
268        else:
269            raise IndexError, "n must be 0"
270
271    def degree(self):
272        return 1
273
274    def ngens(self):
275        return 1
276
277    def is_subring(self, K):
278        if K.is_field():
279            return K.characteristic() == 0
280        if K.characteristic() != 0:
281            return False
282        raise NotImplementedError
283
284    def is_field(self):
285        """
286        Return True, since the rational field is a field.
287        """
288        return True
289
290    def is_finite(self):
291        """
292        Return False, since the rational field is not finite.
293        """
294        return False
295
296    def is_prime_field(self):
297        return True
298       
299    def is_atomic_repr(self):
300        return True
301   
302    def characteristic(self):
303        """
304        Return 0, since the rational field has characteristic 0.
305
306        EXAMPLES:
307            sage: c = QQ.characteristic(); c
308            0
309            sage: parent(c)
310            Integer Ring
311        """
312        return sage.rings.integer.Integer(0)
313   
314    def number_field(self, poly_var='x', nf_var='a'):
315        from sage.rings.number_field.all import NumberField
316        x = sage.rings.polynomial.polynomial_ring.PolynomialRing(self, poly_var).gen()
317        return NumberField(x-1, nf_var)
318
319    def order(self):
320        """
321        EXAMPLES:
322            sage: QQ.order()
323            +Infinity
324        """
325        return infinity.infinity
326       
327    def _an_element_impl(self):
328        return sage.rings.rational.Rational((1,2))
329   
330    def random_element(self, num_bound=None, den_bound=None, distribution=None):
331        """
332        EXAMPLES:
333            sage: QQ.random_element(10,10)
334            -5/3
335        """
336        global ZZ
337        if ZZ is None:
338            import integer_ring
339            ZZ = integer_ring.ZZ
340        if num_bound == None:
341            return self((ZZ.random_element(distribution=distribution),
342                         ZZ.random_element(distribution=distribution)))
343        else:
344            if num_bound == 0:
345                num_bound = 2
346            if den_bound is None:
347                den_bound = num_bound
348                if den_bound < 1:
349                    den_bound = 2
350            return self((ZZ.random_element(-num_bound, num_bound+1, distribution=distribution),
351                         ZZ.random_element(1, den_bound+1, distribution=distribution)))
352    def zeta(self, n=2):
353        """
354        Return a root of unity in self.
355
356        INPUT:
357            n -- integer (default: 2) order of the root of unity
358
359        EXAMPLES:
360            sage: QQ.zeta()
361            -1
362            sage: QQ.zeta(2)
363            -1
364            sage: QQ.zeta(1)
365            1
366            sage: QQ.zeta(3)
367            Traceback (most recent call last):
368            ...
369            ValueError: no n-th root of unity in rational field       
370        """
371        if n == 1:
372            return sage.rings.rational.Rational(1)
373        elif n == 2:
374            return sage.rings.rational.Rational(-1)
375        else:
376            raise ValueError, "no n-th root of unity in rational field"
377
378    #################################
379    ## Coercions to interfaces
380    #################################
381    def _gap_init_(self):
382        """
383        EXAMPLES:
384            sage: gap(QQ)                     
385            Rationals
386        """
387        return 'Rationals'
388   
389    def _magma_init_(self):
390        """
391        EXAMPLES:
392            sage: magma(QQ)                       # optional
393            Rational Field
394        """
395        return 'RationalField()'
396
397
398QQ = RationalField()
399Q = QQ
400
401def is_RationalField(x):
402    return isinstance(x, RationalField)
403
404def frac(n,d):
405    return sage.rings.rational.Rational(n)/sage.rings.rational.Rational(d)
406
407def factor(x):
408    assert isinstance(x, sage.rings.rational.Rational)
409    return x.numerator().factor() * \
410           sage.structure.factorization.Factorization([(p,-e) for p, e in x.denominator().factor()])
Note: See TracBrowser for help on using the repository browser.