Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download
Project: Math 582b
Views: 2495
1
"""
2
Number Field Elements
3
4
AUTHORS:
5
6
- William Stein: version before it got Cython'd
7
8
- Joel B. Mohler (2007-03-09): First reimplementation in Cython
9
10
- William Stein (2007-09-04): add doctests
11
12
- Robert Bradshaw (2007-09-15): specialized classes for relative and
13
absolute elements
14
15
- John Cremona (2009-05-15): added support for local and global
16
logarithmic heights.
17
18
- Robert Harron (2012-08): conjugate() now works for all fields contained in
19
CM fields
20
21
"""
22
#*****************************************************************************
23
# Copyright (C) 2004, 2007 William Stein <[email protected]>
24
#
25
# Distributed under the terms of the GNU General Public License (GPL)
26
# as published by the Free Software Foundation; either version 2 of
27
# the License, or (at your option) any later version.
28
# http://www.gnu.org/licenses/
29
#*****************************************************************************
30
31
import operator
32
33
include 'sage/ext/interrupt.pxi'
34
from cpython.int cimport *
35
include "sage/ext/stdsage.pxi"
36
37
from sage.libs.gmp.mpz cimport *
38
from sage.libs.gmp.mpq cimport *
39
40
import sage.rings.infinity
41
import sage.rings.polynomial.polynomial_element
42
import sage.rings.rational_field
43
import sage.rings.rational
44
import sage.rings.integer_ring
45
import sage.rings.integer
46
import sage.rings.arith
47
48
import number_field
49
50
from sage.rings.integer_ring cimport IntegerRing_class
51
from sage.rings.rational cimport Rational
52
from sage.rings.infinity import infinity
53
from sage.categories.fields import Fields
54
55
from sage.modules.free_module_element import vector
56
57
from sage.libs.pari.all import pari_gen
58
from sage.libs.pari.pari_instance cimport PariInstance
59
60
from sage.structure.element cimport Element, generic_power_c, FieldElement
61
from sage.structure.element import canonical_coercion, parent, coerce_binop
62
63
cdef PariInstance pari = sage.libs.pari.pari_instance.pari
64
65
QQ = sage.rings.rational_field.QQ
66
ZZ = sage.rings.integer_ring.ZZ
67
Integer_sage = sage.rings.integer.Integer
68
69
from sage.rings.real_mpfi import RealInterval
70
71
from sage.rings.complex_field import ComplexField
72
CC = ComplexField(53)
73
74
# this is a threshold for the charpoly() methods in this file
75
# for degrees <= this threshold, pari is used
76
# for degrees > this threshold, sage matrices are used
77
# the value was decided by running a tuning script on a number of
78
# architectures; you can find this script attached to trac
79
# ticket 5213
80
TUNE_CHARPOLY_NF = 25
81
82
def is_NumberFieldElement(x):
83
"""
84
Return True if x is of type NumberFieldElement, i.e., an element of
85
a number field.
86
87
EXAMPLES::
88
89
sage: from sage.rings.number_field.number_field_element import is_NumberFieldElement
90
sage: is_NumberFieldElement(2)
91
False
92
sage: k.<a> = NumberField(x^7 + 17*x + 1)
93
sage: is_NumberFieldElement(a+1)
94
True
95
"""
96
return isinstance(x, NumberFieldElement)
97
98
def __create__NumberFieldElement_version0(parent, poly):
99
"""
100
Used in unpickling elements of number fields pickled under very old Sage versions.
101
102
EXAMPLE::
103
104
sage: k.<a> = NumberField(x^3 - 2)
105
sage: R.<z> = QQ[]
106
sage: sage.rings.number_field.number_field_element.__create__NumberFieldElement_version0(k, z^2 + z + 1)
107
a^2 + a + 1
108
"""
109
return NumberFieldElement(parent, poly)
110
111
def __create__NumberFieldElement_version1(parent, cls, poly):
112
"""
113
Used in unpickling elements of number fields.
114
115
EXAMPLES:
116
117
Since this is just used in unpickling, we unpickle.
118
119
::
120
121
sage: k.<a> = NumberField(x^3 - 2)
122
sage: loads(dumps(a+1)) == a + 1 # indirect doctest
123
True
124
125
This also gets called for unpickling order elements; we check that #6462 is
126
fixed::
127
128
sage: L = NumberField(x^3 - x - 1,'a'); OL = L.maximal_order(); w = OL.0
129
sage: loads(dumps(w)) == w # indirect doctest
130
True
131
"""
132
return cls(parent, poly)
133
134
def _inverse_mod_generic(elt, I):
135
r"""
136
Return an inverse of elt modulo the given ideal. This is a separate
137
function called from each of the OrderElement_xxx classes, since
138
otherwise we'd have to have the same code three times over (there
139
is no OrderElement_generic class - no multiple inheritance). See
140
trac 4190.
141
142
EXAMPLES::
143
144
sage: OE = NumberField(x^3 - x + 2, 'w').ring_of_integers()
145
sage: w = OE.ring_generators()[0]
146
sage: from sage.rings.number_field.number_field_element import _inverse_mod_generic
147
sage: _inverse_mod_generic(w, 13*OE)
148
6*w^2 - 6
149
"""
150
from sage.matrix.constructor import matrix
151
R = elt.parent()
152
try:
153
I = R.ideal(I)
154
except ValueError:
155
raise ValueError, "inverse is only defined modulo integral ideals"
156
if I == 0:
157
raise ValueError, "inverse is not defined modulo the zero ideal"
158
n = R.absolute_degree()
159
m = matrix(ZZ, map(R.coordinates, I.integral_basis() + [elt*s for s in R.gens()]))
160
a, b = m.echelon_form(transformation=True)
161
if a[0:n] != 1:
162
raise ZeroDivisionError, "%s is not invertible modulo %s" % (elt, I)
163
v = R.coordinates(1)
164
y = R(0)
165
for j in xrange(n):
166
if v[j] != 0:
167
y += v[j] * sum([b[j,i+n] * R.gen(i) for i in xrange(n)])
168
return I.small_residue(y)
169
170
__pynac_pow = False
171
172
cdef class NumberFieldElement(FieldElement):
173
"""
174
An element of a number field.
175
176
EXAMPLES::
177
178
sage: k.<a> = NumberField(x^3 + x + 1)
179
sage: a^3
180
-a - 1
181
"""
182
cdef _new(self):
183
"""
184
Quickly creates a new initialized NumberFieldElement with the same
185
parent as self.
186
"""
187
cdef type t = type(self)
188
cdef NumberFieldElement x = <NumberFieldElement>t.__new__(t)
189
x._parent = self._parent
190
x.__fld_numerator = self.__fld_numerator
191
x.__fld_denominator = self.__fld_denominator
192
return x
193
194
cdef number_field(self):
195
r"""
196
197
Return the number field of self. Only accessible from Cython.
198
EXAMPLE::
199
200
sage: K.<a> = NumberField(x^3 + 3)
201
sage: a._number_field() # indirect doctest
202
Number Field in a with defining polynomial x^3 + 3
203
"""
204
return self._parent
205
206
def _number_field(self):
207
r"""
208
EXAMPLE::
209
210
sage: K.<a> = NumberField(x^3 + 3)
211
sage: a._number_field()
212
Number Field in a with defining polynomial x^3 + 3
213
"""
214
return self.number_field()
215
216
def __init__(self, parent, f):
217
"""
218
INPUT:
219
220
221
- ``parent`` - a number field
222
223
- ``f`` - defines an element of a number field.
224
225
226
EXAMPLES:
227
228
The following examples illustrate creation of elements of
229
number fields, and some basic arithmetic.
230
231
First we define a polynomial over Q::
232
233
sage: R.<x> = PolynomialRing(QQ)
234
sage: f = x^2 + 1
235
236
Next we use f to define the number field::
237
238
sage: K.<a> = NumberField(f); K
239
Number Field in a with defining polynomial x^2 + 1
240
sage: a = K.gen()
241
sage: a^2
242
-1
243
sage: (a+1)^2
244
2*a
245
sage: a^2
246
-1
247
sage: z = K(5); 1/z
248
1/5
249
250
We create a cube root of 2::
251
252
sage: K.<b> = NumberField(x^3 - 2)
253
sage: b = K.gen()
254
sage: b^3
255
2
256
sage: (b^2 + b + 1)^3
257
12*b^2 + 15*b + 19
258
259
This example illustrates save and load::
260
261
sage: K.<a> = NumberField(x^17 - 2)
262
sage: s = a^15 - 19*a + 3
263
sage: loads(s.dumps()) == s
264
True
265
"""
266
FieldElement.__init__(self, parent)
267
self.__fld_numerator, self.__fld_denominator = parent.absolute_polynomial_ntl()
268
269
cdef ZZ_c coeff
270
if isinstance(f, (int, long, Integer_sage)):
271
# set it up and exit immediately
272
# fast pathway
273
(<Integer>ZZ(f))._to_ZZ(&coeff)
274
ZZX_SetCoeff( self.__numerator, 0, coeff )
275
ZZ_conv_from_int( self.__denominator, 1 )
276
return
277
elif isinstance(f, NumberFieldElement):
278
if type(self) is type(f):
279
self.__numerator = (<NumberFieldElement>f).__numerator
280
self.__denominator = (<NumberFieldElement>f).__denominator
281
return
282
else:
283
f = f.polynomial()
284
285
modulus = parent.absolute_polynomial()
286
f = modulus.parent()(f)
287
if f.degree() >= modulus.degree():
288
f %= modulus
289
290
cdef long i
291
den = f.denominator()
292
(<Integer>ZZ(den))._to_ZZ(&self.__denominator)
293
num = f * den
294
for i from 0 <= i <= num.degree():
295
(<Integer>ZZ(num[i]))._to_ZZ(&coeff)
296
ZZX_SetCoeff( self.__numerator, i, coeff )
297
298
def _lift_cyclotomic_element(self, new_parent, bint check=True, int rel=0):
299
"""
300
Creates an element of the passed field from this field. This is
301
specific to creating elements in a cyclotomic field from elements
302
in another cyclotomic field, in the case that
303
self.number_field()._n() divides new_parent()._n(). This
304
function aims to make this common coercion extremely fast!
305
306
More general coercion (i.e. of zeta6 into CyclotomicField(3)) is
307
implemented in the _coerce_from_other_cyclotomic_field method
308
of a CyclotomicField.
309
310
EXAMPLES::
311
312
sage: C.<zeta5>=CyclotomicField(5)
313
sage: CyclotomicField(10)(zeta5+1) # The function _lift_cyclotomic_element does the heavy lifting in the background
314
zeta10^2 + 1
315
sage: (zeta5+1)._lift_cyclotomic_element(CyclotomicField(10)) # There is rarely a purpose to call this function directly
316
zeta10^2 + 1
317
sage: cf4 = CyclotomicField(4)
318
sage: cf1 = CyclotomicField(1) ; one = cf1.0
319
sage: cf4(one)
320
1
321
sage: type(cf4(1))
322
<type 'sage.rings.number_field.number_field_element_quadratic.NumberFieldElement_quadratic'>
323
sage: cf33 = CyclotomicField(33) ; z33 = cf33.0
324
sage: cf66 = CyclotomicField(66) ; z66 = cf66.0
325
sage: z33._lift_cyclotomic_element(cf66)
326
zeta66^2
327
sage: z66._lift_cyclotomic_element(cf33)
328
Traceback (most recent call last):
329
...
330
TypeError: The zeta_order of the new field must be a multiple of the zeta_order of the original.
331
sage: cf33(z66)
332
-zeta33^17
333
334
AUTHORS:
335
336
- Joel B. Mohler
337
338
- Craig Citro (fixed behavior for different representation of
339
quadratic field elements)
340
"""
341
if check:
342
if not isinstance(self.number_field(), number_field.NumberField_cyclotomic) \
343
or not isinstance(new_parent, number_field.NumberField_cyclotomic):
344
raise TypeError, "The field and the new parent field must both be cyclotomic fields."
345
346
if rel == 0:
347
small_order = self.number_field()._n()
348
large_order = new_parent._n()
349
350
try:
351
rel = ZZ(large_order / small_order)
352
except TypeError:
353
raise TypeError, "The zeta_order of the new field must be a multiple of the zeta_order of the original."
354
355
## degree 2 is handled differently, because elements are
356
## represented differently
357
if new_parent.degree() == 2:
358
if rel == 1:
359
return new_parent._element_class(new_parent, self)
360
else:
361
return self.polynomial()(new_parent.gen()**rel)
362
363
cdef type t = type(self)
364
cdef NumberFieldElement x = <NumberFieldElement>t.__new__(t)
365
x._parent = <ParentWithBase>new_parent
366
x.__fld_numerator, x.__fld_denominator = new_parent.polynomial_ntl()
367
x.__denominator = self.__denominator
368
cdef ZZX_c result
369
cdef ZZ_c tmp
370
cdef int i
371
cdef ntl_ZZX _num
372
cdef ntl_ZZ _den
373
for i from 0 <= i <= ZZX_deg(self.__numerator):
374
tmp = ZZX_coeff(self.__numerator, i)
375
ZZX_SetCoeff(result, i*rel, tmp)
376
ZZX_rem(x.__numerator, result, x.__fld_numerator.x)
377
return x
378
379
def __reduce__(self):
380
"""
381
Used in pickling number field elements.
382
383
Note for developers: If this is changed, please also change the doctests of __create__NumberFieldElement_version1.
384
385
EXAMPLES::
386
387
sage: k.<a> = NumberField(x^3 - 17*x^2 + 1)
388
sage: t = a.__reduce__(); t
389
(<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))
390
sage: t[0](*t[1]) == a
391
True
392
"""
393
return __create__NumberFieldElement_version1, \
394
(self.parent(), type(self), self.polynomial())
395
396
def _repr_(self):
397
"""
398
String representation of this number field element, which is just a
399
polynomial in the generator.
400
401
EXAMPLES::
402
403
sage: k.<a> = NumberField(x^2 + 2)
404
sage: b = (2/3)*a + 3/5
405
sage: b._repr_()
406
'2/3*a + 3/5'
407
"""
408
x = self.polynomial()
409
K = self.number_field()
410
return str(x).replace(x.parent().variable_name(), K.variable_name())
411
412
def _im_gens_(self, codomain, im_gens):
413
"""
414
This is used in computing homomorphisms between number fields.
415
416
EXAMPLES::
417
418
sage: k.<a> = NumberField(x^2 - 2)
419
sage: m.<b> = NumberField(x^4 - 2)
420
sage: phi = k.hom([b^2])
421
sage: phi(a+1)
422
b^2 + 1
423
sage: (a+1)._im_gens_(m, [b^2])
424
b^2 + 1
425
"""
426
# NOTE -- if you ever want to change this so relative number
427
# fields are in terms of a root of a poly. The issue is that
428
# elements of a relative number field are represented in terms
429
# of a generator for the absolute field. However the morphism
430
# gives the image of gen, which need not be a generator for
431
# the absolute field. The morphism has to be *over* the
432
# relative element.
433
return codomain(self.polynomial()(im_gens[0]))
434
435
def _latex_(self):
436
"""
437
Returns the latex representation for this element.
438
439
EXAMPLES::
440
441
sage: C.<zeta12> = CyclotomicField(12)
442
sage: latex(zeta12^4-zeta12) # indirect doctest
443
\zeta_{12}^{2} - \zeta_{12} - 1
444
"""
445
return self.polynomial()._latex_(name=self.number_field().latex_variable_name())
446
447
def _gap_init_(self):
448
"""
449
Return gap string representation of self.
450
451
EXAMPLES::
452
453
sage: F=CyclotomicField(8)
454
sage: F.gen()
455
zeta8
456
sage: F._gap_init_()
457
'CyclotomicField(8)'
458
sage: f = gap(F)
459
sage: f.GeneratorsOfDivisionRing()
460
[ E(8) ]
461
sage: p=F.gen()^2+2*F.gen()-3
462
sage: p
463
zeta8^2 + 2*zeta8 - 3
464
sage: p._gap_init_() # The variable name $sage2 belongs to the gap(F) and is somehow random
465
'GeneratorsOfField($sage2)[1]^2 + 2*GeneratorsOfField($sage2)[1] - 3'
466
sage: gap(p._gap_init_())
467
-3+2*E(8)+E(8)^2
468
"""
469
s = self._repr_()
470
return s.replace(str(self.parent().gen()), 'GeneratorsOfField(%s)[1]'%sage.interfaces.gap.gap(self.parent()).name())
471
472
def _libgap_(self):
473
"""
474
Return a LibGAP representation of ``self``.
475
476
EXAMPLES::
477
478
sage: F = CyclotomicField(8)
479
sage: F.gen()._libgap_()
480
E(8)
481
sage: libgap(F.gen()) # syntactic sugar
482
E(8)
483
sage: E8 = F.gen()
484
sage: libgap(E8 + 3/2*E8^2 + 100*E8^7)
485
E(8)+3/2*E(8)^2-100*E(8)^3
486
sage: type(_)
487
<type 'sage.libs.gap.element.GapElement_Cyclotomic'>
488
"""
489
n = self.parent()._n()
490
from sage.libs.gap.libgap import libgap
491
En = libgap(self.parent()).GeneratorsOfField()[0]
492
return self.polynomial()(En)
493
494
def _pari_polynomial(self, name='y'):
495
"""
496
Return a PARI polynomial representing ``self``.
497
498
TESTS:
499
500
sage: K.<a> = NumberField(x^3 + 2)
501
sage: K.zero()._pari_polynomial('x')
502
0
503
sage: K.one()._pari_polynomial()
504
1
505
sage: (a + 1)._pari_polynomial()
506
y + 1
507
sage: a._pari_polynomial('c')
508
c
509
"""
510
f = pari(self._coefficients()).Polrev()
511
if f.poldegree() > 0:
512
alpha = self.number_field()._pari_absolute_structure()[1]
513
f = f(alpha).lift()
514
return f.change_variable_name(name)
515
516
def _pari_(self, name='y'):
517
r"""
518
Return PARI representation of self.
519
520
The returned element is a PARI ``POLMOD`` in the variable
521
``name``, which is by default 'y' - not the name of the generator
522
of the number field.
523
524
INPUT:
525
526
- ``name`` -- (default: 'y') the PARI variable name used.
527
528
EXAMPLES::
529
530
sage: K.<a> = NumberField(x^3 + 2)
531
sage: K(1)._pari_()
532
Mod(1, y^3 + 2)
533
sage: (a + 2)._pari_()
534
Mod(y + 2, y^3 + 2)
535
sage: L.<b> = K.extension(x^2 + 2)
536
sage: (b + a)._pari_()
537
Mod(24/101*y^5 - 9/101*y^4 + 160/101*y^3 - 156/101*y^2 + 397/101*y + 364/101, y^6 + 6*y^4 - 4*y^3 + 12*y^2 + 24*y + 12)
538
539
::
540
541
sage: k.<j> = QuadraticField(-1)
542
sage: j._pari_('j')
543
Mod(j, j^2 + 1)
544
sage: pari(j)
545
Mod(y, y^2 + 1)
546
547
By default the variable name is 'y'. This allows 'x' to be used
548
as polynomial variable::
549
550
sage: P.<a> = PolynomialRing(QQ)
551
sage: K.<b> = NumberField(a^2 + 1)
552
sage: R.<x> = PolynomialRing(K)
553
sage: pari(b*x)
554
Mod(y, y^2 + 1)*x
555
556
In PARI many variable names are reserved, for example ``theta``
557
and ``I``::
558
559
sage: R.<theta> = PolynomialRing(QQ)
560
sage: K.<theta> = NumberField(theta^2 + 1)
561
sage: theta._pari_('theta')
562
Traceback (most recent call last):
563
...
564
PariError: theta already exists with incompatible valence
565
sage: theta._pari_()
566
Mod(y, y^2 + 1)
567
sage: k.<I> = QuadraticField(-1)
568
sage: I._pari_('I')
569
Traceback (most recent call last):
570
...
571
PariError: I already exists with incompatible valence
572
573
Instead, request the variable be named different for the coercion::
574
575
sage: pari(I)
576
Mod(y, y^2 + 1)
577
sage: I._pari_('i')
578
Mod(i, i^2 + 1)
579
sage: I._pari_('II')
580
Mod(II, II^2 + 1)
581
582
Examples with relative number fields, which always yield an
583
*absolute* representation of the element::
584
585
sage: y = QQ['y'].gen()
586
sage: k.<j> = NumberField([y^2 - 7, y^3 - 2])
587
sage: pari(j)
588
Mod(42/5515*y^5 - 9/11030*y^4 - 196/1103*y^3 + 273/5515*y^2 + 10281/5515*y + 4459/11030, y^6 - 21*y^4 + 4*y^3 + 147*y^2 + 84*y - 339)
589
sage: j^2
590
7
591
sage: pari(j)^2
592
Mod(7, y^6 - 21*y^4 + 4*y^3 + 147*y^2 + 84*y - 339)
593
sage: (j^2)._pari_('x')
594
Mod(7, x^6 - 21*x^4 + 4*x^3 + 147*x^2 + 84*x - 339)
595
596
A tower of three number fields::
597
598
sage: x = polygen(QQ)
599
sage: K.<a> = NumberField(x^2 + 2)
600
sage: L.<b> = NumberField(polygen(K)^2 + a)
601
sage: M.<c> = NumberField(polygen(L)^3 + b)
602
sage: L(b)._pari_()
603
Mod(y, y^4 + 2)
604
sage: M(b)._pari_('c')
605
Mod(-c^3, c^12 + 2)
606
sage: c._pari_('c')
607
Mod(c, c^12 + 2)
608
"""
609
f = self._pari_polynomial(name)
610
g = self.number_field().pari_polynomial(name)
611
return f.Mod(g)
612
613
def _pari_init_(self, name='y'):
614
"""
615
Return PARI/GP string representation of self.
616
617
The returned string defines a PARI ``POLMOD`` in the variable
618
``name``, which is by default 'y' - not the name of the generator
619
of the number field.
620
621
INPUT:
622
623
- ``name`` -- (default: 'y') the PARI variable name used.
624
625
EXAMPLES::
626
627
sage: K.<a> = NumberField(x^5 - x - 1)
628
sage: ((1 + 1/3*a)^4)._pari_init_()
629
'Mod(1/81*y^4 + 4/27*y^3 + 2/3*y^2 + 4/3*y + 1, y^5 - y - 1)'
630
sage: ((1 + 1/3*a)^4)._pari_init_('a')
631
'Mod(1/81*a^4 + 4/27*a^3 + 2/3*a^2 + 4/3*a + 1, a^5 - a - 1)'
632
633
Note that _pari_init_ can fail because of reserved words in
634
PARI, and since it actually works by obtaining the PARI
635
representation of something::
636
637
sage: K.<theta> = NumberField(x^5 - x - 1)
638
sage: b = (1/2 - 2/3*theta)^3; b
639
-8/27*theta^3 + 2/3*theta^2 - 1/2*theta + 1/8
640
sage: b._pari_init_('theta')
641
Traceback (most recent call last):
642
...
643
PariError: theta already exists with incompatible valence
644
645
Fortunately pari_init returns everything in terms of y by
646
default::
647
648
sage: pari(b)
649
Mod(-8/27*y^3 + 2/3*y^2 - 1/2*y + 1/8, y^5 - y - 1)
650
"""
651
return repr(self._pari_(name=name))
652
653
def __getitem__(self, n):
654
"""
655
Return the n-th coefficient of this number field element, written
656
as a polynomial in the generator.
657
658
Note that `n` must be between 0 and `d-1`, where
659
`d` is the degree of the number field.
660
661
EXAMPLES::
662
663
sage: m.<b> = NumberField(x^4 - 1789)
664
sage: c = (2/3-4/5*b)^3; c
665
-64/125*b^3 + 32/25*b^2 - 16/15*b + 8/27
666
sage: c[0]
667
8/27
668
sage: c[2]
669
32/25
670
sage: c[3]
671
-64/125
672
673
We illustrate bounds checking::
674
675
sage: c[-1]
676
Traceback (most recent call last):
677
...
678
IndexError: index must be between 0 and degree minus 1.
679
sage: c[4]
680
Traceback (most recent call last):
681
...
682
IndexError: index must be between 0 and degree minus 1.
683
684
The list method implicitly calls ``__getitem__``::
685
686
sage: list(c)
687
[8/27, -16/15, 32/25, -64/125]
688
sage: m(list(c)) == c
689
True
690
"""
691
if n < 0 or n >= self.number_field().degree(): # make this faster.
692
raise IndexError, "index must be between 0 and degree minus 1."
693
return self.polynomial()[n]
694
695
cpdef int _cmp_(left, sage.structure.element.Element right) except -2:
696
r"""
697
EXAMPLE::
698
699
sage: K.<a> = NumberField(x^3 - 3*x + 8)
700
sage: a + 1 > a # indirect doctest
701
True
702
sage: a + 1 < a # indirect doctest
703
False
704
"""
705
cdef NumberFieldElement _right = right
706
return (left.__numerator != _right.__numerator) or (left.__denominator != _right.__denominator)
707
708
def _random_element(self, num_bound=None, den_bound=None, distribution=None):
709
"""
710
Return a new random element with the same parent as self.
711
712
INPUT:
713
714
- ``num_bound`` - Bound for the numerator of coefficients of result
715
716
- ``den_bound`` - Bound for the denominator of coefficients of result
717
718
- ``distribution`` - Distribution to use for coefficients of result
719
720
EXAMPLES::
721
722
sage: K.<a> = NumberField(x^3-2)
723
sage: a._random_element()
724
-1/2*a^2 - 4
725
sage: K.<a> = NumberField(x^2-5)
726
sage: a._random_element()
727
-2*a - 1
728
"""
729
cdef NumberFieldElement elt = self._new()
730
elt._randomize(num_bound, den_bound, distribution)
731
return elt
732
733
cdef int _randomize(self, num_bound, den_bound, distribution) except -1:
734
cdef int i
735
cdef Integer denom_temp = PY_NEW(Integer)
736
cdef Integer tmp_integer = PY_NEW(Integer)
737
cdef ZZ_c ntl_temp
738
cdef list coeff_list
739
cdef Rational tmp_rational
740
741
# It seems like a simpler approach would be to simply generate
742
# random integers for each coefficient of self.__numerator
743
# and an integer for self.__denominator. However, this would
744
# generate things with a fairly fixed shape: in particular,
745
# we'd be very unlikely to get elements like 1/3*a^3 + 1/7,
746
# or anything where the denominators are actually unrelated
747
# to one another. The extra code below is to make exactly
748
# these kinds of results possible.
749
750
if den_bound == 1:
751
# in this case, we can skip all the business with LCMs,
752
# storing a list of rationals, etc. this gives a factor of
753
# two or so speedup ...
754
755
# set the denominator
756
mpz_set_si(denom_temp.value, 1)
757
denom_temp._to_ZZ(&self.__denominator)
758
for i from 0 <= i < ZZX_deg(self.__fld_numerator.x):
759
tmp_integer = <Integer>(ZZ.random_element(x=num_bound,
760
distribution=distribution))
761
tmp_integer._to_ZZ(&ntl_temp)
762
ZZX_SetCoeff(self.__numerator, i, ntl_temp)
763
764
else:
765
coeff_list = []
766
mpz_set_si(denom_temp.value, 1)
767
tmp_integer = PY_NEW(Integer)
768
769
for i from 0 <= i < ZZX_deg(self.__fld_numerator.x):
770
tmp_rational = <Rational>(QQ.random_element(num_bound=num_bound,
771
den_bound=den_bound,
772
distribution=distribution))
773
coeff_list.append(tmp_rational)
774
mpz_lcm(denom_temp.value, denom_temp.value,
775
mpq_denref(tmp_rational.value))
776
777
# now denom_temp has the denominator, and we just need to
778
# scale the numerators and set everything appropriately
779
780
# first, the denominator (easy)
781
denom_temp._to_ZZ(&self.__denominator)
782
783
# now the coefficients themselves.
784
for i from 0 <= i < ZZX_deg(self.__fld_numerator.x):
785
# calculate the new numerator. if our old entry is
786
# p/q, and the lcm is k, it's just pk/q, which we
787
# also know is integral -- so we can use mpz_divexact
788
# below
789
tmp_rational = <Rational>(coeff_list[i])
790
mpz_mul(tmp_integer.value, mpq_numref(tmp_rational.value),
791
denom_temp.value)
792
mpz_divexact(tmp_integer.value, tmp_integer.value,
793
mpq_denref(tmp_rational.value))
794
795
# now set the coefficient of self
796
tmp_integer._to_ZZ(&ntl_temp)
797
ZZX_SetCoeff(self.__numerator, i, ntl_temp)
798
799
return 0 # No error
800
801
802
def __abs__(self):
803
r"""
804
Return the numerical absolute value of this number field element
805
with respect to the first archimedean embedding, to double
806
precision.
807
808
This is the ``abs( )`` Python function. If you want a
809
different embedding or precision, use
810
``self.abs(...)``.
811
812
EXAMPLES::
813
814
sage: k.<a> = NumberField(x^3 - 2)
815
sage: abs(a)
816
1.25992104989487
817
sage: abs(a)^3
818
2.00000000000000
819
sage: a.abs(prec=128)
820
1.2599210498948731647672106072782283506
821
"""
822
return self.abs(prec=53, i=None)
823
824
def abs(self, prec=53, i=None):
825
r"""
826
Return the absolute value of this element.
827
828
If ``i`` is provided, then the absolute of the `i`-th embedding is
829
given. Otherwise, if the number field as a defined embedding into `\CC`
830
then the corresponding absolute value is returned and if there is none,
831
it corresponds to the choice ``i=0``.
832
833
If prec is 53 (the default), then the complex double field is
834
used; otherwise the arbitrary precision (but slow) complex
835
field is used.
836
837
INPUT:
838
839
840
- ``prec`` - (default: 53) integer bits of precision
841
842
- ``i`` - (default: ) integer, which embedding to
843
use
844
845
846
EXAMPLES::
847
848
sage: z = CyclotomicField(7).gen()
849
sage: abs(z)
850
1.00000000000000
851
sage: abs(z^2 + 17*z - 3)
852
16.0604426799931
853
sage: K.<a> = NumberField(x^3+17)
854
sage: abs(a)
855
2.57128159065824
856
sage: a.abs(prec=100)
857
2.5712815906582353554531872087
858
sage: a.abs(prec=100,i=1)
859
2.5712815906582353554531872087
860
sage: a.abs(100, 2)
861
2.5712815906582353554531872087
862
863
Here's one where the absolute value depends on the embedding.
864
865
::
866
867
sage: K.<b> = NumberField(x^2-2)
868
sage: a = 1 + b
869
sage: a.abs(i=0)
870
0.414213562373095
871
sage: a.abs(i=1)
872
2.41421356237309
873
874
Check that :trac:`16147` is fixed::
875
876
sage: x = polygen(ZZ)
877
sage: f = x^3 - x - 1
878
sage: beta = f.complex_roots()[0]; beta
879
1.32471795724475
880
sage: K.<b> = NumberField(f, embedding=beta)
881
sage: b.abs()
882
1.32471795724475
883
"""
884
CCprec = ComplexField(prec)
885
if i is None and CCprec.has_coerce_map_from(self.parent()):
886
return CCprec(self).abs()
887
else:
888
i = 0 if i is None else i
889
P = self.number_field().complex_embeddings(prec)[i]
890
return P(self).abs()
891
892
def abs_non_arch(self, P, prec=None):
893
r"""
894
Return the non-archimedean absolute value of this element with
895
respect to the prime `P`, to the given precision.
896
897
INPUT:
898
899
- ``P`` - a prime ideal of the parent of self
900
901
- ``prec`` (int) -- desired floating point precision (default:
902
default RealField precision).
903
904
OUTPUT:
905
906
(real) the non-archimedean absolute value of this element with
907
respect to the prime `P`, to the given precision. This is the
908
normalised absolute value, so that the underlying prime number
909
`p` has absolute value `1/p`.
910
911
912
EXAMPLES::
913
914
sage: K.<a> = NumberField(x^2+5)
915
sage: [1/K(2).abs_non_arch(P) for P in K.primes_above(2)]
916
[2.00000000000000]
917
sage: [1/K(3).abs_non_arch(P) for P in K.primes_above(3)]
918
[3.00000000000000, 3.00000000000000]
919
sage: [1/K(5).abs_non_arch(P) for P in K.primes_above(5)]
920
[5.00000000000000]
921
922
A relative example::
923
924
sage: L.<b> = K.extension(x^2-5)
925
sage: [b.abs_non_arch(P) for P in L.primes_above(b)]
926
[0.447213595499958, 0.447213595499958]
927
"""
928
from sage.rings.real_mpfr import RealField
929
if prec is None:
930
R = RealField()
931
else:
932
R = RealField(prec)
933
934
if self.is_zero():
935
return R.zero()
936
val = self.valuation(P)
937
nP = P.residue_class_degree()*P.absolute_ramification_index()
938
return R(P.absolute_norm()) ** (-R(val) / R(nP))
939
940
def coordinates_in_terms_of_powers(self):
941
r"""
942
Let `\alpha` be self. Return a callable object (of type
943
:class:`~CoordinateFunction`) that takes any element of the
944
parent of self in `\QQ(\alpha)` and writes it in terms of the
945
powers of `\alpha`: `1, \alpha, \alpha^2, ...`.
946
947
(NOT CACHED).
948
949
EXAMPLES:
950
951
This function allows us to write elements of a number
952
field in terms of a different generator without having to construct
953
a whole separate number field.
954
955
::
956
957
sage: y = polygen(QQ,'y'); K.<beta> = NumberField(y^3 - 2); K
958
Number Field in beta with defining polynomial y^3 - 2
959
sage: alpha = beta^2 + beta + 1
960
sage: c = alpha.coordinates_in_terms_of_powers(); c
961
Coordinate function that writes elements in terms of the powers of beta^2 + beta + 1
962
sage: c(beta)
963
[-2, -3, 1]
964
sage: c(alpha)
965
[0, 1, 0]
966
sage: c((1+beta)^5)
967
[3, 3, 3]
968
sage: c((1+beta)^10)
969
[54, 162, 189]
970
971
This function works even if self only generates a subfield of this
972
number field.
973
974
::
975
976
sage: k.<a> = NumberField(x^6 - 5)
977
sage: alpha = a^3
978
sage: c = alpha.coordinates_in_terms_of_powers()
979
sage: c((2/3)*a^3 - 5/3)
980
[-5/3, 2/3]
981
sage: c
982
Coordinate function that writes elements in terms of the powers of a^3
983
sage: c(a)
984
Traceback (most recent call last):
985
...
986
ArithmeticError: vector is not in free module
987
"""
988
K = self.number_field()
989
V, from_V, to_V = K.absolute_vector_space()
990
h = K(1)
991
B = [to_V(h)]
992
f = self.absolute_minpoly()
993
for i in range(f.degree()-1):
994
h *= self
995
B.append(to_V(h))
996
W = V.span_of_basis(B)
997
return CoordinateFunction(self, W, to_V)
998
999
def complex_embeddings(self, prec=53):
1000
"""
1001
Return the images of this element in the floating point complex
1002
numbers, to the given bits of precision.
1003
1004
INPUT:
1005
1006
1007
- ``prec`` - integer (default: 53) bits of precision
1008
1009
1010
EXAMPLES::
1011
1012
sage: k.<a> = NumberField(x^3 - 2)
1013
sage: a.complex_embeddings()
1014
[-0.629960524947437 - 1.09112363597172*I, -0.629960524947437 + 1.09112363597172*I, 1.25992104989487]
1015
sage: a.complex_embeddings(10)
1016
[-0.63 - 1.1*I, -0.63 + 1.1*I, 1.3]
1017
sage: a.complex_embeddings(100)
1018
[-0.62996052494743658238360530364 - 1.0911236359717214035600726142*I, -0.62996052494743658238360530364 + 1.0911236359717214035600726142*I, 1.2599210498948731647672106073]
1019
"""
1020
phi = self.number_field().complex_embeddings(prec)
1021
return [f(self) for f in phi]
1022
1023
def complex_embedding(self, prec=53, i=0):
1024
"""
1025
Return the i-th embedding of self in the complex numbers, to the
1026
given precision.
1027
1028
EXAMPLES::
1029
1030
sage: k.<a> = NumberField(x^3 - 2)
1031
sage: a.complex_embedding()
1032
-0.629960524947437 - 1.09112363597172*I
1033
sage: a.complex_embedding(10)
1034
-0.63 - 1.1*I
1035
sage: a.complex_embedding(100)
1036
-0.62996052494743658238360530364 - 1.0911236359717214035600726142*I
1037
sage: a.complex_embedding(20, 1)
1038
-0.62996 + 1.0911*I
1039
sage: a.complex_embedding(20, 2)
1040
1.2599
1041
"""
1042
return self.number_field().complex_embeddings(prec)[i](self)
1043
1044
def is_unit(self):
1045
"""
1046
Return ``True`` if ``self`` is a unit in the ring where it is defined.
1047
1048
EXAMPLES::
1049
1050
sage: K.<a> = NumberField(x^2 - x - 1)
1051
sage: OK = K.ring_of_integers()
1052
sage: OK(a).is_unit()
1053
True
1054
sage: OK(13).is_unit()
1055
False
1056
sage: K(13).is_unit()
1057
True
1058
1059
It also works for relative fields and orders::
1060
1061
sage: K.<a,b> = NumberField([x^2 - 3, x^4 + x^3 + x^2 + x + 1])
1062
sage: OK = K.ring_of_integers()
1063
sage: OK(b).is_unit()
1064
True
1065
sage: OK(a).is_unit()
1066
False
1067
sage: a.is_unit()
1068
True
1069
"""
1070
if self.parent().is_field():
1071
return bool(self)
1072
return self.norm().is_unit()
1073
1074
def is_norm(self, L, element=False, proof=True):
1075
r"""
1076
Determine whether self is the relative norm of an element
1077
of L/K, where K is self.parent().
1078
1079
INPUT:
1080
1081
- L -- a number field containing K=self.parent()
1082
- element -- True or False, whether to also output an element
1083
of which self is a norm
1084
- proof -- If True, then the output is correct unconditionally.
1085
If False, then the output is correct under GRH.
1086
1087
OUTPUT:
1088
1089
If element is False, then the output is a boolean B, which is
1090
True if and only if self is the relative norm of an element of L
1091
to K.
1092
If element is False, then the output is a pair (B, x), where
1093
B is as above. If B is True, then x is an element of L such that
1094
self == x.norm(K). Otherwise, x is None.
1095
1096
ALGORITHM:
1097
1098
Uses PARI's rnfisnorm. See self._rnfisnorm().
1099
1100
EXAMPLES::
1101
1102
sage: K.<beta> = NumberField(x^3+5)
1103
sage: Q.<X> = K[]
1104
sage: L = K.extension(X^2+X+beta, 'gamma')
1105
sage: (beta/2).is_norm(L)
1106
False
1107
sage: beta.is_norm(L)
1108
True
1109
1110
With a relative base field::
1111
1112
sage: K.<a, b> = NumberField([x^2 - 2, x^2 - 3])
1113
sage: L.<c> = K.extension(x^2 - 5)
1114
sage: (2*a*b).is_norm(L)
1115
True
1116
sage: _, v = (2*b*a).is_norm(L, element=True)
1117
sage: v.norm(K) == 2*a*b
1118
True
1119
1120
Non-Galois number fields::
1121
1122
sage: K.<a> = NumberField(x^2 + x + 1)
1123
sage: Q.<X> = K[]
1124
sage: L.<b> = NumberField(X^4 + a + 2)
1125
sage: (a/4).is_norm(L)
1126
True
1127
sage: (a/2).is_norm(L)
1128
Traceback (most recent call last):
1129
...
1130
NotImplementedError: is_norm is not implemented unconditionally for norms from non-Galois number fields
1131
sage: (a/2).is_norm(L, proof=False)
1132
False
1133
1134
sage: K.<a> = NumberField(x^3 + x + 1)
1135
sage: Q.<X> = K[]
1136
sage: L.<b> = NumberField(X^4 + a)
1137
sage: t = (-a).is_norm(L, element=True); t
1138
(True, b^3 + 1)
1139
sage: t[1].norm(K)
1140
-a
1141
1142
AUTHORS:
1143
1144
- Craig Citro (2008-04-05)
1145
1146
- Marco Streng (2010-12-03)
1147
"""
1148
if not element:
1149
return self.is_norm(L, element=True, proof=proof)[0]
1150
1151
K = self.parent()
1152
from sage.rings.number_field.number_field_base import is_NumberField
1153
if not is_NumberField(L):
1154
raise ValueError, "L (=%s) must be a NumberField in is_norm" % L
1155
1156
from sage.rings.number_field.number_field import is_AbsoluteNumberField
1157
if is_AbsoluteNumberField(L):
1158
Lrel = L.relativize(K.hom(L), (L.variable_name()+'0', K.variable_name()+'0') )
1159
b, x = self.is_norm(Lrel, element=True, proof=proof)
1160
h = Lrel.structure()[0]
1161
return b, h(x)
1162
1163
if L.relative_degree() == 1 or self.is_zero():
1164
return True, L(self)
1165
1166
a, b = self._rnfisnorm(L, proof=proof)
1167
if b == 1:
1168
assert a.norm(K) == self
1169
return True, a
1170
1171
if L.is_galois_relative():
1172
return False, None
1173
1174
# The following gives the Galois closure of K/QQ, but the Galois
1175
# closure of K/self.parent() would suffice.
1176
M = L.galois_closure('a')
1177
from sage.functions.log import log
1178
from sage.functions.other import floor
1179
extra_primes = floor(12*log(abs(M.discriminant()))**2)
1180
a, b = self._rnfisnorm(L, proof=proof, extra_primes=extra_primes)
1181
if b == 1:
1182
assert a.norm(K) == self
1183
return True, a
1184
1185
if proof:
1186
raise NotImplementedError, "is_norm is not implemented unconditionally for norms from non-Galois number fields"
1187
return False, None
1188
1189
def _rnfisnorm(self, L, proof=True, extra_primes=0):
1190
r"""
1191
Gives the output of the PARI function rnfisnorm.
1192
1193
This tries to decide whether the number field element self is
1194
the norm of some x in the extension L/K (with K = self.parent()).
1195
1196
The output is a pair (x, q), where self = Norm(x)*q. The
1197
algorithm looks for a solution x that is an S-integer, with S
1198
a list of places of L containing at least the ramified primes,
1199
the generators of the class group of L, as well as those primes
1200
dividing self.
1201
1202
If L/K is Galois, then this is enough; otherwise,
1203
extra_primes is used to add more primes to S: all the places
1204
above the primes p <= extra_primes (resp. p|extra_primes) if
1205
extra_primes > 0 (resp. extra_primes < 0).
1206
1207
The answer is guaranteed (i.e., self is a norm iff q = 1) if the
1208
field is Galois, or, under GRH, if S contains all primes less
1209
than 12log^2|\disc(M)|, where M is the normal closure of L/K.
1210
1211
INPUT:
1212
1213
- L -- a relative number field with base field self.parent()
1214
- proof -- whether to certify outputs of PARI init functions.
1215
If false, truth of the output depends on GRH.
1216
- extra_primes -- an integer as explained above.
1217
1218
OUTPUT:
1219
1220
A pair (x, q) with x in L and q in K as explained above
1221
such that self == x.norm(K)*q.
1222
1223
ALGORITHM:
1224
1225
Uses PARI's rnfisnorm.
1226
1227
EXAMPLES::
1228
1229
sage: K.<a> = NumberField(x^3 + x^2 - 2*x - 1, 'a')
1230
sage: P.<X> = K[]
1231
sage: L = NumberField(X^2 + a^2 + 2*a + 1, 'b')
1232
sage: K(17)._rnfisnorm(L)
1233
((a^2 - 2)*b - 4, 1)
1234
1235
sage: K.<a> = NumberField(x^3 + x + 1)
1236
sage: Q.<X> = K[]
1237
sage: L.<b> = NumberField(X^4 + a)
1238
sage: t = (-a)._rnfisnorm(L); t
1239
(b^3 + 1, 1)
1240
sage: t[0].norm(K)
1241
-a
1242
sage: t = K(3)._rnfisnorm(L); t
1243
((a^2 + 1)*b^3 - b^2 - a*b - a^2, -3*a^2 + 3*a - 3)
1244
sage: t[0].norm(K)*t[1]
1245
3
1246
1247
An example where the base field is a relative field::
1248
1249
sage: K.<a, b> = NumberField([x^2 - 2, x^2 - 3])
1250
sage: L.<c> = K.extension(x^3 + 2)
1251
sage: s = 2*a + b
1252
sage: t = s._rnfisnorm(L)
1253
sage: t[1] == 1 # True iff s is a norm
1254
False
1255
sage: s == t[0].norm(K)*t[1]
1256
True
1257
1258
TESTS:
1259
1260
Number fields defined by non-monic and non-integral
1261
polynomials are supported (:trac:`252`)::
1262
1263
sage: K.<a> = NumberField(x^2 + 1/2)
1264
sage: L.<b> = K.extension(x^2 - 1/2)
1265
sage: a._rnfisnorm(L)
1266
(a*b + a + 1/2, 1)
1267
1268
AUTHORS:
1269
1270
- Craig Citro (2008-04-05)
1271
1272
- Marco Streng (2010-12-03)
1273
1274
- Francis Clarke (2010-12-26)
1275
"""
1276
K = self.parent()
1277
from sage.rings.number_field.number_field_rel import is_RelativeNumberField
1278
if (not is_RelativeNumberField(L)) or L.base_field() != K:
1279
raise ValueError, "L (=%s) must be a relative number field with base field K (=%s) in rnfisnorm" % (L, K)
1280
1281
rnf_data = K.pari_rnfnorm_data(L, proof=proof)
1282
x, q = self._pari_().rnfisnorm(rnf_data)
1283
return L(x, check=False), K(q, check=False)
1284
1285
def _mpfr_(self, R):
1286
"""
1287
EXAMPLES::
1288
1289
sage: k.<a> = NumberField(x^2 + 1)
1290
sage: RR(a^2)
1291
-1.00000000000000
1292
sage: RR(a)
1293
Traceback (most recent call last):
1294
...
1295
TypeError: Unable to coerce a to a rational
1296
sage: (a^2)._mpfr_(RR)
1297
-1.00000000000000
1298
1299
Verify that :trac:`13005` has been fixed::
1300
1301
sage: K.<a> = NumberField(x^2-5)
1302
sage: RR(K(1))
1303
1.00000000000000
1304
sage: RR(a)
1305
Traceback (most recent call last):
1306
...
1307
TypeError: Unable to coerce a to a rational
1308
sage: K.<a> = NumberField(x^3+2, embedding=-1.25)
1309
sage: RR(a)
1310
-1.25992104989487
1311
sage: RealField(prec=100)(a)
1312
-1.2599210498948731647672106073
1313
"""
1314
if self.parent().coerce_embedding() is None:
1315
return R(self.base_ring()(self))
1316
else:
1317
return R(R.complex_field()(self))
1318
1319
def __float__(self):
1320
"""
1321
EXAMPLES::
1322
1323
sage: k.<a> = NumberField(x^2 + 1)
1324
sage: float(a^2)
1325
-1.0
1326
sage: float(a)
1327
Traceback (most recent call last):
1328
...
1329
TypeError: Unable to coerce a to a rational
1330
sage: (a^2).__float__()
1331
-1.0
1332
sage: k.<a> = NumberField(x^2 + 1,embedding=I)
1333
sage: float(a)
1334
Traceback (most recent call last):
1335
...
1336
TypeError: unable to coerce to a real number
1337
"""
1338
if self.parent().coerce_embedding() is None:
1339
return float(self.base_ring()(self))
1340
else:
1341
c = complex(self)
1342
if c.imag == 0:
1343
return c.real
1344
raise TypeError('unable to coerce to a real number')
1345
1346
def _complex_double_(self, CDF):
1347
"""
1348
EXAMPLES::
1349
1350
sage: k.<a> = NumberField(x^2 + 1)
1351
sage: abs(CDF(a))
1352
1.0
1353
"""
1354
return CDF(CC(self))
1355
1356
def __complex__(self):
1357
"""
1358
EXAMPLES::
1359
1360
sage: k.<a> = NumberField(x^2 + 1)
1361
sage: complex(a)
1362
1j
1363
sage: a.__complex__()
1364
1j
1365
"""
1366
return complex(CC(self))
1367
1368
def factor(self):
1369
"""
1370
Return factorization of this element into prime elements and a unit.
1371
1372
OUTPUT:
1373
1374
(Factorization) If all the prime ideals in the support are
1375
principal, the output is a Factorization as a product of prime
1376
elements raised to appropriate powers, with an appropriate
1377
unit factor.
1378
1379
Raise ValueError if the factorization of the
1380
ideal (self) contains a non-principal prime ideal.
1381
1382
EXAMPLES::
1383
1384
sage: K.<i> = NumberField(x^2+1)
1385
sage: (6*i + 6).factor()
1386
(-i) * (i + 1)^3 * 3
1387
1388
In the following example, the class number is 2. If a factorization
1389
in prime elements exists, we will find it::
1390
1391
sage: K.<a> = NumberField(x^2-10)
1392
sage: factor(169*a + 531)
1393
(-6*a - 19) * (-3*a - 1) * (-2*a + 9)
1394
sage: factor(K(3))
1395
Traceback (most recent call last):
1396
...
1397
ArithmeticError: non-principal ideal in factorization
1398
1399
Factorization of 0 is not allowed::
1400
1401
sage: K.<i> = QuadraticField(-1)
1402
sage: K(0).factor()
1403
Traceback (most recent call last):
1404
...
1405
ArithmeticError: factorization of 0 is not defined
1406
1407
"""
1408
if self.is_zero():
1409
raise ArithmeticError("factorization of 0 is not defined")
1410
1411
K = self.parent()
1412
fac = K.ideal(self).factor()
1413
# Check whether all prime ideals in `fac` are principal
1414
for P,e in fac:
1415
if not P.is_principal():
1416
raise ArithmeticError("non-principal ideal in factorization")
1417
element_fac = [(P.gens_reduced()[0],e) for P,e in fac]
1418
# Compute the product of the p^e to figure out the unit
1419
from sage.misc.all import prod
1420
element_product = prod([p**e for p,e in element_fac], K(1))
1421
from sage.structure.all import Factorization
1422
return Factorization(element_fac, unit=self/element_product)
1423
1424
@coerce_binop
1425
def gcd(self, other):
1426
"""
1427
Return the greatest common divisor of ``self`` and ``other``.
1428
1429
INPUT:
1430
1431
- ``self``, ``other`` -- elements of a number field or maximal
1432
order.
1433
1434
OUTPUT:
1435
1436
- A generator of the ideal ``(self, other)``. If the parent is
1437
a number field, this always returns 0 or 1. For maximal orders,
1438
this raises ``ArithmeticError`` if the ideal is not principal.
1439
1440
EXAMPLES::
1441
1442
sage: K.<i> = QuadraticField(-1)
1443
sage: (i+1).gcd(2)
1444
1
1445
sage: K(1).gcd(0)
1446
1
1447
sage: K(0).gcd(0)
1448
0
1449
sage: R = K.maximal_order()
1450
sage: R(i+1).gcd(2)
1451
i + 1
1452
1453
Non-maximal orders are not supported::
1454
1455
sage: R = K.order(2*i)
1456
sage: R(1).gcd(R(4*i))
1457
Traceback (most recent call last):
1458
...
1459
NotImplementedError: gcd() for Order in Number Field in i with defining polynomial x^2 + 1 is not implemented
1460
1461
The following field has class number 3, but if the ideal
1462
``(self, other)`` happens to be principal, this still works::
1463
1464
sage: K.<a> = NumberField(x^3 - 7)
1465
sage: K.class_number()
1466
3
1467
sage: a.gcd(7)
1468
1
1469
sage: R = K.maximal_order()
1470
sage: R(a).gcd(7)
1471
a
1472
sage: R(a+1).gcd(2)
1473
Traceback (most recent call last):
1474
...
1475
ArithmeticError: ideal (a + 1, 2) is not principal, gcd is not defined
1476
sage: R(2*a - a^2).gcd(0)
1477
a
1478
"""
1479
# gcd(0,0) = 0
1480
if not self and not other:
1481
return self
1482
1483
R = self.parent()
1484
if R.is_field():
1485
return R.one()
1486
1487
from order import is_NumberFieldOrder
1488
if not is_NumberFieldOrder(R) or not R.is_maximal():
1489
raise NotImplementedError("gcd() for %r is not implemented" % R)
1490
1491
g = R.ideal(self, other).gens_reduced()
1492
if len(g) > 1:
1493
raise ArithmeticError("ideal (%r, %r) is not principal, gcd is not defined" % (self, other) )
1494
1495
return g[0]
1496
1497
1498
def is_totally_positive(self):
1499
"""
1500
Returns True if self is positive for all real embeddings of its
1501
parent number field. We do nothing at complex places, so e.g. any
1502
element of a totally complex number field will return True.
1503
1504
EXAMPLES::
1505
1506
sage: F.<b> = NumberField(x^3-3*x-1)
1507
sage: b.is_totally_positive()
1508
False
1509
sage: (b^2).is_totally_positive()
1510
True
1511
1512
TESTS:
1513
1514
Check that the output is correct even for numbers that are
1515
very close to zero (ticket #9596)::
1516
1517
sage: K.<sqrt2> = QuadraticField(2)
1518
sage: a = 30122754096401; b = 21300003689580
1519
sage: (a/b)^2 > 2
1520
True
1521
sage: (a/b+sqrt2).is_totally_positive()
1522
True
1523
sage: r = RealField(3020)(2).sqrt()*2^3000
1524
sage: a = floor(r)/2^3000
1525
sage: b = ceil(r)/2^3000
1526
sage: (a+sqrt2).is_totally_positive()
1527
False
1528
sage: (b+sqrt2).is_totally_positive()
1529
True
1530
1531
Check that 0 is handled correctly::
1532
1533
sage: K.<a> = NumberField(x^5+4*x+1)
1534
sage: K(0).is_totally_positive()
1535
False
1536
"""
1537
for v in self.number_field().embeddings(sage.rings.qqbar.AA):
1538
if v(self) <= 0:
1539
return False
1540
return True
1541
1542
def is_square(self, root=False):
1543
"""
1544
Return True if self is a square in its parent number field and
1545
otherwise return False.
1546
1547
INPUT:
1548
1549
1550
- ``root`` - if True, also return a square root (or
1551
None if self is not a perfect square)
1552
1553
1554
EXAMPLES::
1555
1556
sage: m.<b> = NumberField(x^4 - 1789)
1557
sage: b.is_square()
1558
False
1559
sage: c = (2/3*b + 5)^2; c
1560
4/9*b^2 + 20/3*b + 25
1561
sage: c.is_square()
1562
True
1563
sage: c.is_square(True)
1564
(True, 2/3*b + 5)
1565
1566
We also test the functional notation.
1567
1568
::
1569
1570
sage: is_square(c, True)
1571
(True, 2/3*b + 5)
1572
sage: is_square(c)
1573
True
1574
sage: is_square(c+1)
1575
False
1576
1577
TESTS:
1578
1579
Test that :trac:`16894` is fixed::
1580
1581
sage: K.<a> = QuadraticField(22)
1582
sage: u = K.units()[0]
1583
sage: (u^14).is_square()
1584
True
1585
"""
1586
v = self.sqrt(all=True)
1587
t = len(v) > 0
1588
if root:
1589
if t:
1590
return t, v[0]
1591
else:
1592
return False, None
1593
else:
1594
return t
1595
1596
def sqrt(self, all=False):
1597
"""
1598
Returns the square root of this number in the given number field.
1599
1600
EXAMPLES::
1601
1602
sage: K.<a> = NumberField(x^2 - 3)
1603
sage: K(3).sqrt()
1604
a
1605
sage: K(3).sqrt(all=True)
1606
[a, -a]
1607
sage: K(a^10).sqrt()
1608
9*a
1609
sage: K(49).sqrt()
1610
7
1611
sage: K(1+a).sqrt()
1612
Traceback (most recent call last):
1613
...
1614
ValueError: a + 1 not a square in Number Field in a with defining polynomial x^2 - 3
1615
sage: K(0).sqrt()
1616
0
1617
sage: K((7+a)^2).sqrt(all=True)
1618
[a + 7, -a - 7]
1619
1620
::
1621
1622
sage: K.<a> = CyclotomicField(7)
1623
sage: a.sqrt()
1624
a^4
1625
1626
::
1627
1628
sage: K.<a> = NumberField(x^5 - x + 1)
1629
sage: (a^4 + a^2 - 3*a + 2).sqrt()
1630
a^3 - a^2
1631
1632
ALGORITHM: Use PARI to factor `x^2` - ``self`` in `K`.
1633
"""
1634
# For now, use pari's factoring abilities
1635
R = self.number_field()['t']
1636
f = R([-self, 0, 1])
1637
roots = f.roots()
1638
if all:
1639
return [r[0] for r in roots]
1640
elif len(roots) > 0:
1641
return roots[0][0]
1642
else:
1643
try:
1644
# This is what integers, rationals do...
1645
from sage.all import SR, sqrt
1646
return sqrt(SR(self))
1647
except TypeError:
1648
raise ValueError, "%s not a square in %s"%(self, self._parent)
1649
1650
def nth_root(self, n, all=False):
1651
r"""
1652
Return an `n`'th root of ``self`` in its parent `K`.
1653
1654
EXAMPLES::
1655
1656
sage: K.<a> = NumberField(x^4-7)
1657
sage: K(7).nth_root(2)
1658
a^2
1659
sage: K((a-3)^5).nth_root(5)
1660
a - 3
1661
1662
ALGORITHM: Use PARI to factor `x^n` - ``self`` in `K`.
1663
"""
1664
R = self.number_field()['t']
1665
if not self:
1666
return [self] if all else self
1667
f = (R.gen(0) << (n-1)) - self
1668
roots = f.roots()
1669
if all:
1670
return [r[0] for r in roots]
1671
elif len(roots) > 0:
1672
return roots[0][0]
1673
else:
1674
raise ValueError, "%s not a %s-th root in %s"%(self, n, self._parent)
1675
1676
def is_nth_power(self, n):
1677
r"""
1678
Return True if ``self`` is an `n`'th power in its parent `K`.
1679
1680
EXAMPLES::
1681
1682
sage: K.<a> = NumberField(x^4-7)
1683
sage: K(7).is_nth_power(2)
1684
True
1685
sage: K(7).is_nth_power(4)
1686
True
1687
sage: K(7).is_nth_power(8)
1688
False
1689
sage: K((a-3)^5).is_nth_power(5)
1690
True
1691
1692
ALGORITHM: Use PARI to factor `x^n` - ``self`` in `K`.
1693
"""
1694
return len(self.nth_root(n, all=True)) > 0
1695
1696
def __pow__(base, exp, dummy):
1697
"""
1698
EXAMPLES::
1699
1700
sage: K.<sqrt2> = QuadraticField(2)
1701
sage: sqrt2^2
1702
2
1703
sage: sqrt2^5
1704
4*sqrt2
1705
sage: (1+sqrt2)^100
1706
66992092050551637663438906713182313772*sqrt2 + 94741125149636933417873079920900017937
1707
sage: (1+sqrt2)^-1
1708
sqrt2 - 1
1709
1710
If the exponent is not integral, perform this operation in
1711
the symbolic ring::
1712
1713
sage: sqrt2^(1/5)
1714
2^(1/10)
1715
sage: sqrt2^sqrt2
1716
2^(1/2*sqrt(2))
1717
1718
Sage follows Python's convention 0^0 = 1::
1719
1720
sage: a = K(0)^0; a
1721
1
1722
sage: a.parent()
1723
Number Field in sqrt2 with defining polynomial x^2 - 2
1724
1725
TESTS::
1726
1727
sage: 2^I
1728
2^I
1729
1730
Test :trac:`14895`::
1731
1732
sage: K.<sqrt2> = QuadraticField(2)
1733
sage: 2^sqrt2
1734
2^sqrt(2)
1735
sage: K.<a> = NumberField(x^2+1)
1736
sage: 2^a
1737
Traceback (most recent call last):
1738
...
1739
TypeError: an embedding into RR or CC must be specified
1740
"""
1741
if (isinstance(base, NumberFieldElement) and
1742
(isinstance(exp, Integer) or type(exp) is int or exp in ZZ)):
1743
return generic_power_c(base, exp, None)
1744
else:
1745
cbase, cexp = canonical_coercion(base, exp)
1746
if not isinstance(cbase, NumberFieldElement):
1747
return cbase ** cexp
1748
# Return a symbolic expression.
1749
# We use the hold=True keyword argument to prevent the
1750
# symbolics library from trying to simplify this expression
1751
# again. This would lead to infinite loops otherwise.
1752
from sage.symbolic.ring import SR
1753
try:
1754
res = QQ(base)**QQ(exp)
1755
except TypeError:
1756
pass
1757
else:
1758
if res.parent() is not SR:
1759
return parent(cbase)(res)
1760
return res
1761
sbase = SR(base)
1762
if sbase.operator() is operator.pow:
1763
nbase, pexp = sbase.operands()
1764
return nbase.power(pexp * exp, hold=True)
1765
else:
1766
return sbase.power(exp, hold=True)
1767
1768
cdef void _reduce_c_(self):
1769
"""
1770
Pull out common factors from the numerator and denominator!
1771
"""
1772
cdef ZZ_c gcd
1773
cdef ZZ_c t1
1774
cdef ZZX_c t2
1775
ZZX_content(t1, self.__numerator)
1776
ZZ_GCD(gcd, t1, self.__denominator)
1777
if ZZ_sign(gcd) != ZZ_sign(self.__denominator):
1778
ZZ_negate(t1, gcd)
1779
gcd = t1
1780
ZZX_div_ZZ(t2, self.__numerator, gcd)
1781
ZZ_div(t1, self.__denominator, gcd)
1782
self.__numerator = t2
1783
self.__denominator = t1
1784
1785
cpdef ModuleElement _add_(self, ModuleElement right):
1786
r"""
1787
EXAMPLE::
1788
1789
sage: K.<s> = QuadraticField(2)
1790
sage: s + s # indirect doctest
1791
2*s
1792
sage: s + ZZ(3) # indirect doctest
1793
s + 3
1794
"""
1795
cdef NumberFieldElement x
1796
cdef NumberFieldElement _right = right
1797
x = self._new()
1798
ZZ_mul(x.__denominator, self.__denominator, _right.__denominator)
1799
cdef ZZX_c t1, t2
1800
ZZX_mul_ZZ(t1, self.__numerator, _right.__denominator)
1801
ZZX_mul_ZZ(t2, _right.__numerator, self.__denominator)
1802
ZZX_add(x.__numerator, t1, t2)
1803
x._reduce_c_()
1804
return x
1805
1806
cpdef ModuleElement _sub_(self, ModuleElement right):
1807
r"""
1808
EXAMPLES::
1809
1810
sage: K.<a> = NumberField(x^3 + 2)
1811
sage: (a/2) - (a + 3) # indirect doctest
1812
-1/2*a - 3
1813
"""
1814
cdef NumberFieldElement x
1815
cdef NumberFieldElement _right = right
1816
x = self._new()
1817
ZZ_mul(x.__denominator, self.__denominator, _right.__denominator)
1818
cdef ZZX_c t1, t2
1819
ZZX_mul_ZZ(t1, self.__numerator, _right.__denominator)
1820
ZZX_mul_ZZ(t2, _right.__numerator, self.__denominator)
1821
ZZX_sub(x.__numerator, t1, t2)
1822
x._reduce_c_()
1823
return x
1824
1825
cpdef RingElement _mul_(self, RingElement right):
1826
"""
1827
Returns the product of self and other as elements of a number
1828
field.
1829
1830
EXAMPLES::
1831
1832
sage: C.<zeta12>=CyclotomicField(12)
1833
sage: zeta12*zeta12^11
1834
1
1835
sage: G.<a> = NumberField(x^3 + 2/3*x + 1)
1836
sage: a^3 # indirect doctest
1837
-2/3*a - 1
1838
sage: a^3+a # indirect doctest
1839
1/3*a - 1
1840
"""
1841
cdef NumberFieldElement x
1842
cdef NumberFieldElement _right = right
1843
cdef ZZX_c temp
1844
cdef ZZ_c temp1
1845
x = self._new()
1846
sig_on()
1847
# MulMod doesn't handle non-monic polynomials.
1848
# Therefore, we handle the non-monic case entirely separately.
1849
1850
if ZZ_IsOne(ZZX_LeadCoeff(self.__fld_numerator.x)):
1851
ZZ_mul(x.__denominator, self.__denominator, _right.__denominator)
1852
ZZX_MulMod(x.__numerator, self.__numerator, _right.__numerator, self.__fld_numerator.x)
1853
else:
1854
ZZ_mul(x.__denominator, self.__denominator, _right.__denominator)
1855
ZZX_mul(x.__numerator, self.__numerator, _right.__numerator)
1856
if ZZX_deg(x.__numerator) >= ZZX_deg(self.__fld_numerator.x):
1857
ZZX_mul_ZZ( x.__numerator, x.__numerator, self.__fld_denominator.x )
1858
ZZX_mul_ZZ( temp, self.__fld_numerator.x, x.__denominator )
1859
ZZ_power(temp1,ZZX_LeadCoeff(temp),ZZX_deg(x.__numerator)-ZZX_deg(self.__fld_numerator.x)+1)
1860
ZZX_PseudoRem(x.__numerator, x.__numerator, temp)
1861
ZZ_mul(x.__denominator, x.__denominator, self.__fld_denominator.x)
1862
ZZ_mul(x.__denominator, x.__denominator, temp1)
1863
sig_off()
1864
x._reduce_c_()
1865
return x
1866
1867
#NOTES: In LiDIA, they build a multiplication table for the
1868
#number field, so it's not necessary to reduce modulo the
1869
#defining polynomial every time:
1870
# src/number_fields/algebraic_num/order.cc: compute_table
1871
# but asymptotically fast poly multiplication means it's
1872
# actually faster to *not* build a table!?!
1873
1874
cpdef RingElement _div_(self, RingElement right):
1875
"""
1876
Returns the quotient of self and other as elements of a number
1877
field.
1878
1879
EXAMPLES::
1880
1881
sage: C.<I>=CyclotomicField(4)
1882
sage: 1/I # indirect doctest
1883
-I
1884
sage: I/0 # indirect doctest
1885
Traceback (most recent call last):
1886
...
1887
ZeroDivisionError: rational division by zero
1888
1889
::
1890
1891
sage: G.<a> = NumberField(x^3 + 2/3*x + 1)
1892
sage: a/a # indirect doctest
1893
1
1894
sage: 1/a # indirect doctest
1895
-a^2 - 2/3
1896
sage: a/0 # indirect doctest
1897
Traceback (most recent call last):
1898
...
1899
ZeroDivisionError: Number field element division by zero
1900
"""
1901
cdef NumberFieldElement x
1902
cdef NumberFieldElement _right = right
1903
cdef ZZX_c inv_num
1904
cdef ZZ_c inv_den
1905
cdef ZZX_c temp
1906
cdef ZZ_c temp1
1907
if not _right:
1908
raise ZeroDivisionError, "Number field element division by zero"
1909
x = self._new()
1910
sig_on()
1911
_right._invert_c_(&inv_num, &inv_den)
1912
if ZZ_IsOne(ZZX_LeadCoeff(self.__fld_numerator.x)):
1913
ZZ_mul(x.__denominator, self.__denominator, inv_den)
1914
ZZX_MulMod(x.__numerator, self.__numerator, inv_num, self.__fld_numerator.x)
1915
else:
1916
ZZ_mul(x.__denominator, self.__denominator, inv_den)
1917
ZZX_mul(x.__numerator, self.__numerator, inv_num)
1918
if ZZX_deg(x.__numerator) >= ZZX_deg(self.__fld_numerator.x):
1919
ZZX_mul_ZZ( x.__numerator, x.__numerator, self.__fld_denominator.x )
1920
ZZX_mul_ZZ( temp, self.__fld_numerator.x, x.__denominator )
1921
ZZ_power(temp1,ZZX_LeadCoeff(temp),ZZX_deg(x.__numerator)-ZZX_deg(self.__fld_numerator.x)+1)
1922
ZZX_PseudoRem(x.__numerator, x.__numerator, temp)
1923
ZZ_mul(x.__denominator, x.__denominator, self.__fld_denominator.x)
1924
ZZ_mul(x.__denominator, x.__denominator, temp1)
1925
x._reduce_c_()
1926
sig_off()
1927
return x
1928
1929
def __floordiv__(self, other):
1930
"""
1931
Return the quotient of self and other. Since these are field
1932
elements the floor division is exactly the same as usual division.
1933
1934
EXAMPLES::
1935
1936
sage: m.<b> = NumberField(x^4 + x^2 + 2/3)
1937
sage: c = (1+b) // (1-b); c
1938
3/4*b^3 + 3/4*b^2 + 3/2*b + 1/2
1939
sage: (1+b) / (1-b) == c
1940
True
1941
sage: c * (1-b)
1942
b + 1
1943
"""
1944
return self / other
1945
1946
def __nonzero__(self):
1947
"""
1948
Return True if this number field element is nonzero.
1949
1950
EXAMPLES::
1951
1952
sage: m.<b> = CyclotomicField(17)
1953
sage: m(0).__nonzero__()
1954
False
1955
sage: b.__nonzero__()
1956
True
1957
1958
Nonzero is used by the bool command::
1959
1960
sage: bool(b + 1)
1961
True
1962
sage: bool(m(0))
1963
False
1964
"""
1965
return not IsZero_ZZX(self.__numerator)
1966
1967
cpdef ModuleElement _neg_(self):
1968
r"""
1969
EXAMPLE::
1970
1971
sage: K.<a> = NumberField(x^3 + 2)
1972
sage: -a # indirect doctest
1973
-a
1974
"""
1975
cdef NumberFieldElement x
1976
x = self._new()
1977
ZZX_mul_long(x.__numerator, self.__numerator, -1)
1978
x.__denominator = self.__denominator
1979
return x
1980
1981
def __copy__(self):
1982
r"""
1983
EXAMPLE::
1984
1985
sage: K.<a> = NumberField(x^3 + 2)
1986
sage: b = copy(a)
1987
sage: b == a
1988
True
1989
sage: b is a
1990
False
1991
"""
1992
cdef NumberFieldElement x
1993
x = self._new()
1994
x.__numerator = self.__numerator
1995
x.__denominator = self.__denominator
1996
return x
1997
1998
def __int__(self):
1999
"""
2000
Attempt to convert this number field element to a Python integer,
2001
if possible.
2002
2003
EXAMPLES::
2004
2005
sage: C.<I>=CyclotomicField(4)
2006
sage: int(1/I)
2007
Traceback (most recent call last):
2008
...
2009
TypeError: cannot coerce nonconstant polynomial to int
2010
sage: int(I*I)
2011
-1
2012
2013
::
2014
2015
sage: K.<a> = NumberField(x^10 - x - 1)
2016
sage: int(a)
2017
Traceback (most recent call last):
2018
...
2019
TypeError: cannot coerce nonconstant polynomial to int
2020
sage: int(K(9390283))
2021
9390283
2022
2023
The semantics are like in Python, so the value does not have to
2024
preserved.
2025
2026
::
2027
2028
sage: int(K(393/29))
2029
13
2030
"""
2031
return int(self.polynomial())
2032
2033
def __long__(self):
2034
"""
2035
Attempt to convert this number field element to a Python long, if
2036
possible.
2037
2038
EXAMPLES::
2039
2040
sage: K.<a> = NumberField(x^10 - x - 1)
2041
sage: long(a)
2042
Traceback (most recent call last):
2043
...
2044
TypeError: cannot coerce nonconstant polynomial to long
2045
sage: long(K(1234))
2046
1234L
2047
2048
The value does not have to be preserved, in the case of fractions.
2049
2050
::
2051
2052
sage: long(K(393/29))
2053
13L
2054
"""
2055
return long(self.polynomial())
2056
2057
cdef void _invert_c_(self, ZZX_c *num, ZZ_c *den):
2058
"""
2059
Computes the numerator and denominator of the multiplicative
2060
inverse of this element.
2061
2062
Suppose that this element is x/d and the parent mod'ding polynomial
2063
is M/D. The NTL function XGCD( r, s, t, a, b ) computes r,s,t such
2064
that `r=s*a+t*b`. We compute XGCD( r, s, t, x\*D, M\*d )
2065
and set num=s\*D\*d den=r
2066
2067
EXAMPLES:
2068
2069
I'd love to, but since we are dealing with c-types, I
2070
can't at this level. Check __invert__ for doc-tests that rely
2071
on this functionality.
2072
"""
2073
cdef ZZX_c t # unneeded except to be there
2074
cdef ZZX_c a, b
2075
ZZX_mul_ZZ( a, self.__numerator, self.__fld_denominator.x )
2076
ZZX_mul_ZZ( b, self.__fld_numerator.x, self.__denominator )
2077
ZZX_XGCD( den[0], num[0], t, a, b, 1 )
2078
ZZX_mul_ZZ( num[0], num[0], self.__fld_denominator.x )
2079
ZZX_mul_ZZ( num[0], num[0], self.__denominator )
2080
2081
def __invert__(self):
2082
"""
2083
Returns the multiplicative inverse of self in the number field.
2084
2085
EXAMPLES::
2086
2087
sage: C.<I>=CyclotomicField(4)
2088
sage: ~I
2089
-I
2090
sage: (2*I).__invert__()
2091
-1/2*I
2092
"""
2093
if IsZero_ZZX(self.__numerator):
2094
raise ZeroDivisionError
2095
cdef NumberFieldElement x
2096
x = self._new()
2097
self._invert_c_(&x.__numerator, &x.__denominator)
2098
x._reduce_c_()
2099
return x
2100
2101
def _integer_(self, Z=None):
2102
"""
2103
Returns an integer if this element is actually an integer.
2104
2105
EXAMPLES::
2106
2107
sage: C.<I>=CyclotomicField(4)
2108
sage: (~I)._integer_()
2109
Traceback (most recent call last):
2110
...
2111
TypeError: Unable to coerce -I to an integer
2112
sage: (2*I*I)._integer_()
2113
-2
2114
"""
2115
if ZZX_deg(self.__numerator) >= 1:
2116
raise TypeError, "Unable to coerce %s to an integer"%self
2117
return ZZ(self._rational_())
2118
2119
def _rational_(self):
2120
"""
2121
Returns a rational number if this element is actually a rational
2122
number.
2123
2124
EXAMPLES::
2125
2126
sage: C.<I>=CyclotomicField(4)
2127
sage: (~I)._rational_()
2128
Traceback (most recent call last):
2129
...
2130
TypeError: Unable to coerce -I to a rational
2131
sage: (I*I/2)._rational_()
2132
-1/2
2133
"""
2134
if ZZX_deg(self.__numerator) >= 1:
2135
raise TypeError, "Unable to coerce %s to a rational"%self
2136
cdef Integer num
2137
num = PY_NEW(Integer)
2138
ZZX_getitem_as_mpz(num.value, &self.__numerator, 0)
2139
return num / (<IntegerRing_class>ZZ)._coerce_ZZ(&self.__denominator)
2140
2141
def _symbolic_(self, SR):
2142
"""
2143
If an embedding into CC is specified, then a representation of this
2144
element can be made in the symbolic ring (assuming roots of the
2145
minimal polynomial can be found symbolically).
2146
2147
EXAMPLES::
2148
2149
sage: K.<a> = QuadraticField(2)
2150
sage: SR(a) # indirect doctest
2151
sqrt(2)
2152
sage: SR(3*a-5) # indirect doctest
2153
3*sqrt(2) - 5
2154
sage: K.<a> = QuadraticField(2, embedding=-1.4)
2155
sage: SR(a) # indirect doctest
2156
-sqrt(2)
2157
sage: K.<a> = NumberField(x^2 - 2)
2158
sage: SR(a) # indirect doctest
2159
Traceback (most recent call last):
2160
...
2161
TypeError: an embedding into RR or CC must be specified
2162
2163
Now a more complicated example::
2164
2165
sage: K.<a> = NumberField(x^3 + x - 1, embedding=0.68)
2166
sage: b = SR(a); b # indirect doctest
2167
(1/18*sqrt(31)*sqrt(3) + 1/2)^(1/3) - 1/3/(1/18*sqrt(31)*sqrt(3) + 1/2)^(1/3)
2168
sage: (b^3 + b - 1).canonicalize_radical()
2169
0
2170
2171
Make sure we got the right one::
2172
2173
sage: CC(a)
2174
0.682327803828019
2175
sage: CC(b)
2176
0.682327803828019
2177
2178
Special case for cyclotomic fields::
2179
2180
sage: K.<zeta> = CyclotomicField(19)
2181
sage: SR(zeta) # indirect doctest
2182
e^(2/19*I*pi)
2183
sage: CC(zeta)
2184
0.945817241700635 + 0.324699469204683*I
2185
sage: CC(SR(zeta))
2186
0.945817241700635 + 0.324699469204683*I
2187
2188
sage: SR(zeta^5 + 2)
2189
e^(10/19*I*pi) + 2
2190
2191
For degree greater than 5, sometimes Galois theory prevents a
2192
closed-form solution. In this case, an algebraic number is
2193
embedded into the symbolic ring, which will usually get
2194
printed as a numerical approximation::
2195
2196
sage: K.<a> = NumberField(x^5-x+1, embedding=-1)
2197
sage: SR(a)
2198
-1.167303978261419?
2199
2200
::
2201
2202
sage: K.<a> = NumberField(x^6-x^3-1, embedding=1)
2203
sage: SR(a)
2204
(1/2*sqrt(5) + 1/2)^(1/3)
2205
2206
In this field, general elements cannot be written in terms of
2207
radicals, but particular elements might be::
2208
2209
sage: K.<a> = NumberField(x^10 + 6*x^6 + 9*x^2 + 1, embedding=CC(0.332*I))
2210
sage: SR(a)
2211
0.3319890295845093?*I
2212
sage: SR(a^5+3*a)
2213
I
2214
2215
Conversely, some elements are too complicated to be written in
2216
terms of radicals directly. At least until :trac:`17516` gets
2217
addressed. In those cases, the generator might be converted
2218
and its expression be used to convert other elements. This
2219
avoids regressions but can lead to fairly complicated
2220
expressions::
2221
2222
sage: K.<a> = NumberField(QQ['x']([6, -65, 163, -185, 81, -15, 1]), embedding=4.9)
2223
sage: b = a + a^3
2224
sage: SR(b.minpoly()).solve(SR('x'), explicit_solutions=True)
2225
[]
2226
sage: SR(b)
2227
1/8*(sqrt(4*(1/9*sqrt(109)*sqrt(3) + 2)^(1/3) - 4/3/(1/9*sqrt(109)*sqrt(3) + 2)^(1/3) + 17) + 5)^3 + 1/2*sqrt(4*(1/9*sqrt(109)*sqrt(3) + 2)^(1/3) - 4/3/(1/9*sqrt(109)*sqrt(3) + 2)^(1/3) + 17) + 5/2
2228
2229
"""
2230
K = self._parent.fraction_field()
2231
2232
embedding = K.specified_complex_embedding()
2233
if embedding is None:
2234
raise TypeError("an embedding into RR or CC must be specified")
2235
2236
if isinstance(K, number_field.NumberField_cyclotomic):
2237
# solution by radicals may be difficult, but we have a closed form
2238
from sage.all import exp, I, pi, ComplexField, RR
2239
CC = ComplexField(53)
2240
two_pi_i = 2 * pi * I
2241
k = ( K._n()*CC(K.gen()).log() / CC(two_pi_i) ).real().round() # n ln z / (2 pi i)
2242
gen_image = exp(k*two_pi_i/K._n())
2243
return self.polynomial()(gen_image)
2244
else:
2245
# Convert the embedding to an embedding into AA or QQbar
2246
embedding = number_field.refine_embedding(embedding, infinity)
2247
a = embedding(self).radical_expression()
2248
if a.parent() == SR:
2249
return a
2250
# Once #17516 gets fixed, the next three lines can be dropped
2251
# and the remaining lines be simplified to undo df03633.
2252
b = embedding.im_gens()[0].radical_expression()
2253
if b.parent() == SR:
2254
return self.polynomial()(b)
2255
return SR(a)
2256
2257
def galois_conjugates(self, K):
2258
r"""
2259
Return all Gal(Qbar/Q)-conjugates of this number field element in
2260
the field K.
2261
2262
EXAMPLES:
2263
2264
In the first example the conjugates are obvious::
2265
2266
sage: K.<a> = NumberField(x^2 - 2)
2267
sage: a.galois_conjugates(K)
2268
[a, -a]
2269
sage: K(3).galois_conjugates(K)
2270
[3]
2271
2272
In this example the field is not Galois, so we have to pass to an
2273
extension to obtain the Galois conjugates.
2274
2275
::
2276
2277
sage: K.<a> = NumberField(x^3 - 2)
2278
sage: c = a.galois_conjugates(K); c
2279
[a]
2280
sage: K.<a> = NumberField(x^3 - 2)
2281
sage: c = a.galois_conjugates(K.galois_closure('a1')); c
2282
[1/18*a1^4, -1/36*a1^4 + 1/2*a1, -1/36*a1^4 - 1/2*a1]
2283
sage: c[0]^3
2284
2
2285
sage: parent(c[0])
2286
Number Field in a1 with defining polynomial x^6 + 108
2287
sage: parent(c[0]).is_galois()
2288
True
2289
2290
There is only one Galois conjugate of `\sqrt[3]{2}` in
2291
`\QQ(\sqrt[3]{2})`.
2292
2293
::
2294
2295
sage: a.galois_conjugates(K)
2296
[a]
2297
2298
Galois conjugates of `\sqrt[3]{2}` in the field
2299
`\QQ(\zeta_3,\sqrt[3]{2})`::
2300
2301
sage: L.<a> = CyclotomicField(3).extension(x^3 - 2)
2302
sage: a.galois_conjugates(L)
2303
[a, (-zeta3 - 1)*a, zeta3*a]
2304
"""
2305
f = self.absolute_minpoly()
2306
g = K['x'](f)
2307
return [a for a,_ in g.roots()]
2308
2309
def conjugate(self):
2310
"""
2311
Return the complex conjugate of the number field element.
2312
2313
This is only well-defined for fields contained in CM fields
2314
(i.e. for totally real fields and CM fields). Recall that a CM
2315
field is a totally imaginary quadratic extension of a totally
2316
real field. For other fields, a ValueError is raised.
2317
2318
EXAMPLES::
2319
2320
sage: k.<I> = QuadraticField(-1)
2321
sage: I.conjugate()
2322
-I
2323
sage: (I/(1+I)).conjugate()
2324
-1/2*I + 1/2
2325
sage: z6 = CyclotomicField(6).gen(0)
2326
sage: (2*z6).conjugate()
2327
-2*zeta6 + 2
2328
2329
The following example now works.
2330
2331
::
2332
2333
sage: F.<b> = NumberField(x^2 - 2)
2334
sage: K.<j> = F.extension(x^2 + 1)
2335
sage: j.conjugate()
2336
-j
2337
2338
Raise a ValueError if the field is not contained in a CM field.
2339
2340
::
2341
2342
sage: K.<b> = NumberField(x^3 - 2)
2343
sage: b.conjugate()
2344
Traceback (most recent call last):
2345
...
2346
ValueError: Complex conjugation is only well-defined for fields contained in CM fields.
2347
2348
An example of a non-quadratic totally real field.
2349
2350
::
2351
2352
sage: F.<a> = NumberField(x^4 + x^3 - 3*x^2 - x + 1)
2353
sage: a.conjugate()
2354
a
2355
2356
An example of a non-cyclotomic CM field.
2357
2358
::
2359
2360
sage: K.<a> = NumberField(x^4 - x^3 + 2*x^2 + x + 1)
2361
sage: a.conjugate()
2362
-1/2*a^3 - a - 1/2
2363
sage: (2*a^2 - 1).conjugate()
2364
a^3 - 2*a^2 - 2
2365
2366
"""
2367
2368
nf = self.number_field()
2369
return nf.complex_conjugation()(self)
2370
2371
def polynomial(self, var='x'):
2372
"""
2373
Return the underlying polynomial corresponding to this number field
2374
element.
2375
2376
The resulting polynomial is currently *not* cached.
2377
2378
EXAMPLES::
2379
2380
sage: K.<a> = NumberField(x^5 - x - 1)
2381
sage: f = (-2/3 + 1/3*a)^4; f
2382
1/81*a^4 - 8/81*a^3 + 8/27*a^2 - 32/81*a + 16/81
2383
sage: g = f.polynomial(); g
2384
1/81*x^4 - 8/81*x^3 + 8/27*x^2 - 32/81*x + 16/81
2385
sage: parent(g)
2386
Univariate Polynomial Ring in x over Rational Field
2387
2388
Note that the result of this function is not cached (should this be
2389
changed?)::
2390
2391
sage: g is f.polynomial()
2392
False
2393
"""
2394
return QQ[var](self._coefficients())
2395
2396
def __hash__(self):
2397
"""
2398
Return hash of this number field element, which is just the
2399
hash of the underlying polynomial.
2400
2401
EXAMPLE::
2402
2403
sage: K.<b> = NumberField(x^3 - 2)
2404
sage: hash(b^2 + 1) == hash((b^2 + 1).polynomial()) # indirect doctest
2405
True
2406
"""
2407
return hash(self.polynomial())
2408
2409
def _coefficients(self):
2410
"""
2411
Return the coefficients of the underlying polynomial corresponding
2412
to this number field element.
2413
2414
OUTPUT:
2415
2416
- a list whose length corresponding to the degree of this
2417
element written in terms of a generator.
2418
2419
EXAMPLES::
2420
2421
sage: K.<b> = NumberField(x^3 - 2)
2422
sage: (b^2 + 1)._coefficients()
2423
[1, 0, 1]
2424
"""
2425
coeffs = []
2426
cdef Integer den = (<IntegerRing_class>ZZ)._coerce_ZZ(&self.__denominator)
2427
cdef Integer numCoeff
2428
cdef int i
2429
for i from 0 <= i <= ZZX_deg(self.__numerator):
2430
numCoeff = PY_NEW(Integer)
2431
ZZX_getitem_as_mpz(numCoeff.value, &self.__numerator, i)
2432
coeffs.append( numCoeff / den )
2433
return coeffs
2434
2435
cdef void _ntl_coeff_as_mpz(self, mpz_t z, long i):
2436
if i > ZZX_deg(self.__numerator):
2437
mpz_set_ui(z, 0)
2438
else:
2439
ZZX_getitem_as_mpz(z, &self.__numerator, i)
2440
2441
cdef void _ntl_denom_as_mpz(self, mpz_t z):
2442
cdef Integer denom = (<IntegerRing_class>ZZ)._coerce_ZZ(&self.__denominator)
2443
mpz_set(z, denom.value)
2444
2445
def denominator(self):
2446
"""
2447
Return the denominator of this element, which is by definition the
2448
denominator of the corresponding polynomial representation. I.e.,
2449
elements of number fields are represented as a polynomial (in
2450
reduced form) modulo the modulus of the number field, and the
2451
denominator is the denominator of this polynomial.
2452
2453
EXAMPLES::
2454
2455
sage: K.<z> = CyclotomicField(3)
2456
sage: a = 1/3 + (1/5)*z
2457
sage: print a.denominator()
2458
15
2459
"""
2460
return (<IntegerRing_class>ZZ)._coerce_ZZ(&self.__denominator)
2461
2462
def _set_multiplicative_order(self, n):
2463
"""
2464
Set the multiplicative order of this number field element.
2465
2466
.. warning::
2467
2468
Use with caution - only for internal use! End users should
2469
never call this unless they have a very good reason to do
2470
so.
2471
2472
EXAMPLES::
2473
2474
sage: K.<a> = NumberField(x^2 + x + 1)
2475
sage: a._set_multiplicative_order(3)
2476
sage: a.multiplicative_order()
2477
3
2478
2479
You can be evil with this so be careful. That's why the function
2480
name begins with an underscore.
2481
2482
::
2483
2484
sage: a._set_multiplicative_order(389)
2485
sage: a.multiplicative_order()
2486
389
2487
"""
2488
self.__multiplicative_order = n
2489
2490
def multiplicative_order(self):
2491
"""
2492
Return the multiplicative order of this number field element.
2493
2494
EXAMPLES::
2495
2496
sage: K.<z> = CyclotomicField(5)
2497
sage: z.multiplicative_order()
2498
5
2499
sage: (-z).multiplicative_order()
2500
10
2501
sage: (1+z).multiplicative_order()
2502
+Infinity
2503
2504
sage: x = polygen(QQ)
2505
sage: K.<a>=NumberField(x^40 - x^20 + 4)
2506
sage: u = 1/4*a^30 + 1/4*a^10 + 1/2
2507
sage: u.multiplicative_order()
2508
6
2509
sage: a.multiplicative_order()
2510
+Infinity
2511
2512
An example in a relative extension::
2513
2514
sage: K.<a, b> = NumberField([x^2 + x + 1, x^2 - 3])
2515
sage: z = (a - 1)*b/3
2516
sage: z.multiplicative_order()
2517
12
2518
sage: z^12==1 and z^6!=1 and z^4!=1
2519
True
2520
2521
"""
2522
if self.__multiplicative_order is None:
2523
if self.is_rational():
2524
if self.is_one():
2525
self.__multiplicative_order = ZZ(1)
2526
elif (-self).is_one():
2527
self.__multiplicative_order = ZZ(2)
2528
else:
2529
self.__multiplicative_order = sage.rings.infinity.infinity
2530
elif not (self.is_integral() and self.norm().is_one()):
2531
self.__multiplicative_order = sage.rings.infinity.infinity
2532
elif isinstance(self.number_field(), number_field.NumberField_cyclotomic):
2533
t = self.number_field()._multiplicative_order_table()
2534
f = self.polynomial()
2535
if f in t:
2536
self.__multiplicative_order = t[f]
2537
else:
2538
self.__multiplicative_order = sage.rings.infinity.infinity
2539
else:
2540
# Now we have a unit of norm 1, and check if it is a root of unity
2541
n = self.number_field().zeta_order()
2542
if not self**n ==1:
2543
self.__multiplicative_order = sage.rings.infinity.infinity
2544
else:
2545
from sage.groups.generic import order_from_multiple
2546
self.__multiplicative_order = order_from_multiple(self,n,operation='*')
2547
2548
return self.__multiplicative_order
2549
2550
def additive_order(self):
2551
r"""
2552
Return the additive order of this element (i.e. infinity if
2553
self != 0, 1 if self == 0)
2554
2555
EXAMPLES::
2556
2557
sage: K.<u> = NumberField(x^4 - 3*x^2 + 3)
2558
sage: u.additive_order()
2559
+Infinity
2560
sage: K(0).additive_order()
2561
1
2562
sage: K.ring_of_integers().characteristic() # implicit doctest
2563
0
2564
"""
2565
if not self: return ZZ.one()
2566
else: return sage.rings.infinity.infinity
2567
2568
cpdef bint is_one(self):
2569
r"""
2570
Test whether this number field element is `1`.
2571
2572
EXAMPLES::
2573
2574
sage: K.<a> = NumberField(x^3 + 3)
2575
sage: K(1).is_one()
2576
True
2577
sage: K(0).is_one()
2578
False
2579
sage: K(-1).is_one()
2580
False
2581
sage: K(1/2).is_one()
2582
False
2583
sage: a.is_one()
2584
False
2585
"""
2586
return ZZX_IsOne(self.__numerator) == 1 and \
2587
ZZ_IsOne(self.__denominator) == 1
2588
2589
cpdef bint is_rational(self):
2590
r"""
2591
Test whether this number field element is a rational number
2592
2593
.. SEEALSO:
2594
2595
- :meth:`is_integer` to test if this element is an integer
2596
- :meth:`is_integral` to test if this element is an algebraic integer
2597
2598
EXAMPLES::
2599
2600
sage: K.<cbrt3> = NumberField(x^3 - 3)
2601
sage: cbrt3.is_rational()
2602
False
2603
sage: (cbrt3**2 - cbrt3 + 1/2).is_rational()
2604
False
2605
sage: K(-12).is_rational()
2606
True
2607
sage: K(0).is_rational()
2608
True
2609
sage: K(1/2).is_rational()
2610
True
2611
"""
2612
return ZZX_deg(self.__numerator) <= 0
2613
2614
def is_integer(self):
2615
r"""
2616
Test whether this number field element is an integer
2617
2618
.. SEEALSO:
2619
2620
- :meth:`is_rational` to test if this element is a rational number
2621
- :meth:`is_integral` to test if this element is an algebraic integer
2622
2623
EXAMPLES::
2624
2625
sage: K.<cbrt3> = NumberField(x^3 - 3)
2626
sage: cbrt3.is_integer()
2627
False
2628
sage: (cbrt3**2 - cbrt3 + 2).is_integer()
2629
False
2630
sage: K(-12).is_integer()
2631
True
2632
sage: K(0).is_integer()
2633
True
2634
sage: K(1/2).is_integer()
2635
False
2636
"""
2637
return ZZX_deg(self.__numerator) <= 0 and ZZ_IsOne(self.__denominator) == 1
2638
2639
def trace(self, K=None):
2640
"""
2641
Return the absolute or relative trace of this number field
2642
element.
2643
2644
If K is given then K must be a subfield of the parent L of self, in
2645
which case the trace is the relative trace from L to K. In all
2646
other cases, the trace is the absolute trace down to QQ.
2647
2648
EXAMPLES::
2649
2650
sage: K.<a> = NumberField(x^3 -132/7*x^2 + x + 1); K
2651
Number Field in a with defining polynomial x^3 - 132/7*x^2 + x + 1
2652
sage: a.trace()
2653
132/7
2654
sage: (a+1).trace() == a.trace() + 3
2655
True
2656
2657
If we are in an order, the trace is an integer::
2658
2659
sage: K.<zeta> = CyclotomicField(17)
2660
sage: R = K.ring_of_integers()
2661
sage: R(zeta).trace().parent()
2662
Integer Ring
2663
2664
TESTS::
2665
2666
sage: F.<z> = CyclotomicField(5) ; t = 3*z**3 + 4*z**2 + 2
2667
sage: t.trace(F)
2668
3*z^3 + 4*z^2 + 2
2669
"""
2670
if K is None:
2671
trace = self._pari_('x').trace()
2672
return QQ(trace) if self._parent.is_field() else ZZ(trace)
2673
return self.matrix(K).trace()
2674
2675
def norm(self, K=None):
2676
"""
2677
Return the absolute or relative norm of this number field element.
2678
2679
If K is given then K must be a subfield of the parent L of self, in
2680
which case the norm is the relative norm from L to K. In all other
2681
cases, the norm is the absolute norm down to QQ.
2682
2683
EXAMPLES::
2684
2685
sage: K.<a> = NumberField(x^3 + x^2 + x - 132/7); K
2686
Number Field in a with defining polynomial x^3 + x^2 + x - 132/7
2687
sage: a.norm()
2688
132/7
2689
sage: factor(a.norm())
2690
2^2 * 3 * 7^-1 * 11
2691
sage: K(0).norm()
2692
0
2693
2694
Some complicated relatives norms in a tower of number fields.
2695
2696
::
2697
2698
sage: K.<a,b,c> = NumberField([x^2 + 1, x^2 + 3, x^2 + 5])
2699
sage: L = K.base_field(); M = L.base_field()
2700
sage: a.norm()
2701
1
2702
sage: a.norm(L)
2703
1
2704
sage: a.norm(M)
2705
1
2706
sage: a
2707
a
2708
sage: (a+b+c).norm()
2709
121
2710
sage: (a+b+c).norm(L)
2711
2*c*b - 7
2712
sage: (a+b+c).norm(M)
2713
-11
2714
2715
We illustrate that norm is compatible with towers::
2716
2717
sage: z = (a+b+c).norm(L); z.norm(M)
2718
-11
2719
2720
If we are in an order, the norm is an integer::
2721
2722
sage: K.<a> = NumberField(x^3-2)
2723
sage: a.norm().parent()
2724
Rational Field
2725
sage: R = K.ring_of_integers()
2726
sage: R(a).norm().parent()
2727
Integer Ring
2728
2729
When the base field is given by an embedding::
2730
2731
sage: K.<a> = NumberField(x^4 + 1)
2732
sage: L.<a2> = NumberField(x^2 + 1)
2733
sage: v = L.embeddings(K)
2734
sage: a.norm(v[1])
2735
a2
2736
sage: a.norm(v[0])
2737
-a2
2738
2739
TESTS::
2740
2741
sage: F.<z> = CyclotomicField(5)
2742
sage: t = 3*z**3 + 4*z**2 + 2
2743
sage: t.norm(F)
2744
3*z^3 + 4*z^2 + 2
2745
"""
2746
if K is None or (K in Fields and K.absolute_degree() == 1):
2747
norm = self._pari_('x').norm()
2748
return QQ(norm) if self._parent in Fields else ZZ(norm)
2749
return self.matrix(K).determinant()
2750
2751
def absolute_norm(self):
2752
"""
2753
Return the absolute norm of this number field element.
2754
2755
EXAMPLES::
2756
2757
sage: K1.<a1> = CyclotomicField(11)
2758
sage: K2.<a2> = K1.extension(x^2 - 3)
2759
sage: K3.<a3> = K2.extension(x^2 + 1)
2760
sage: (a1 + a2 + a3).absolute_norm()
2761
1353244757701
2762
2763
sage: QQ(7/5).absolute_norm()
2764
7/5
2765
"""
2766
return self.norm()
2767
2768
def relative_norm(self):
2769
"""
2770
Return the relative norm of this number field element over the next field
2771
down in some tower of number fields.
2772
2773
EXAMPLES::
2774
2775
sage: K1.<a1> = CyclotomicField(11)
2776
sage: K2.<a2> = K1.extension(x^2 - 3)
2777
sage: (a1 + a2).relative_norm()
2778
a1^2 - 3
2779
sage: (a1 + a2).relative_norm().relative_norm() == (a1 + a2).absolute_norm()
2780
True
2781
2782
sage: K.<x,y,z> = NumberField([x^2 + 1, x^3 - 3, x^2 - 5])
2783
sage: (x + y + z).relative_norm()
2784
y^2 + 2*z*y + 6
2785
"""
2786
return self.norm(self.parent().base_field())
2787
2788
def vector(self):
2789
"""
2790
Return vector representation of self in terms of the basis for the
2791
ambient number field.
2792
2793
EXAMPLES::
2794
2795
sage: K.<a> = NumberField(x^2 + 1)
2796
sage: (2/3*a - 5/6).vector()
2797
(-5/6, 2/3)
2798
sage: (-5/6, 2/3)
2799
(-5/6, 2/3)
2800
sage: O = K.order(2*a)
2801
sage: (O.1).vector()
2802
(0, 2)
2803
sage: K.<a,b> = NumberField([x^2 + 1, x^2 - 3])
2804
sage: (a + b).vector()
2805
(b, 1)
2806
sage: O = K.order([a,b])
2807
sage: (O.1).vector()
2808
(-b, 1)
2809
sage: (O.2).vector()
2810
(1, -b)
2811
"""
2812
return self.number_field().relative_vector_space()[2](self)
2813
2814
def charpoly(self, var='x'):
2815
r"""
2816
Return the characteristic polynomial of this number field element.
2817
2818
EXAMPLE::
2819
2820
sage: K.<a> = NumberField(x^3 + 7)
2821
sage: a.charpoly()
2822
x^3 + 7
2823
sage: K(1).charpoly()
2824
x^3 - 3*x^2 + 3*x - 1
2825
"""
2826
raise NotImplementedError, "Subclasses of NumberFieldElement must override charpoly()"
2827
2828
def minpoly(self, var='x'):
2829
"""
2830
Return the minimal polynomial of this number field element.
2831
2832
EXAMPLES::
2833
2834
sage: K.<a> = NumberField(x^2+3)
2835
sage: a.minpoly('x')
2836
x^2 + 3
2837
sage: R.<X> = K['X']
2838
sage: L.<b> = K.extension(X^2-(22 + a))
2839
sage: b.minpoly('t')
2840
t^2 - a - 22
2841
sage: b.absolute_minpoly('t')
2842
t^4 - 44*t^2 + 487
2843
sage: b^2 - (22+a)
2844
0
2845
"""
2846
return self.charpoly(var).radical() # square free part of charpoly
2847
2848
def is_integral(self):
2849
r"""
2850
Determine if a number is in the ring of integers of this number
2851
field.
2852
2853
EXAMPLES::
2854
2855
sage: K.<a> = NumberField(x^2 + 23)
2856
sage: a.is_integral()
2857
True
2858
sage: t = (1+a)/2
2859
sage: t.is_integral()
2860
True
2861
sage: t.minpoly()
2862
x^2 - x + 6
2863
sage: t = a/2
2864
sage: t.is_integral()
2865
False
2866
sage: t.minpoly()
2867
x^2 + 23/4
2868
2869
An example in a relative extension::
2870
2871
sage: K.<a,b> = NumberField([x^2+1, x^2+3])
2872
sage: (a+b).is_integral()
2873
True
2874
sage: ((a-b)/2).is_integral()
2875
False
2876
"""
2877
return all([a in ZZ for a in self.absolute_minpoly()])
2878
2879
def matrix(self, base=None):
2880
r"""
2881
If base is None, return the matrix of right multiplication by the
2882
element on the power basis `1, x, x^2, \ldots, x^{d-1}` for
2883
the number field. Thus the *rows* of this matrix give the images of
2884
each of the `x^i`.
2885
2886
If base is not None, then base must be either a field that embeds
2887
in the parent of self or a morphism to the parent of self, in which
2888
case this function returns the matrix of multiplication by self on
2889
the power basis, where we view the parent field as a field over
2890
base.
2891
2892
Specifying base as the base field over which the parent of self
2893
is a relative extension is equivalent to base being None
2894
2895
INPUT:
2896
2897
2898
- ``base`` - field or morphism
2899
2900
2901
EXAMPLES:
2902
2903
Regular number field::
2904
2905
sage: K.<a> = NumberField(QQ['x'].0^3 - 5)
2906
sage: M = a.matrix(); M
2907
[0 1 0]
2908
[0 0 1]
2909
[5 0 0]
2910
sage: M.base_ring() is QQ
2911
True
2912
2913
Relative number field::
2914
2915
sage: L.<b> = K.extension(K['x'].0^2 - 2)
2916
sage: M = b.matrix(); M
2917
[0 1]
2918
[2 0]
2919
sage: M.base_ring() is K
2920
True
2921
2922
Absolute number field::
2923
2924
sage: M = L.absolute_field('c').gen().matrix(); M
2925
[ 0 1 0 0 0 0]
2926
[ 0 0 1 0 0 0]
2927
[ 0 0 0 1 0 0]
2928
[ 0 0 0 0 1 0]
2929
[ 0 0 0 0 0 1]
2930
[-17 -60 -12 -10 6 0]
2931
sage: M.base_ring() is QQ
2932
True
2933
2934
More complicated relative number field::
2935
2936
sage: L.<b> = K.extension(K['x'].0^2 - a); L
2937
Number Field in b with defining polynomial x^2 - a over its base field
2938
sage: M = b.matrix(); M
2939
[0 1]
2940
[a 0]
2941
sage: M.base_ring() is K
2942
True
2943
2944
An example where we explicitly give the subfield or the embedding::
2945
2946
sage: K.<a> = NumberField(x^4 + 1); L.<a2> = NumberField(x^2 + 1)
2947
sage: a.matrix(L)
2948
[ 0 1]
2949
[a2 0]
2950
2951
Notice that if we compute all embeddings and choose a different
2952
one, then the matrix is changed as it should be::
2953
2954
sage: v = L.embeddings(K)
2955
sage: a.matrix(v[1])
2956
[ 0 1]
2957
[-a2 0]
2958
2959
The norm is also changed::
2960
2961
sage: a.norm(v[1])
2962
a2
2963
sage: a.norm(v[0])
2964
-a2
2965
2966
TESTS::
2967
2968
sage: F.<z> = CyclotomicField(5) ; t = 3*z**3 + 4*z**2 + 2
2969
sage: t.matrix(F)
2970
[3*z^3 + 4*z^2 + 2]
2971
sage: x=QQ['x'].gen()
2972
sage: K.<v>=NumberField(x^4 + 514*x^2 + 64321)
2973
sage: R.<r>=NumberField(x^2 + 4*v*x + 5*v^2 + 514)
2974
sage: r.matrix()
2975
[ 0 1]
2976
[-5*v^2 - 514 -4*v]
2977
sage: r.matrix(K)
2978
[ 0 1]
2979
[-5*v^2 - 514 -4*v]
2980
sage: r.matrix(R)
2981
[r]
2982
sage: foo=R.random_element()
2983
sage: foo.matrix(R) == matrix(1,1,[foo])
2984
True
2985
"""
2986
from sage.matrix.constructor import matrix
2987
if base is self.parent():
2988
return matrix(1,1,[self])
2989
if base is not None and base is not self.base_ring():
2990
if number_field.is_NumberField(base):
2991
return self._matrix_over_base(base)
2992
else:
2993
return self._matrix_over_base_morphism(base)
2994
# Multiply each power of field generator on
2995
# the left by this element; make matrix
2996
# whose rows are the coefficients of the result,
2997
# and transpose.
2998
if self.__matrix is None:
2999
K = self.number_field()
3000
v = []
3001
x = K.gen()
3002
a = K(1)
3003
d = K.relative_degree()
3004
for n in range(d):
3005
v += (a*self).list()
3006
a *= x
3007
k = K.base_ring()
3008
import sage.matrix.matrix_space
3009
M = sage.matrix.matrix_space.MatrixSpace(k, d)
3010
self.__matrix = M(v)
3011
return self.__matrix
3012
3013
def valuation(self, P):
3014
"""
3015
Returns the valuation of self at a given prime ideal P.
3016
3017
INPUT:
3018
3019
3020
- ``P`` - a prime ideal of the parent of self
3021
3022
3023
.. note::
3024
3025
The function ``ord()`` is an alias for ``valuation()``.
3026
3027
EXAMPLES::
3028
3029
sage: R.<x> = QQ[]
3030
sage: K.<a> = NumberField(x^4+3*x^2-17)
3031
sage: P = K.ideal(61).factor()[0][0]
3032
sage: b = a^2 + 30
3033
sage: b.valuation(P)
3034
1
3035
sage: b.ord(P)
3036
1
3037
sage: type(b.valuation(P))
3038
<type 'sage.rings.integer.Integer'>
3039
3040
The function can be applied to elements in relative number fields::
3041
3042
sage: L.<b> = K.extension(x^2 - 3)
3043
sage: [L(6).valuation(P) for P in L.primes_above(2)]
3044
[4]
3045
sage: [L(6).valuation(P) for P in L.primes_above(3)]
3046
[2, 2]
3047
"""
3048
from number_field_ideal import is_NumberFieldIdeal
3049
if not is_NumberFieldIdeal(P):
3050
if is_NumberFieldElement(P):
3051
P = self.number_field().fractional_ideal(P)
3052
else:
3053
raise TypeError, "P must be an ideal"
3054
if not P.is_prime():
3055
raise ValueError, "P must be prime"
3056
if self == 0:
3057
return infinity
3058
return Integer_sage(self.number_field().pari_nf().elementval(self._pari_(), P.pari_prime()))
3059
3060
ord = valuation
3061
3062
def local_height(self, P, prec=None, weighted=False):
3063
r"""
3064
Returns the local height of self at a given prime ideal `P`.
3065
3066
INPUT:
3067
3068
3069
- ``P`` - a prime ideal of the parent of self
3070
3071
- ``prec`` (int) -- desired floating point precision (defult:
3072
default RealField precision).
3073
3074
- ``weighted`` (bool, default False) -- if True, apply local
3075
degree weighting.
3076
3077
OUTPUT:
3078
3079
(real) The local height of this number field element at the
3080
place `P`. If ``weighted`` is True, this is multiplied by the
3081
local degree (as required for global heights).
3082
3083
EXAMPLES::
3084
3085
sage: R.<x> = QQ[]
3086
sage: K.<a> = NumberField(x^4+3*x^2-17)
3087
sage: P = K.ideal(61).factor()[0][0]
3088
sage: b = 1/(a^2 + 30)
3089
sage: b.local_height(P)
3090
4.11087386417331
3091
sage: b.local_height(P, weighted=True)
3092
8.22174772834662
3093
sage: b.local_height(P, 200)
3094
4.1108738641733112487513891034256147463156817430812610629374
3095
sage: (b^2).local_height(P)
3096
8.22174772834662
3097
sage: (b^-1).local_height(P)
3098
0.000000000000000
3099
3100
A relative example::
3101
3102
sage: PK.<y> = K[]
3103
sage: L.<c> = NumberField(y^2 + a)
3104
sage: L(1/4).local_height(L.ideal(2, c-a+1))
3105
1.38629436111989
3106
"""
3107
if self.valuation(P) >= 0: ## includes the case self=0
3108
from sage.rings.real_mpfr import RealField
3109
if prec is None:
3110
return RealField().zero()
3111
else:
3112
return RealField(prec).zero()
3113
ht = self.abs_non_arch(P,prec).log()
3114
if not weighted:
3115
return ht
3116
nP = P.residue_class_degree()*P.absolute_ramification_index()
3117
return nP*ht
3118
3119
def local_height_arch(self, i, prec=None, weighted=False):
3120
r"""
3121
Returns the local height of self at the `i`'th infinite place.
3122
3123
INPUT:
3124
3125
3126
- ``i`` (int) - an integer in ``range(r+s)`` where `(r,s)` is the
3127
signature of the parent field (so `n=r+2s` is the degree).
3128
3129
- ``prec`` (int) -- desired floating point precision (default:
3130
default RealField precision).
3131
3132
- ``weighted`` (bool, default False) -- if True, apply local
3133
degree weighting, i.e. double the value for complex places.
3134
3135
OUTPUT:
3136
3137
(real) The archimedean local height of this number field
3138
element at the `i`'th infinite place. If ``weighted`` is
3139
True, this is multiplied by the local degree (as required for
3140
global heights), i.e. 1 for real places and 2 for complex
3141
places.
3142
3143
EXAMPLES::
3144
3145
sage: R.<x> = QQ[]
3146
sage: K.<a> = NumberField(x^4+3*x^2-17)
3147
sage: [p.codomain() for p in K.places()]
3148
[Real Field with 106 bits of precision,
3149
Real Field with 106 bits of precision,
3150
Complex Field with 53 bits of precision]
3151
sage: [a.local_height_arch(i) for i in range(3)]
3152
[0.5301924545717755083366563897519,
3153
0.5301924545717755083366563897519,
3154
0.886414217456333]
3155
sage: [a.local_height_arch(i, weighted=True) for i in range(3)]
3156
[0.5301924545717755083366563897519,
3157
0.5301924545717755083366563897519,
3158
1.77282843491267]
3159
3160
A relative example::
3161
3162
sage: L.<b, c> = NumberFieldTower([x^2 - 5, x^3 + x + 3])
3163
sage: [(b + c).local_height_arch(i) for i in range(4)]
3164
[1.238223390757884911842206617439,
3165
0.02240347229957875780769746914391,
3166
0.780028961749618,
3167
1.16048938497298]
3168
"""
3169
K = self.number_field()
3170
emb = K.places(prec=prec)[i]
3171
a = emb(self).abs()
3172
Kv = emb.codomain()
3173
if a <= Kv.one():
3174
return Kv.zero()
3175
ht = a.log()
3176
from sage.rings.real_mpfr import is_RealField
3177
if weighted and not is_RealField(Kv):
3178
ht*=2
3179
return ht
3180
3181
def global_height_non_arch(self, prec=None):
3182
"""
3183
Returns the total non-archimedean component of the height of self.
3184
3185
INPUT:
3186
3187
- ``prec`` (int) -- desired floating point precision (default:
3188
default RealField precision).
3189
3190
OUTPUT:
3191
3192
(real) The total non-archimedean component of the height of
3193
this number field element; that is, the sum of the local
3194
heights at all finite places, weighted by the local degrees.
3195
3196
ALGORITHM:
3197
3198
An alternative formula is `\log(d)` where `d` is the norm of
3199
the denominator ideal; this is used to avoid factorization.
3200
3201
EXAMPLES::
3202
3203
sage: R.<x> = QQ[]
3204
sage: K.<a> = NumberField(x^4+3*x^2-17)
3205
sage: b = a/6
3206
sage: b.global_height_non_arch()
3207
7.16703787691222
3208
3209
Check that this is equal to the sum of the non-archimedean
3210
local heights::
3211
3212
sage: [b.local_height(P) for P in b.support()]
3213
[0.000000000000000, 0.693147180559945, 1.09861228866811, 1.09861228866811]
3214
sage: [b.local_height(P, weighted=True) for P in b.support()]
3215
[0.000000000000000, 2.77258872223978, 2.19722457733622, 2.19722457733622]
3216
sage: sum([b.local_height(P,weighted=True) for P in b.support()])
3217
7.16703787691222
3218
3219
A relative example::
3220
3221
sage: PK.<y> = K[]
3222
sage: L.<c> = NumberField(y^2 + a)
3223
sage: (c/10).global_height_non_arch()
3224
18.4206807439524
3225
"""
3226
from sage.rings.real_mpfr import RealField
3227
if prec is None:
3228
R = RealField()
3229
else:
3230
R = RealField(prec)
3231
if self.is_zero():
3232
return R.zero()
3233
return R(self.denominator_ideal().absolute_norm()).log()
3234
3235
def global_height_arch(self, prec=None):
3236
"""
3237
Returns the total archimedean component of the height of self.
3238
3239
INPUT:
3240
3241
- ``prec`` (int) -- desired floating point precision (defult:
3242
default RealField precision).
3243
3244
OUTPUT:
3245
3246
(real) The total archimedean component of the height of
3247
this number field element; that is, the sum of the local
3248
heights at all infinite places.
3249
3250
EXAMPLES::
3251
3252
sage: R.<x> = QQ[]
3253
sage: K.<a> = NumberField(x^4+3*x^2-17)
3254
sage: b = a/2
3255
sage: b.global_height_arch()
3256
0.38653407379277...
3257
"""
3258
r,s = self.number_field().signature()
3259
hts = [self.local_height_arch(i, prec, weighted=True) for i in range(r+s)]
3260
return sum(hts, hts[0].parent().zero())
3261
3262
def global_height(self, prec=None):
3263
"""
3264
Returns the absolute logarithmic height of this number field element.
3265
3266
INPUT:
3267
3268
- ``prec`` (int) -- desired floating point precision (defult:
3269
default RealField precision).
3270
3271
OUTPUT:
3272
3273
(real) The absolute logarithmic height of this number field
3274
element; that is, the sum of the local heights at all finite
3275
and infinite places, scaled by the degree to make the result independent of
3276
the parent field.
3277
3278
EXAMPLES::
3279
3280
sage: R.<x> = QQ[]
3281
sage: K.<a> = NumberField(x^4+3*x^2-17)
3282
sage: b = a/2
3283
sage: b.global_height()
3284
0.789780699008...
3285
sage: b.global_height(prec=200)
3286
0.78978069900813892060267152032141577237037181070060784564457
3287
3288
The global height of an algebraic number is absolute, i.e. it
3289
does not depend on the parent field::
3290
3291
sage: QQ(6).global_height()
3292
1.79175946922805
3293
sage: K(6).global_height()
3294
1.79175946922805
3295
3296
sage: L.<b> = NumberField((a^2).minpoly())
3297
sage: L.degree()
3298
2
3299
sage: b.global_height() # element of L (degree 2 field)
3300
1.41660667202811
3301
sage: (a^2).global_height() # element of K (degree 4 field)
3302
1.41660667202811
3303
3304
And of course every element has the same height as it's inverse::
3305
3306
sage: K.<s> = QuadraticField(2)
3307
sage: s.global_height()
3308
0.346573590279973
3309
sage: (1/s).global_height() #make sure that 11758 is fixed
3310
0.346573590279973
3311
3312
"""
3313
return (self.global_height_non_arch(prec)+self.global_height_arch(prec))/self.number_field().absolute_degree()
3314
3315
def numerator_ideal(self):
3316
"""
3317
Return the numerator ideal of this number field element.
3318
3319
The numerator ideal of a number field element `a` is the ideal of
3320
the ring of integers `R` obtained by intersecting `aR` with `R`.
3321
3322
.. seealso::
3323
3324
:meth:`denominator_ideal`
3325
3326
EXAMPLES::
3327
3328
sage: K.<a> = NumberField(x^2+5)
3329
sage: b = (1+a)/2
3330
sage: b.norm()
3331
3/2
3332
sage: N = b.numerator_ideal(); N
3333
Fractional ideal (3, a + 1)
3334
sage: N.norm()
3335
3
3336
sage: (1/b).numerator_ideal()
3337
Fractional ideal (2, a + 1)
3338
sage: K(0).numerator_ideal()
3339
Ideal (0) of Number Field in a with defining polynomial x^2 + 5
3340
"""
3341
if self.is_zero():
3342
return self.number_field().ideal(0)
3343
return self.number_field().ideal(self).numerator()
3344
3345
def denominator_ideal(self):
3346
"""
3347
Return the denominator ideal of this number field element.
3348
3349
The denominator ideal of a number field element `a` is the
3350
integral ideal consisting of all elements of the ring of
3351
integers `R` whose product with `a` is also in `R`.
3352
3353
.. seealso::
3354
3355
:meth:`numerator_ideal`
3356
3357
EXAMPLES::
3358
3359
sage: K.<a> = NumberField(x^2+5)
3360
sage: b = (1+a)/2
3361
sage: b.norm()
3362
3/2
3363
sage: D = b.denominator_ideal(); D
3364
Fractional ideal (2, a + 1)
3365
sage: D.norm()
3366
2
3367
sage: (1/b).denominator_ideal()
3368
Fractional ideal (3, a + 1)
3369
sage: K(0).denominator_ideal()
3370
Fractional ideal (1)
3371
"""
3372
if self.is_zero():
3373
return self.number_field().ideal(1)
3374
return self.number_field().ideal(self).denominator()
3375
3376
def support(self):
3377
"""
3378
Return the support of this number field element.
3379
3380
OUTPUT: A sorted list of the primes ideals at which this number
3381
field element has nonzero valuation. An error is raised if the
3382
element is zero.
3383
3384
EXAMPLES::
3385
3386
sage: x = ZZ['x'].gen()
3387
sage: F.<t> = NumberField(x^3 - 2)
3388
3389
::
3390
3391
sage: P5s = F(5).support()
3392
sage: P5s
3393
[Fractional ideal (-t^2 - 1), Fractional ideal (t^2 - 2*t - 1)]
3394
sage: all(5 in P5 for P5 in P5s)
3395
True
3396
sage: all(P5.is_prime() for P5 in P5s)
3397
True
3398
sage: [ P5.norm() for P5 in P5s ]
3399
[5, 25]
3400
3401
TESTS:
3402
3403
It doesn't make sense to factor the ideal (0)::
3404
3405
sage: F(0).support()
3406
Traceback (most recent call last):
3407
...
3408
ArithmeticError: Support of 0 is not defined.
3409
"""
3410
if self.is_zero():
3411
raise ArithmeticError, "Support of 0 is not defined."
3412
return self.number_field().primes_above(self)
3413
3414
def _matrix_over_base(self, L):
3415
"""
3416
Return the matrix of self over the base field L.
3417
3418
EXAMPLES::
3419
3420
sage: K.<a> = NumberField(ZZ['x'].0^3-2, 'a')
3421
sage: L.<b> = K.extension(ZZ['x'].0^2+3, 'b')
3422
sage: L(a)._matrix_over_base(K) == L(a).matrix()
3423
True
3424
"""
3425
K = self.number_field()
3426
E = L.embeddings(K)
3427
if len(E) == 0:
3428
raise ValueError, "no way to embed L into parent's base ring K"
3429
phi = E[0]
3430
return self._matrix_over_base_morphism(phi)
3431
3432
def _matrix_over_base_morphism(self, phi):
3433
"""
3434
Return the matrix of self over a specified base, where phi gives a
3435
map from the specified base to self.parent().
3436
3437
EXAMPLES::
3438
3439
sage: F.<alpha> = NumberField(ZZ['x'].0^5-2)
3440
sage: h = Hom(QQ,F)([1])
3441
sage: alpha._matrix_over_base_morphism(h) == alpha.matrix()
3442
True
3443
sage: alpha._matrix_over_base_morphism(h) == alpha.matrix(QQ)
3444
True
3445
"""
3446
L = phi.domain()
3447
3448
## the code below doesn't work if the morphism is
3449
## over QQ, since QQ.primitive_element() doesn't
3450
## make sense
3451
if L is QQ:
3452
K = phi.codomain()
3453
if K != self.number_field():
3454
raise ValueError, "codomain of phi must be parent of self"
3455
## the variable name is irrelevant below, because the
3456
## matrix is over QQ
3457
F = K.absolute_field('alpha')
3458
from_f, to_F = F.structure()
3459
return to_F(self).matrix()
3460
3461
alpha = L.primitive_element()
3462
beta = phi(alpha)
3463
K = phi.codomain()
3464
if K != self.number_field():
3465
raise ValueError, "codomain of phi must be parent of self"
3466
3467
# Construct a relative extension over L (= QQ(beta))
3468
M = K.relativize(beta, (K.variable_name()+'0', L.variable_name()+'0') )
3469
3470
# Carry self over to M.
3471
from_M, to_M = M.structure()
3472
try:
3473
z = to_M(self)
3474
except Exception:
3475
return to_M, self, K, beta
3476
3477
# Compute the relative matrix of self, but in M
3478
R = z.matrix()
3479
3480
# Map back to L.
3481
psi = M.base_field().hom([alpha])
3482
return R.apply_morphism(psi)
3483
3484
3485
def list(self):
3486
"""
3487
Return the list of coefficients of self written in terms of a power
3488
basis.
3489
3490
EXAMPLE::
3491
3492
sage: K.<a> = NumberField(x^3 - x + 2); ((a + 1)/(a + 2)).list()
3493
[1/4, 1/2, -1/4]
3494
sage: K.<a, b> = NumberField([x^3 - x + 2, x^2 + 23]); ((a + b)/(a + 2)).list()
3495
[3/4*b - 1/2, -1/2*b + 1, 1/4*b - 1/2]
3496
"""
3497
raise NotImplementedError
3498
3499
def inverse_mod(self, I):
3500
"""
3501
Returns the inverse of self mod the integral ideal I.
3502
3503
INPUT:
3504
3505
- ``I`` - may be an ideal of self.parent(), or an element or list
3506
of elements of self.parent() generating a nonzero ideal. A ValueError
3507
is raised if I is non-integral or zero. A ZeroDivisionError is
3508
raised if I + (x) != (1).
3509
3510
NOTE: It's not implemented yet for non-integral elements.
3511
3512
EXAMPLES::
3513
3514
sage: k.<a> = NumberField(x^2 + 23)
3515
sage: N = k.ideal(3)
3516
sage: d = 3*a + 1
3517
sage: d.inverse_mod(N)
3518
1
3519
3520
::
3521
3522
sage: k.<a> = NumberField(x^3 + 11)
3523
sage: d = a + 13
3524
sage: d.inverse_mod(a^2)*d - 1 in k.ideal(a^2)
3525
True
3526
sage: d.inverse_mod((5, a + 1))*d - 1 in k.ideal(5, a + 1)
3527
True
3528
sage: K.<b> = k.extension(x^2 + 3)
3529
sage: b.inverse_mod([37, a - b])
3530
7
3531
sage: 7*b - 1 in K.ideal(37, a - b)
3532
True
3533
sage: b.inverse_mod([37, a - b]).parent() == K
3534
True
3535
"""
3536
R = self.number_field().ring_of_integers()
3537
try:
3538
return _inverse_mod_generic(R(self), I)
3539
except TypeError: # raised by failure of R(self)
3540
raise NotImplementedError, "inverse_mod is not implemented for non-integral elements"
3541
3542
3543
def residue_symbol(self, P, m, check=True):
3544
r"""
3545
The m-th power residue symbol for an element self and proper ideal P.
3546
3547
.. math:: \left(\frac{\alpha}{\mathbf{P}}\right) \equiv \alpha^{\frac{N(\mathbf{P})-1}{m}} \operatorname{mod} \mathbf{P}
3548
3549
.. note:: accepts m=1, in which case returns 1
3550
3551
.. note:: can also be called for an ideal from sage.rings.number_field_ideal.residue_symbol
3552
3553
.. note:: self is coerced into the number field of the ideal P
3554
3555
.. note:: if m=2, self is an integer, and P is an ideal of a number field of absolute degree 1 (i.e. it is a copy of the rationals), then this calls kronecker_symbol, which is implemented using GMP.
3556
3557
INPUT:
3558
3559
- ``P`` - proper ideal of the number field (or an extension)
3560
3561
- ``m`` - positive integer
3562
3563
OUTPUT:
3564
3565
- an m-th root of unity in the number field
3566
3567
EXAMPLES:
3568
3569
Quadratic Residue (11 is not a square modulo 17)::
3570
3571
sage: K.<a> = NumberField(x - 1)
3572
sage: K(11).residue_symbol(K.ideal(17),2)
3573
-1
3574
sage: kronecker_symbol(11,17)
3575
-1
3576
3577
The result depends on the number field of the ideal::
3578
3579
sage: K.<a> = NumberField(x - 1)
3580
sage: L.<b> = K.extension(x^2 + 1)
3581
sage: K(7).residue_symbol(K.ideal(11),2)
3582
-1
3583
sage: K(7).residue_symbol(L.ideal(11),2)
3584
1
3585
3586
Cubic Residue::
3587
3588
sage: K.<w> = NumberField(x^2 - x + 1)
3589
sage: (w^2 + 3).residue_symbol(K.ideal(17),3)
3590
-w
3591
3592
The field must contain the m-th roots of unity::
3593
3594
sage: K.<w> = NumberField(x^2 - x + 1)
3595
sage: (w^2 + 3).residue_symbol(K.ideal(17),5)
3596
Traceback (most recent call last):
3597
...
3598
ValueError: The residue symbol to that power is not defined for the number field
3599
3600
"""
3601
return P.residue_symbol(self,m,check)
3602
3603
def descend_mod_power(self, K=QQ, d=2):
3604
r"""
3605
Return a list of elements of the subfield `K` equal to
3606
``self`` modulo `d`'th powers.
3607
3608
INPUT:
3609
3610
- ``K`` (number field, default \QQ) -- a subfield of the
3611
parent number field `L` of ``self``
3612
3613
- ``d`` (positive integer, default 2) -- an integer at least 2
3614
3615
OUTPUT:
3616
3617
A list, possibly empty, of elements of ``K`` equal to ``self``
3618
modulo `d`'th powers, i.e. the preimages of ``self`` under the
3619
map `K^*/(K^*)^d \rightarrow L^*/(L^*)^d` where `L` is the
3620
parent of ``self``. A ``ValueError`` is raised if `K` does
3621
not embed into `L`.
3622
3623
ALGORITHM:
3624
3625
All preimages must lie in the Selmer group `K(S,d)` for a
3626
suitable finite set of primes `S`, which reduces the question
3627
to a finite set of possibilities. We may take `S` to be the
3628
set of primes which ramify in `L` together with those for
3629
which the valuation of ``self`` is not divisible by `d`.
3630
3631
EXAMPLES:
3632
3633
A relative example::
3634
3635
sage: Qi.<i> = QuadraticField(-1)
3636
sage: K.<zeta> = CyclotomicField(8)
3637
sage: f = Qi.embeddings(K)[0]
3638
sage: a = f(2+3*i) * (2-zeta)^2
3639
sage: a.descend_mod_power(Qi,2)
3640
[-3*i - 2, -2*i + 3]
3641
3642
An absolute example::
3643
3644
sage: K.<zeta> = CyclotomicField(8)
3645
sage: K(1).descend_mod_power(QQ,2)
3646
[1, 2, -1, -2]
3647
sage: a = 17*K.random_element()^2
3648
sage: a.descend_mod_power(QQ,2)
3649
[17, 34, -17, -34]
3650
"""
3651
if not self:
3652
raise ValueError("element must be nonzero")
3653
L = self.parent()
3654
if K is L:
3655
return [self]
3656
3657
from sage.sets.set import Set
3658
3659
if K is QQ: # simpler special case avoids relativizing
3660
# First set of primes: those which ramify in L/K:
3661
S1 = L.absolute_discriminant().prime_factors()
3662
# Second set of primes: those where self has nonzero valuation mod d:
3663
S2 = Set([p.norm().support()[0]
3664
for p in self.support()
3665
if self.valuation(p)%d !=0])
3666
S = S1 + [p for p in S2 if not p in S1]
3667
return [a for a in K.selmer_group_iterator(S,d)
3668
if (self/a).is_nth_power(d)]
3669
3670
embs = K.embeddings(L)
3671
if len(embs) == 0:
3672
raise ValueError("K = %s does not embed into %s" % (K,L))
3673
f = embs[0]
3674
LK = L.relativize(f, L.variable_name()+'0')
3675
# Unfortunately the base field of LK is not K but an
3676
# isomorphic field, and we must make sure to use the correct
3677
# isomorphism!
3678
KK = LK.base_field()
3679
h = [h for h in KK.embeddings(K) if f(h(KK.gen())) == L(LK(KK.gen()))][0]
3680
3681
# First set of primes: those which ramify in L/K:
3682
S1 = LK.relative_discriminant().prime_factors()
3683
# Second set of primes: those where self has nonzero valuation mod d:
3684
S2 = Set([p.relative_norm().prime_factors()[0]
3685
for p in LK(self).support()
3686
if LK(self).valuation(p) % d != 0])
3687
S = S1 + [p for p in S2 if p not in S1]
3688
candidates = [h(a) for a in K.selmer_group_iterator(S,d)]
3689
return [a for a in candidates if (self/f(a)).is_nth_power(d)]
3690
3691
cdef class NumberFieldElement_absolute(NumberFieldElement):
3692
3693
def _magma_init_(self, magma):
3694
"""
3695
Return Magma version of this number field element.
3696
3697
INPUT:
3698
3699
3700
- ``magma`` - a Magma interpreter
3701
3702
3703
OUTPUT: MagmaElement that has parent the Magma object corresponding
3704
to the parent number field.
3705
3706
EXAMPLES::
3707
3708
sage: K.<a> = NumberField(x^3 + 2)
3709
sage: a._magma_init_(magma) # optional - magma
3710
'(_sage_[...]![0, 1, 0])'
3711
sage: m = magma((2/3)*a^2 - 17/3); m # optional - magma
3712
1/3*(2*a^2 - 17)
3713
sage: m.sage() # optional - magma
3714
2/3*a^2 - 17/3
3715
3716
An element of a cyclotomic field.
3717
3718
::
3719
3720
sage: K = CyclotomicField(9)
3721
sage: K.gen()
3722
zeta9
3723
sage: K.gen()._magma_init_(magma) # optional - magma
3724
'(_sage_[...]![0, 1, 0, 0, 0, 0])'
3725
sage: magma(K.gen()) # optional - magma
3726
zeta9
3727
sage: _.sage() # optional - magma
3728
zeta9
3729
"""
3730
K = magma(self.parent())
3731
return '(%s!%s)'%(K.name(), self.list())
3732
3733
def absolute_charpoly(self, var='x', algorithm=None):
3734
r"""
3735
Return the characteristic polynomial of this element over `\QQ`.
3736
3737
For the meaning of the optional argument ``algorithm``, see :meth:`charpoly`.
3738
3739
EXAMPLES::
3740
3741
sage: x = ZZ['x'].0
3742
sage: K.<a> = NumberField(x^4 + 2, 'a')
3743
sage: a.absolute_charpoly()
3744
x^4 + 2
3745
sage: a.absolute_charpoly('y')
3746
y^4 + 2
3747
sage: (-a^2).absolute_charpoly()
3748
x^4 + 4*x^2 + 4
3749
sage: (-a^2).absolute_minpoly()
3750
x^2 + 2
3751
3752
sage: a.absolute_charpoly(algorithm='pari') == a.absolute_charpoly(algorithm='sage')
3753
True
3754
"""
3755
# this hack is necessary because quadratic fields override
3756
# charpoly(), and they don't take the argument 'algorithm'
3757
if algorithm is None:
3758
return self.charpoly(var)
3759
return self.charpoly(var, algorithm)
3760
3761
def absolute_minpoly(self, var='x', algorithm=None):
3762
r"""
3763
Return the minimal polynomial of this element over
3764
`\QQ`.
3765
3766
For the meaning of the optional argument algorithm, see :meth:`charpoly`.
3767
3768
EXAMPLES::
3769
3770
sage: x = ZZ['x'].0
3771
sage: f = x^10 - 5*x^9 + 15*x^8 - 68*x^7 + 81*x^6 - 221*x^5 + 141*x^4 - 242*x^3 - 13*x^2 - 33*x - 135
3772
sage: K.<a> = NumberField(f, 'a')
3773
sage: a.absolute_charpoly()
3774
x^10 - 5*x^9 + 15*x^8 - 68*x^7 + 81*x^6 - 221*x^5 + 141*x^4 - 242*x^3 - 13*x^2 - 33*x - 135
3775
sage: a.absolute_charpoly('y')
3776
y^10 - 5*y^9 + 15*y^8 - 68*y^7 + 81*y^6 - 221*y^5 + 141*y^4 - 242*y^3 - 13*y^2 - 33*y - 135
3777
sage: b = -79/9995*a^9 + 52/9995*a^8 + 271/9995*a^7 + 1663/9995*a^6 + 13204/9995*a^5 + 5573/9995*a^4 + 8435/1999*a^3 - 3116/9995*a^2 + 7734/1999*a + 1620/1999
3778
sage: b.absolute_charpoly()
3779
x^10 + 10*x^9 + 25*x^8 - 80*x^7 - 438*x^6 + 80*x^5 + 2950*x^4 + 1520*x^3 - 10439*x^2 - 5130*x + 18225
3780
sage: b.absolute_minpoly()
3781
x^5 + 5*x^4 - 40*x^2 - 19*x + 135
3782
3783
sage: b.absolute_minpoly(algorithm='pari') == b.absolute_minpoly(algorithm='sage')
3784
True
3785
"""
3786
# this hack is necessary because quadratic fields override
3787
# minpoly(), and they don't take the argument 'algorithm'
3788
if algorithm is None:
3789
return self.minpoly(var)
3790
return self.minpoly(var, algorithm)
3791
3792
def charpoly(self, var='x', algorithm=None):
3793
r"""
3794
The characteristic polynomial of this element, over
3795
`\QQ` if self is an element of a field, and over
3796
`\ZZ` is self is an element of an order.
3797
3798
This is the same as ``self.absolute_charpoly`` since
3799
this is an element of an absolute extension.
3800
3801
The optional argument algorithm controls how the
3802
characteristic polynomial is computed: 'pari' uses PARI,
3803
'sage' uses charpoly for Sage matrices. The default value
3804
None means that 'pari' is used for small degrees (up to the
3805
value of the constant TUNE_CHARPOLY_NF, currently at 25),
3806
otherwise 'sage' is used. The constant TUNE_CHARPOLY_NF
3807
should give reasonable performance on all architectures;
3808
however, if you feel the need to customize it to your own
3809
machine, see trac ticket 5213 for a tuning script.
3810
3811
EXAMPLES:
3812
3813
We compute the characteristic polynomial of the cube root of `2`.
3814
3815
::
3816
3817
sage: R.<x> = QQ[]
3818
sage: K.<a> = NumberField(x^3-2)
3819
sage: a.charpoly('x')
3820
x^3 - 2
3821
sage: a.charpoly('y').parent()
3822
Univariate Polynomial Ring in y over Rational Field
3823
3824
TESTS::
3825
3826
sage: R = K.ring_of_integers()
3827
sage: R(a).charpoly()
3828
x^3 - 2
3829
sage: R(a).charpoly().parent()
3830
Univariate Polynomial Ring in x over Integer Ring
3831
3832
sage: R(a).charpoly(algorithm='pari') == R(a).charpoly(algorithm='sage')
3833
True
3834
"""
3835
if algorithm is None:
3836
if self._parent.degree() <= TUNE_CHARPOLY_NF:
3837
algorithm = 'pari'
3838
else:
3839
algorithm = 'sage'
3840
R = self._parent.base_ring()[var]
3841
if algorithm == 'pari':
3842
return R(self._pari_('x').charpoly())
3843
if algorithm == 'sage':
3844
return R(self.matrix().charpoly())
3845
3846
def minpoly(self, var='x', algorithm=None):
3847
"""
3848
Return the minimal polynomial of this number field element.
3849
3850
For the meaning of the optional argument algorithm, see charpoly().
3851
3852
EXAMPLES:
3853
3854
We compute the characteristic polynomial of cube root of `2`.
3855
3856
::
3857
3858
sage: R.<x> = QQ[]
3859
sage: K.<a> = NumberField(x^3-2)
3860
sage: a.minpoly('x')
3861
x^3 - 2
3862
sage: a.minpoly('y').parent()
3863
Univariate Polynomial Ring in y over Rational Field
3864
3865
TESTS::
3866
3867
sage: R = K.ring_of_integers()
3868
sage: R(a).minpoly()
3869
x^3 - 2
3870
sage: R(a).minpoly().parent()
3871
Univariate Polynomial Ring in x over Integer Ring
3872
3873
sage: R(a).minpoly(algorithm='pari') == R(a).minpoly(algorithm='sage')
3874
True
3875
3876
"""
3877
return self.charpoly(var, algorithm).radical() # square free part of charpoly
3878
3879
def list(self):
3880
"""
3881
Return the list of coefficients of self written in terms of a power
3882
basis.
3883
3884
EXAMPLE::
3885
3886
sage: K.<z> = CyclotomicField(3)
3887
sage: (2+3/5*z).list()
3888
[2, 3/5]
3889
sage: (5*z).list()
3890
[0, 5]
3891
sage: K(3).list()
3892
[3, 0]
3893
"""
3894
n = self.number_field().degree()
3895
v = self._coefficients()
3896
z = sage.rings.rational.Rational(0)
3897
return v + [z]*(n - len(v))
3898
3899
def lift(self, var='x'):
3900
"""
3901
Return an element of QQ[x], where this number field element
3902
lives in QQ[x]/(f(x)).
3903
3904
EXAMPLES::
3905
3906
sage: K.<a> = QuadraticField(-3)
3907
sage: a.lift()
3908
x
3909
3910
"""
3911
R = self.number_field().base_field()[var]
3912
return R(self.list())
3913
3914
def is_real_positive(self, min_prec=53):
3915
r"""
3916
Using the ``n`` method of approximation, return ``True`` if
3917
``self`` is a real positive number and ``False`` otherwise.
3918
This method is completely dependent of the embedding used by
3919
the ``n`` method.
3920
3921
The algorithm first checks that ``self`` is not a strictly
3922
complex number. Then if ``self`` is not zero, by approximation
3923
more and more precise, the method answers True if the
3924
number is positive. Using `RealInterval`, the result is
3925
guaranteed to be correct.
3926
3927
For CyclotomicField, the embedding is the natural one
3928
sending `zetan` on `cos(2*pi/n)`.
3929
3930
EXAMPLES::
3931
3932
sage: K.<a> = CyclotomicField(3)
3933
sage: (a+a^2).is_real_positive()
3934
False
3935
sage: (-a-a^2).is_real_positive()
3936
True
3937
sage: K.<a> = CyclotomicField(1000)
3938
sage: (a+a^(-1)).is_real_positive()
3939
True
3940
sage: K.<a> = CyclotomicField(1009)
3941
sage: d = a^252
3942
sage: (d+d.conjugate()).is_real_positive()
3943
True
3944
sage: d = a^253
3945
sage: (d+d.conjugate()).is_real_positive()
3946
False
3947
sage: K.<a> = QuadraticField(3)
3948
sage: a.is_real_positive()
3949
True
3950
sage: K.<a> = QuadraticField(-3)
3951
sage: a.is_real_positive()
3952
False
3953
sage: (a-a).is_real_positive()
3954
False
3955
"""
3956
if self != self.conjugate() or self.is_zero():
3957
return False
3958
else:
3959
approx = RealInterval(self.n(min_prec).real())
3960
if approx.lower() > 0:
3961
return True
3962
else:
3963
if approx.upper() < 0:
3964
return False
3965
else:
3966
return self.is_real_positive(min_prec+20)
3967
3968
cdef class NumberFieldElement_relative(NumberFieldElement):
3969
r"""
3970
The current relative number field element implementation
3971
does everything in terms of absolute polynomials.
3972
3973
All conversions from relative polynomials, lists, vectors, etc
3974
should happen in the parent.
3975
"""
3976
def __init__(self, parent, f):
3977
r"""
3978
EXAMPLE::
3979
3980
sage: L.<a, b> = NumberField([x^2 + 1, x^2 + 2])
3981
sage: type(a) # indirect doctest
3982
<type 'sage.rings.number_field.number_field_element.NumberFieldElement_relative'>
3983
"""
3984
NumberFieldElement.__init__(self, parent, f)
3985
3986
def __getitem__(self, n):
3987
"""
3988
Return the n-th coefficient of this relative number field element, written
3989
as a polynomial in the generator.
3990
3991
Note that `n` must be between 0 and `d-1`, where
3992
`d` is the relative degree of the number field.
3993
3994
EXAMPLES::
3995
3996
sage: K.<a, b> = NumberField([x^3 - 5, x^2 + 3])
3997
sage: c = (a + b)^3; c
3998
3*b*a^2 - 9*a - 3*b + 5
3999
sage: c[0]
4000
-3*b + 5
4001
4002
We illustrate bounds checking::
4003
4004
sage: c[-1]
4005
Traceback (most recent call last):
4006
...
4007
IndexError: index must be between 0 and the relative degree minus 1.
4008
sage: c[4]
4009
Traceback (most recent call last):
4010
...
4011
IndexError: index must be between 0 and the relative degree minus 1.
4012
4013
The list method implicitly calls ``__getitem__``::
4014
4015
sage: list(c)
4016
[-3*b + 5, -9, 3*b]
4017
sage: K(list(c)) == c
4018
True
4019
"""
4020
if n < 0 or n >= self.parent().relative_degree():
4021
raise IndexError, "index must be between 0 and the relative degree minus 1."
4022
return self.vector()[n]
4023
4024
def _magma_init_(self, magma):
4025
"""
4026
EXAMPLES::
4027
4028
sage: K.<a, b> = NumberField([x^3 - 5, x^2 + 3])
4029
sage: a._magma_init_(magma)
4030
Traceback (most recent call last):
4031
...
4032
TypeError: coercion of relative number field elements to Magma is not implemented
4033
"""
4034
raise TypeError, "coercion of relative number field elements to Magma is not implemented"
4035
4036
def list(self):
4037
"""
4038
Return the list of coefficients of self written in terms of a power
4039
basis.
4040
4041
EXAMPLES::
4042
4043
sage: K.<a,b> = NumberField([x^3+2, x^2+1])
4044
sage: a.list()
4045
[0, 1, 0]
4046
sage: v = (K.base_field().0 + a)^2 ; v
4047
a^2 + 2*b*a - 1
4048
sage: v.list()
4049
[-1, 2*b, 1]
4050
"""
4051
return self.vector().list()
4052
4053
def lift(self, var='x'):
4054
"""
4055
Return an element of K[x], where this number field element
4056
lives in the relative number field K[x]/(f(x)).
4057
4058
EXAMPLES::
4059
4060
sage: K.<a> = QuadraticField(-3)
4061
sage: x = polygen(K)
4062
sage: L.<b> = K.extension(x^7 + 5)
4063
sage: u = L(1/2*a + 1/2 + b + (a-9)*b^5)
4064
sage: u.lift()
4065
(a - 9)*x^5 + x + 1/2*a + 1/2
4066
4067
"""
4068
K = self.number_field()
4069
# Compute representation of self in terms of relative vector space.
4070
R = K.base_field()[var]
4071
return R(self.list())
4072
4073
def _repr_(self):
4074
r"""
4075
EXAMPLE::
4076
4077
sage: L.<a, b> = NumberField([x^3 - x + 1, x^2 + 23])
4078
sage: repr(a^4*b) # indirect doctest
4079
'b*a^2 - b*a'
4080
"""
4081
K = self.number_field()
4082
# Compute representation of self in terms of relative vector space.
4083
R = K.base_field()[K.variable_name()]
4084
return repr(R(self.list()))
4085
4086
def _latex_(self):
4087
r"""
4088
Returns the latex representation for this element.
4089
4090
EXAMPLES::
4091
4092
sage: C.<zeta> = CyclotomicField(12)
4093
sage: PC.<x> = PolynomialRing(C)
4094
sage: K.<alpha> = NumberField(x^2 - 7)
4095
sage: latex((alpha + zeta)^4) # indirect doctest
4096
\left(4 \zeta_{12}^{3} + 28 \zeta_{12}\right) \alpha + 43 \zeta_{12}^{2} + 48
4097
sage: PK.<y> = PolynomialRing(K)
4098
sage: L.<beta> = NumberField(y^3 + y + alpha)
4099
sage: latex((beta + zeta)^3) # indirect doctest
4100
3 \zeta_{12} \beta^{2} + \left(3 \zeta_{12}^{2} - 1\right) \beta - \alpha + \zeta_{12}^{3}
4101
"""
4102
K = self.number_field()
4103
R = K.base_field()[K.variable_name()]
4104
return R(self.list())._latex_()
4105
4106
def charpoly(self, var='x'):
4107
r"""
4108
The characteristic polynomial of this element over its base field.
4109
4110
EXAMPLES::
4111
4112
sage: x = ZZ['x'].0
4113
sage: K.<a, b> = QQ.extension([x^2 + 2, x^5 + 400*x^4 + 11*x^2 + 2])
4114
sage: a.charpoly()
4115
x^2 + 2
4116
sage: b.charpoly()
4117
x^2 - 2*b*x + b^2
4118
sage: b.minpoly()
4119
x - b
4120
4121
sage: K.<a, b> = NumberField([x^2 + 2, x^2 + 1000*x + 1])
4122
sage: y = K['y'].0
4123
sage: L.<c> = K.extension(y^2 + a*y + b)
4124
sage: c.charpoly()
4125
x^2 + a*x + b
4126
sage: c.minpoly()
4127
x^2 + a*x + b
4128
sage: L(a).charpoly()
4129
x^2 - 2*a*x - 2
4130
sage: L(a).minpoly()
4131
x - a
4132
sage: L(b).charpoly()
4133
x^2 - 2*b*x - 1000*b - 1
4134
sage: L(b).minpoly()
4135
x - b
4136
"""
4137
R = self._parent.base_ring()[var]
4138
return R(self.matrix().charpoly())
4139
4140
def absolute_charpoly(self, var='x', algorithm=None):
4141
r"""
4142
The characteristic polynomial of this element over
4143
`\QQ`.
4144
4145
We construct a relative extension and find the characteristic
4146
polynomial over `\QQ`.
4147
4148
The optional argument algorithm controls how the
4149
characteristic polynomial is computed: 'pari' uses PARI,
4150
'sage' uses charpoly for Sage matrices. The default value
4151
None means that 'pari' is used for small degrees (up to the
4152
value of the constant TUNE_CHARPOLY_NF, currently at 25),
4153
otherwise 'sage' is used. The constant TUNE_CHARPOLY_NF
4154
should give reasonable performance on all architectures;
4155
however, if you feel the need to customize it to your own
4156
machine, see trac ticket 5213 for a tuning script.
4157
4158
EXAMPLES::
4159
4160
sage: R.<x> = QQ[]
4161
sage: K.<a> = NumberField(x^3-2)
4162
sage: S.<X> = K[]
4163
sage: L.<b> = NumberField(X^3 + 17); L
4164
Number Field in b with defining polynomial X^3 + 17 over its base field
4165
sage: b.absolute_charpoly()
4166
x^9 + 51*x^6 + 867*x^3 + 4913
4167
sage: b.charpoly()(b)
4168
0
4169
sage: a = L.0; a
4170
b
4171
sage: a.absolute_charpoly('x')
4172
x^9 + 51*x^6 + 867*x^3 + 4913
4173
sage: a.absolute_charpoly('y')
4174
y^9 + 51*y^6 + 867*y^3 + 4913
4175
4176
sage: a.absolute_charpoly(algorithm='pari') == a.absolute_charpoly(algorithm='sage')
4177
True
4178
"""
4179
if algorithm is None:
4180
# this might not be the optimal condition; maybe it should
4181
# be .degree() instead of .absolute_degree()
4182
# there are too many bugs in relative number fields to
4183
# figure this out now
4184
if self._parent.absolute_degree() <= TUNE_CHARPOLY_NF:
4185
algorithm = 'pari'
4186
else:
4187
algorithm = 'sage'
4188
R = QQ[var]
4189
if algorithm == 'pari':
4190
return R(self._pari_().charpoly())
4191
if algorithm == 'sage':
4192
return R(self.matrix(QQ).charpoly())
4193
4194
def absolute_minpoly(self, var='x', algorithm=None):
4195
r"""
4196
Return the minimal polynomial over `\QQ` of this element.
4197
4198
For the meaning of the optional argument ``algorithm``, see :meth:`absolute_charpoly`.
4199
4200
EXAMPLES::
4201
4202
sage: K.<a, b> = NumberField([x^2 + 2, x^2 + 1000*x + 1])
4203
sage: y = K['y'].0
4204
sage: L.<c> = K.extension(y^2 + a*y + b)
4205
sage: c.absolute_charpoly()
4206
x^8 - 1996*x^6 + 996006*x^4 + 1997996*x^2 + 1
4207
sage: c.absolute_minpoly()
4208
x^8 - 1996*x^6 + 996006*x^4 + 1997996*x^2 + 1
4209
sage: L(a).absolute_charpoly()
4210
x^8 + 8*x^6 + 24*x^4 + 32*x^2 + 16
4211
sage: L(a).absolute_minpoly()
4212
x^2 + 2
4213
sage: L(b).absolute_charpoly()
4214
x^8 + 4000*x^7 + 6000004*x^6 + 4000012000*x^5 + 1000012000006*x^4 + 4000012000*x^3 + 6000004*x^2 + 4000*x + 1
4215
sage: L(b).absolute_minpoly()
4216
x^2 + 1000*x + 1
4217
"""
4218
return self.absolute_charpoly(var, algorithm).radical()
4219
4220
def valuation(self, P):
4221
"""
4222
Returns the valuation of self at a given prime ideal P.
4223
4224
INPUT:
4225
4226
4227
- ``P`` - a prime ideal of relative number field which is the parent of self
4228
4229
4230
EXAMPLES::
4231
4232
sage: K.<a, b, c> = NumberField([x^2 - 2, x^2 - 3, x^2 - 5])
4233
sage: P = K.prime_factors(5)[0]
4234
sage: (2*a + b - c).valuation(P)
4235
1
4236
"""
4237
P_abs = P.absolute_ideal()
4238
abs = P_abs.number_field()
4239
to_abs = abs.structure()[1]
4240
return to_abs(self).valuation(P_abs)
4241
4242
4243
cdef class OrderElement_absolute(NumberFieldElement_absolute):
4244
"""
4245
Element of an order in an absolute number field.
4246
4247
EXAMPLES::
4248
4249
sage: K.<a> = NumberField(x^2 + 1)
4250
sage: O2 = K.order(2*a)
4251
sage: w = O2.1; w
4252
2*a
4253
sage: parent(w)
4254
Order in Number Field in a with defining polynomial x^2 + 1
4255
4256
sage: w.absolute_charpoly()
4257
x^2 + 4
4258
sage: w.absolute_charpoly().parent()
4259
Univariate Polynomial Ring in x over Integer Ring
4260
sage: w.absolute_minpoly()
4261
x^2 + 4
4262
sage: w.absolute_minpoly().parent()
4263
Univariate Polynomial Ring in x over Integer Ring
4264
"""
4265
def __init__(self, order, f):
4266
r"""
4267
EXAMPLE::
4268
4269
sage: K.<a> = NumberField(x^3 + 2)
4270
sage: O2 = K.order(2*a)
4271
sage: type(O2.1) # indirect doctest
4272
<type 'sage.rings.number_field.number_field_element.OrderElement_absolute'>
4273
"""
4274
K = order.number_field()
4275
NumberFieldElement_absolute.__init__(self, K, f)
4276
self._number_field = K
4277
(<Element>self)._parent = order
4278
4279
cdef _new(self):
4280
"""
4281
Quickly creates a new initialized NumberFieldElement with the same
4282
parent as self.
4283
4284
EXAMPLES:
4285
4286
This is called implicitly in multiplication::
4287
4288
sage: O = EquationOrder(x^3 + 18, 'a')
4289
sage: O.1 * O.1 * O.1
4290
-18
4291
"""
4292
cdef type t = type(self)
4293
cdef OrderElement_absolute x = <OrderElement_absolute>t.__new__(t)
4294
x._parent = self._parent
4295
x._number_field = self._parent.number_field()
4296
x.__fld_numerator = self.__fld_numerator
4297
x.__fld_denominator = self.__fld_denominator
4298
return x
4299
4300
cdef number_field(self):
4301
r"""
4302
Return the number field of self. Only accessible from Cython.
4303
4304
EXAMPLE::
4305
4306
sage: K = NumberField(x^3 - 17, 'a')
4307
sage: OK = K.ring_of_integers()
4308
sage: a = OK(K.gen())
4309
sage: a._number_field() is K # indirect doctest
4310
True
4311
"""
4312
return self._number_field
4313
4314
cpdef RingElement _div_(self, RingElement other):
4315
r"""
4316
Implement division, checking that the result has the right parent.
4317
It's not so crucial what the parent actually is, but it is crucial
4318
that the returned value really is an element of its supposed
4319
parent! This fixes trac #4190.
4320
4321
EXAMPLES::
4322
4323
sage: K = NumberField(x^3 - 17, 'a')
4324
sage: OK = K.ring_of_integers()
4325
sage: a = OK(K.gen())
4326
sage: (17/a) in OK # indirect doctest
4327
True
4328
sage: (17/a).parent() is K # indirect doctest
4329
True
4330
sage: (17/(2*a)).parent() is K # indirect doctest
4331
True
4332
sage: (17/(2*a)) in OK # indirect doctest
4333
False
4334
"""
4335
cdef NumberFieldElement_absolute x
4336
x = NumberFieldElement_absolute._div_(self, other)
4337
return self._parent.number_field()(x)
4338
4339
def inverse_mod(self, I):
4340
r"""
4341
Return an inverse of self modulo the given ideal.
4342
4343
INPUT:
4344
4345
4346
- ``I`` - may be an ideal of self.parent(), or an
4347
element or list of elements of self.parent() generating a nonzero
4348
ideal. A ValueError is raised if I is non-integral or is zero.
4349
A ZeroDivisionError is raised if I + (x) != (1).
4350
4351
4352
EXAMPLES::
4353
4354
sage: OE = NumberField(x^3 - x + 2, 'w').ring_of_integers()
4355
sage: w = OE.ring_generators()[0]
4356
sage: w.inverse_mod(13*OE)
4357
6*w^2 - 6
4358
sage: w * (w.inverse_mod(13)) - 1 in 13*OE
4359
True
4360
sage: w.inverse_mod(13).parent() == OE
4361
True
4362
sage: w.inverse_mod(2*OE)
4363
Traceback (most recent call last):
4364
...
4365
ZeroDivisionError: w is not invertible modulo Fractional ideal (2)
4366
"""
4367
R = self.parent()
4368
return R(_inverse_mod_generic(self, I))
4369
4370
def __invert__(self):
4371
r"""
4372
Implement inversion, checking that the return value has the right
4373
parent. See trac #4190.
4374
4375
EXAMPLE::
4376
4377
sage: K = NumberField(x^3 -x + 2, 'a')
4378
sage: OK = K.ring_of_integers()
4379
sage: a = OK(K.gen())
4380
sage: (~a).parent() is K
4381
True
4382
sage: (~a) in OK
4383
False
4384
sage: a**(-1) in OK
4385
False
4386
"""
4387
return self._parent.number_field()(NumberFieldElement_absolute.__invert__(self))
4388
4389
cdef class OrderElement_relative(NumberFieldElement_relative):
4390
"""
4391
Element of an order in a relative number field.
4392
4393
EXAMPLES::
4394
4395
sage: O = EquationOrder([x^2 + x + 1, x^3 - 2],'a,b')
4396
sage: c = O.1; c
4397
(-2*b^2 - 2)*a - 2*b^2 - b
4398
sage: type(c)
4399
<type 'sage.rings.number_field.number_field_element.OrderElement_relative'>
4400
"""
4401
def __init__(self, order, f):
4402
r"""
4403
EXAMPLE::
4404
4405
sage: O = EquationOrder([x^2 + x + 1, x^3 - 2],'a,b')
4406
sage: type(O.1) # indirect doctest
4407
<type 'sage.rings.number_field.number_field_element.OrderElement_relative'>
4408
"""
4409
K = order.number_field()
4410
NumberFieldElement_relative.__init__(self, K, f)
4411
(<Element>self)._parent = order
4412
self._number_field = K
4413
4414
cdef number_field(self):
4415
return self._number_field
4416
4417
cdef _new(self):
4418
"""
4419
Quickly creates a new initialized NumberFieldElement with the same
4420
parent as self.
4421
4422
EXAMPLES:
4423
4424
This is called implicitly in multiplication::
4425
4426
sage: O = EquationOrder([x^2 + 18, x^3 + 2], 'a,b')
4427
sage: c = O.1 * O.2; c
4428
(-23321*b^2 - 9504*b + 10830)*a + 10152*b^2 - 104562*b - 110158
4429
sage: parent(c) == O
4430
True
4431
"""
4432
cdef type t = type(self)
4433
cdef OrderElement_relative x = <OrderElement_relative>t.__new__(t)
4434
x._parent = self._parent
4435
x._number_field = self._parent.number_field()
4436
x.__fld_numerator = self.__fld_numerator
4437
x.__fld_denominator = self.__fld_denominator
4438
return x
4439
4440
cpdef RingElement _div_(self, RingElement other):
4441
r"""
4442
Implement division, checking that the result has the right parent.
4443
It's not so crucial what the parent actually is, but it is crucial
4444
that the returned value really is an element of its supposed
4445
parent. This fixes trac #4190.
4446
4447
EXAMPLES::
4448
4449
sage: K1.<a> = NumberField(x^3 - 17)
4450
sage: R.<y> = K1[]
4451
sage: K2 = K1.extension(y^2 - a, 'b')
4452
sage: OK2 = K2.order(K2.gen()) # (not maximal)
4453
sage: b = OK2.gens()[1]; b
4454
b
4455
sage: (17/b).parent() is K2 # indirect doctest
4456
True
4457
sage: (17/b) in OK2 # indirect doctest
4458
True
4459
sage: (17/b^7) in OK2 # indirect doctest
4460
False
4461
"""
4462
cdef NumberFieldElement_relative x
4463
x = NumberFieldElement_relative._div_(self, other)
4464
return self._parent.number_field()(x)
4465
4466
def __invert__(self):
4467
r"""
4468
Implement division, checking that the result has the right parent.
4469
See trac #4190.
4470
4471
EXAMPLES::
4472
4473
sage: K1.<a> = NumberField(x^3 - 17)
4474
sage: R.<y> = K1[]
4475
sage: K2 = K1.extension(y^2 - a, 'b')
4476
sage: OK2 = K2.order(K2.gen()) # (not maximal)
4477
sage: b = OK2.gens()[1]; b
4478
b
4479
sage: b.parent() is OK2
4480
True
4481
sage: (~b).parent() is K2
4482
True
4483
sage: (~b) in OK2 # indirect doctest
4484
False
4485
sage: b**(-1) in OK2 # indirect doctest
4486
False
4487
"""
4488
return self._parent.number_field()(NumberFieldElement_relative.__invert__(self))
4489
4490
def inverse_mod(self, I):
4491
r"""
4492
Return an inverse of self modulo the given ideal.
4493
4494
INPUT:
4495
4496
4497
- ``I`` - may be an ideal of self.parent(), or an
4498
element or list of elements of self.parent() generating a nonzero
4499
ideal. A ValueError is raised if I is non-integral or is zero.
4500
A ZeroDivisionError is raised if I + (x) != (1).
4501
4502
4503
EXAMPLES::
4504
4505
sage: E.<a,b> = NumberField([x^2 - x + 2, x^2 + 1])
4506
sage: OE = E.ring_of_integers()
4507
sage: t = OE(b - a).inverse_mod(17*b)
4508
sage: t*(b - a) - 1 in E.ideal(17*b)
4509
True
4510
sage: t.parent() == OE
4511
True
4512
"""
4513
R = self.parent()
4514
return R(_inverse_mod_generic(self, I))
4515
4516
def charpoly(self, var='x'):
4517
r"""
4518
The characteristic polynomial of this order element over its base ring.
4519
4520
This special implementation works around bug \#4738. At this
4521
time the base ring of relative order elements is ZZ; it should
4522
be the ring of integers of the base field.
4523
4524
EXAMPLES::
4525
4526
sage: x = ZZ['x'].0
4527
sage: K.<a,b> = NumberField([x^2 + 1, x^2 - 3])
4528
sage: OK = K.maximal_order(); OK.basis()
4529
[1, 1/2*a - 1/2*b, -1/2*b*a + 1/2, a]
4530
sage: charpoly(OK.1)
4531
x^2 + b*x + 1
4532
sage: charpoly(OK.1).parent()
4533
Univariate Polynomial Ring in x over Maximal Order in Number Field in b with defining polynomial x^2 - 3
4534
sage: [ charpoly(t) for t in OK.basis() ]
4535
[x^2 - 2*x + 1, x^2 + b*x + 1, x^2 - x + 1, x^2 + 1]
4536
"""
4537
R = self.parent().number_field().base_field().ring_of_integers()[var]
4538
return R(self.matrix().charpoly(var))
4539
4540
def minpoly(self, var='x'):
4541
r"""
4542
The minimal polynomial of this order element over its base ring.
4543
4544
This special implementation works around bug \#4738. At this
4545
time the base ring of relative order elements is ZZ; it should
4546
be the ring of integers of the base field.
4547
4548
EXAMPLES::
4549
4550
sage: x = ZZ['x'].0
4551
sage: K.<a,b> = NumberField([x^2 + 1, x^2 - 3])
4552
sage: OK = K.maximal_order(); OK.basis()
4553
[1, 1/2*a - 1/2*b, -1/2*b*a + 1/2, a]
4554
sage: minpoly(OK.1)
4555
x^2 + b*x + 1
4556
sage: charpoly(OK.1).parent()
4557
Univariate Polynomial Ring in x over Maximal Order in Number Field in b with defining polynomial x^2 - 3
4558
sage: _, u, _, v = OK.basis()
4559
sage: t = 2*u - v; t
4560
-b
4561
sage: t.charpoly()
4562
x^2 + 2*b*x + 3
4563
sage: t.minpoly()
4564
x + b
4565
4566
sage: t.absolute_charpoly()
4567
x^4 - 6*x^2 + 9
4568
sage: t.absolute_minpoly()
4569
x^2 - 3
4570
"""
4571
K = self.parent().number_field()
4572
R = K.base_field().ring_of_integers()[var]
4573
return R(K(self).minpoly(var))
4574
4575
def absolute_charpoly(self, var='x'):
4576
r"""
4577
The absolute characteristic polynomial of this order element over ZZ.
4578
4579
EXAMPLES::
4580
4581
sage: x = ZZ['x'].0
4582
sage: K.<a,b> = NumberField([x^2 + 1, x^2 - 3])
4583
sage: OK = K.maximal_order()
4584
sage: _, u, _, v = OK.basis()
4585
sage: t = 2*u - v; t
4586
-b
4587
sage: t.absolute_charpoly()
4588
x^4 - 6*x^2 + 9
4589
sage: t.absolute_minpoly()
4590
x^2 - 3
4591
sage: t.absolute_charpoly().parent()
4592
Univariate Polynomial Ring in x over Integer Ring
4593
"""
4594
K = self.parent().number_field()
4595
R = ZZ[var]
4596
return R(K(self).absolute_charpoly(var))
4597
4598
def absolute_minpoly(self, var='x'):
4599
r"""
4600
The absolute minimal polynomial of this order element over ZZ.
4601
4602
EXAMPLES::
4603
4604
sage: x = ZZ['x'].0
4605
sage: K.<a,b> = NumberField([x^2 + 1, x^2 - 3])
4606
sage: OK = K.maximal_order()
4607
sage: _, u, _, v = OK.basis()
4608
sage: t = 2*u - v; t
4609
-b
4610
sage: t.absolute_charpoly()
4611
x^4 - 6*x^2 + 9
4612
sage: t.absolute_minpoly()
4613
x^2 - 3
4614
sage: t.absolute_minpoly().parent()
4615
Univariate Polynomial Ring in x over Integer Ring
4616
"""
4617
K = self.parent().number_field()
4618
R = ZZ[var]
4619
return R(K(self).absolute_minpoly(var))
4620
4621
4622
4623
class CoordinateFunction:
4624
r"""
4625
This class provides a callable object which expresses
4626
elements in terms of powers of a fixed field generator `\alpha`.
4627
4628
EXAMPLE::
4629
4630
sage: K.<a> = NumberField(x^2 + x + 3)
4631
sage: f = (a + 1).coordinates_in_terms_of_powers(); f
4632
Coordinate function that writes elements in terms of the powers of a + 1
4633
sage: f.__class__
4634
<class sage.rings.number_field.number_field_element.CoordinateFunction at ...>
4635
sage: f(a)
4636
[-1, 1]
4637
sage: f == loads(dumps(f))
4638
True
4639
"""
4640
def __init__(self, NumberFieldElement alpha, W, to_V):
4641
r"""
4642
EXAMPLE::
4643
4644
sage: K.<a> = NumberField(x^2 + x + 3)
4645
sage: f = (a + 1).coordinates_in_terms_of_powers(); f # indirect doctest
4646
Coordinate function that writes elements in terms of the powers of a + 1
4647
"""
4648
self.__alpha = alpha
4649
self.__W = W
4650
self.__to_V = to_V
4651
self.__K = alpha.number_field()
4652
4653
def __repr__(self):
4654
r"""
4655
EXAMPLE::
4656
4657
sage: K.<a> = NumberField(x^2 + x + 3)
4658
sage: f = (a + 1).coordinates_in_terms_of_powers(); repr(f) # indirect doctest
4659
'Coordinate function that writes elements in terms of the powers of a + 1'
4660
"""
4661
return "Coordinate function that writes elements in terms of the powers of %s"%self.__alpha
4662
4663
def alpha(self):
4664
r"""
4665
EXAMPLE::
4666
4667
sage: K.<a> = NumberField(x^3 + 2)
4668
sage: (a + 2).coordinates_in_terms_of_powers().alpha()
4669
a + 2
4670
"""
4671
return self.__alpha
4672
4673
def __call__(self, x):
4674
r"""
4675
EXAMPLE::
4676
4677
sage: K.<a> = NumberField(x^3 + 2)
4678
sage: f = (a + 2).coordinates_in_terms_of_powers()
4679
sage: f(1/a)
4680
[-2, 2, -1/2]
4681
sage: f(ZZ(2))
4682
[2, 0, 0]
4683
sage: L.<b> = K.extension(x^2 + 7)
4684
sage: g = (a + b).coordinates_in_terms_of_powers()
4685
sage: g(a/b)
4686
[-3379/5461, -371/10922, -4125/38227, -15/5461, -14/5461, -9/76454]
4687
sage: g(a)
4688
[4459/10922, -4838/5461, -273/5461, -980/5461, -9/10922, -42/5461]
4689
sage: f(b)
4690
Traceback (most recent call last):
4691
...
4692
TypeError: Cannot coerce element into this number field
4693
"""
4694
from sage.all import parent
4695
if not self.__K.has_coerce_map_from(parent(x)):
4696
raise TypeError, "Cannot coerce element into this number field"
4697
return self.__W.coordinates(self.__to_V(self.__K(x)))
4698
4699
def __cmp__(self, other):
4700
r"""
4701
EXAMPLE::
4702
4703
sage: K.<a> = NumberField(x^4 + 1)
4704
sage: f = (a + 1).coordinates_in_terms_of_powers()
4705
sage: f == loads(dumps(f))
4706
True
4707
sage: f == (a + 2).coordinates_in_terms_of_powers()
4708
False
4709
sage: f == NumberField(x^2 + 3,'b').gen().coordinates_in_terms_of_powers()
4710
False
4711
"""
4712
return cmp(self.__class__, other.__class__) or cmp(self.__K, other.__K) or cmp(self.__alpha, other.__alpha)
4713
4714
4715
4716
#################
4717
4718
cdef void _ntl_poly(f, ZZX_c *num, ZZ_c *den):
4719
cdef long i
4720
cdef ZZ_c coeff
4721
cdef ntl_ZZX _num
4722
cdef ntl_ZZ _den
4723
4724
__den = f.denominator()
4725
(<Integer>ZZ(__den))._to_ZZ(den)
4726
4727
__num = f * __den
4728
for i from 0 <= i <= __num.degree():
4729
(<Integer>ZZ(__num[i]))._to_ZZ(&coeff)
4730
ZZX_SetCoeff( num[0], i, coeff )
4731
4732
4733
4734