This repository has been archived by the owner on Jan 30, 2023. It is now read-only.
/
number_field_element.pyx
4834 lines (3915 loc) · 156 KB
/
number_field_element.pyx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Number Field Elements
AUTHORS:
- William Stein: version before it got Cython'd
- Joel B. Mohler (2007-03-09): First reimplementation in Cython
- William Stein (2007-09-04): add doctests
- Robert Bradshaw (2007-09-15): specialized classes for relative and
absolute elements
- John Cremona (2009-05-15): added support for local and global
logarithmic heights.
- Robert Harron (2012-08): conjugate() now works for all fields contained in
CM fields
"""
#*****************************************************************************
# Copyright (C) 2004, 2007 William Stein <wstein@gmail.com>
#
# Distributed under the terms of the GNU General Public License (GPL)
# as published by the Free Software Foundation; either version 2 of
# the License, or (at your option) any later version.
# http://www.gnu.org/licenses/
#*****************************************************************************
import operator
include 'sage/ext/interrupt.pxi'
from cpython.int cimport *
include "sage/ext/stdsage.pxi"
import sage.rings.field_element
import sage.rings.infinity
import sage.rings.polynomial.polynomial_element
import sage.rings.rational_field
import sage.rings.rational
import sage.rings.integer_ring
import sage.rings.integer
import sage.rings.arith
import number_field
from sage.rings.integer_ring cimport IntegerRing_class
from sage.rings.rational cimport Rational
from sage.rings.infinity import infinity
from sage.categories.fields import Fields
from sage.modules.free_module_element import vector
from sage.libs.pari.all import pari_gen
from sage.structure.element cimport Element, generic_power_c
from sage.structure.element import canonical_coercion, parent, coerce_binop
QQ = sage.rings.rational_field.QQ
ZZ = sage.rings.integer_ring.ZZ
Integer_sage = sage.rings.integer.Integer
from sage.rings.real_mpfi import RealInterval
from sage.rings.complex_field import ComplexField
CC = ComplexField(53)
# this is a threshold for the charpoly() methods in this file
# for degrees <= this threshold, pari is used
# for degrees > this threshold, sage matrices are used
# the value was decided by running a tuning script on a number of
# architectures; you can find this script attached to trac
# ticket 5213
TUNE_CHARPOLY_NF = 25
def is_NumberFieldElement(x):
"""
Return True if x is of type NumberFieldElement, i.e., an element of
a number field.
EXAMPLES::
sage: from sage.rings.number_field.number_field_element import is_NumberFieldElement
sage: is_NumberFieldElement(2)
False
sage: k.<a> = NumberField(x^7 + 17*x + 1)
sage: is_NumberFieldElement(a+1)
True
"""
return isinstance(x, NumberFieldElement)
def __create__NumberFieldElement_version0(parent, poly):
"""
Used in unpickling elements of number fields pickled under very old Sage versions.
EXAMPLE::
sage: k.<a> = NumberField(x^3 - 2)
sage: R.<z> = QQ[]
sage: sage.rings.number_field.number_field_element.__create__NumberFieldElement_version0(k, z^2 + z + 1)
a^2 + a + 1
"""
return NumberFieldElement(parent, poly)
def __create__NumberFieldElement_version1(parent, cls, poly):
"""
Used in unpickling elements of number fields.
EXAMPLES:
Since this is just used in unpickling, we unpickle.
::
sage: k.<a> = NumberField(x^3 - 2)
sage: loads(dumps(a+1)) == a + 1 # indirect doctest
True
This also gets called for unpickling order elements; we check that #6462 is
fixed::
sage: L = NumberField(x^3 - x - 1,'a'); OL = L.maximal_order(); w = OL.0
sage: loads(dumps(w)) == w # indirect doctest
True
"""
return cls(parent, poly)
def _inverse_mod_generic(elt, I):
r"""
Return an inverse of elt modulo the given ideal. This is a separate
function called from each of the OrderElement_xxx classes, since
otherwise we'd have to have the same code three times over (there
is no OrderElement_generic class - no multiple inheritance). See
trac 4190.
EXAMPLES::
sage: OE = NumberField(x^3 - x + 2, 'w').ring_of_integers()
sage: w = OE.ring_generators()[0]
sage: from sage.rings.number_field.number_field_element import _inverse_mod_generic
sage: _inverse_mod_generic(w, 13*OE)
6*w^2 - 6
"""
from sage.matrix.constructor import matrix
R = elt.parent()
try:
I = R.ideal(I)
except ValueError:
raise ValueError, "inverse is only defined modulo integral ideals"
if I == 0:
raise ValueError, "inverse is not defined modulo the zero ideal"
n = R.absolute_degree()
m = matrix(ZZ, map(R.coordinates, I.integral_basis() + [elt*s for s in R.gens()]))
a, b = m.echelon_form(transformation=True)
if a[0:n] != 1:
raise ZeroDivisionError, "%s is not invertible modulo %s" % (elt, I)
v = R.coordinates(1)
y = R(0)
for j in xrange(n):
if v[j] != 0:
y += v[j] * sum([b[j,i+n] * R.gen(i) for i in xrange(n)])
return I.small_residue(y)
__pynac_pow = False
cdef class NumberFieldElement(FieldElement):
"""
An element of a number field.
EXAMPLES::
sage: k.<a> = NumberField(x^3 + x + 1)
sage: a^3
-a - 1
"""
cdef _new(self):
"""
Quickly creates a new initialized NumberFieldElement with the same
parent as self.
"""
cdef type t = type(self)
cdef NumberFieldElement x = <NumberFieldElement>t.__new__(t)
x._parent = self._parent
x.__fld_numerator = self.__fld_numerator
x.__fld_denominator = self.__fld_denominator
return x
cdef number_field(self):
r"""
Return the number field of self. Only accessible from Cython.
EXAMPLE::
sage: K.<a> = NumberField(x^3 + 3)
sage: a._number_field() # indirect doctest
Number Field in a with defining polynomial x^3 + 3
"""
return self._parent
def _number_field(self):
r"""
EXAMPLE::
sage: K.<a> = NumberField(x^3 + 3)
sage: a._number_field()
Number Field in a with defining polynomial x^3 + 3
"""
return self.number_field()
def __init__(self, parent, f):
"""
INPUT:
- ``parent`` - a number field
- ``f`` - defines an element of a number field.
EXAMPLES:
The following examples illustrate creation of elements of
number fields, and some basic arithmetic.
First we define a polynomial over Q::
sage: R.<x> = PolynomialRing(QQ)
sage: f = x^2 + 1
Next we use f to define the number field::
sage: K.<a> = NumberField(f); K
Number Field in a with defining polynomial x^2 + 1
sage: a = K.gen()
sage: a^2
-1
sage: (a+1)^2
2*a
sage: a^2
-1
sage: z = K(5); 1/z
1/5
We create a cube root of 2::
sage: K.<b> = NumberField(x^3 - 2)
sage: b = K.gen()
sage: b^3
2
sage: (b^2 + b + 1)^3
12*b^2 + 15*b + 19
We can create number field elements from PARI::
sage: K.<a> = NumberField(x^3 - 17)
sage: K(pari(42))
42
sage: K(pari("5/3"))
5/3
sage: K(pari("[3/2, -5, 0]~")) # Uses Z-basis
-5/3*a^2 + 5/3*a - 1/6
From a PARI polynomial or ``POLMOD``, note that the variable
name does not matter::
sage: K(pari("-5/3*q^2 + 5/3*q - 1/6"))
-5/3*a^2 + 5/3*a - 1/6
sage: K(pari("Mod(-5/3*q^2 + 5/3*q - 1/6, q^3 - 17)"))
-5/3*a^2 + 5/3*a - 1/6
sage: K(pari("x^5/17"))
a^2
sage: K(pari("Mod(-5/3*q^2 + 5/3*q - 1/6, q^3 - 999)")) # Wrong modulus
Traceback (most recent call last):
...
TypeError: Coercion of PARI polmod with modulus q^3 - 999 into number field with defining polynomial x^3 - 17 failed
This example illustrates save and load::
sage: K.<a> = NumberField(x^17 - 2)
sage: s = a^15 - 19*a + 3
sage: loads(s.dumps()) == s
True
TESTS:
Test round-trip conversion to PARI and back::
sage: x = polygen(QQ)
sage: K.<a> = NumberField(x^3 - 1/2*x + 1/3)
sage: b = K.random_element()
sage: K(pari(b)) == b
True
"""
sage.rings.field_element.FieldElement.__init__(self, parent)
self.__fld_numerator, self.__fld_denominator = parent.absolute_polynomial_ntl()
cdef ZZ_c coeff
if isinstance(f, (int, long, Integer_sage)):
# set it up and exit immediately
# fast pathway
(<Integer>ZZ(f))._to_ZZ(&coeff)
ZZX_SetCoeff( self.__numerator, 0, coeff )
ZZ_conv_from_int( self.__denominator, 1 )
return
elif isinstance(f, NumberFieldElement):
if type(self) is type(f):
self.__numerator = (<NumberFieldElement>f).__numerator
self.__denominator = (<NumberFieldElement>f).__denominator
return
else:
f = f.polynomial()
from sage.rings.number_field import number_field_rel
if isinstance(parent, number_field_rel.NumberField_relative):
ppr = parent.base_field().polynomial_ring()
else:
ppr = parent.polynomial_ring()
cdef long i
if isinstance(f, pari_gen):
if f.type() in ["t_INT", "t_FRAC", "t_POL"]:
pass
elif f.type() == "t_POLMOD":
# Check whether we are dealing with a *relative*
# number field element
if parent.is_relative():
# If the modulus is a polynomial with polynomial
# coefficients, then the element is relative.
fmod = f.mod()
for i from 0 <= i <= fmod.poldegree():
if fmod.polcoeff(i).type() in ["t_POL", "t_POLMOD"]:
# Convert relative element to absolute.
# Sometimes the result is a polynomial,
# sometimed a polmod. Lift to convert to a
# polynomial in all cases.
f = parent.pari_rnf().rnfeltreltoabs(f).lift()
break
# Check that the modulus is actually the defining polynomial
# of the number field.
# Unfortunately, this check only works for absolute elements
# since the rnfeltreltoabs() destroys all information about
# the number field.
if f.type() == "t_POLMOD":
fmod = f.mod()
if fmod != parent.pari_polynomial(fmod.variable()):
raise TypeError("Coercion of PARI polmod with modulus %s into number field with defining polynomial %s failed"%(fmod, parent.pari_polynomial()))
f = f.lift()
else:
f = parent.pari_nf().nfbasistoalg_lift(f)
f = ppr(f)
if f.degree() >= parent.absolute_degree():
from sage.rings.number_field import number_field_rel
if isinstance(parent, number_field_rel.NumberField_relative):
f %= ppr(parent.absolute_polynomial())
else:
f %= parent.polynomial()
# Set Denominator
den = f.denominator()
(<Integer>ZZ(den))._to_ZZ(&self.__denominator)
num = f * den
for i from 0 <= i <= num.degree():
(<Integer>ZZ(num[i]))._to_ZZ(&coeff)
ZZX_SetCoeff( self.__numerator, i, coeff )
def __cinit__(self):
r"""
Initialise C variables.
EXAMPLE::
sage: K.<b> = NumberField(x^3 - 2)
sage: b = K.gen(); b # indirect doctest
b
"""
ZZX_construct(&self.__numerator)
ZZ_construct(&self.__denominator)
def __dealloc__(self):
ZZX_destruct(&self.__numerator)
ZZ_destruct(&self.__denominator)
def _lift_cyclotomic_element(self, new_parent, bint check=True, int rel=0):
"""
Creates an element of the passed field from this field. This is
specific to creating elements in a cyclotomic field from elements
in another cyclotomic field, in the case that
self.number_field()._n() divides new_parent()._n(). This
function aims to make this common coercion extremely fast!
More general coercion (i.e. of zeta6 into CyclotomicField(3)) is
implemented in the _coerce_from_other_cyclotomic_field method
of a CyclotomicField.
EXAMPLES::
sage: C.<zeta5>=CyclotomicField(5)
sage: CyclotomicField(10)(zeta5+1) # The function _lift_cyclotomic_element does the heavy lifting in the background
zeta10^2 + 1
sage: (zeta5+1)._lift_cyclotomic_element(CyclotomicField(10)) # There is rarely a purpose to call this function directly
zeta10^2 + 1
sage: cf4 = CyclotomicField(4)
sage: cf1 = CyclotomicField(1) ; one = cf1.0
sage: cf4(one)
1
sage: type(cf4(1))
<type 'sage.rings.number_field.number_field_element_quadratic.NumberFieldElement_quadratic'>
sage: cf33 = CyclotomicField(33) ; z33 = cf33.0
sage: cf66 = CyclotomicField(66) ; z66 = cf66.0
sage: z33._lift_cyclotomic_element(cf66)
zeta66^2
sage: z66._lift_cyclotomic_element(cf33)
Traceback (most recent call last):
...
TypeError: The zeta_order of the new field must be a multiple of the zeta_order of the original.
sage: cf33(z66)
-zeta33^17
AUTHORS:
- Joel B. Mohler
- Craig Citro (fixed behavior for different representation of
quadratic field elements)
"""
if check:
if not isinstance(self.number_field(), number_field.NumberField_cyclotomic) \
or not isinstance(new_parent, number_field.NumberField_cyclotomic):
raise TypeError, "The field and the new parent field must both be cyclotomic fields."
if rel == 0:
small_order = self.number_field()._n()
large_order = new_parent._n()
try:
rel = ZZ(large_order / small_order)
except TypeError:
raise TypeError, "The zeta_order of the new field must be a multiple of the zeta_order of the original."
## degree 2 is handled differently, because elements are
## represented differently
if new_parent.degree() == 2:
if rel == 1:
return new_parent._element_class(new_parent, self)
else:
return self.polynomial()(new_parent.gen()**rel)
cdef type t = type(self)
cdef NumberFieldElement x = <NumberFieldElement>t.__new__(t)
x._parent = <ParentWithBase>new_parent
x.__fld_numerator, x.__fld_denominator = new_parent.polynomial_ntl()
x.__denominator = self.__denominator
cdef ZZX_c result
cdef ZZ_c tmp
cdef int i
cdef ntl_ZZX _num
cdef ntl_ZZ _den
for i from 0 <= i <= ZZX_deg(self.__numerator):
tmp = ZZX_coeff(self.__numerator, i)
ZZX_SetCoeff(result, i*rel, tmp)
ZZX_rem(x.__numerator, result, x.__fld_numerator.x)
return x
def __reduce__(self):
"""
Used in pickling number field elements.
Note for developers: If this is changed, please also change the doctests of __create__NumberFieldElement_version1.
EXAMPLES::
sage: k.<a> = NumberField(x^3 - 17*x^2 + 1)
sage: t = a.__reduce__(); t
(<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))
sage: t[0](*t[1]) == a
True
"""
return __create__NumberFieldElement_version1, \
(self.parent(), type(self), self.polynomial())
def _repr_(self):
"""
String representation of this number field element, which is just a
polynomial in the generator.
EXAMPLES::
sage: k.<a> = NumberField(x^2 + 2)
sage: b = (2/3)*a + 3/5
sage: b._repr_()
'2/3*a + 3/5'
"""
x = self.polynomial()
K = self.number_field()
return str(x).replace(x.parent().variable_name(), K.variable_name())
def _im_gens_(self, codomain, im_gens):
"""
This is used in computing homomorphisms between number fields.
EXAMPLES::
sage: k.<a> = NumberField(x^2 - 2)
sage: m.<b> = NumberField(x^4 - 2)
sage: phi = k.hom([b^2])
sage: phi(a+1)
b^2 + 1
sage: (a+1)._im_gens_(m, [b^2])
b^2 + 1
"""
# NOTE -- if you ever want to change this so relative number
# fields are in terms of a root of a poly. The issue is that
# elements of a relative number field are represented in terms
# of a generator for the absolute field. However the morphism
# gives the image of gen, which need not be a generator for
# the absolute field. The morphism has to be *over* the
# relative element.
return codomain(self.polynomial()(im_gens[0]))
def _latex_(self):
"""
Returns the latex representation for this element.
EXAMPLES::
sage: C.<zeta12> = CyclotomicField(12)
sage: latex(zeta12^4-zeta12) # indirect doctest
\zeta_{12}^{2} - \zeta_{12} - 1
"""
return self.polynomial()._latex_(name=self.number_field().latex_variable_name())
def _gap_init_(self):
"""
Return gap string representation of self.
EXAMPLES::
sage: F=CyclotomicField(8)
sage: F.gen()
zeta8
sage: F._gap_init_()
'CyclotomicField(8)'
sage: f = gap(F)
sage: f.GeneratorsOfDivisionRing()
[ E(8) ]
sage: p=F.gen()^2+2*F.gen()-3
sage: p
zeta8^2 + 2*zeta8 - 3
sage: p._gap_init_() # The variable name $sage2 belongs to the gap(F) and is somehow random
'GeneratorsOfField($sage2)[1]^2 + 2*GeneratorsOfField($sage2)[1] - 3'
sage: gap(p._gap_init_())
-3+2*E(8)+E(8)^2
"""
s = self._repr_()
return s.replace(str(self.parent().gen()), 'GeneratorsOfField(%s)[1]'%sage.interfaces.gap.gap(self.parent()).name())
def _libgap_(self):
"""
Return a LibGAP representation of ``self``.
EXAMPLES::
sage: F = CyclotomicField(8)
sage: F.gen()._libgap_()
E(8)
sage: libgap(F.gen()) # syntactic sugar
E(8)
sage: E8 = F.gen()
sage: libgap(E8 + 3/2*E8^2 + 100*E8^7)
E(8)+3/2*E(8)^2-100*E(8)^3
sage: type(_)
<type 'sage.libs.gap.element.GapElement_Cyclotomic'>
"""
n = self.parent()._n()
from sage.libs.gap.libgap import libgap
En = libgap(self.parent()).GeneratorsOfField()[0]
return self.polynomial()(En)
def _pari_(self, name='y'):
r"""
Return PARI representation of self.
The returned element is a PARI ``POLMOD`` in the variable
``name``, which is by default 'y' - not the name of the generator
of the number field.
INPUT:
- ``name`` -- (default: 'y') the PARI variable name used.
EXAMPLES::
sage: K.<a> = NumberField(x^3 + 2)
sage: K(1)._pari_()
Mod(1, y^3 + 2)
sage: (a + 2)._pari_()
Mod(y + 2, y^3 + 2)
sage: L.<b> = K.extension(x^2 + 2)
sage: (b + a)._pari_()
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)
::
sage: k.<j> = QuadraticField(-1)
sage: j._pari_('j')
Mod(j, j^2 + 1)
sage: pari(j)
Mod(y, y^2 + 1)
By default the variable name is 'y'. This allows 'x' to be used
as polynomial variable::
sage: P.<a> = PolynomialRing(QQ)
sage: K.<b> = NumberField(a^2 + 1)
sage: R.<x> = PolynomialRing(K)
sage: pari(b*x)
Mod(y, y^2 + 1)*x
In PARI many variable names are reserved, for example ``theta``
and ``I``::
sage: R.<theta> = PolynomialRing(QQ)
sage: K.<theta> = NumberField(theta^2 + 1)
sage: theta._pari_('theta')
Traceback (most recent call last):
...
PariError: theta already exists with incompatible valence
sage: theta._pari_()
Mod(y, y^2 + 1)
sage: k.<I> = QuadraticField(-1)
sage: I._pari_('I')
Traceback (most recent call last):
...
PariError: I already exists with incompatible valence
Instead, request the variable be named different for the coercion::
sage: pari(I)
Mod(y, y^2 + 1)
sage: I._pari_('i')
Mod(i, i^2 + 1)
sage: I._pari_('II')
Mod(II, II^2 + 1)
Examples with relative number fields, which always yield an
*absolute* representation of the element::
sage: y = QQ['y'].gen()
sage: k.<j> = NumberField([y^2 - 7, y^3 - 2])
sage: pari(j)
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)
sage: j^2
7
sage: pari(j)^2
Mod(7, y^6 - 21*y^4 + 4*y^3 + 147*y^2 + 84*y - 339)
sage: (j^2)._pari_('x')
Mod(7, x^6 - 21*x^4 + 4*x^3 + 147*x^2 + 84*x - 339)
A tower of three number fields::
sage: x = polygen(QQ)
sage: K.<a> = NumberField(x^2 + 2)
sage: L.<b> = NumberField(polygen(K)^2 + a)
sage: M.<c> = NumberField(polygen(L)^3 + b)
sage: L(b)._pari_()
Mod(y, y^4 + 2)
sage: M(b)._pari_('c')
Mod(-c^3, c^12 + 2)
sage: c._pari_('c')
Mod(c, c^12 + 2)
"""
try:
return self.__pari[name]
except KeyError:
pass
except TypeError:
self.__pari = {}
f = self.polynomial()._pari_or_constant(name)
g = self.number_field().pari_polynomial(name)
h = f.Mod(g)
self.__pari[name] = h
return h
def _pari_init_(self, name='y'):
"""
Return PARI/GP string representation of self.
The returned string defines a PARI ``POLMOD`` in the variable
``name``, which is by default 'y' - not the name of the generator
of the number field.
INPUT:
- ``name`` -- (default: 'y') the PARI variable name used.
EXAMPLES::
sage: K.<a> = NumberField(x^5 - x - 1)
sage: ((1 + 1/3*a)^4)._pari_init_()
'Mod(1/81*y^4 + 4/27*y^3 + 2/3*y^2 + 4/3*y + 1, y^5 - y - 1)'
sage: ((1 + 1/3*a)^4)._pari_init_('a')
'Mod(1/81*a^4 + 4/27*a^3 + 2/3*a^2 + 4/3*a + 1, a^5 - a - 1)'
Note that _pari_init_ can fail because of reserved words in
PARI, and since it actually works by obtaining the PARI
representation of something::
sage: K.<theta> = NumberField(x^5 - x - 1)
sage: b = (1/2 - 2/3*theta)^3; b
-8/27*theta^3 + 2/3*theta^2 - 1/2*theta + 1/8
sage: b._pari_init_('theta')
Traceback (most recent call last):
...
PariError: theta already exists with incompatible valence
Fortunately pari_init returns everything in terms of y by
default::
sage: pari(b)
Mod(-8/27*y^3 + 2/3*y^2 - 1/2*y + 1/8, y^5 - y - 1)
"""
return repr(self._pari_(name=name))
def __getitem__(self, n):
"""
Return the n-th coefficient of this number field element, written
as a polynomial in the generator.
Note that `n` must be between 0 and `d-1`, where
`d` is the degree of the number field.
EXAMPLES::
sage: m.<b> = NumberField(x^4 - 1789)
sage: c = (2/3-4/5*b)^3; c
-64/125*b^3 + 32/25*b^2 - 16/15*b + 8/27
sage: c[0]
8/27
sage: c[2]
32/25
sage: c[3]
-64/125
We illustrate bounds checking::
sage: c[-1]
Traceback (most recent call last):
...
IndexError: index must be between 0 and degree minus 1.
sage: c[4]
Traceback (most recent call last):
...
IndexError: index must be between 0 and degree minus 1.
The list method implicitly calls ``__getitem__``::
sage: list(c)
[8/27, -16/15, 32/25, -64/125]
sage: m(list(c)) == c
True
"""
if n < 0 or n >= self.number_field().degree(): # make this faster.
raise IndexError, "index must be between 0 and degree minus 1."
return self.polynomial()[n]
def __richcmp__(left, right, int op):
r"""
EXAMPLE::
sage: K.<a> = NumberField(x^3 - 3*x + 8)
sage: a + 1 > a # indirect doctest
True
sage: a + 1 < a # indirect doctest
False
"""
return (<Element>left)._richcmp(right, op)
cpdef int _cmp_(left, sage.structure.element.Element right) except -2:
cdef NumberFieldElement _right = right
return not (ZZX_equal(left.__numerator, _right.__numerator) and ZZ_equal(left.__denominator, _right.__denominator))
def _random_element(self, num_bound=None, den_bound=None, distribution=None):
"""
Return a new random element with the same parent as self.
INPUT:
- ``num_bound`` - Bound for the numerator of coefficients of result
- ``den_bound`` - Bound for the denominator of coefficients of result
- ``distribution`` - Distribution to use for coefficients of result
EXAMPLES::
sage: K.<a> = NumberField(x^3-2)
sage: a._random_element()
-1/2*a^2 - 4
sage: K.<a> = NumberField(x^2-5)
sage: a._random_element()
-2*a - 1
"""
cdef NumberFieldElement elt = self._new()
elt._randomize(num_bound, den_bound, distribution)
return elt
cdef int _randomize(self, num_bound, den_bound, distribution) except -1:
cdef int i
cdef Integer denom_temp = PY_NEW(Integer)
cdef Integer tmp_integer = PY_NEW(Integer)
cdef ZZ_c ntl_temp
cdef list coeff_list
cdef Rational tmp_rational
# It seems like a simpler approach would be to simply generate
# random integers for each coefficient of self.__numerator
# and an integer for self.__denominator. However, this would
# generate things with a fairly fixed shape: in particular,
# we'd be very unlikely to get elements like 1/3*a^3 + 1/7,
# or anything where the denominators are actually unrelated
# to one another. The extra code below is to make exactly
# these kinds of results possible.
if den_bound == 1:
# in this case, we can skip all the business with LCMs,
# storing a list of rationals, etc. this gives a factor of
# two or so speedup ...
# set the denominator
mpz_set_si(denom_temp.value, 1)
denom_temp._to_ZZ(&self.__denominator)
for i from 0 <= i < ZZX_deg(self.__fld_numerator.x):
tmp_integer = <Integer>(ZZ.random_element(x=num_bound,
distribution=distribution))
tmp_integer._to_ZZ(&ntl_temp)
ZZX_SetCoeff(self.__numerator, i, ntl_temp)
else:
coeff_list = []
mpz_set_si(denom_temp.value, 1)
tmp_integer = PY_NEW(Integer)
for i from 0 <= i < ZZX_deg(self.__fld_numerator.x):
tmp_rational = <Rational>(QQ.random_element(num_bound=num_bound,
den_bound=den_bound,
distribution=distribution))
coeff_list.append(tmp_rational)
mpz_lcm(denom_temp.value, denom_temp.value,
mpq_denref(tmp_rational.value))
# now denom_temp has the denominator, and we just need to
# scale the numerators and set everything appropriately
# first, the denominator (easy)
denom_temp._to_ZZ(&self.__denominator)
# now the coefficients themselves.
for i from 0 <= i < ZZX_deg(self.__fld_numerator.x):
# calculate the new numerator. if our old entry is
# p/q, and the lcm is k, it's just pk/q, which we
# also know is integral -- so we can use mpz_divexact
# below
tmp_rational = <Rational>(coeff_list[i])
mpz_mul(tmp_integer.value, mpq_numref(tmp_rational.value),
denom_temp.value)
mpz_divexact(tmp_integer.value, tmp_integer.value,
mpq_denref(tmp_rational.value))
# now set the coefficient of self
tmp_integer._to_ZZ(&ntl_temp)
ZZX_SetCoeff(self.__numerator, i, ntl_temp)
return 0 # No error
def __abs__(self):
r"""
Return the numerical absolute value of this number field element
with respect to the first archimedean embedding, to double
precision.
This is the ``abs( )`` Python function. If you want a
different embedding or precision, use
``self.abs(...)``.
EXAMPLES::
sage: k.<a> = NumberField(x^3 - 2)
sage: abs(a)
1.25992104989487
sage: abs(a)^3
2.00000000000000
sage: a.abs(prec=128)
1.2599210498948731647672106072782283506
"""
return self.abs(prec=53, i=None)
def abs(self, prec=53, i=None):
r"""
Return the absolute value of this element.
If ``i`` is provided, then the absolute of the `i`-th embedding is
given. Otherwise, if the number field as a defined embedding into `\CC`
then the corresponding absolute value is returned and if there is none,
it corresponds to the choice ``i=0``.
If prec is 53 (the default), then the complex double field is
used; otherwise the arbitrary precision (but slow) complex
field is used.
INPUT:
- ``prec`` - (default: 53) integer bits of precision
- ``i`` - (default: ) integer, which embedding to
use
EXAMPLES::
sage: z = CyclotomicField(7).gen()
sage: abs(z)
1.00000000000000
sage: abs(z^2 + 17*z - 3)
16.0604426799931
sage: K.<a> = NumberField(x^3+17)
sage: abs(a)
2.57128159065824
sage: a.abs(prec=100)
2.5712815906582353554531872087
sage: a.abs(prec=100,i=1)
2.5712815906582353554531872087
sage: a.abs(100, 2)
2.5712815906582353554531872087
Here's one where the absolute value depends on the embedding.
::
sage: K.<b> = NumberField(x^2-2)
sage: a = 1 + b
sage: a.abs(i=0)
0.414213562373095
sage: a.abs(i=1)
2.41421356237309
Check that :trac:`16147` is fixed::
sage: x = polygen(ZZ)
sage: f = x^3 - x - 1
sage: beta = f.complex_roots()[0]; beta
1.32471795724475
sage: K.<b> = NumberField(f, embedding=beta)
sage: b.abs()
1.32471795724475
"""
CCprec = ComplexField(prec)
if i is None and CCprec.has_coerce_map_from(self.parent()):
return CCprec(self).abs()
else:
i = 0 if i is None else i
P = self.number_field().complex_embeddings(prec)[i]
return P(self).abs()
def abs_non_arch(self, P, prec=None):
r"""
Return the non-archimedean absolute value of this element with
respect to the prime `P`, to the given precision.
INPUT:
- ``P`` - a prime ideal of the parent of self
- ``prec`` (int) -- desired floating point precision (default:
default RealField precision).
OUTPUT:
(real) the non-archimedean absolute value of this element with
respect to the prime `P`, to the given precision. This is the
normalised absolute value, so that the underlying prime number
`p` has absolute value `1/p`.
EXAMPLES::
sage: K.<a> = NumberField(x^2+5)
sage: [1/K(2).abs_non_arch(P) for P in K.primes_above(2)]
[2.00000000000000]
sage: [1/K(3).abs_non_arch(P) for P in K.primes_above(3)]
[3.00000000000000, 3.00000000000000]
sage: [1/K(5).abs_non_arch(P) for P in K.primes_above(5)]
[5.00000000000000]
A relative example::
sage: L.<b> = K.extension(x^2-5)