source: sage/rings/number_field/number_field_element.pyx @ 6788:1e78fbd0f56f

Revision 6788:1e78fbd0f56f, 62.2 KB checked in by William Stein <wstein@…>, 6 years ago (diff)

Work on relative orders.

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    -- Robert Bradshaw (2007-09-15): specialized classes for relative and absolute elements
9"""
10
11# TODO -- relative extensions need to be completely rewritten, so one
12# can get easy access to representation of elements in their relative
13# form.  Functions like matrix below can't be done until relative
14# extensions are re-written this way.  Also there needs to be class
15# hierarchy for number field elements, integers, etc.  This is a
16# nontrivial project, and it needs somebody to attack it.  I'm amazed
17# how long this has gone unattacked.
18
19# Relative elements need to be a derived class or something.  This is
20# terrible as it is now.
21
22#*****************************************************************************
23#       Copyright (C) 2004, 2007 William Stein <wstein@gmail.com>
24#
25#  Distributed under the terms of the GNU General Public License (GPL)
26#
27#    This code is distributed in the hope that it will be useful,
28#    but WITHOUT ANY WARRANTY; without even the implied warranty of
29#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
30#    General Public License for more details.
31#
32#  The full text of the GPL is available at:
33#
34#                  http://www.gnu.org/licenses/
35#*****************************************************************************
36
37import operator
38
39include '../../ext/interrupt.pxi'
40include '../../ext/python_int.pxi'
41include "../../ext/stdsage.pxi"
42cdef extern from *:
43    # TODO: move to stdsage.pxi
44    object PY_NEW_SAME_TYPE(object o)
45
46import sage.rings.field_element
47import sage.rings.infinity
48import sage.rings.polynomial.polynomial_element
49import sage.rings.polynomial.polynomial_ring
50import sage.rings.rational_field
51import sage.rings.rational
52import sage.rings.integer_ring
53import sage.rings.integer
54import sage.rings.arith
55
56import number_field
57
58from sage.libs.ntl.ntl_ZZ cimport ntl_ZZ
59from sage.libs.ntl.ntl_ZZX cimport ntl_ZZX
60from sage.rings.integer_ring cimport IntegerRing_class
61
62from sage.libs.all import pari_gen
63from sage.libs.pari.gen import PariError
64from sage.structure.element cimport Element
65
66QQ = sage.rings.rational_field.QQ
67ZZ = sage.rings.integer_ring.ZZ
68Integer_sage = sage.rings.integer.Integer
69
70
71def is_NumberFieldElement(x):
72    """
73    Return True if x is of type NumberFieldElement, i.e., an
74    element of a number field.
75
76    EXAMPLES:
77        sage: is_NumberFieldElement(2)
78        False
79        sage: k.<a> = NumberField(x^7 + 17*x + 1)
80        sage: is_NumberFieldElement(a+1)
81        True
82    """
83    return PY_TYPE_CHECK(x, NumberFieldElement)
84
85def __create__NumberFieldElement_version0(parent, poly):
86    """
87    Used in unpickling elements of number fields.
88
89    EXAMPLES:
90    Since this is just used in unpickling, we unpickle.
91   
92        sage: k.<a> = NumberField(x^3 - 2)
93        sage: loads(dumps(a+1)) == a + 1
94        True       
95    """
96    return NumberFieldElement(parent, poly)
97
98def __create__NumberFieldElement_version1(parent, cls, poly):
99    """
100    Used in unpickling elements of number fields.
101
102    EXAMPLES:
103    Since this is just used in unpickling, we unpickle.
104   
105        sage: k.<a> = NumberField(x^3 - 2)
106        sage: loads(dumps(a+1)) == a + 1
107        True       
108    """
109    return cls(parent, poly)
110
111cdef class NumberFieldElement(FieldElement):
112    """
113    An element of a number field.
114
115    EXAMPLES:
116        sage: k.<a> = NumberField(x^3 + x + 1)
117        sage: a^3
118        -a - 1       
119    """
120    cdef NumberFieldElement _new(self):
121        """
122        Quickly creates a new initialized NumberFieldElement with the
123        same parent as self.
124        """
125        cdef NumberFieldElement x
126        x = <NumberFieldElement>PY_NEW_SAME_TYPE(self)
127        x._parent = self._parent
128        return x
129
130    def __init__(self, parent, f):
131        """
132        INPUT:
133            parent -- a number field
134            f -- defines an element of a number field.
135
136        EXAMPLES:
137        The following examples illustrate creation of elements of
138        number fields, and some basic arithmetic.
139
140        First we define a polynomial over Q.
141            sage: R.<x> = PolynomialRing(QQ)
142            sage: f = x^2 + 1
143
144        Next we use f to define the number field.
145            sage: K.<a> = NumberField(f); K
146            Number Field in a with defining polynomial x^2 + 1
147            sage: a = K.gen()
148            sage: a^2
149            -1
150            sage: (a+1)^2
151            2*a
152            sage: a^2
153            -1
154            sage: z = K(5); 1/z
155            1/5
156
157        We create a cube root of 2.
158            sage: K.<b> = NumberField(x^3 - 2)
159            sage: b = K.gen()
160            sage: b^3
161            2
162            sage: (b^2 + b + 1)^3
163            12*b^2 + 15*b + 19
164
165        This example illustrates save and load:
166            sage: K.<a> = NumberField(x^17 - 2)
167            sage: s = a^15 - 19*a + 3
168            sage: loads(s.dumps()) == s
169            True
170        """
171        sage.rings.field_element.FieldElement.__init__(self, parent)
172
173        cdef ZZ_c coeff
174        if isinstance(f, (int, long, Integer_sage)):
175            # set it up and exit immediately
176            # fast pathway
177            (<Integer>ZZ(f))._to_ZZ(&coeff)
178            ZZX_SetCoeff( self.__numerator, 0, coeff )
179            conv_ZZ_int( self.__denominator, 1 )
180            return
181           
182        elif isinstance(f, NumberFieldElement):
183            if PY_TYPE(self) is PY_TYPE(f):
184                self.__numerator = (<NumberFieldElement>f).__numerator
185                self.__denominator = (<NumberFieldElement>f).__denominator
186                return
187            else:
188                f = f.polynomial()
189
190        ppr = parent.polynomial_ring()
191        if isinstance(parent, number_field.NumberField_relative):
192            ppr = parent.base_field().polynomial_ring()
193
194        cdef long i
195        if isinstance(f, pari_gen):
196            if f.type() == "t_COL":
197                newf = ppr(0)
198                Zbasis = self.parent().pari_nf().getattr('zk')
199                # Note that this integral basis is not the same as that returned by parent.integral_basis() !
200                for i from 0 <= i < parent.degree():
201                    if f[i] != 0:
202                        newf += QQ(f[i]) * ppr(Zbasis[i])
203                f = newf
204            else:
205                if f.type() == "t_POLMOD":
206                    f = f.lift()
207                if f.type() in ["t_INT", "t_FRAC", "t_POL"]:
208                    f = ppr(f)
209                else:
210                    raise TypeError, "Unsupported Pari type"
211        if not isinstance(f, sage.rings.polynomial.polynomial_element.Polynomial):
212            f = ppr(f)
213        if f.degree() >= parent.absolute_degree():
214            if f.variable_name() != 'x':
215                f = f.change_variable_name('x')
216            if isinstance(parent, number_field.NumberField_relative):
217                f %= parent.absolute_polynomial()
218            else:
219                f %= parent.polynomial()
220
221        # Set Denominator
222        den = f.denominator()
223        (<Integer>ZZ(den))._to_ZZ(&self.__denominator)
224
225        num = f * den
226        for i from 0 <= i <= num.degree():
227            (<Integer>ZZ(num[i]))._to_ZZ(&coeff)
228            ZZX_SetCoeff( self.__numerator, i, coeff )
229
230    def __new__(self, parent = None, f = None):
231        ZZX_construct(&self.__numerator)
232        ZZ_construct(&self.__denominator)
233
234    def __dealloc__(self):
235        ZZX_destruct(&self.__numerator)
236        ZZ_destruct(&self.__denominator)
237
238    def _lift_cyclotomic_element(self, new_parent):
239        """
240        Creates an element of the passed field from this field.  This
241        is specific to creating elements in a cyclotomic field from
242        elements in another cyclotomic field.  This function aims to
243        make this common coercion extremely fast!
244
245        EXAMPLES:
246            sage: C.<zeta5>=CyclotomicField(5)
247            sage: CyclotomicField(10)(zeta5+1)  # The function _lift_cyclotomic_element does the heavy lifting in the background
248            zeta10^2 + 1
249            sage: (zeta5+1)._lift_cyclotomic_element(CyclotomicField(10))  # There is rarely a purpose to call this function directly
250            zeta10^2 + 1
251
252        AUTHOR:
253            Joel B. Mohler
254        """
255        # Right now, I'm a little confused why quadratic extension fields have a zeta_order function
256        # I would rather they not have this function since I don't want to do this isinstance check here.
257        if not isinstance(self.parent(), number_field.NumberField_cyclotomic) or not isinstance(new_parent, number_field.NumberField_cyclotomic):
258            raise TypeError, "The field and the new parent field must both be cyclotomic fields."
259
260        try:
261            small_order = self.parent().zeta_order()
262            large_order = new_parent.zeta_order()
263        except AttributeError:
264            raise TypeError, "The field and the new parent field must both be cyclotomic fields."
265
266        try:
267            _rel = ZZ(large_order / small_order)
268        except TypeError:
269            raise TypeError, "The zeta_order of the new field must be a multiple of the zeta_order of the original."
270
271        cdef NumberFieldElement x = <NumberFieldElement>PY_NEW_SAME_TYPE(self)
272        x._parent = <ParentWithBase>new_parent
273        x.__denominator = self.__denominator
274        cdef ZZX_c result
275        cdef ZZ_c tmp
276        cdef int i
277        cdef int rel = _rel
278        cdef ntl_ZZX _num
279        cdef ntl_ZZ _den
280        _num, _den = new_parent.polynomial_ntl()
281        for i from 0 <= i <= ZZX_deg(self.__numerator):
282            tmp = ZZX_coeff(self.__numerator, i)
283            ZZX_SetCoeff(result, i*rel, tmp)
284        rem_ZZX(x.__numerator, result, _num.x)
285        return x
286
287    def __reduce__(self):
288        """
289        Used in pickling number field elements.
290
291        EXAMPLES:
292            sage: k.<a> = NumberField(x^3 - 17*x^2 + 1)
293            sage: t = a.__reduce__(); t
294            (<built-in function __create__NumberFieldElement_version1>, (Number Field in a with defining polynomial x^3 - 17*x^2 + 1, <type 'sage.rings.number_field.number_field_element.NumberFieldElement_absolute'>, x))
295            sage: t[0](*t[1]) == a
296            True       
297        """
298        return __create__NumberFieldElement_version1, \
299               (self.parent(), type(self), self.polynomial())
300
301    def __repr__(self):
302        """
303        String representation of this number field element,
304        which is just a polynomial in the generator.
305
306        EXAMPLES:
307            sage: k.<a> = NumberField(x^2 + 2)
308            sage: b = (2/3)*a + 3/5
309            sage: b.__repr__()
310            '2/3*a + 3/5'       
311        """
312        x = self.polynomial()
313        return str(x).replace(x.parent().variable_name(),self.parent().variable_name())
314
315    def _im_gens_(self, codomain, im_gens):
316        """
317        This is used in computing homomorphisms between number fields.
318
319        EXAMPLES:
320            sage: k.<a> = NumberField(x^2 - 2)
321            sage: m.<b> = NumberField(x^4 - 2)
322            sage: phi = k.hom([b^2])
323            sage: phi(a+1)
324            b^2 + 1
325            sage: (a+1)._im_gens_(m, [b^2])
326            b^2 + 1       
327        """
328        # NOTE -- if you ever want to change this so relative number fields are
329        # in terms of a root of a poly.
330        # The issue is that elements of a relative number field are represented in terms
331        # of a generator for the absolute field.  However the morphism gives the image
332        # of gen, which need not be a generator for the absolute field.  The morphism
333        # has to be *over* the relative element.
334        return codomain(self.polynomial()(im_gens[0]))
335
336    def _latex_(self):
337        """
338        Returns the latex representation for this element.
339
340        EXAMPLES:
341            sage: C,zeta12=CyclotomicField(12).objgen()
342            sage: latex(zeta12^4-zeta12)
343            \zeta_{12}^{2} - \zeta_{12} - 1
344        """
345        return self.polynomial()._latex_(name=self.parent().latex_variable_name())
346
347    def _pari_(self, var='x'):
348        raise NotImplementedError, "NumberFieldElement sub-classes must override _pari_"
349
350    def _pari_init_(self, var='x'):
351        """
352        Return GP/PARI string representation of self. This is used for
353        converting this number field element to GP/PARI.  The returned
354        string defines a pari Mod in the variable is var, which is by
355        default 'x' -- not the name of the generator of the number
356        field.
357
358        INPUT:
359            var -- (default: 'x') the variable of the pari Mod.
360
361        EXAMPLES:
362            sage: K.<a> = NumberField(x^5 - x - 1)
363            sage: ((1 + 1/3*a)^4)._pari_init_()
364            'Mod(1/81*x^4 + 4/27*x^3 + 2/3*x^2 + 4/3*x + 1, x^5 - x - 1)'
365            sage: ((1 + 1/3*a)^4)._pari_init_('a')
366            'Mod(1/81*a^4 + 4/27*a^3 + 2/3*a^2 + 4/3*a + 1, a^5 - a - 1)'
367
368        Note that _pari_init_ can fail because of reserved words in PARI,
369        and since it actually works by obtaining the PARI representation
370        of something.
371            sage: K.<theta> = NumberField(x^5 - x - 1)
372            sage: b = (1/2 - 2/3*theta)^3; b
373            -8/27*theta^3 + 2/3*theta^2 - 1/2*theta + 1/8
374            sage: b._pari_init_('theta')
375            Traceback (most recent call last):
376            ...
377            PariError: unexpected character (2)
378
379        Fortunately pari_init returns everything in terms of x by default.
380            sage: pari(b)
381            Mod(-8/27*x^3 + 2/3*x^2 - 1/2*x + 1/8, x^5 - x - 1)
382        """
383        return repr(self._pari_(var=var))
384##         if var == None:
385##             var = self.parent().variable_name()
386##         if isinstance(self.parent(), sage.rings.number_field.number_field.NumberField_relative):
387##             f = self.polynomial()._pari_()
388##             g = str(self.parent().pari_relative_polynomial())
389##             base = self.parent().base_ring()
390##             gsub = base.gen()._pari_()
391##             gsub = str(gsub).replace(base.variable_name(), "y")
392##             g = g.replace("y", gsub)
393##         else:
394##             f = str(self.polynomial()).replace("x",var)
395##             g = str(self.parent().polynomial()).replace("x",var)
396##         return 'Mod(%s, %s)'%(f,g)
397
398    def __getitem__(self, n):
399        """
400        Return the n-th coefficient of this number field element, written
401        as a polynomial in the generator.
402
403        Note that $n$ must be between 0 and $d-1$, where $d$ is the
404        degree of the number field.
405
406        EXAMPLES:
407            sage: m.<b> = NumberField(x^4 - 1789)
408            sage: c = (2/3-4/5*b)^3; c
409            -64/125*b^3 + 32/25*b^2 - 16/15*b + 8/27
410            sage: c[0]
411            8/27
412            sage: c[2]
413            32/25
414            sage: c[3]
415            -64/125
416
417        We illustrate bounds checking:
418            sage: c[-1]
419            Traceback (most recent call last):
420            ...
421            IndexError: index must be between 0 and degree minus 1.
422            sage: c[4]
423            Traceback (most recent call last):
424            ...
425            IndexError: index must be between 0 and degree minus 1.
426
427        The list method implicitly calls __getitem__:
428            sage: list(c)
429            [8/27, -16/15, 32/25, -64/125]
430            sage: m(list(c)) == c
431            True           
432        """
433        if n < 0 or n >= self.parent().degree():     # make this faster.
434            raise IndexError, "index must be between 0 and degree minus 1."
435        return self.polynomial()[n]
436
437    cdef int _cmp_c_impl(left, sage.structure.element.Element right) except -2:
438        cdef NumberFieldElement _right = right
439        return not (ZZX_equal(&left.__numerator, &_right.__numerator) and ZZ_equal(&left.__denominator, &_right.__denominator))
440
441    def __abs__(self):
442        r"""
443        Return the numerical absolute value of this number field
444        element with respect to the first archimedean embedding, to
445        double precision.
446
447        This is the \code{abs( )} Python function.  If you want a different
448        embedding or precision, use \code{self.abs(...)}.
449
450        EXAMPLES:
451            sage: k.<a> = NumberField(x^3 - 2)
452            sage: abs(a)
453            1.25992104989
454            sage: abs(a)^3
455            2.0
456            sage: a.abs(prec=128)
457            1.2599210498948731647672106072782283506       
458        """
459        return self.abs(prec=53, i=0)
460
461    def abs(self, prec=53, i=0):
462        """
463        Return the absolute value of this element with respect to the
464        ith complex embedding of parent, to the given precision.
465
466        INPUT:
467            prec -- (default: 53) integer bits of precision
468            i -- (default: ) integer, which embedding to use
469
470        EXAMPLES:
471            sage: z = CyclotomicField(7).gen()
472            sage: abs(z)
473            1.00000000000000
474            sage: abs(z^2 + 17*z - 3)
475            16.0604426799931
476            sage: K.<a> = NumberField(x^3+17)
477            sage: abs(a)
478            2.57128159066
479            sage: a.abs(prec=100)
480            2.5712815906582353554531872087
481            sage: a.abs(prec=100,i=1)
482            2.5712815906582353554531872087
483            sage: a.abs(100, 2)
484            2.5712815906582353554531872087
485
486        Here's one where the absolute value depends on the embedding.
487            sage: K.<b> = NumberField(x^2-2)
488            sage: a = 1 + b
489            sage: a.abs(i=0)
490            0.414213562373
491            sage: a.abs(i=1)
492            2.41421356237
493        """
494        P = self.parent().complex_embeddings(prec)[i]
495        return abs(P(self))
496
497    def coordinates_in_terms_of_powers(self):
498        r"""
499        Let $\alpha$ be self.  Return a Python function that takes any
500        element of the parent of self in $\QQ(\alpha)$ and writes it in
501        terms of the powers of $\alpha$: $1, \alpha, \alpha^2, ...$.
502
503        (NOT CACHED).
504
505        EXAMPLES:
506        This function allows us to write elements of a number field in
507        terms of a different generator without having to construct a
508        whole separate number field.
509
510            sage: y = polygen(QQ,'y'); K.<beta> = NumberField(y^3 - 2); K
511            Number Field in beta with defining polynomial y^3 - 2
512            sage: alpha = beta^2 + beta + 1
513            sage: c = alpha.coordinates_in_terms_of_powers(); c
514            Coordinate function that writes elements in terms of the powers of beta^2 + beta + 1
515            sage: c(beta)
516            [-2, -3, 1]
517            sage: c(alpha)
518            [0, 1, 0]
519            sage: c((1+beta)^5)
520            [3, 3, 3]
521            sage: c((1+beta)^10)
522            [54, 162, 189]
523       
524        This function works even if self only generates a subfield
525        of this number field.
526            sage: k.<a> = NumberField(x^6 - 5)
527            sage: alpha = a^3
528            sage: c = alpha.coordinates_in_terms_of_powers()
529            sage: c((2/3)*a^3 - 5/3)
530            [-5/3, 2/3]
531            sage: c
532            Coordinate function that writes elements in terms of the powers of a^3
533            sage: c(a)
534            Traceback (most recent call last):
535            ...
536            ArithmeticError: vector is not in free module
537        """
538        K = self.parent()
539        V, from_V, to_V = K.absolute_vector_space()
540        h = K(1)
541        B = [to_V(h)]
542        f = self.minpoly()
543        for i in range(f.degree()-1):
544            h *= self
545            B.append(to_V(h))
546        W = V.span_of_basis(B)
547        return CoordinateFunction(self, W, to_V)
548
549    def complex_embeddings(self, prec=53):
550        """
551        Return the images of this element in the floating point
552        complex numbers, to the given bits of precision.
553
554        INPUT:
555            prec -- integer (default: 53) bits of precision
556
557        EXAMPLES:
558            sage: k.<a> = NumberField(x^3 - 2)
559            sage: a.complex_embeddings()
560            [-0.629960524947 - 1.09112363597*I, -0.629960524947 + 1.09112363597*I, 1.25992104989]
561            sage: a.complex_embeddings(10)
562            [-0.63 - 1.1*I, -0.63 + 1.1*I, 1.3]
563            sage: a.complex_embeddings(100)
564            [-0.62996052494743658238360530364 - 1.0911236359717214035600726142*I, -0.62996052494743658238360530364 + 1.0911236359717214035600726142*I, 1.2599210498948731647672106073]
565        """
566        phi = self.parent().complex_embeddings(prec)
567        return [f(self) for f in phi]
568
569    def complex_embedding(self, prec=53, i=0):
570        """
571        Return the i-th embedding of self in the complex numbers, to
572        the given precision.
573
574        EXAMPLES:
575            sage: k.<a> = NumberField(x^3 - 2)
576            sage: a.complex_embedding()
577            -0.629960524947 - 1.09112363597*I
578            sage: a.complex_embedding(10)
579            -0.63 - 1.1*I
580            sage: a.complex_embedding(100)
581            -0.62996052494743658238360530364 - 1.0911236359717214035600726142*I
582            sage: a.complex_embedding(20, 1)
583            -0.62996 + 1.0911*I
584            sage: a.complex_embedding(20, 2)
585            1.2599
586        """
587        return self.parent().complex_embeddings(prec)[i](self)
588
589    def is_square(self, root=False):
590        """
591        Return True if self is a square in its parent number field and
592        otherwise return False.
593
594        INPUT:
595            root -- if True, also return a square root (or None if self
596                    is not a perfect square)
597
598        EXAMPLES:
599            sage: m.<b> = NumberField(x^4 - 1789)
600            sage: b.is_square()
601            False
602            sage: c = (2/3*b + 5)^2; c
603            4/9*b^2 + 20/3*b + 25
604            sage: c.is_square()
605            True
606            sage: c.is_square(True)
607            (True, 2/3*b + 5)
608
609        We also test the functional notation.
610            sage: is_square(c, True)
611            (True, 2/3*b + 5)
612            sage: is_square(c)
613            True
614            sage: is_square(c+1)
615            False
616        """
617        v = self.sqrt(all=True)
618        t = len(v) > 0
619        if root:
620            if t:
621                return t, v[0]
622            else:
623                return False, None
624        else:
625            return t
626       
627    def sqrt(self, all=False):
628        """
629        Returns the square root of this number in the given number field.
630       
631        EXAMPLES:
632            sage: K.<a> = NumberField(x^2 - 3)
633            sage: K(3).sqrt()
634            a
635            sage: K(3).sqrt(all=True)
636            [a, -a]
637            sage: K(a^10).sqrt()
638            9*a
639            sage: K(49).sqrt()
640            7
641            sage: K(1+a).sqrt()
642            Traceback (most recent call last):
643            ...
644            ValueError: a + 1 not a square in Number Field in a with defining polynomial x^2 - 3
645            sage: K(0).sqrt()
646            0
647            sage: K((7+a)^2).sqrt(all=True)
648            [a + 7, -a - 7]
649           
650            sage: K.<a> = CyclotomicField(7)
651            sage: a.sqrt() 
652            a^4
653           
654            sage: K.<a> = NumberField(x^5 - x + 1)
655            sage: (a^4 + a^2 - 3*a + 2).sqrt()
656            a^3 - a^2
657
658        ALGORITHM:
659            Use Pari to factor $x^2$ - \code{self} in K.
660           
661        """
662        # For now, use pari's factoring abilities
663        R = sage.rings.polynomial.polynomial_ring.PolynomialRing(self._parent, 't')
664        f = R([-self, 0, 1])
665        roots = f.roots()
666        if all:
667            return [r[0] for r in roots]
668        elif len(roots) > 0:
669            return roots[0][0]
670        else:
671            raise ValueError, "%s not a square in %s"%(self, self._parent)
672
673    cdef void _reduce_c_(self):
674        """
675        Pull out common factors from the numerator and denominator!
676        """
677        cdef ZZ_c gcd
678        cdef ZZ_c t1
679        cdef ZZX_c t2
680        content(t1, self.__numerator)
681        GCD_ZZ(gcd, t1, self.__denominator)
682        if sign(gcd) != sign(self.__denominator):
683            ZZ_negate(t1, gcd)
684            gcd = t1
685        div_ZZX_ZZ(t2, self.__numerator, gcd)
686        div_ZZ_ZZ(t1, self.__denominator, gcd)
687        self.__numerator = t2
688        self.__denominator = t1
689
690    cdef ModuleElement _add_c_impl(self, ModuleElement right):
691        cdef NumberFieldElement x
692        cdef NumberFieldElement _right = right
693        x = self._new()
694        mul_ZZ(x.__denominator, self.__denominator, _right.__denominator)
695        cdef ZZX_c t1, t2
696        mul_ZZX_ZZ(t1, self.__numerator, _right.__denominator)
697        mul_ZZX_ZZ(t2, _right.__numerator, self.__denominator)
698        add_ZZX(x.__numerator, t1, t2)
699        x._reduce_c_()
700        return x
701
702    cdef ModuleElement _sub_c_impl(self, ModuleElement right):
703        cdef NumberFieldElement x
704        cdef NumberFieldElement _right = right
705        x = self._new()
706        mul_ZZ(x.__denominator, self.__denominator, _right.__denominator)
707        cdef ZZX_c t1, t2
708        mul_ZZX_ZZ(t1, self.__numerator, _right.__denominator)
709        mul_ZZX_ZZ(t2, _right.__numerator, self.__denominator)
710        sub_ZZX(x.__numerator, t1, t2)
711        x._reduce_c_()
712        return x
713
714    cdef RingElement _mul_c_impl(self, RingElement right):
715        """
716        Returns the product of self and other as elements of a number field.
717
718        EXAMPLES:
719            sage: C.<zeta12>=CyclotomicField(12)
720            sage: zeta12*zeta12^11
721            1
722            sage: G.<a> = NumberField(x^3 + 2/3*x + 1)
723            sage: a^3
724            -2/3*a - 1
725            sage: a^3+a
726            1/3*a - 1
727        """
728        cdef NumberFieldElement x
729        cdef NumberFieldElement _right = right
730        cdef ZZX_c temp
731        cdef ZZ_c temp1
732        cdef ZZ_c parent_den
733        cdef ZZX_c parent_num
734        self._parent_poly_c_( &parent_num, &parent_den )
735        x = self._new()
736        _sig_on
737        # MulMod doesn't handle non-monic polynomials.
738        # Therefore, we handle the non-monic case entirely separately.
739        if ZZX_is_monic( &parent_num ):
740            mul_ZZ(x.__denominator, self.__denominator, _right.__denominator)
741            MulMod_ZZX(x.__numerator, self.__numerator, _right.__numerator, parent_num)
742        else:
743            mul_ZZ(x.__denominator, self.__denominator, _right.__denominator)
744            mul_ZZX(x.__numerator, self.__numerator, _right.__numerator)
745            if ZZX_degree(&x.__numerator) >= ZZX_degree(&parent_num):
746                mul_ZZX_ZZ( x.__numerator, x.__numerator, parent_den )
747                mul_ZZX_ZZ( temp, parent_num, x.__denominator )
748                power_ZZ(temp1,LeadCoeff_ZZX(temp),ZZX_degree(&x.__numerator)-ZZX_degree(&parent_num)+1)
749                PseudoRem_ZZX(x.__numerator, x.__numerator, temp)
750                mul_ZZ(x.__denominator, x.__denominator, parent_den)
751                mul_ZZ(x.__denominator, x.__denominator, temp1)
752        _sig_off
753        x._reduce_c_()
754        return x
755
756        #NOTES: In LiDIA, they build a multiplication table for the
757        #number field, so it's not necessary to reduce modulo the
758        #defining polynomial every time:
759        #     src/number_fields/algebraic_num/order.cc: compute_table
760        # but asymptotically fast poly multiplication means it's
761        # actually faster to *not* build a table!?!
762
763    cdef RingElement _div_c_impl(self, RingElement right):
764        """
765        Returns the quotient of self and other as elements of a number field.
766
767        EXAMPLES:
768            sage: C.<I>=CyclotomicField(4)
769            sage: 1/I
770            -I
771            sage: I/0
772            Traceback (most recent call last):
773            ...
774            ZeroDivisionError: Number field element division by zero
775           
776            sage: G.<a> = NumberField(x^3 + 2/3*x + 1)
777            sage: a/a
778            1
779            sage: 1/a
780            -a^2 - 2/3
781            sage: a/0
782            Traceback (most recent call last):
783            ...
784            ZeroDivisionError: Number field element division by zero
785        """
786        cdef NumberFieldElement x
787        cdef NumberFieldElement _right = right
788        cdef ZZX_c inv_num
789        cdef ZZ_c inv_den
790        cdef ZZ_c parent_den
791        cdef ZZX_c parent_num
792        cdef ZZX_c temp
793        cdef ZZ_c temp1
794        if not _right:
795            raise ZeroDivisionError, "Number field element division by zero"
796        self._parent_poly_c_( &parent_num, &parent_den )
797        x = self._new()
798        _sig_on
799        _right._invert_c_(&inv_num, &inv_den)
800        if ZZX_is_monic( &parent_num ):
801            mul_ZZ(x.__denominator, self.__denominator, inv_den)
802            MulMod_ZZX(x.__numerator, self.__numerator, inv_num, parent_num)
803        else:
804            mul_ZZ(x.__denominator, self.__denominator, inv_den)
805            mul_ZZX(x.__numerator, self.__numerator, inv_num)
806            if ZZX_degree(&x.__numerator) >= ZZX_degree(&parent_num):
807                mul_ZZX_ZZ( x.__numerator, x.__numerator, parent_den )
808                mul_ZZX_ZZ( temp, parent_num, x.__denominator )
809                power_ZZ(temp1,LeadCoeff_ZZX(temp),ZZX_degree(&x.__numerator)-ZZX_degree(&parent_num)+1)
810                PseudoRem_ZZX(x.__numerator, x.__numerator, temp)
811                mul_ZZ(x.__denominator, x.__denominator, parent_den)
812                mul_ZZ(x.__denominator, x.__denominator, temp1)
813        x._reduce_c_()
814        _sig_off
815        return x
816
817    def __floordiv__(self, other):
818        """
819        Return the quotient of self and other.  Since these are field
820        elements the floor division is exactly the same as usual
821        division.
822
823        EXAMPLES:
824            sage: m.<b> = NumberField(x^4 + x^2 + 2/3)
825            sage: c = (1+b) // (1-b); c
826            3/4*b^3 + 3/4*b^2 + 3/2*b + 1/2
827            sage: (1+b) / (1-b) == c
828            True
829            sage: c * (1-b)
830            b + 1       
831        """
832        return self / other
833
834    def __nonzero__(self):
835        """
836        Return True if this number field element is nonzero.
837
838        EXAMPLES:
839            sage: m.<b> = CyclotomicField(17)
840            sage: m(0).__nonzero__()
841            False
842            sage: b.__nonzero__()
843            True
844
845        Nonzero is used by the bool command:
846            sage: bool(b + 1)
847            True
848            sage: bool(m(0))
849            False
850        """
851        return not IsZero_ZZX(self.__numerator)
852
853    cdef ModuleElement _neg_c_impl(self):
854        cdef NumberFieldElement x
855        x = self._new()
856        mul_ZZX_long(x.__numerator, self.__numerator, -1)
857        x.__denominator = self.__denominator
858        return x
859
860    def __copy__(self):
861        cdef NumberFieldElement x
862        x = self._new()
863        x.__numerator = self.__numerator
864        x.__denominator = self.__denominator
865        return x
866
867    def __int__(self):
868        """
869        Attempt to convert this number field element to a Python integer,
870        if possible.
871       
872        EXAMPLES:
873            sage: C.<I>=CyclotomicField(4)
874            sage: int(1/I)
875            Traceback (most recent call last):
876            ...
877            TypeError: cannot coerce nonconstant polynomial to int
878            sage: int(I*I)
879            -1
880
881            sage: K.<a> = NumberField(x^10 - x - 1)
882            sage: int(a)
883            Traceback (most recent call last):
884            ...
885            TypeError: cannot coerce nonconstant polynomial to int
886            sage: int(K(9390283))
887            9390283
888
889        The semantics are like in Python, so the value does not have
890        to preserved.
891            sage: int(K(393/29))
892            13           
893        """
894        return int(self.polynomial())
895
896    def __long__(self):
897        """
898        Attempt to convert this number field element to a Python long,
899        if possible.
900       
901        EXAMPLES:
902            sage: K.<a> = NumberField(x^10 - x - 1)
903            sage: long(a)
904            Traceback (most recent call last):
905            ...
906            TypeError: cannot coerce nonconstant polynomial to long
907            sage: long(K(1234))
908            1234L
909
910        The value does not have to be preserved, in the case of fractions.
911            sage: long(K(393/29))
912            13L       
913        """
914        return long(self.polynomial())
915
916    cdef void _parent_poly_c_(self, ZZX_c *num, ZZ_c *den):
917        raise NotImplementedError, "NumberFieldElement subclasses must override _parent_poly_c_()"
918        cdef long i
919        cdef ZZ_c coeff
920        cdef ntl_ZZX _num
921        cdef ntl_ZZ _den
922        if isinstance(self.parent(), number_field.NumberField_relative):
923            # ugly temp code
924            f = self.parent().absolute_polynomial()
925
926            __den = f.denominator()
927            (<Integer>ZZ(__den))._to_ZZ(den)
928
929            __num = f * __den
930            for i from 0 <= i <= __num.degree():
931                (<Integer>ZZ(__num[i]))._to_ZZ(&coeff)
932                ZZX_SetCoeff( num[0], i, coeff )
933        else:
934            _num, _den = self.parent().polynomial_ntl()
935            num[0] = _num.x
936            den[0] = _den.x
937
938    cdef void _invert_c_(self, ZZX_c *num, ZZ_c *den):
939        """
940        Computes the numerator and denominator of the multiplicative inverse of this element.
941
942        Suppose that this element is x/d and the parent mod'ding polynomial is M/D.  The NTL function
943        XGCD( r, s, t, a, b ) computes r,s,t such that $r=s*a+t*b$.  We compute
944        XGCD( r, s, t, x*D, M*d ) and set
945        num=s*D*d
946        den=r
947
948        EXAMPLES:
949            I'd love to, but since we are dealing with c-types, I can't at this level.
950            Check __invert__ for doc-tests that rely on this functionality.
951        """
952        cdef ZZ_c parent_den
953        cdef ZZX_c parent_num
954        self._parent_poly_c_( &parent_num, &parent_den )
955
956        cdef ZZX_c t # unneeded except to be there
957        cdef ZZX_c a, b
958        mul_ZZX_ZZ( a, self.__numerator, parent_den )
959        mul_ZZX_ZZ( b, parent_num, self.__denominator )
960        XGCD_ZZX( den[0], num[0],  t, a, b, 1 )
961        mul_ZZX_ZZ( num[0], num[0], parent_den )
962        mul_ZZX_ZZ( num[0], num[0], self.__denominator )
963
964    def __invert__(self):
965        """
966        Returns the multiplicative inverse of self in the number field.
967
968        EXAMPLES:
969            sage: C.<I>=CyclotomicField(4)
970            sage: ~I
971            -I
972            sage: (2*I).__invert__()
973            -1/2*I
974        """
975        if IsZero_ZZX(self.__numerator):
976            raise ZeroDivisionError
977        cdef NumberFieldElement x
978        x = self._new()
979        self._invert_c_(&x.__numerator, &x.__denominator)
980        x._reduce_c_()
981        return x
982#        K = self.parent()
983#        quotient = K(1)._pari_('x') / self._pari_('x')
984#        if isinstance(K, sage.rings.number_field.number_field.NumberField_relative):
985#            return K(K.pari_rnf().rnfeltreltoabs(quotient))
986#        else:
987#            return K(quotient)
988
989    def _integer_(self):
990        """
991        Returns a rational integer if this element is actually a rational integer.
992
993        EXAMPLES:
994            sage: C.<I>=CyclotomicField(4)
995            sage: (~I)._integer_()
996            Traceback (most recent call last):
997            ...
998            TypeError: Unable to coerce -I to an integer
999            sage: (2*I*I)._integer_()
1000            -2
1001        """
1002        if ZZX_deg(self.__numerator) >= 1:
1003            raise TypeError, "Unable to coerce %s to an integer"%self
1004        return ZZ(self._rational_())
1005
1006    def _rational_(self):
1007        """
1008        Returns a rational number if this element is actually a rational number.
1009
1010        EXAMPLES:
1011            sage: C.<I>=CyclotomicField(4)
1012            sage: (~I)._rational_()
1013            Traceback (most recent call last):
1014            ...
1015            TypeError: Unable to coerce -I to a rational
1016            sage: (I*I/2)._rational_()
1017            -1/2
1018        """
1019        if ZZX_deg(self.__numerator) >= 1:
1020            raise TypeError, "Unable to coerce %s to a rational"%self
1021        cdef Integer num
1022        num = PY_NEW(Integer)
1023        ZZX_getitem_as_mpz(&num.value, &self.__numerator, 0)
1024        return num / (<IntegerRing_class>ZZ)._coerce_ZZ(&self.__denominator)
1025
1026    def galois_conjugates(self, K=None):
1027        r"""
1028        Return all Gal(Qbar/Q)-conjugates of this number field element in
1029        the Galois closure of the parent field if K is not given, or
1030        in K if K is given.
1031
1032        EXAMPLES:
1033        In the first example the conjugates are obvious:
1034            sage: K.<a> = NumberField(x^2 - 2)
1035            sage: a.galois_conjugates()
1036            [a, -a]
1037            sage: K(3).galois_conjugates()
1038            [3]
1039
1040        In this example the field is not Galois, so we have to pass
1041        to an extension to obtain the Galois conjugates.
1042            sage: K.<a> = NumberField(x^3 - 2)
1043            sage: a.galois_conjugates()
1044            [1/84*a1^4 + 13/42*a1, -1/252*a1^4 - 55/126*a1, -1/126*a1^4 + 8/63*a1]
1045            sage: K.<a> = NumberField(x^3 - 2)
1046            sage: c = a.galois_conjugates(); c
1047            [1/84*a1^4 + 13/42*a1, -1/252*a1^4 - 55/126*a1, -1/126*a1^4 + 8/63*a1]
1048            sage: c[0]^3
1049            2
1050            sage: parent(c[0])
1051            Number Field in a1 with defining polynomial x^6 + 40*x^3 + 1372
1052            sage: parent(c[0]).is_galois()
1053            True
1054
1055        There is only one Galois conjugate of $\sqrt[3]{2}$ in
1056        $\QQ(\sqrt[3]{2})$.
1057            sage: a.galois_conjugates(K)
1058            [a]
1059
1060        Galois conjugates of $\sqrt[3]{2}$ in the field $\QQ(\zeta_3,\sqrt[3]{2})$:
1061            sage: L.<a> = CyclotomicField(3).extension(x^3 - 2)
1062            sage: a.galois_conjugates()
1063            [a, (-zeta3 - 1)*a, zeta3*a]
1064        """
1065        if K is None:
1066            L = self.parent()
1067            K = L.galois_closure()
1068        f = self.absolute_minpoly()
1069        g = K['x'](f)
1070        return [a for a,_ in g.roots()]
1071
1072    def conjugate(self):
1073        """
1074        Return the complex conjugate of the number field element.  Currently,
1075        this is implemented for cyclotomic fields and quadratic extensions of Q. 
1076        It seems likely that there are other number fields for which the idea of
1077        a conjugate would be easy to compute.
1078
1079        EXAMPLES:
1080            sage: k.<I> = QuadraticField(-1)
1081            sage: I.conjugate()
1082            -I
1083            sage: (I/(1+I)).conjugate()
1084            -1/2*I + 1/2
1085            sage: z6=CyclotomicField(6).gen(0)
1086            sage: (2*z6).conjugate()
1087            -2*zeta6 + 2
1088
1089            sage: K.<b> = NumberField(x^3 - 2)
1090            sage: b.conjugate()
1091            Traceback (most recent call last):
1092            ...
1093            NotImplementedError: complex conjugation is not implemented (or doesn't make sense).
1094        """
1095        coeffs = self.parent().polynomial().list()
1096        if len(coeffs) == 3 and coeffs[2] == 1 and coeffs[1] == 0:
1097            # polynomial looks like x^2+d
1098            # i.e. we live in a quadratic extension of QQ
1099            if coeffs[0] > 0:
1100                gen = self.parent().gen()
1101                return self.polynomial()(-gen)
1102            else:
1103                return self
1104        elif isinstance(self.parent(), number_field.NumberField_cyclotomic):
1105            # We are in a cyclotomic field
1106            # Replace the generator zeta_n with (zeta_n)^(n-1)
1107            gen = self.parent().gen()
1108            return self.polynomial()(gen ** (gen.multiplicative_order()-1))
1109        else:
1110            raise NotImplementedError, "complex conjugation is not implemented (or doesn't make sense)."
1111
1112    def polynomial(self, var='x'):
1113        """
1114        Return the underlying polynomial corresponding to this
1115        number field element.
1116
1117        The resulting polynomial is currently *not* cached.
1118
1119        EXAMPLES:
1120            sage: K.<a> = NumberField(x^5 - x - 1)
1121            sage: f = (-2/3 + 1/3*a)^4; f
1122            1/81*a^4 - 8/81*a^3 + 8/27*a^2 - 32/81*a + 16/81
1123            sage: g = f.polynomial(); g
1124            1/81*x^4 - 8/81*x^3 + 8/27*x^2 - 32/81*x + 16/81
1125            sage: parent(g)
1126            Univariate Polynomial Ring in x over Rational Field
1127
1128        Note that the result of this function is not cached (should this
1129        be changed?):
1130            sage: g is f.polynomial()
1131            False       
1132        """
1133        return QQ[var](self._coefficients())
1134
1135    def _coefficients(self):
1136        """
1137        Return the coefficients of the underlying polynomial corresponding to this
1138        number field element.
1139
1140        OUTPUT:
1141             -- a list whose length corresponding to the degree of this element
1142                written in terms of a generator.
1143
1144        EXAMPLES:
1145           
1146        """
1147        coeffs = []
1148        cdef Integer den = (<IntegerRing_class>ZZ)._coerce_ZZ(&self.__denominator)
1149        cdef Integer numCoeff
1150        cdef int i
1151        for i from 0 <= i <= ZZX_deg(self.__numerator):
1152            numCoeff = PY_NEW(Integer)
1153            ZZX_getitem_as_mpz(&numCoeff.value, &self.__numerator, i)
1154            coeffs.append( numCoeff / den )
1155        return coeffs
1156       
1157    cdef void _ntl_coeff_as_mpz(self, mpz_t* z, long i):
1158        if i > ZZX_deg(self.__numerator):
1159            mpz_set_ui(z[0], 0)
1160        else:
1161            ZZX_getitem_as_mpz(z, &self.__numerator, i)
1162       
1163    cdef void _ntl_denom_as_mpz(self, mpz_t* z):
1164        cdef Integer denom = (<IntegerRing_class>ZZ)._coerce_ZZ(&self.__denominator)
1165        mpz_set(z[0], denom.value)
1166
1167    def denominator(self):
1168        """
1169        Return the denominator of this element, which is by definition
1170        the denominator of the corresponding polynomial
1171        representation.  I.e., elements of number fields are
1172        represented as a polynomial (in reduced form) modulo the
1173        modulus of the number field, and the denominator is the
1174        denominator of this polynomial.
1175
1176        EXAMPLES:
1177            sage: K.<z> = CyclotomicField(3)
1178            sage: a = 1/3 + (1/5)*z
1179            sage: print a.denominator()
1180            15
1181        """
1182        return (<IntegerRing_class>ZZ)._coerce_ZZ(&self.__denominator)
1183
1184    def _set_multiplicative_order(self, n):
1185        """
1186        Set the multiplicative order of this number field element.
1187
1188        WARNING -- use with caution -- only for internal use!  End
1189        users should never call this unless they have a very good
1190        reason to do so.
1191
1192        EXAMPLES:
1193            sage: K.<a> = NumberField(x^2 + x + 1)
1194            sage: a._set_multiplicative_order(3)
1195            sage: a.multiplicative_order()
1196            3
1197
1198        You can be evil with this so be careful.  That's why the function
1199        name begins with an underscore.
1200            sage: a._set_multiplicative_order(389)
1201            sage: a.multiplicative_order()
1202            389       
1203        """
1204        self.__multiplicative_order = n
1205
1206    def multiplicative_order(self):
1207        """
1208        Return the multiplicative order of this number field element.
1209
1210        EXAMPLES:
1211            sage: K.<z> = CyclotomicField(5)
1212            sage: z.multiplicative_order()
1213            5
1214            sage: (-z).multiplicative_order()
1215            10
1216            sage: (1+z).multiplicative_order()
1217            +Infinity       
1218        """
1219        if self.__multiplicative_order is not None:
1220            return self.__multiplicative_order
1221
1222        if self.is_rational_c():
1223            self.__multiplicative_order = self._rational_().multiplicative_order()
1224            return self.__multiplicative_order
1225
1226        if isinstance(self.parent(), number_field.NumberField_cyclotomic):
1227            t = self.parent()._multiplicative_order_table()
1228            f = self.polynomial()
1229            if t.has_key(f):
1230                self.__multiplicative_order = t[f]
1231                return self.__multiplicative_order
1232
1233        ####################################################################
1234        # VERY DUMB Algorithm to compute the multiplicative_order of
1235        # an element x of a number field K.
1236        #
1237        # 1. Find an integer B such that if n>=B then phi(n) > deg(K).
1238        #    For this use that for n>6 we have phi(n) >= log_2(n)
1239        #    (to see this think about the worst prime factorization
1240        #    in the multiplicative formula for phi.)
1241        # 2. Compute x, x^2, ..., x^B in order to determine the multiplicative_order.
1242        #
1243        # todo-- Alternative: Only do the above if we don't require an optional
1244        # argument which gives a multiple of the order, which is usually
1245        # something available in any actual application.
1246        #
1247        # BETTER TODO: Factor cyclotomic polynomials over K to determine
1248        # possible orders of elements?  Is there something even better?
1249        #
1250        ####################################################################
1251        d = self.parent().degree()
1252        B = max(7, 2**d+1)
1253        x = self
1254        i = 1
1255        while i < B:
1256            if x == 1:
1257                self.__multiplicative_order = i
1258                return self.__multiplicative_order
1259            x *= self
1260            i += 1
1261
1262        # it must have infinite order
1263        self.__multiplicative_order = sage.rings.infinity.infinity
1264        return self.__multiplicative_order
1265
1266    cdef bint is_rational_c(self):
1267        return ZZX_deg(self.__numerator) == 0
1268               
1269    def trace(self, K=None):
1270        """
1271        Return the absolute or relative trace of this number field
1272        element.
1273
1274        If K is given then K must be a subfield of the parent L of
1275        self, in which case the trace is the relative trace from L to K.
1276        In all other cases, the trace is the absolute trace down to QQ.
1277
1278        EXAMPLES:
1279            sage: K.<a> = NumberField(x^3 -132/7*x^2 + x + 1); K
1280            Number Field in a with defining polynomial x^3 - 132/7*x^2 + x + 1
1281            sage: a.trace()
1282            132/7
1283            sage: (a+1).trace() == a.trace() + 3
1284            True       
1285        """
1286        if K is None:
1287            return QQ(self._pari_('x').trace())
1288        return self.matrix(K).trace()
1289
1290    def norm(self, K=None):
1291        """
1292        Return the absolute or relative norm of this number field
1293        element.
1294
1295        If K is given then K must be a subfield of the parent L of
1296        self, in which case the norm is the relative norm from L to K.
1297        In all other cases, the norm is the absolute norm down to QQ.
1298
1299        EXAMPLES:
1300            sage: K.<a> = NumberField(x^3 + x^2 + x + -132/7); K
1301            Number Field in a with defining polynomial x^3 + x^2 + x - 132/7
1302            sage: a.norm()
1303            132/7
1304            sage: factor(a.norm())
1305            2^2 * 3 * 7^-1 * 11
1306            sage: K(0).norm()
1307            0
1308
1309        Some complicated relatives norms in a tower of number fields.
1310            sage: K.<a,b,c> = NumberField([x^2 + 1, x^2 + 3, x^2 + 5])
1311            sage: L = K.base_field(); M = L.base_field()
1312            sage: a.norm()
1313            1
1314            sage: a.norm(L)
1315            1
1316            sage: a.norm(M)
1317            1
1318            sage: a
1319            a
1320            sage: (a+b+c).norm()
1321            121
1322            sage: (a+b+c).norm(L)
1323            2*c*b + -7
1324            sage: (a+b+c).norm(M)
1325            -11
1326
1327        We illustrate that norm is compatible with towers:
1328            sage: z = (a+b+c).norm(L); z.norm(M)
1329            -11
1330        """
1331        if K is None:
1332            return QQ(self._pari_('x').norm())
1333        return self.matrix(K).determinant()
1334
1335    def charpoly(self, var='x'):
1336        raise NotImplementedError, "Subclasses of NumberFieldElement must override charpoly()"
1337
1338    def minpoly(self, var='x'):
1339        """
1340        Return the minimal polynomial of this number field element.
1341
1342        EXAMPLES:
1343            sage: K.<a> = NumberField(x^2+3)
1344            sage: a.minpoly('x')
1345            x^2 + 3
1346            sage: R.<X> = K['X']
1347            sage: L.<b> = K.extension(X^2-(22 + a))
1348            sage: b.minpoly('t')
1349            t^2 + -a - 22
1350            sage: b.absolute_minpoly('t')
1351            t^4 - 44*t^2 + 487
1352            sage: b^2 - (22+a)
1353            0       
1354        """
1355        return self.charpoly(var).radical() # square free part of charpoly
1356
1357    def is_integral(self):
1358        r"""
1359        Determine if a number is in the ring of integers
1360        of this number field.
1361       
1362        EXAMPLES:
1363            sage: K.<a> = NumberField(x^2 + 23)
1364            sage: a.is_integral()
1365            True
1366            sage: t = (1+a)/2
1367            sage: t.is_integral()
1368            True
1369            sage: t.minpoly()
1370            x^2 - x + 6
1371            sage: t = a/2
1372            sage: t.is_integral()
1373            False
1374            sage: t.minpoly()
1375            x^2 + 23/4
1376
1377        An example in a relative extension:
1378            sage: K.<a,b> = NumberField([x^2+1, x^2+3])
1379            sage: (a+b).is_integral()
1380            True
1381            sage: ((a-b)/2).is_integral()
1382            False
1383        """
1384        return all([a in ZZ for a in self.absolute_minpoly()])
1385
1386    def matrix(self, base=None):
1387        r"""
1388        If base is None, return the matrix of right multiplication by
1389        the element on the power basis $1, x, x^2, \ldots, x^{d-1}$
1390        for the number field.  Thus the {\em rows} of this matrix give
1391        the images of each of the $x^i$.
1392
1393        If base is not None, then base must be either a field that
1394        embeds in the parent of self or a morphism to the parent of
1395        self, in which case this function returns the matrix of
1396        multiplication by self on the power basis, where we view the
1397        parent field as a field over base.
1398
1399        INPUT:
1400            base -- field or morphism
1401
1402        EXAMPLES:
1403        Regular number field:
1404            sage: K.<a> = NumberField(QQ['x'].0^3 - 5)
1405            sage: M = a.matrix(); M
1406            [0 1 0]
1407            [0 0 1]
1408            [5 0 0]
1409            sage: M.base_ring() is QQ
1410            True
1411
1412        Relative number field:
1413            sage: L.<b> = K.extension(K['x'].0^2 - 2)
1414            sage: M = b.matrix(); M
1415            [0 1]
1416            [2 0]
1417            sage: M.base_ring() is K
1418            True
1419
1420        Absolute number field:
1421            sage: M = L.absolute_field('c').gen().matrix(); M
1422            [  0   1   0   0   0   0]
1423            [  0   0   1   0   0   0]
1424            [  0   0   0   1   0   0]
1425            [  0   0   0   0   1   0]
1426            [  0   0   0   0   0   1]
1427            [-17 -60 -12 -10   6   0]
1428            sage: M.base_ring() is QQ
1429            True
1430
1431        More complicated relative number field:
1432            sage: L.<b> = K.extension(K['x'].0^2 - a); L
1433            Number Field in b with defining polynomial x^2 + -a over its base field
1434            sage: M = b.matrix(); M
1435            [0 1]
1436            [a 0]
1437            sage: M.base_ring() is K
1438            True
1439
1440        An example where we explicitly give the subfield or the embedding:
1441            sage: K.<a> = NumberField(x^4 + 1); L.<a2> = NumberField(x^2 + 1)
1442            sage: a.matrix(L)
1443            [ 0  1]
1444            [a2  0]
1445
1446        Notice that if we compute all embeddings and choose a different one,
1447        then the matrix is changed as it should be:
1448            sage: v = L.embeddings(K)
1449            sage: a.matrix(v[1])
1450            [  0   1]
1451            [-a2   0]
1452
1453        The norm is also changed:
1454            sage: a.norm(v[1])
1455            a2
1456            sage: a.norm(v[0])
1457            -a2
1458        """
1459        if base is not None:
1460            if number_field.is_NumberField(base):
1461                return self._matrix_over_base(base)
1462            else:
1463                return self._matrix_over_base_morphism(base)
1464        # Mutiply each power of field generator on
1465        # the left by this element; make matrix
1466        # whose rows are the coefficients of the result,
1467        # and transpose.
1468        if self.__matrix is None:
1469            K = self.parent()
1470            v = []
1471            x = K.gen()
1472            a = K(1)
1473            d = K.degree()
1474            for n in range(d):
1475                v += (a*self).list()
1476                a *= x
1477            k = K.base_ring()
1478            import sage.matrix.matrix_space
1479            M = sage.matrix.matrix_space.MatrixSpace(k, d)
1480            self.__matrix = M(v)
1481        return self.__matrix
1482
1483    def valuation(self, P):
1484        """
1485        Returns the valuation of self at a given prime ideal P.
1486
1487        INPUT:
1488           P -- a prime ideal of the parent of self
1489       
1490        EXAMPLES:
1491        sage: R.<x> = QQ[]
1492        sage: K.<a> = NumberField(x^4+3*x^2-17)
1493        sage: P = K.ideal(61).factor()[0][0]
1494        sage: b = a^2 + 30
1495        sage: b.valuation(P)
1496        1
1497        """
1498        from number_field_ideal import is_NumberFieldIdeal
1499        if not is_NumberFieldIdeal(P):
1500            if is_NumberFieldElement(P):
1501                P = self.parent().ideal(P)
1502            else:
1503                raise TypeError, "P must be an ideal"
1504        if not P.is_prime():
1505            # We always check this because it caches the pari prime representation of this ideal.
1506            raise ValueError, "P must be prime"
1507        return self.parent()._pari_().elementval(self._pari_(), P._pari_prime)
1508
1509    def _matrix_over_base(self, L):
1510        K = self.parent()
1511        E = L.embeddings(K)
1512        if len(E) == 0:
1513            raise ValueError, "no way to embed L into parent's base ring K"
1514        phi = E[0]
1515        return self._matrix_over_base_morphism(phi)
1516
1517    def _matrix_over_base_morphism(self, phi):
1518        L = phi.domain()
1519        alpha = L.primitive_element()
1520        beta = phi(alpha)
1521        K = phi.codomain()
1522        if K != self.parent():
1523            raise ValueError, "codomain of phi must be parent of self"
1524
1525        # Construct a relative extension over L (= QQ(beta))
1526        M = K.relativize(beta, ('a','b'))
1527                     # variable name a is OK, since this is temporary
1528
1529        # Carry self over to M.
1530        from_M, to_M = M.structure()
1531        try:
1532            z = to_M(self)
1533        except Exception:
1534            return to_M, self, K, beta
1535
1536        # Compute the relative matrix of self, but in M
1537        R = z.matrix()
1538
1539        # Map back to L.
1540        psi = M.base_field().hom([alpha])
1541        return R.apply_morphism(psi)
1542       
1543
1544    def list(self):
1545        """
1546        Return list of coefficients of self written in terms of a power basis.
1547        """
1548        # Power basis list is total nonsense, unless the parent of self is an
1549        # absolute extension.
1550        raise NotImplementedError
1551       
1552       
1553cdef class NumberFieldElement_absolute(NumberFieldElement):
1554
1555    def _pari_(self, var='x'):
1556        """
1557        Return PARI C-library object corresponding to self.
1558
1559        EXAMPLES:
1560            sage: k.<j> = QuadraticField(-1)
1561            sage: j._pari_('j')
1562            Mod(j, j^2 + 1)
1563            sage: pari(j)
1564            Mod(x, x^2 + 1)
1565
1566            sage: y = QQ['y'].gen()
1567            sage: k.<j> = NumberField(y^3 - 2)
1568            sage: pari(j)
1569            Mod(x, x^3 - 2)
1570
1571        By default the variable name is 'x', since in PARI many variable
1572        names are reserved:
1573            sage: theta = polygen(QQ, 'theta')
1574            sage: M.<theta> = NumberField(theta^2 + 1)
1575            sage: pari(theta)
1576            Mod(x, x^2 + 1)
1577
1578        If you try do coerce a generator called I to PARI, hell may
1579        break loose:
1580            sage: k.<I> = QuadraticField(-1)
1581            sage: I._pari_('I')
1582            Traceback (most recent call last):
1583            ...
1584            PariError: forbidden (45)
1585
1586        Instead, request the variable be named different for the coercion:
1587            sage: pari(I)
1588            Mod(x, x^2 + 1)
1589            sage: I._pari_('i')
1590            Mod(i, i^2 + 1)
1591            sage: I._pari_('II')
1592            Mod(II, II^2 + 1)
1593        """
1594        try:
1595            return self.__pari[var]
1596        except KeyError:
1597            pass
1598        except TypeError:
1599            self.__pari = {}
1600        if var is None:
1601            var = self.parent().variable_name()
1602        f = self.polynomial()._pari_()
1603        gp = self.parent().polynomial()
1604        if gp.name() != 'x':
1605            gp = gp.change_variable_name('x')
1606        g = gp._pari_()
1607        gv = str(gp.parent().gen())
1608        if var != 'x':
1609            f = f.subst("x",var)
1610        if var != gv:
1611            g = g.subst(gv, var)
1612        h = f.Mod(g)
1613        self.__pari[var] = h
1614        return h
1615       
1616    cdef void _parent_poly_c_(self, ZZX_c *num, ZZ_c *den):
1617        cdef ntl_ZZX _num
1618        cdef ntl_ZZ _den
1619        _num, _den = self.parent().polynomial_ntl()
1620        num[0] = _num.x
1621        den[0] = _den.x
1622
1623    def absolute_charpoly(self, var='x'):
1624        r"""
1625        Return the characteristic polynomial of this element over $\QQ$.
1626        """
1627        return self.charpoly(var=var)
1628
1629    def absolute_minpoly(self, var='x'):
1630        r"""
1631        Return the minimal polynomial of this element over $\QQ$.
1632
1633        EXAMPLES:
1634
1635       
1636        """
1637        return self.minpoly(var=var)
1638
1639    def charpoly(self, var='x'):
1640        r"""
1641        The characteristic polynomial of this element over $\QQ$.
1642
1643        This is the same as \code{self.absolute_charpoly} since this
1644        is an element of an absolute extension.
1645
1646        EXAMPLES:
1647
1648        We compute the charpoly of cube root of $2$.
1649
1650            sage: R.<x> = QQ[]
1651            sage: K.<a> = NumberField(x^3-2)
1652            sage: a.charpoly('x')
1653            x^3 - 2
1654
1655        """
1656        R = self.parent().base_ring()[var]
1657        return R(self._pari_('x').charpoly())
1658       
1659    def list(self):
1660        """
1661        Return list of coefficients of self written in terms of a power basis.
1662       
1663        EXAMPLE:
1664            sage: K.<z> = CyclotomicField(3)
1665            sage: (2+3/5*z).list()
1666            [2, 3/5]
1667            sage: (5*z).list()
1668            [0, 5]
1669            sage: K(3).list()
1670            [3, 0]
1671        """
1672        n = self.parent().degree()
1673        v = self._coefficients()
1674        z = sage.rings.rational.Rational(0)
1675        return v + [z]*(n - len(v))
1676       
1677               
1678
1679cdef class NumberFieldElement_relative(NumberFieldElement):
1680    def list(self):
1681        """
1682        Return list of coefficients of self written in terms of a
1683        power basis.
1684
1685        EXAMPLES:
1686            sage: K.<a,b> = NumberField([x^3+2, x^2+1])
1687            sage: a.list()
1688            [0, 1, 0]
1689            sage: v = (K.base_field().0 + a)^2 ; v
1690            a^2 + 2*b*a + -1
1691            sage: v.list()
1692            [-1, 2*b, 1]
1693        """
1694        return self.vector().list()
1695
1696    def _pari_(self, var='x'):
1697        """
1698        Return PARI C-library object corresponding to self.
1699
1700        EXAMPLES:
1701        By default the variable name is 'x', since in PARI many variable
1702        names are reserved.
1703            sage: y = QQ['y'].gen()
1704            sage: k.<j> = NumberField([y^2 - 7, y^3 - 2])
1705            sage: pari(j)
1706            Mod(42/5515*x^5 - 9/11030*x^4 - 196/1103*x^3 + 273/5515*x^2 + 10281/5515*x + 4459/11030, x^6 - 21*x^4 + 4*x^3 + 147*x^2 + 84*x - 339)
1707            sage: j^2
1708            7
1709            sage: pari(j)^2
1710            Mod(7, x^6 - 21*x^4 + 4*x^3 + 147*x^2 + 84*x - 339)
1711        """
1712        try:
1713            return self.__pari[var]
1714        except KeyError:
1715            pass
1716        except TypeError:
1717            self.__pari = {}
1718        if var is None:
1719            var = self.parent().variable_name()
1720        f = self.polynomial()._pari_()
1721        g = str(self.parent().pari_polynomial())
1722        base = self.parent().base_ring()
1723        gsub = base.gen()._pari_()
1724        gsub = str(gsub).replace('x', 'y')
1725        g = g.replace('y', gsub)
1726        h = f.Mod(g)
1727        self.__pari[var] = h
1728        return h
1729       
1730    cdef void _parent_poly_c_(self, ZZX_c *num, ZZ_c *den):
1731        cdef long i
1732        cdef ZZ_c coeff
1733        cdef ntl_ZZX _num
1734        cdef ntl_ZZ _den
1735        # ugly temp code
1736        f = self.parent().absolute_polynomial()
1737
1738        __den = f.denominator()
1739        (<Integer>ZZ(__den))._to_ZZ(den)
1740
1741        __num = f * __den
1742        for i from 0 <= i <= __num.degree():
1743            (<Integer>ZZ(__num[i]))._to_ZZ(&coeff)
1744            ZZX_SetCoeff( num[0], i, coeff )
1745
1746    def __repr__(self):
1747        K = self.parent()
1748        # Compute representation of self in terms of relative vector space.
1749        w = self.vector()
1750        R = K.base_field()[K.variable_name()]
1751        return repr(R(w.list()))
1752
1753    def vector(self):
1754        return self.parent().vector_space()[2](self)
1755
1756    def charpoly(self, var='x'):
1757        r"""
1758        The characteristic polynomial of this element over its base field.
1759
1760        EXAMPLES:
1761       
1762        """
1763        return self.matrix().charpoly(var)
1764
1765    def absolute_charpoly(self, var='x'):
1766        r"""
1767        The characteristic polynomial of this element over $\QQ$.
1768
1769        We construct a relative extension and find the characteristic
1770        polynomial over $\QQ$.
1771
1772        EXAMPLES:
1773            sage: R.<x> = QQ[]
1774            sage: K.<a> = NumberField(x^3-2)
1775            sage: S.<X> = K[]
1776            sage: L.<b> = NumberField(X^3 + 17); L
1777            Number Field in b with defining polynomial X^3 + 17 over its base field
1778            sage: b.absolute_charpoly()
1779            x^9 + 51*x^6 + 867*x^3 + 4913
1780            sage: b.charpoly()(b)
1781            0
1782            sage: a = L.0; a
1783            b
1784            sage: a.absolute_charpoly('x')
1785            x^9 + 51*x^6 + 867*x^3 + 4913
1786            sage: a.absolute_charpoly('y')
1787            y^9 + 51*y^6 + 867*y^3 + 4913
1788        """
1789        g = self.polynomial()  # in QQ[x]
1790        R = g.parent()
1791        f = self.parent().pari_polynomial()  # # field is QQ[x]/(f)
1792        return R( (g._pari_().Mod(f)).charpoly() ).change_variable_name(var)
1793
1794    def absolute_minpoly(self, var='x'):
1795        r"""
1796        Return the minpoly over $\QQ$ of this element.
1797       
1798        EXAMPLES:
1799        """
1800        return self.absolute_charpoly(var).radical()
1801
1802## This might be useful for computing relative charpoly.
1803## BUT -- currently I don't even know how to view elements
1804## as being in terms of the right thing, i.e., this code
1805## below as is lies.
1806##             nf = self.parent()._pari_base_nf()
1807##             prp = self.parent().pari_relative_polynomial()
1808##             elt = str(self.polynomial()._pari_())
1809##             return R(nf.rnfcharpoly(prp, elt))
1810##         # return self.matrix().charpoly('x')
1811
1812
1813cdef class OrderElement_absolute(NumberFieldElement_absolute):
1814    """
1815    Element of an order in an absolute number field.
1816
1817    EXAMPLES:
1818        sage: k.<a> = NumberField(x^2 + 1)
1819    """
1820    def __init__(self, order, f):
1821        K = order.number_field()
1822        NumberFieldElement_absolute.__init__(self, K, f)
1823        self._order = order
1824        (<Element>self)._parent = order
1825
1826cdef class OrderElement_relative(NumberFieldElement_relative):
1827    """
1828    Element of an order in a relative number field.
1829    """
1830    def __init__(self, order, f):
1831        K = order.number_field()
1832        NumberFieldElement_relative.__init__(self, K, f)
1833        self._order = order
1834        (<Element>self)._parent = order
1835
1836
1837
1838class CoordinateFunction:
1839    def __init__(self, alpha, W, to_V):
1840        self.__alpha = alpha
1841        self.__W = W
1842        self.__to_V = to_V
1843        self.__K = alpha.parent()
1844
1845    def __repr__(self):
1846        return "Coordinate function that writes elements in terms of the powers of %s"%self.__alpha
1847
1848    def alpha(self):
1849        return self.__alpha
1850
1851    def __call__(self, x):
1852        return self.__W.coordinates(self.__to_V(self.__K(x)))
1853   
Note: See TracBrowser for help on using the repository browser.