source: sage/rings/number_field/number_field_element.pyx @ 6367:ffe64ef3d32a

Revision 6367:ffe64ef3d32a, 48.4 KB checked in by Robert Bradshaw <robertwb@…>, 6 years ago (diff)

seperate class for relative/absolute number fields

Line 
1"""
2Number Field Elements
3
4AUTHORS:
5    -- William Stein version before it got cython'd
6    -- Joel B. Mohler (2007-03-09): First reimplementation into cython
7    -- William Stein (2007-09-04): add doctests
8"""
9
10# TODO -- relative extensions need to be completely rewritten, so one
11# can get easy access to representation of elements in their relative
12# form.  Functions like matrix below can't be done until relative
13# extensions are re-written this way.  Also there needs to be class
14# hierarchy for number field elements, integers, etc.  This is a
15# nontrivial project, and it needs somebody to attack it.  I'm amazed
16# how long this has gone unattacked.
17
18# Relative elements need to be a derived class or something.  This is
19# terrible as it is now.
20
21#*****************************************************************************
22#       Copyright (C) 2004, 2007 William Stein <wstein@gmail.com>
23#
24#  Distributed under the terms of the GNU General Public License (GPL)
25#
26#    This code is distributed in the hope that it will be useful,
27#    but WITHOUT ANY WARRANTY; without even the implied warranty of
28#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
29#    General Public License for more details.
30#
31#  The full text of the GPL is available at:
32#
33#                  http://www.gnu.org/licenses/
34#*****************************************************************************
35
36import operator
37
38include "../../ext/stdsage.pxi"
39include '../../ext/interrupt.pxi'
40
41import sage.rings.field_element
42import sage.rings.infinity
43import sage.rings.polynomial.polynomial_element
44import sage.rings.polynomial.polynomial_ring
45import sage.rings.rational_field
46import sage.rings.rational
47import sage.rings.integer_ring
48import sage.rings.integer
49import sage.rings.arith
50
51import sage.rings.number_field.number_field
52
53from sage.libs.ntl.ntl cimport ntl_ZZ, ntl_ZZX
54from sage.rings.integer_ring cimport IntegerRing_class
55
56from sage.libs.all import pari_gen
57from sage.libs.pari.gen import PariError
58
59QQ = sage.rings.rational_field.QQ
60ZZ = sage.rings.integer_ring.ZZ
61Integer_sage = sage.rings.integer.Integer
62
63def is_NumberFieldElement(x):
64    """
65    Return True if x is of type NumberFieldElement, i.e., an
66    element of a number field.
67
68    EXAMPLES:
69        sage: is_NumberFieldElement(2)
70        False
71        sage: k.<a> = NumberField(x^7 + 17*x + 1)
72        sage: is_NumberFieldElement(a+1)
73        True
74    """
75    return PY_TYPE_CHECK(x, NumberFieldElement)
76
77def __create__NumberFieldElement_version0(parent, poly):
78    """
79    Used in unpickling elements of number fields.
80
81    EXAMPLES:
82    Since this is just used in unpickling, we unpickle.
83   
84        sage: k.<a> = NumberField(x^3 - 2)
85        sage: loads(dumps(a+1)) == a + 1
86        True       
87    """
88    return NumberFieldElement(parent, poly)
89
90cdef class NumberFieldElement(FieldElement):
91    """
92    An element of a number field.
93
94    EXAMPLES:
95        sage: k.<a> = NumberField(x^3 + x + 1)
96        sage: a^3
97        -a - 1       
98    """
99    cdef NumberFieldElement _new(self):
100        """
101        Quickly creates a new initialized NumberFieldElement with the
102        same parent as self.
103        """
104        cdef NumberFieldElement x
105        x = PY_NEW(NumberFieldElement)
106        x._parent = self._parent
107        return x
108
109    def __init__(self, parent, f):
110        """
111        INPUT:
112            parent -- a number field
113            f -- defines an element of a number field.
114
115        EXAMPLES:
116        The following examples illustrate creation of elements of
117        number fields, and some basic arithmetic.
118
119        First we define a polynomial over Q.
120            sage: R.<x> = PolynomialRing(QQ)
121            sage: f = x^2 + 1
122
123        Next we use f to define the number field.
124            sage: K.<a> = NumberField(f); K
125            Number Field in a with defining polynomial x^2 + 1
126            sage: a = K.gen()
127            sage: a^2
128            -1
129            sage: (a+1)^2
130            2*a
131            sage: a^2
132            -1
133            sage: z = K(5); 1/z
134            1/5
135
136        We create a cube root of 2.
137            sage: K.<b> = NumberField(x^3 - 2)
138            sage: b = K.gen()
139            sage: b^3
140            2
141            sage: (b^2 + b + 1)^3
142            12*b^2 + 15*b + 19
143
144        This example illustrates save and load:
145            sage: K.<a> = NumberField(x^17 - 2)
146            sage: s = a^15 - 19*a + 3
147            sage: loads(s.dumps()) == s
148            True
149        """
150        sage.rings.field_element.FieldElement.__init__(self, parent)
151
152        cdef ZZ_c coeff
153        if isinstance(f, (int, long, Integer_sage)):
154            # set it up and exit immediately
155            # fast pathway
156            (<Integer>ZZ(f))._to_ZZ(&coeff)
157            SetCoeff( self.__numerator, 0, coeff )
158            conv_ZZ_int( self.__denominator, 1 )
159            return
160           
161        elif isinstance(f, NumberFieldElement):
162            self.__numerator = (<NumberFieldElement>f).__numerator
163            self.__denominator = (<NumberFieldElement>f).__denominator
164            return
165
166        ppr = parent.polynomial_ring()
167        if isinstance(parent, sage.rings.number_field.number_field.NumberField_extension):
168            ppr = parent.base_field().polynomial_ring()
169
170        if isinstance(f, pari_gen):
171            f = f.lift()
172            f = ppr(f)
173        if not isinstance(f, sage.rings.polynomial.polynomial_element.Polynomial):
174            f = ppr(f)
175        if f.degree() >= parent.degree():
176            if isinstance(parent, sage.rings.number_field.number_field.NumberField_extension):
177                f %= parent.absolute_polynomial()
178            else:
179                f %= parent.polynomial()
180
181        # Set Denominator
182        den = f.denominator()
183        (<Integer>ZZ(den))._to_ZZ(&self.__denominator)
184
185        cdef long i
186        num = f * den
187        for i from 0 <= i <= num.degree():
188            (<Integer>ZZ(num[i]))._to_ZZ(&coeff)
189            SetCoeff( self.__numerator, i, coeff )
190
191    def __alloc__(self):
192        ZZX_construct(&self.__numerator)
193        ZZ_construct(&self.__denominator)
194
195    def __dealloc__(self):
196        ZZX_destruct(&self.__numerator)
197        ZZ_destruct(&self.__denominator)
198
199    def _lift_cyclotomic_element(self, new_parent):
200        """
201        Creates an element of the passed field from this field.  This
202        is specific to creating elements in a cyclotomic field from
203        elements in another cyclotomic field.  This function aims to
204        make this common coercion extremely fast!
205
206        EXAMPLES:
207            sage: C.<zeta5>=CyclotomicField(5)
208            sage: CyclotomicField(10)(zeta5+1)  # The function _lift_cyclotomic_element does the heavy lifting in the background
209            zeta10^2 + 1
210            sage: (zeta5+1)._lift_cyclotomic_element(CyclotomicField(10))  # There is rarely a purpose to call this function directly
211            zeta10^2 + 1
212
213        AUTHOR:
214            Joel B. Mohler
215        """
216        # Right now, I'm a little confused why quadratic extension fields have a zeta_order function
217        # I would rather they not have this function since I don't want to do this isinstance check here.
218        if not isinstance(self.parent(), sage.rings.number_field.number_field.NumberField_cyclotomic) or not isinstance(new_parent, sage.rings.number_field.number_field.NumberField_cyclotomic):
219            raise TypeError, "The field and the new parent field must both be cyclotomic fields."
220
221        try:
222            small_order = self.parent().zeta_order()
223            large_order = new_parent.zeta_order()
224        except AttributeError:
225            raise TypeError, "The field and the new parent field must both be cyclotomic fields."
226
227        try:
228            _rel = ZZ(large_order / small_order)
229        except TypeError:
230            raise TypeError, "The zeta_order of the new field must be a multiple of the zeta_order of the original."
231
232        cdef NumberFieldElement x
233        x = PY_NEW(NumberFieldElement)
234        x._parent = <ParentWithBase>new_parent
235        x.__denominator = self.__denominator
236        cdef ZZX_c result
237        cdef ZZ_c tmp
238        cdef int i
239        cdef int rel = _rel
240        cdef ntl_ZZX _num
241        cdef ntl_ZZ _den
242        _num, _den = new_parent.polynomial_ntl()
243        for i from 0 <= i <= deg(self.__numerator):
244            GetCoeff(tmp, self.__numerator, i)
245            SetCoeff(result, i*rel, tmp)
246        rem_ZZX(x.__numerator, result, _num.x[0])
247        return x
248
249    def __reduce__(self):
250        """
251        Used in pickling number field elements.
252
253        EXAMPLES:
254            sage: k.<a> = NumberField(x^3 - 17*x^2 + 1)
255            sage: t = a.__reduce__(); t
256            (<built-in function __create__NumberFieldElement_version0>, (Number Field in a with defining polynomial x^3 - 17*x^2 + 1, x))
257            sage: t[0](*t[1]) == a
258            True       
259        """
260        return __create__NumberFieldElement_version0, \
261               (self.parent(), self.polynomial())
262
263    def __repr__(self):
264        """
265        String representation of this number field element,
266        which is just a polynomial in the generator.
267
268        EXAMPLES:
269            sage: k.<a> = NumberField(x^2 + 2)
270            sage: b = (2/3)*a + 3/5
271            sage: b.__repr__()
272            '2/3*a + 3/5'       
273        """
274        x = self.polynomial()
275        return str(x).replace(x.parent().variable_name(),self.parent().variable_name())
276
277    def _im_gens_(self, codomain, im_gens):
278        """
279        This is used in computing homomorphisms between number fields.
280
281        EXAMPLES:
282            sage: k.<a> = NumberField(x^2 - 2)
283            sage: m.<b> = NumberField(x^4 - 2)
284            sage: phi = k.hom([b^2])
285            sage: phi(a+1)
286            b^2 + 1
287            sage: (a+1)._im_gens_(m, [b^2])
288            b^2 + 1       
289        """
290        # NOTE -- if you ever want to change this so relative number fields are
291        # in terms of a root of a poly.
292        # The issue is that elements of a relative number field are represented in terms
293        # of a generator for the absolute field.  However the morphism gives the image
294        # of gen, which need not be a generator for the absolute field.  The morphism
295        # has to be *over* the relative element.
296        return codomain(self.polynomial()(im_gens[0]))
297
298    def _latex_(self):
299        """
300        Returns the latex representation for this element.
301
302        EXAMPLES:
303            sage: C,zeta12=CyclotomicField(12).objgen()
304            sage: latex(zeta12^4-zeta12)
305            \zeta_{12}^{2} - \zeta_{12} - 1
306        """
307        return self.polynomial()._latex_(name=self.parent().latex_variable_name())
308
309    def _pari_(self, var='x'):
310        """
311        Return PARI C-library object corresponding to self.
312
313        EXAMPLES:
314            sage: k.<j> = QuadraticField(-1)
315            sage: j._pari_('j')
316            Mod(j, j^2 + 1)
317            sage: pari(j)
318            Mod(x, x^2 + 1)
319
320            sage: y = QQ['y'].gen()
321            sage: k.<j> = NumberField(y^3 - 2)
322            sage: pari(j)
323            Mod(x, x^3 - 2)
324
325        By default the variable name is 'x', since in PARI many variable
326        names are reserved:
327            sage: theta = polygen(QQ, 'theta')
328            sage: M.<theta> = NumberField(theta^2 + 1)
329            sage: pari(theta)
330            Mod(x, x^2 + 1)
331
332        If you try do coerce a generator called I to PARI, hell may
333        break loose:
334            sage: k.<I> = QuadraticField(-1)
335            sage: I._pari_('I')
336            Traceback (most recent call last):
337            ...
338            PariError: forbidden (45)
339
340        Instead, request the variable be named different for the coercion:
341            sage: pari(I)
342            Mod(x, x^2 + 1)
343            sage: I._pari_('i')
344            Mod(i, i^2 + 1)
345            sage: I._pari_('II')
346            Mod(II, II^2 + 1)
347        """
348        try:
349            return self.__pari[var]
350        except KeyError:
351            pass
352        except TypeError:
353            self.__pari = {}
354        if var is None:
355            var = self.parent().variable_name()
356        if isinstance(self.parent(),
357                      sage.rings.number_field.number_field.NumberField_extension):
358            f = self.polynomial()._pari_()
359            g = str(self.parent().pari_polynomial())
360            base = self.parent().base_ring()
361            gsub = base.gen()._pari_()
362            gsub = str(gsub).replace('x', "y")
363            g = g.replace("y", gsub)
364        else:
365            f = self.polynomial()._pari_()
366            gp = self.parent().polynomial()
367            if gp.name() != 'x':
368                gp = gp.change_variable_name('x')
369            g = gp._pari_()
370            gv = str(gp.parent().gen())
371            if var != 'x':
372                f = f.subst("x",var)
373            if var != gv:
374                g = g.subst(gv, var)
375        h = f.Mod(g)
376        self.__pari[var] = h
377        return h
378
379    def _pari_init_(self, var='x'):
380        """
381        Return GP/PARI string representation of self. This is used for
382        converting this number field element to GP/PARI.  The returned
383        string defines a pari Mod in the variable is var, which is by
384        default 'x' -- not the name of the generator of the number
385        field.
386
387        INPUT:
388            var -- (default: 'x') the variable of the pari Mod.
389
390        EXAMPLES:
391            sage: K.<a> = NumberField(x^5 - x - 1)
392            sage: ((1 + 1/3*a)^4)._pari_init_()
393            'Mod(1/81*x^4 + 4/27*x^3 + 2/3*x^2 + 4/3*x + 1, x^5 - x - 1)'
394            sage: ((1 + 1/3*a)^4)._pari_init_('a')
395            'Mod(1/81*a^4 + 4/27*a^3 + 2/3*a^2 + 4/3*a + 1, a^5 - a - 1)'
396
397        Note that _pari_init_ can fail because of reserved words in PARI,
398        and since it actually works by obtaining the PARI representation
399        of something.
400            sage: K.<theta> = NumberField(x^5 - x - 1)
401            sage: b = (1/2 - 2/3*theta)^3; b
402            -8/27*theta^3 + 2/3*theta^2 - 1/2*theta + 1/8
403            sage: b._pari_init_('theta')
404            Traceback (most recent call last):
405            ...
406            PariError: unexpected character (2)
407
408        Fortunately pari_init returns everything in terms of x by default.
409            sage: pari(b)
410            Mod(-8/27*x^3 + 2/3*x^2 - 1/2*x + 1/8, x^5 - x - 1)
411        """
412        return repr(self._pari_(var=var))
413##         if var == None:
414##             var = self.parent().variable_name()
415##         if isinstance(self.parent(), sage.rings.number_field.number_field.NumberField_extension):
416##             f = self.polynomial()._pari_()
417##             g = str(self.parent().pari_relative_polynomial())
418##             base = self.parent().base_ring()
419##             gsub = base.gen()._pari_()
420##             gsub = str(gsub).replace(base.variable_name(), "y")
421##             g = g.replace("y", gsub)
422##         else:
423##             f = str(self.polynomial()).replace("x",var)
424##             g = str(self.parent().polynomial()).replace("x",var)
425##         return 'Mod(%s, %s)'%(f,g)
426
427    def __getitem__(self, n):
428        """
429        Return the n-th coefficient of this number field element, written
430        as a polynomial in the generator.
431
432        Note that $n$ must be between 0 and $d-1$, where $d$ is the
433        degree of the number field.
434
435        EXAMPLES:
436            sage: m.<b> = NumberField(x^4 - 1789)
437            sage: c = (2/3-4/5*b)^3; c
438            -64/125*b^3 + 32/25*b^2 - 16/15*b + 8/27
439            sage: c[0]
440            8/27
441            sage: c[2]
442            32/25
443            sage: c[3]
444            -64/125
445
446        We illustrate bounds checking:
447            sage: c[-1]
448            Traceback (most recent call last):
449            ...
450            IndexError: index must be between 0 and degree minus 1.
451            sage: c[4]
452            Traceback (most recent call last):
453            ...
454            IndexError: index must be between 0 and degree minus 1.
455
456        The list method implicitly calls __getitem__:
457            sage: list(c)
458            [8/27, -16/15, 32/25, -64/125]
459            sage: m(list(c)) == c
460            True           
461        """
462        if n < 0 or n >= self.parent().degree():     # make this faster.
463            raise IndexError, "index must be between 0 and degree minus 1."
464        return self.polynomial()[n]
465
466    cdef int _cmp_c_impl(left, sage.structure.element.Element right) except -2:
467        cdef NumberFieldElement _right = right
468        return not (ZZX_equal(&left.__numerator, &_right.__numerator) and ZZ_equal(&left.__denominator, &_right.__denominator))
469
470    def __abs__(self):
471        r"""
472        Return the numerical absolute value of this number field
473        element with respect to the first archimedean embedding, to 53
474        bits of precision.
475
476        This is the \code{abs( )} Python function.  If you want a different
477        embedding or precision, use \code{self.abs(...)}.
478
479        EXAMPLES:
480            sage: k.<a> = NumberField(x^3 - 2)
481            sage: abs(a)
482            1.25992104989487
483            sage: abs(a)^3
484            2.00000000000000
485            sage: a.abs(prec=128)
486            1.2599210498948731647672106072782283506       
487        """
488        return self.abs(prec=53, i=0)
489
490    def abs(self, prec=53, i=0):
491        """
492        Return the absolute value of this element with respect to the
493        ith complex embedding of parent, to the given precision.
494
495        INPUT:
496            prec -- (default: 53) integer bits of precision
497            i -- (default: ) integer, which embedding to use
498
499        EXAMPLES:
500            sage: z = CyclotomicField(7).gen()
501            sage: abs(z)
502            1.00000000000000
503            sage: abs(z^2 + 17*z - 3)
504            16.0604426799931
505            sage: K.<a> = NumberField(x^3+17)
506            sage: abs(a)
507            2.57128159065824
508            sage: a.abs(prec=100)
509            2.5712815906582353554531872087
510            sage: a.abs(prec=100,i=1)
511            2.5712815906582353554531872087
512            sage: a.abs(100, 2)
513            2.5712815906582353554531872087
514
515        Here's one where the absolute value depends on the embedding.
516            sage: K.<b> = NumberField(x^2-2)
517            sage: a = 1 + b
518            sage: a.abs(i=0)
519            2.41421356237309
520            sage: a.abs(i=1)
521            0.414213562373095
522        """
523        P = self.parent().complex_embeddings(prec)[i]
524        return abs(P(self))
525
526    def complex_embeddings(self, prec=53):
527        """
528        Return the images of this element in the floating point
529        complex numbers, to the given bits of precision.
530
531        INPUT:
532            prec -- integer (default: 53) bits of precision
533
534        EXAMPLES:
535            sage: k.<a> = NumberField(x^3 - 2)
536            sage: a.complex_embeddings()
537            [1.25992104989487, -0.629960524947437 + 1.09112363597172*I, -0.629960524947437 - 1.09112363597172*I]
538            sage: a.complex_embeddings(10)
539            [1.3, -0.63 + 1.1*I, -0.63 - 1.1*I]
540            sage: a.complex_embeddings(100)
541            [1.2599210498948731647672106073, -0.62996052494743658238360530364 + 1.0911236359717214035600726142*I, -0.62996052494743658238360530364 - 1.0911236359717214035600726142*I]
542        """
543        phi = self.parent().complex_embeddings(prec)
544        return [f(self) for f in phi]
545
546    def complex_embedding(self, prec=53, i=0):
547        """
548        Return the i-th embedding of self in the complex numbers, to
549        the given precision.
550
551        EXAMPLES:
552            sage: k.<a> = NumberField(x^3 - 2)
553            sage: a.complex_embedding()
554            1.25992104989487
555            sage: a.complex_embedding(10)
556            1.3
557            sage: a.complex_embedding(100)
558            1.2599210498948731647672106073
559            sage: a.complex_embedding(20, 1)
560            -0.62996 + 1.0911*I
561            sage: a.complex_embedding(20, 2)
562            -0.62996 - 1.0911*I
563        """
564        return self.parent().complex_embeddings(prec)[i](self)
565
566    def is_square(self, root=False):
567        """
568        Return True if self is a square in its parent number field and
569        otherwise return False.
570
571        INPUT:
572            root -- if True, also return a square root (or None if self
573                    is not a perfect square)
574
575        EXAMPLES:
576            sage: m.<b> = NumberField(x^4 - 1789)
577            sage: b.is_square()
578            False
579            sage: c = (2/3*b + 5)^2; c
580            4/9*b^2 + 20/3*b + 25
581            sage: c.is_square()
582            True
583            sage: c.is_square(True)
584            (True, 2/3*b + 5)
585
586        We also test the functional notation.
587            sage: is_square(c, True)
588            (True, 2/3*b + 5)
589            sage: is_square(c)
590            True
591            sage: is_square(c+1)
592            False
593        """
594        v = self.sqrt(all=True)
595        t = len(v) > 0
596        if root:
597            if t:
598                return t, v[0]
599            else:
600                return False, None
601        else:
602            return t
603       
604    def sqrt(self, all=False):
605        """
606        Returns the square root of this number in the given number field.
607       
608        EXAMPLES:
609            sage: K.<a> = NumberField(x^2 - 3)
610            sage: K(3).sqrt()
611            a
612            sage: K(3).sqrt(all=True)
613            [a, -a]
614            sage: K(a^10).sqrt()
615            9*a
616            sage: K(49).sqrt()
617            7
618            sage: K(1+a).sqrt()
619            Traceback (most recent call last):
620            ...
621            ValueError: a + 1 not a square in Number Field in a with defining polynomial x^2 - 3
622            sage: K(0).sqrt()
623            0
624            sage: K((7+a)^2).sqrt(all=True)
625            [a + 7, -a - 7]
626           
627            sage: K.<a> = CyclotomicField(7)
628            sage: a.sqrt() 
629            a^4
630           
631            sage: K.<a> = NumberField(x^5 - x + 1)
632            sage: (a^4 + a^2 - 3*a + 2).sqrt()
633            a^3 - a^2
634
635        ALGORITHM:
636            Use Pari to factor $x^2$ - \code{self} in K.
637           
638        """
639        # For now, use pari's factoring abilities
640        R = sage.rings.polynomial.polynomial_ring.PolynomialRing(self._parent, 't')
641        f = R([-self, 0, 1])
642        roots = f.roots()
643        if all:
644            return [r[0] for r in roots]
645        elif len(roots) > 0:
646            return roots[0][0]
647        else:
648            raise ValueError, "%s not a square in %s"%(self, self._parent)
649
650    cdef void _reduce_c_(self):
651        """
652        Pull out common factors from the numerator and denominator!
653        """
654        cdef ZZ_c gcd
655        cdef ZZ_c t1
656        cdef ZZX_c t2
657        content(t1, self.__numerator)
658        GCD_ZZ(gcd, t1, self.__denominator)
659        if sign(gcd) != sign(self.__denominator):
660            negate(t1, gcd)
661            gcd = t1
662        div_ZZX_ZZ(t2, self.__numerator, gcd)
663        div_ZZ_ZZ(t1, self.__denominator, gcd)
664        self.__numerator = t2
665        self.__denominator = t1
666
667    cdef ModuleElement _add_c_impl(self, ModuleElement right):
668        cdef NumberFieldElement x
669        cdef NumberFieldElement _right = right
670        x = self._new()
671        mul_ZZ(x.__denominator, self.__denominator, _right.__denominator)
672        cdef ZZX_c t1, t2
673        mul_ZZX_ZZ(t1, self.__numerator, _right.__denominator)
674        mul_ZZX_ZZ(t2, _right.__numerator, self.__denominator)
675        add_ZZX(x.__numerator, t1, t2)
676        x._reduce_c_()
677        return x
678
679    cdef ModuleElement _sub_c_impl(self, ModuleElement right):
680        cdef NumberFieldElement x
681        cdef NumberFieldElement _right = right
682        x = self._new()
683        mul_ZZ(x.__denominator, self.__denominator, _right.__denominator)
684        cdef ZZX_c t1, t2
685        mul_ZZX_ZZ(t1, self.__numerator, _right.__denominator)
686        mul_ZZX_ZZ(t2, _right.__numerator, self.__denominator)
687        sub_ZZX(x.__numerator, t1, t2)
688        x._reduce_c_()
689        return x
690
691    cdef RingElement _mul_c_impl(self, RingElement right):
692        """
693        Returns the product of self and other as elements of a number field.
694
695        EXAMPLES:
696            sage: C.<zeta12>=CyclotomicField(12)
697            sage: zeta12*zeta12^11
698            1
699            sage: G.<a> = NumberField(x^3 + 2/3*x + 1)
700            sage: a^3
701            -2/3*a - 1
702            sage: a^3+a
703            1/3*a - 1
704        """
705        cdef NumberFieldElement x
706        cdef NumberFieldElement _right = right
707        cdef ZZX_c temp
708        cdef ZZ_c temp1
709        cdef ZZ_c parent_den
710        cdef ZZX_c parent_num
711        self._parent_poly_c_( &parent_num, &parent_den )
712        x = self._new()
713        _sig_on
714        # MulMod doesn't handle non-monic polynomials.
715        # Therefore, we handle the non-monic case entirely separately.
716        if ZZX_is_monic( &parent_num ):
717            mul_ZZ(x.__denominator, self.__denominator, _right.__denominator)
718            MulMod_ZZX(x.__numerator, self.__numerator, _right.__numerator, parent_num)
719        else:
720            mul_ZZ(x.__denominator, self.__denominator, _right.__denominator)
721            mul_ZZX(x.__numerator, self.__numerator, _right.__numerator)
722            if ZZX_degree(&x.__numerator) >= ZZX_degree(&parent_num):
723                mul_ZZX_ZZ( x.__numerator, x.__numerator, parent_den )
724                mul_ZZX_ZZ( temp, parent_num, x.__denominator )
725                power_ZZ(temp1,LeadCoeff_ZZX(temp),ZZX_degree(&x.__numerator)-ZZX_degree(&parent_num)+1)
726                PseudoRem_ZZX(x.__numerator, x.__numerator, temp)
727                mul_ZZ(x.__denominator, x.__denominator, parent_den)
728                mul_ZZ(x.__denominator, x.__denominator, temp1)
729        _sig_off
730        x._reduce_c_()
731        return x
732
733        #NOTES: In LiDIA, they build a multiplication table for the
734        #number field, so it's not necessary to reduce modulo the
735        #defining polynomial every time:
736        #     src/number_fields/algebraic_num/order.cc: compute_table
737        # but asymptotically fast poly multiplication means it's
738        # actually faster to *not* build a table!?!
739
740    cdef RingElement _div_c_impl(self, RingElement right):
741        """
742        Returns the quotient of self and other as elements of a number field.
743
744        EXAMPLES:
745            sage: C.<I>=CyclotomicField(4)
746            sage: 1/I
747            -I
748            sage: I/0
749            Traceback (most recent call last):
750            ...
751            ZeroDivisionError: Number field element division by zero
752           
753            sage: G.<a> = NumberField(x^3 + 2/3*x + 1)
754            sage: a/a
755            1
756            sage: 1/a
757            -a^2 - 2/3
758            sage: a/0
759            Traceback (most recent call last):
760            ...
761            ZeroDivisionError: Number field element division by zero
762        """
763        cdef NumberFieldElement x
764        cdef NumberFieldElement _right = right
765        cdef ZZX_c inv_num
766        cdef ZZ_c inv_den
767        cdef ZZ_c parent_den
768        cdef ZZX_c parent_num
769        cdef ZZX_c temp
770        cdef ZZ_c temp1
771        if not _right:
772            raise ZeroDivisionError, "Number field element division by zero"
773        self._parent_poly_c_( &parent_num, &parent_den )
774        x = self._new()
775        _sig_on
776        _right._invert_c_(&inv_num, &inv_den)
777        if ZZX_is_monic( &parent_num ):
778            mul_ZZ(x.__denominator, self.__denominator, inv_den)
779            MulMod_ZZX(x.__numerator, self.__numerator, inv_num, parent_num)
780        else:
781            mul_ZZ(x.__denominator, self.__denominator, inv_den)
782            mul_ZZX(x.__numerator, self.__numerator, inv_num)
783            if ZZX_degree(&x.__numerator) >= ZZX_degree(&parent_num):
784                mul_ZZX_ZZ( x.__numerator, x.__numerator, parent_den )
785                mul_ZZX_ZZ( temp, parent_num, x.__denominator )
786                power_ZZ(temp1,LeadCoeff_ZZX(temp),ZZX_degree(&x.__numerator)-ZZX_degree(&parent_num)+1)
787                PseudoRem_ZZX(x.__numerator, x.__numerator, temp)
788                mul_ZZ(x.__denominator, x.__denominator, parent_den)
789                mul_ZZ(x.__denominator, x.__denominator, temp1)
790        x._reduce_c_()
791        _sig_off
792        return x
793
794    def __floordiv__(self, other):
795        """
796        Return the quotient of self and other.  Since these are field
797        elements the floor division is exactly the same as usual
798        division.
799
800        EXAMPLES:
801            sage: m.<b> = NumberField(x^4 + x^2 + 2/3)
802            sage: c = (1+b) // (1-b); c
803            3/4*b^3 + 3/4*b^2 + 3/2*b + 1/2
804            sage: (1+b) / (1-b) == c
805            True
806            sage: c * (1-b)
807            b + 1       
808        """
809        return self / other
810
811    def __nonzero__(self):
812        """
813        Return True if this number field element is nonzero.
814
815        EXAMPLES:
816            sage: m.<b> = CyclotomicField(17)
817            sage: m(0).__nonzero__()
818            False
819            sage: b.__nonzero__()
820            True
821
822        Nonzero is used by the bool command:
823            sage: bool(b + 1)
824            True
825            sage: bool(m(0))
826            False
827        """
828        return not IsZero_ZZX(self.__numerator)
829
830    cdef ModuleElement _neg_c_impl(self):
831        cdef NumberFieldElement x
832        x = self._new()
833        mul_ZZX_long(x.__numerator, self.__numerator, -1)
834        x.__denominator = self.__denominator
835        return x
836
837    def __int__(self):
838        """
839        Attempt to convert this number field element to a Python integer,
840        if possible.
841       
842        EXAMPLES:
843            sage: C.<I>=CyclotomicField(4)
844            sage: int(1/I)
845            Traceback (most recent call last):
846            ...
847            TypeError: cannot coerce nonconstant polynomial to int
848            sage: int(I*I)
849            -1
850
851            sage: K.<a> = NumberField(x^10 - x - 1)
852            sage: int(a)
853            Traceback (most recent call last):
854            ...
855            TypeError: cannot coerce nonconstant polynomial to int
856            sage: int(K(9390283))
857            9390283
858
859        The semantics are like in Python, so the value does not have
860        to preserved.
861            sage: int(K(393/29))
862            13           
863        """
864        return int(self.polynomial())
865
866    def __long__(self):
867        """
868        Attempt to convert this number field element to a Python long,
869        if possible.
870       
871        EXAMPLES:
872            sage: K.<a> = NumberField(x^10 - x - 1)
873            sage: long(a)
874            Traceback (most recent call last):
875            ...
876            TypeError: cannot coerce nonconstant polynomial to long
877            sage: long(K(1234))
878            1234L
879
880        The value does not have to be preserved, in the case of fractions.
881            sage: long(K(393/29))
882            13L       
883        """
884        return long(self.polynomial())
885
886    cdef void _parent_poly_c_(self, ZZX_c *num, ZZ_c *den):
887        cdef long i
888        cdef ZZ_c coeff
889        cdef ntl_ZZX _num
890        cdef ntl_ZZ _den
891        if isinstance(self.parent(), sage.rings.number_field.number_field.NumberField_extension):
892            # ugly temp code
893            f = self.parent().absolute_polynomial()
894
895            __den = f.denominator()
896            (<Integer>ZZ(__den))._to_ZZ(den)
897
898            __num = f * __den
899            for i from 0 <= i <= __num.degree():
900                (<Integer>ZZ(__num[i]))._to_ZZ(&coeff)
901                SetCoeff( num[0], i, coeff )
902        else:
903            _num, _den = self.parent().polynomial_ntl()
904            num[0] = _num.x[0]
905            den[0] = _den.x[0]
906
907    cdef void _invert_c_(self, ZZX_c *num, ZZ_c *den):
908        """
909        Computes the numerator and denominator of the multiplicative inverse of this element.
910
911        Suppose that this element is x/d and the parent mod'ding polynomial is M/D.  The NTL function
912        XGCD( r, s, t, a, b ) computes r,s,t such that $r=s*a+t*b$.  We compute
913        XGCD( r, s, t, x*D, M*d ) and set
914        num=s*D*d
915        den=r
916
917        EXAMPLES:
918            I'd love to, but since we are dealing with c-types, I can't at this level.
919            Check __invert__ for doc-tests that rely on this functionality.
920        """
921        cdef ZZ_c parent_den
922        cdef ZZX_c parent_num
923        self._parent_poly_c_( &parent_num, &parent_den )
924
925        cdef ZZX_c t # unneeded except to be there
926        cdef ZZX_c a, b
927        mul_ZZX_ZZ( a, self.__numerator, parent_den )
928        mul_ZZX_ZZ( b, parent_num, self.__denominator )
929        XGCD_ZZX( den[0], num[0],  t, a, b, 1 )
930        mul_ZZX_ZZ( num[0], num[0], parent_den )
931        mul_ZZX_ZZ( num[0], num[0], self.__denominator )
932
933    def __invert__(self):
934        """
935        Returns the multiplicative inverse of self in the number field.
936
937        EXAMPLES:
938            sage: C.<I>=CyclotomicField(4)
939            sage: ~I
940            -I
941            sage: (2*I).__invert__()
942            -1/2*I
943        """
944        if IsZero_ZZX(self.__numerator):
945            raise ZeroDivisionError
946        cdef NumberFieldElement x
947        x = self._new()
948        self._invert_c_(&x.__numerator, &x.__denominator)
949        x._reduce_c_()
950        return x
951#        K = self.parent()
952#        quotient = K(1)._pari_('x') / self._pari_('x')
953#        if isinstance(K, sage.rings.number_field.number_field.NumberField_extension):
954#            return K(K.pari_rnf().rnfeltreltoabs(quotient))
955#        else:
956#            return K(quotient)
957
958    def _integer_(self):
959        """
960        Returns a rational integer if this element is actually a rational integer.
961
962        EXAMPLES:
963            sage: C.<I>=CyclotomicField(4)
964            sage: (~I)._integer_()
965            Traceback (most recent call last):
966            ...
967            TypeError: Unable to coerce -I to an integer
968            sage: (2*I*I)._integer_()
969            -2
970        """
971        if deg(self.__numerator) >= 1:
972            raise TypeError, "Unable to coerce %s to an integer"%self
973        return ZZ(self._rational_())
974
975    def _rational_(self):
976        """
977        Returns a rational number if this element is actually a rational number.
978
979        EXAMPLES:
980            sage: C.<I>=CyclotomicField(4)
981            sage: (~I)._rational_()
982            Traceback (most recent call last):
983            ...
984            TypeError: Unable to coerce -I to a rational
985            sage: (I*I/2)._rational_()
986            -1/2
987        """
988        if deg(self.__numerator) >= 1:
989            raise TypeError, "Unable to coerce %s to a rational"%self
990        cdef Integer num
991        num = PY_NEW(Integer)
992        ZZX_getitem_as_mpz(&num.value, &self.__numerator, 0)
993        return num / (<IntegerRing_class>ZZ)._coerce_ZZ(&self.__denominator)
994
995    def conjugate(self):
996        """
997        Return the complex conjugate of the number field element.  Currently,
998        this is implemented for cyclotomic fields and quadratic extensions of Q. 
999        It seems likely that there are other number fields for which the idea of
1000        a conjugate would be easy to compute.
1001
1002        EXAMPLES:
1003            sage: k.<I> = QuadraticField(-1)
1004            sage: I.conjugate()
1005            -I
1006            sage: (I/(1+I)).conjugate()
1007            -1/2*I + 1/2
1008            sage: z6=CyclotomicField(6).gen(0)
1009            sage: (2*z6).conjugate()
1010            -2*zeta6 + 2
1011
1012            sage: K.<b> = NumberField(x^3 - 2)
1013            sage: b.conjugate()
1014            Traceback (most recent call last):
1015            ...
1016            NotImplementedError: complex conjugation is not implemented (or doesn't make sense).
1017        """
1018        coeffs = self.parent().polynomial().list()
1019        if len(coeffs) == 3 and coeffs[2] == 1 and coeffs[1] == 0:
1020            # polynomial looks like x^2+d
1021            # i.e. we live in a quadratic extension of QQ
1022            if coeffs[0] > 0:
1023                gen = self.parent().gen()
1024                return self.polynomial()(-gen)
1025            else:
1026                return self
1027        elif isinstance(self.parent(), sage.rings.number_field.number_field.NumberField_cyclotomic):
1028            # We are in a cyclotomic field
1029            # Replace the generator zeta_n with (zeta_n)^(n-1)
1030            gen = self.parent().gen()
1031            return self.polynomial()(gen ** (gen.multiplicative_order()-1))
1032        else:
1033            raise NotImplementedError, "complex conjugation is not implemented (or doesn't make sense)."
1034
1035    def polynomial(self):
1036        """
1037        Return the underlying polynomial corresponding to this
1038        number field element.
1039
1040        The resulting polynomial is currently *not* cached.
1041
1042        EXAMPLES:
1043            sage: K.<a> = NumberField(x^5 - x - 1)
1044            sage: f = (-2/3 + 1/3*a)^4; f
1045            1/81*a^4 - 8/81*a^3 + 8/27*a^2 - 32/81*a + 16/81
1046            sage: g = f.polynomial(); g
1047            1/81*x^4 - 8/81*x^3 + 8/27*x^2 - 32/81*x + 16/81
1048            sage: parent(g)
1049            Univariate Polynomial Ring in x over Rational Field
1050
1051        Note that the result of this function is not cached (should this
1052        be changed?):
1053            sage: g is f.polynomial()
1054            False       
1055        """
1056        return QQ['x'](self._coefficients())
1057
1058    def _coefficients(self):
1059        """
1060        Return the coefficients of the underlying polynomial corresponding to this
1061        number field element.
1062
1063        OUTPUT:
1064             -- a list whose length corresponding to the degree of this element
1065                written in terms of a generator.
1066
1067        EXAMPLES:
1068           
1069        """
1070        coeffs = []
1071        cdef Integer den = (<IntegerRing_class>ZZ)._coerce_ZZ(&self.__denominator)
1072        cdef Integer numCoeff
1073        cdef int i
1074        for i from 0 <= i <= deg(self.__numerator):
1075            numCoeff = PY_NEW(Integer)
1076            ZZX_getitem_as_mpz(&numCoeff.value, &self.__numerator, i)
1077            coeffs.append( numCoeff / den )
1078        return coeffs
1079
1080    def denominator(self):
1081        """
1082        Return the denominator of this element, which is by definition
1083        the denominator of the corresponding polynomial
1084        representation.  I.e., elements of number fields are
1085        represented as a polynomial (in reduced form) modulo the
1086        modulus of the number field, and the denominator is the
1087        denominator of this polynomial.
1088
1089        EXAMPLES:
1090            sage: K.<z> = CyclotomicField(3)
1091            sage: a = 1/3 + (1/5)*z
1092            sage: print a.denominator()
1093            15
1094        """
1095        return (<IntegerRing_class>ZZ)._coerce_ZZ(&self.__denominator)
1096
1097    def _set_multiplicative_order(self, n):
1098        """
1099        Set the multiplicative order of this number field element.
1100
1101        WARNING -- use with caution -- only for internal use!  End
1102        users should never call this unless they have a very good
1103        reason to do so.
1104
1105        EXAMPLES:
1106            sage: K.<a> = NumberField(x^2 + x + 1)
1107            sage: a._set_multiplicative_order(3)
1108            sage: a.multiplicative_order()
1109            3
1110
1111        You can be evil with this so be careful.  That's why the function
1112        name begins with an underscore.
1113            sage: a._set_multiplicative_order(389)
1114            sage: a.multiplicative_order()
1115            389       
1116        """
1117        self.__multiplicative_order = n
1118
1119    def multiplicative_order(self):
1120        """
1121        Return the multiplicative order of this number field element.
1122
1123        EXAMPLES:
1124            sage: K.<z> = CyclotomicField(5)
1125            sage: z.multiplicative_order()
1126            5
1127            sage: (-z).multiplicative_order()
1128            10
1129            sage: (1+z).multiplicative_order()
1130            +Infinity       
1131        """
1132        if self.__multiplicative_order is not None:
1133            return self.__multiplicative_order
1134
1135        if deg(self.__numerator) == 0:
1136            if self._rational_() == 1:
1137                self.__multiplicative_order = 1
1138                return self.__multiplicative_order
1139            if self._rational_() == -1:
1140                self.__multiplicative_order = 2
1141                return self.__multiplicative_order
1142
1143        if isinstance(self.parent(), sage.rings.number_field.number_field.NumberField_cyclotomic):
1144            t = self.parent()._multiplicative_order_table()
1145            f = self.polynomial()
1146            if t.has_key(f):
1147                self.__multiplicative_order = t[f]
1148                return self.__multiplicative_order
1149
1150        ####################################################################
1151        # VERY DUMB Algorithm to compute the multiplicative_order of
1152        # an element x of a number field K.
1153        #
1154        # 1. Find an integer B such that if n>=B then phi(n) > deg(K).
1155        #    For this use that for n>6 we have phi(n) >= log_2(n)
1156        #    (to see this think about the worst prime factorization
1157        #    in the multiplicative formula for phi.)
1158        # 2. Compute x, x^2, ..., x^B in order to determine the multiplicative_order.
1159        #
1160        # todo-- Alternative: Only do the above if we don't require an optional
1161        # argument which gives a multiple of the order, which is usually
1162        # something available in any actual application.
1163        #
1164        # BETTER TODO: Factor cyclotomic polynomials over K to determine
1165        # possible orders of elements?  Is there something even better?
1166        #
1167        ####################################################################
1168        d = self.parent().degree()
1169        B = max(7, 2**d+1)
1170        x = self
1171        i = 1
1172        while i < B:
1173            if x == 1:
1174                self.__multiplicative_order = i
1175                return self.__multiplicative_order
1176            x *= self
1177            i += 1
1178
1179        # it must have infinite order
1180        self.__multiplicative_order = sage.rings.infinity.infinity
1181        return self.__multiplicative_order
1182
1183    def trace(self):
1184        """
1185        Return the trace of this number field element.
1186
1187        EXAMPLES:
1188            sage: K.<a> = NumberField(x^3 -132/7*x^2 + x + 1); K
1189            Number Field in a with defining polynomial x^3 - 132/7*x^2 + x + 1
1190            sage: a.trace()
1191            132/7
1192            sage: (a+1).trace() == a.trace() + 3
1193            True       
1194        """
1195        K = self.parent().base_ring()
1196        return K(self._pari_('x').trace())
1197
1198    def norm(self):
1199        """
1200        Return the norm of this number field element.
1201
1202        EXAMPLES:
1203            sage: K.<a> = NumberField(x^3 + x^2 + x + -132/7); K
1204            Number Field in a with defining polynomial x^3 + x^2 + x - 132/7
1205            sage: a.norm()
1206            132/7
1207            sage: K(0).norm()
1208            0       
1209        """
1210        K = self.parent().base_ring()
1211        return K(self._pari_('x').norm())
1212
1213    def charpoly(self, var='x'):
1214        r"""
1215        The characteristic polynomial of this element over $\Q$.
1216
1217        EXAMPLES:
1218
1219        We compute the charpoly of cube root of $3$.
1220
1221            sage: R.<x> = QQ[]
1222            sage: K.<a> = NumberField(x^3-2)
1223            sage: a.charpoly('x')
1224            x^3 - 2
1225
1226        We construct a relative extension and find the characteristic
1227        polynomial over $\Q$.
1228
1229            sage: S.<X> = K[]
1230            sage: L.<b> = NumberField(X^3 + 17); L
1231            Number Field in b with defining polynomial X^3 + 17 over its base field
1232            sage: a = L.0; a
1233            b
1234            sage: a.charpoly('x')
1235            x^9 + 57*x^6 + 165*x^3 + 6859
1236            sage: a.charpoly('y')
1237            y^9 + 57*y^6 + 165*y^3 + 6859
1238        """
1239        R = self.parent().base_ring()[var]
1240        if not isinstance(self.parent(), sage.rings.number_field.number_field.NumberField_extension):
1241            return R(self._pari_('x').charpoly())
1242        else:
1243            g = self.polynomial()  # in QQ[x]
1244            f = self.parent().pari_polynomial()  # # field is QQ[x]/(f)
1245            return R( (g._pari_().Mod(f)).charpoly() )
1246
1247## This might be useful for computing relative charpoly.
1248## BUT -- currently I don't even know how to view elements
1249## as being in terms of the right thing, i.e., this code
1250## below as is lies.
1251##             nf = self.parent()._pari_base_nf()
1252##             prp = self.parent().pari_relative_polynomial()
1253##             elt = str(self.polynomial()._pari_())
1254##             return R(nf.rnfcharpoly(prp, elt))
1255##         # return self.matrix().charpoly('x')
1256
1257    def minpoly(self, var='x'):
1258        """
1259        Return the minimal polynomial of this number field element.
1260
1261        EXAMPLES:
1262            sage: K.<a> = NumberField(x^2+3)
1263            sage: a.minpoly('x')
1264            x^2 + 3
1265            sage: R.<X> = K['X']
1266            sage: L.<b> = K.extension(X^2-(22 + a))
1267            sage: b.minpoly('t')
1268            t^4 + (-44)*t^2 + 487
1269            sage: b^2 - (22+a)
1270            0       
1271        """
1272        return self.charpoly(var).radical() # square free part of charpoly
1273
1274    def is_integral(self):
1275        r"""
1276        Determine if a number is in the ring of integers
1277        of this number field.
1278       
1279        EXAMPLES:
1280            sage: K.<a> = NumberField(x^2 + 23, 'a')
1281            sage: a.is_integral()
1282            True
1283            sage: t = (1+a)/2
1284            sage: t.is_integral()
1285            True
1286            sage: t.minpoly()
1287            x^2 - x + 6
1288            sage: t = a/2
1289            sage: t.is_integral()
1290            False
1291            sage: t.minpoly()
1292            x^2 + 23/4
1293        """
1294        return all([a in ZZ for a in self.minpoly()])
1295
1296    def matrix(self):
1297        r"""
1298        The matrix of right multiplication by the element on the power
1299        basis $1, x, x^2, \ldots, x^{d-1}$ for the number field.  Thus
1300        the {\em rows} of this matrix give the images of each of the $x^i$.
1301
1302        EXAMPLES:
1303
1304        Regular number field:
1305            sage: K.<a> = NumberField(QQ['x'].0^3 - 5)
1306            sage: M = a.matrix(); M
1307            [0 1 0]
1308            [0 0 1]
1309            [5 0 0]
1310            sage: M.base_ring() is QQ
1311            True
1312
1313        """
1314##         Relative number field:
1315##             sage: L.<b> = K.extension(K['x'].0^2 - 2)
1316##             sage: 1*b, b*b, b**3, b**6
1317##             (b, b^2, b^3, 6*b^4 - 10*b^3 - 12*b^2 - 60*b - 17)
1318##             sage: L.pari_rnf().rnfeltabstorel(b._pari_())
1319##             x - y
1320##             sage: L.pari_rnf().rnfeltabstorel((b**2)._pari_())
1321##             2
1322##             sage: M = b.matrix(); M
1323##             [0 1]
1324##             [3 0]
1325##             sage: M.base_ring() is K
1326##             True
1327
1328#         Absolute number field:
1329#             sage: M = L.absolute_field().gen().matrix(); M
1330#             [  0   1   0   0   0   0]
1331#             [  0   0   1   0   0   0]
1332#             [  0   0   0   1   0   0]
1333#             [  0   0   0   0   1   0]
1334#             [  0   0   0   0   0   1]
1335#             [  2 -90 -27 -10   9   0]
1336#             sage: M.base_ring() is QQ
1337#             True
1338
1339#         More complicated relative number field:
1340#             sage: L.<b> = K.extension(K['x'].0^2 - a); L
1341#             Extension by x^2 + -a of the Number Field in a with defining polynomial x^3 - 5
1342#             sage: M = b.matrix(); M
1343#             [0 1]
1344#             [a 0]
1345#             sage: M.base_ring()
1346#             sage: M.base_ring() is K
1347#             True
1348        # Mutiply each power of field generator on
1349        # the left by this element; make matrix
1350        # whose rows are the coefficients of the result,
1351        # and transpose.
1352        if self.__matrix is None:
1353            K = self.parent()
1354            v = []
1355            x = K.gen()
1356            a = K(1)
1357            d = K.degree()
1358            for n in range(d):
1359                v += (a*self).list()
1360                a *= x
1361            k = K.base_ring()
1362            import sage.matrix.matrix_space
1363            M = sage.matrix.matrix_space.MatrixSpace(k, d)
1364            self.__matrix = M(v)
1365        return self.__matrix
1366
1367    def list(self):
1368        """
1369        Return list of coefficients of self written in terms of a power basis.
1370       
1371        EXAMPLE:
1372            sage: K.<z> = CyclotomicField(3)
1373            sage: (2+3/5*z).list()
1374            [2, 3/5]
1375            sage: (5*z).list()
1376            [0, 5]
1377            sage: K(3).list()
1378            [3, 0]
1379        """
1380        P = self.parent()
1381        # The algorithm below is total nonsense, unless the parent of self is an
1382        # absolute extension.
1383        if isinstance(P, sage.rings.number_field.number_field.NumberField_extension):
1384            raise NotImplementedError
1385        n = self.parent().degree()
1386        v = self._coefficients()
1387        z = sage.rings.rational.Rational(0)
1388        return v + [z]*(n - len(v))
1389       
1390       
1391cdef class NumberFieldElement_absolute(NumberFieldElement):
1392    def __init__(self, K, f):
1393        NumberFieldElement.__init__(self, K, f)
1394   
1395cdef class NumberFieldElement_relative(NumberFieldElement):
1396    def __init__(self, K, f):
1397        NumberFieldElement.__init__(self, K, f)
1398
1399
1400cdef class OrderElement_absolute(NumberFieldElement_absolute):
1401    """
1402    Element of an order in an absolute number field.
1403
1404    EXAMPLES:
1405        sage: k.<a> = NumberField(x^2 + 1)
1406    """
1407    def __init__(self, order, f):
1408        K = order.number_field()
1409        NumberFieldElement_absolute.__init__(self, K, f)
1410        self._order = order
1411
1412cdef class OrderElement_relative(NumberFieldElement_relative):
1413    """
1414    Element of an order in a relative number field.
1415    """
1416    def __init__(self, order, f):
1417        K = order.number_field()
1418        NumberFieldElement_relative.__init__(self, K, f)
1419        self._order = order
1420
1421
Note: See TracBrowser for help on using the repository browser.