Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagesmc
Path: blob/master/src/sage/libs/pari/gen.pyx
8817 views
1
"""
2
Sage class for PARI's GEN type
3
4
See the ``PariInstance`` class for documentation and examples.
5
6
AUTHORS:
7
8
- William Stein (2006-03-01): updated to work with PARI 2.2.12-beta
9
10
- William Stein (2006-03-06): added newtonpoly
11
12
- Justin Walker: contributed some of the function definitions
13
14
- Gonzalo Tornaria: improvements to conversions; much better error
15
handling.
16
17
- Robert Bradshaw, Jeroen Demeyer, William Stein (2010-08-15):
18
Upgrade to PARI 2.4.3 (#9343)
19
20
- Jeroen Demeyer (2011-11-12): rewrite various conversion routines
21
(#11611, #11854, #11952)
22
23
- Peter Bruin (2013-11-17): move PariInstance to a separate file
24
(#15185)
25
26
"""
27
28
#*****************************************************************************
29
# Copyright (C) 2006,2010 William Stein <[email protected]>
30
# Copyright (C) ???? Justin Walker
31
# Copyright (C) ???? Gonzalo Tornaria
32
# Copyright (C) 2010 Robert Bradshaw <[email protected]>
33
# Copyright (C) 2010,2011 Jeroen Demeyer <[email protected]>
34
#
35
# Distributed under the terms of the GNU General Public License (GPL)
36
# as published by the Free Software Foundation; either version 2 of
37
# the License, or (at your option) any later version.
38
# http://www.gnu.org/licenses/
39
#*****************************************************************************
40
41
42
import math
43
import types
44
import operator
45
import sage.structure.element
46
from sage.structure.element cimport ModuleElement, RingElement, Element
47
from sage.misc.randstate cimport randstate, current_randstate
48
49
from sage.misc.misc_c import is_64_bit
50
51
include 'pari_err.pxi'
52
include 'sage/ext/stdsage.pxi'
53
include 'sage/ext/python.pxi'
54
include 'sage/ext/interrupt.pxi'
55
56
cimport cython
57
58
cdef extern from "misc.h":
59
int factorint_withproof_sage(GEN* ans, GEN x, GEN cutoff)
60
int gcmp_sage(GEN x, GEN y)
61
62
cdef extern from "mpz_pylong.h":
63
cdef int mpz_set_pylong(mpz_t dst, src) except -1
64
65
# Will be imported as needed
66
Integer = None
67
68
import pari_instance
69
from pari_instance cimport PariInstance, prec_bits_to_words
70
cdef PariInstance P = pari_instance.pari
71
72
73
@cython.final
74
cdef class gen(sage.structure.element.RingElement):
75
"""
76
Python extension class that models the PARI GEN type.
77
"""
78
def __init__(self):
79
raise RuntimeError("PARI objects cannot be instantiated directly; use pari(x) to convert x to PARI")
80
81
def __dealloc__(self):
82
if self.b:
83
sage_free(<void*> self.b)
84
85
def __repr__(self):
86
cdef char *c
87
pari_catch_sig_on()
88
# Use sig_block(), which is needed because GENtostr() uses
89
# malloc(), which is dangerous inside sig_on()
90
sig_block()
91
c = GENtostr(self.g)
92
sig_unblock()
93
pari_catch_sig_off()
94
95
s = str(c)
96
pari_free(c)
97
return s
98
99
def __hash__(self):
100
"""
101
Return the hash of self, computed using PARI's hash_GEN().
102
103
TESTS::
104
105
sage: type(pari('1 + 2.0*I').__hash__())
106
<type 'int'>
107
"""
108
cdef long h
109
pari_catch_sig_on()
110
h = hash_GEN(self.g)
111
pari_catch_sig_off()
112
return h
113
114
def _testclass(self):
115
import test
116
T = test.testclass()
117
T._init(self)
118
return T
119
120
def list(self):
121
"""
122
Convert self to a list of PARI gens.
123
124
EXAMPLES:
125
126
A PARI vector becomes a Sage list::
127
128
sage: L = pari("vector(10,i,i^2)").list()
129
sage: L
130
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
131
sage: type(L)
132
<type 'list'>
133
sage: type(L[0])
134
<type 'sage.libs.pari.gen.gen'>
135
136
For polynomials, list() behaves as for ordinary Sage polynomials::
137
138
sage: pol = pari("x^3 + 5/3*x"); pol.list()
139
[0, 5/3, 0, 1]
140
141
For power series or laurent series, we get all coefficients starting
142
from the lowest degree term. This includes trailing zeros::
143
144
sage: R.<x> = LaurentSeriesRing(QQ)
145
sage: s = x^2 + O(x^8)
146
sage: s.list()
147
[1]
148
sage: pari(s).list()
149
[1, 0, 0, 0, 0, 0]
150
sage: s = x^-2 + O(x^0)
151
sage: s.list()
152
[1]
153
sage: pari(s).list()
154
[1, 0]
155
156
For matrices, we get a list of columns::
157
158
sage: M = matrix(ZZ,3,2,[1,4,2,5,3,6]); M
159
[1 4]
160
[2 5]
161
[3 6]
162
sage: pari(M).list()
163
[[1, 2, 3]~, [4, 5, 6]~]
164
165
For "scalar" types, we get a 1-element list containing ``self``::
166
167
sage: pari("42").list()
168
[42]
169
"""
170
if typ(self.g) == t_POL:
171
return list(self.Vecrev())
172
return list(self.Vec())
173
174
def __reduce__(self):
175
"""
176
EXAMPLES::
177
178
sage: f = pari('x^3 - 3')
179
sage: loads(dumps(f)) == f
180
True
181
"""
182
s = str(self)
183
import sage.libs.pari.gen_py
184
return sage.libs.pari.gen_py.pari, (s,)
185
186
cpdef ModuleElement _add_(self, ModuleElement right):
187
pari_catch_sig_on()
188
return P.new_gen(gadd(self.g, (<gen>right).g))
189
190
cpdef ModuleElement _sub_(self, ModuleElement right):
191
pari_catch_sig_on()
192
return P.new_gen(gsub(self.g, (<gen> right).g))
193
194
cpdef RingElement _mul_(self, RingElement right):
195
pari_catch_sig_on()
196
return P.new_gen(gmul(self.g, (<gen>right).g))
197
198
cpdef RingElement _div_(self, RingElement right):
199
pari_catch_sig_on()
200
return P.new_gen(gdiv(self.g, (<gen>right).g))
201
202
def _add_one(gen self):
203
"""
204
Return self + 1.
205
206
OUTPUT: pari gen
207
208
EXAMPLES::
209
210
sage: n = pari(5)
211
sage: n._add_one()
212
6
213
sage: n = pari('x^3')
214
sage: n._add_one()
215
x^3 + 1
216
"""
217
pari_catch_sig_on()
218
return P.new_gen(gaddsg(1, self.g))
219
220
def __mod__(self, other):
221
cdef gen selfgen
222
cdef gen othergen
223
if isinstance(other, gen) and isinstance(self, gen):
224
selfgen = self
225
othergen = other
226
pari_catch_sig_on()
227
return P.new_gen(gmod(selfgen.g, othergen.g))
228
return sage.structure.element.bin_op(self, other, operator.mod)
229
230
def __pow__(gen self, n, m):
231
cdef gen t0 = objtogen(n)
232
pari_catch_sig_on()
233
return P.new_gen(gpow(self.g, t0.g, prec_bits_to_words(0)))
234
235
def __neg__(gen self):
236
pari_catch_sig_on()
237
return P.new_gen(gneg(self.g))
238
239
def __xor__(gen self, n):
240
raise RuntimeError, "Use ** for exponentiation, not '^', which means xor\n"+\
241
"in Python, and has the wrong precedence."
242
243
def __rshift__(gen self, long n):
244
pari_catch_sig_on()
245
return P.new_gen(gshift(self.g, -n))
246
247
def __lshift__(gen self, long n):
248
pari_catch_sig_on()
249
return P.new_gen(gshift(self.g, n))
250
251
def __invert__(gen self):
252
pari_catch_sig_on()
253
return P.new_gen(ginv(self.g))
254
255
def getattr(gen self, attr):
256
"""
257
Return the PARI attribute with the given name.
258
259
EXAMPLES::
260
261
sage: K = pari("nfinit(x^2 - x - 1)")
262
sage: K.getattr("pol")
263
x^2 - x - 1
264
sage: K.getattr("disc")
265
5
266
267
sage: K.getattr("reg")
268
Traceback (most recent call last):
269
...
270
PariError: _.reg: incorrect type in reg
271
sage: K.getattr("zzz")
272
Traceback (most recent call last):
273
...
274
PariError: no function named "_.zzz"
275
276
"""
277
cdef str s = "_." + attr
278
cdef char *t = PyString_AsString(s)
279
pari_catch_sig_on()
280
return P.new_gen(closure_callgen1(strtofunction(t), self.g))
281
282
def mod(self):
283
"""
284
Given an INTMOD or POLMOD ``Mod(a,m)``, return the modulus `m`.
285
286
EXAMPLES::
287
288
sage: pari(4).Mod(5).mod()
289
5
290
sage: pari("Mod(x, x*y)").mod()
291
y*x
292
sage: pari("[Mod(4,5)]").mod()
293
Traceback (most recent call last):
294
...
295
TypeError: Not an INTMOD or POLMOD in mod()
296
"""
297
if typ(self.g) != t_INTMOD and typ(self.g) != t_POLMOD:
298
raise TypeError("Not an INTMOD or POLMOD in mod()")
299
pari_catch_sig_on()
300
# The hardcoded 1 below refers to the position in the internal
301
# representation of a INTMOD or POLDMOD where the modulus is
302
# stored.
303
return P.new_gen(gel(self.g, 1))
304
305
def nf_get_pol(self):
306
"""
307
Returns the defining polynomial of this number field.
308
309
INPUT:
310
311
- ``self`` -- A PARI number field being the output of ``nfinit()``,
312
``bnfinit()`` or ``bnrinit()``.
313
314
EXAMPLES::
315
316
sage: K.<a> = NumberField(x^4 - 4*x^2 + 1)
317
sage: pari(K).nf_get_pol()
318
y^4 - 4*y^2 + 1
319
sage: bnr = pari("K = bnfinit(x^4 - 4*x^2 + 1); bnrinit(K, 2*x)")
320
sage: bnr.nf_get_pol()
321
x^4 - 4*x^2 + 1
322
323
For relative extensions, this returns the absolute polynomial,
324
not the relative one::
325
326
sage: L.<b> = K.extension(x^2 - 5)
327
sage: pari(L).nf_get_pol() # Absolute polynomial
328
y^8 - 28*y^6 + 208*y^4 - 408*y^2 + 36
329
sage: L.pari_rnf().nf_get_pol()
330
x^8 - 28*x^6 + 208*x^4 - 408*x^2 + 36
331
332
TESTS::
333
334
sage: x = polygen(QQ)
335
sage: K.<a> = NumberField(x^4 - 4*x^2 + 1)
336
sage: K.pari_nf().nf_get_pol()
337
y^4 - 4*y^2 + 1
338
sage: K.pari_bnf().nf_get_pol()
339
y^4 - 4*y^2 + 1
340
341
An error is raised for invalid input::
342
343
sage: pari("[0]").nf_get_pol()
344
Traceback (most recent call last):
345
...
346
PariError: incorrect type in pol
347
"""
348
pari_catch_sig_on()
349
return P.new_gen(member_pol(self.g))
350
351
def nf_get_diff(self):
352
"""
353
Returns the different of this number field as a PARI ideal.
354
355
INPUT:
356
357
- ``self`` -- A PARI number field being the output of ``nfinit()``,
358
``bnfinit()`` or ``bnrinit()``.
359
360
EXAMPLES::
361
362
sage: K.<a> = NumberField(x^4 - 4*x^2 + 1)
363
sage: pari(K).nf_get_diff()
364
[12, 0, 0, 0; 0, 12, 8, 0; 0, 0, 4, 0; 0, 0, 0, 4]
365
"""
366
pari_catch_sig_on()
367
return P.new_gen(member_diff(self.g))
368
369
def nf_get_sign(self):
370
"""
371
Returns a Python list ``[r1, r2]``, where ``r1`` and ``r2`` are
372
Python ints representing the number of real embeddings and pairs
373
of complex embeddings of this number field, respectively.
374
375
INPUT:
376
377
- ``self`` -- A PARI number field being the output of ``nfinit()``,
378
``bnfinit()`` or ``bnrinit()``.
379
380
EXAMPLES::
381
382
sage: K.<a> = NumberField(x^4 - 4*x^2 + 1)
383
sage: s = K.pari_nf().nf_get_sign(); s
384
[4, 0]
385
sage: type(s); type(s[0])
386
<type 'list'>
387
<type 'int'>
388
sage: CyclotomicField(15).pari_nf().nf_get_sign()
389
[0, 4]
390
"""
391
cdef long r1
392
cdef long r2
393
cdef GEN sign
394
pari_catch_sig_on()
395
sign = member_sign(self.g)
396
r1 = itos(gel(sign, 1))
397
r2 = itos(gel(sign, 2))
398
pari_catch_sig_off()
399
return [r1, r2]
400
401
def nf_get_zk(self):
402
"""
403
Returns a vector with a `\ZZ`-basis for the ring of integers of
404
this number field. The first element is always `1`.
405
406
INPUT:
407
408
- ``self`` -- A PARI number field being the output of ``nfinit()``,
409
``bnfinit()`` or ``bnrinit()``.
410
411
EXAMPLES::
412
413
sage: K.<a> = NumberField(x^4 - 4*x^2 + 1)
414
sage: pari(K).nf_get_zk()
415
[1, y, y^3 - 4*y, y^2 - 2]
416
"""
417
pari_catch_sig_on()
418
return P.new_gen(member_zk(self.g))
419
420
def bnf_get_no(self):
421
"""
422
Returns the class number of ``self``, a "big number field" (``bnf``).
423
424
EXAMPLES::
425
426
sage: K.<a> = QuadraticField(-65)
427
sage: K.pari_bnf().bnf_get_no()
428
8
429
"""
430
pari_catch_sig_on()
431
return P.new_gen(bnf_get_no(self.g))
432
433
def bnf_get_cyc(self):
434
"""
435
Returns the structure of the class group of this number field as
436
a vector of SNF invariants.
437
438
NOTE: ``self`` must be a "big number field" (``bnf``).
439
440
EXAMPLES::
441
442
sage: K.<a> = QuadraticField(-65)
443
sage: K.pari_bnf().bnf_get_cyc()
444
[4, 2]
445
"""
446
pari_catch_sig_on()
447
return P.new_gen(bnf_get_cyc(self.g))
448
449
def bnf_get_gen(self):
450
"""
451
Returns a vector of generators of the class group of this
452
number field.
453
454
NOTE: ``self`` must be a "big number field" (``bnf``).
455
456
EXAMPLES::
457
458
sage: K.<a> = QuadraticField(-65)
459
sage: G = K.pari_bnf().bnf_get_gen(); G
460
[[3, 2; 0, 1], [2, 1; 0, 1]]
461
sage: map(lambda J: K.ideal(J), G)
462
[Fractional ideal (3, a + 2), Fractional ideal (2, a + 1)]
463
"""
464
pari_catch_sig_on()
465
return P.new_gen(bnf_get_gen(self.g))
466
467
def bnf_get_reg(self):
468
"""
469
Returns the regulator of this number field.
470
471
NOTE: ``self`` must be a "big number field" (``bnf``).
472
473
EXAMPLES::
474
475
sage: K.<a> = NumberField(x^4 - 4*x^2 + 1)
476
sage: K.pari_bnf().bnf_get_reg()
477
2.66089858019037...
478
"""
479
pari_catch_sig_on()
480
return P.new_gen(bnf_get_reg(self.g))
481
482
def pr_get_p(self):
483
"""
484
Returns the prime of `\ZZ` lying below this prime ideal.
485
486
NOTE: ``self`` must be a PARI prime ideal (as returned by
487
``idealfactor`` for example).
488
489
EXAMPLES::
490
491
sage: K.<i> = QuadraticField(-1)
492
sage: F = pari(K).idealfactor(K.ideal(5)); F
493
[[5, [-2, 1]~, 1, 1, [2, 1]~], 1; [5, [2, 1]~, 1, 1, [-2, 1]~], 1]
494
sage: F[0,0].pr_get_p()
495
5
496
"""
497
pari_catch_sig_on()
498
return P.new_gen(pr_get_p(self.g))
499
500
def pr_get_e(self):
501
"""
502
Returns the ramification index (over `\QQ`) of this prime ideal.
503
504
NOTE: ``self`` must be a PARI prime ideal (as returned by
505
``idealfactor`` for example).
506
507
EXAMPLES::
508
509
sage: K.<i> = QuadraticField(-1)
510
sage: pari(K).idealfactor(K.ideal(2))[0,0].pr_get_e()
511
2
512
sage: pari(K).idealfactor(K.ideal(3))[0,0].pr_get_e()
513
1
514
sage: pari(K).idealfactor(K.ideal(5))[0,0].pr_get_e()
515
1
516
"""
517
cdef long e
518
pari_catch_sig_on()
519
e = pr_get_e(self.g)
520
pari_catch_sig_off()
521
return e
522
523
def pr_get_f(self):
524
"""
525
Returns the residue class degree (over `\QQ`) of this prime ideal.
526
527
NOTE: ``self`` must be a PARI prime ideal (as returned by
528
``idealfactor`` for example).
529
530
EXAMPLES::
531
532
sage: K.<i> = QuadraticField(-1)
533
sage: pari(K).idealfactor(K.ideal(2))[0,0].pr_get_f()
534
1
535
sage: pari(K).idealfactor(K.ideal(3))[0,0].pr_get_f()
536
2
537
sage: pari(K).idealfactor(K.ideal(5))[0,0].pr_get_f()
538
1
539
"""
540
cdef long f
541
pari_catch_sig_on()
542
f = pr_get_f(self.g)
543
pari_catch_sig_off()
544
return f
545
546
def pr_get_gen(self):
547
"""
548
Returns the second generator of this PARI prime ideal, where the
549
first generator is ``self.pr_get_p()``.
550
551
NOTE: ``self`` must be a PARI prime ideal (as returned by
552
``idealfactor`` for example).
553
554
EXAMPLES::
555
556
sage: K.<i> = QuadraticField(-1)
557
sage: g = pari(K).idealfactor(K.ideal(2))[0,0].pr_get_gen(); g; K(g)
558
[1, 1]~
559
i + 1
560
sage: g = pari(K).idealfactor(K.ideal(3))[0,0].pr_get_gen(); g; K(g)
561
[3, 0]~
562
3
563
sage: g = pari(K).idealfactor(K.ideal(5))[0,0].pr_get_gen(); g; K(g)
564
[-2, 1]~
565
i - 2
566
"""
567
pari_catch_sig_on()
568
return P.new_gen(pr_get_gen(self.g))
569
570
def bid_get_cyc(self):
571
"""
572
Returns the structure of the group `(O_K/I)^*`, where `I` is the
573
ideal represented by ``self``.
574
575
NOTE: ``self`` must be a "big ideal" (``bid``) as returned by
576
``idealstar`` for example.
577
578
EXAMPLES::
579
580
sage: K.<i> = QuadraticField(-1)
581
sage: J = pari(K).idealstar(K.ideal(4*i + 2))
582
sage: J.bid_get_cyc()
583
[4, 2]
584
"""
585
pari_catch_sig_on()
586
return P.new_gen(bid_get_cyc(self.g))
587
588
def bid_get_gen(self):
589
"""
590
Returns a vector of generators of the group `(O_K/I)^*`, where
591
`I` is the ideal represented by ``self``.
592
593
NOTE: ``self`` must be a "big ideal" (``bid``) with generators,
594
as returned by ``idealstar`` with ``flag`` = 2.
595
596
EXAMPLES::
597
598
sage: K.<i> = QuadraticField(-1)
599
sage: J = pari(K).idealstar(K.ideal(4*i + 2), 2)
600
sage: J.bid_get_gen()
601
[7, [-2, -1]~]
602
603
We get an exception if we do not supply ``flag = 2`` to
604
``idealstar``::
605
606
sage: J = pari(K).idealstar(K.ideal(3))
607
sage: J.bid_get_gen()
608
Traceback (most recent call last):
609
...
610
PariError: missing bid generators. Use idealstar(,,2)
611
"""
612
pari_catch_sig_on()
613
return P.new_gen(bid_get_gen(self.g))
614
615
def __getitem__(gen self, n):
616
"""
617
Return the nth entry of self. The indexing is 0-based, like in
618
Python. Note that this is *different* than the default behavior
619
of the PARI/GP interpreter.
620
621
EXAMPLES::
622
623
sage: p = pari('1 + 2*x + 3*x^2')
624
sage: p[0]
625
1
626
sage: p[2]
627
3
628
sage: p[100]
629
0
630
sage: p[-1]
631
0
632
sage: q = pari('x^2 + 3*x^3 + O(x^6)')
633
sage: q[3]
634
3
635
sage: q[5]
636
0
637
sage: q[6]
638
Traceback (most recent call last):
639
...
640
IndexError: index out of bounds
641
sage: m = pari('[1,2;3,4]')
642
sage: m[0]
643
[1, 3]~
644
sage: m[1,0]
645
3
646
sage: l = pari('List([1,2,3])')
647
sage: l[1]
648
2
649
sage: s = pari('"hello, world!"')
650
sage: s[0]
651
'h'
652
sage: s[4]
653
'o'
654
sage: s[12]
655
'!'
656
sage: s[13]
657
Traceback (most recent call last):
658
...
659
IndexError: index out of bounds
660
sage: v = pari('[1,2,3]')
661
sage: v[0]
662
1
663
sage: c = pari('Col([1,2,3])')
664
sage: c[1]
665
2
666
sage: sv = pari('Vecsmall([1,2,3])')
667
sage: sv[2]
668
3
669
sage: type(sv[2])
670
<type 'int'>
671
sage: tuple(pari(3/5))
672
(3, 5)
673
sage: tuple(pari('1 + 5*I'))
674
(1, 5)
675
sage: tuple(pari('Qfb(1, 2, 3)'))
676
(1, 2, 3)
677
sage: pari(57)[0]
678
Traceback (most recent call last):
679
...
680
TypeError: unindexable object
681
sage: m = pari("[[1,2;3,4],5]") ; m[0][1,0]
682
3
683
sage: v = pari(xrange(20))
684
sage: v[2:5]
685
[2, 3, 4]
686
sage: v[:]
687
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
688
sage: v[10:]
689
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
690
sage: v[:5]
691
[0, 1, 2, 3, 4]
692
sage: v
693
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
694
sage: v[-1]
695
Traceback (most recent call last):
696
...
697
IndexError: index out of bounds
698
sage: v[:-3]
699
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
700
sage: v[5:]
701
[5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
702
sage: pari([])[::]
703
[]
704
"""
705
cdef int pari_type
706
707
pari_type = typ(self.g)
708
709
if isinstance(n, tuple):
710
if pari_type != t_MAT:
711
raise TypeError, "self must be of pari type t_MAT"
712
if len(n) != 2:
713
raise IndexError, "index must be an integer or a 2-tuple (i,j)"
714
i = int(n[0])
715
j = int(n[1])
716
717
if i < 0 or i >= glength(<GEN>(self.g[1])):
718
raise IndexError, "row index out of bounds"
719
if j < 0 or j >= glength(self.g):
720
raise IndexError, "column index out of bounds"
721
722
ind = (i,j)
723
724
if self.refers_to is not None and ind in self.refers_to:
725
return self.refers_to[ind]
726
else:
727
## In this case, we're being asked to return
728
## a GEN that has no gen pointing to it, so
729
## we need to create such a gen, add it to
730
## self.refers_to, and return it.
731
val = P.new_ref(gmael(self.g, j+1, i+1), self)
732
if self.refers_to is None:
733
self.refers_to = {ind: val}
734
else:
735
self.refers_to[ind] = val
736
return val
737
738
elif isinstance(n, slice):
739
l = glength(self.g)
740
start,stop,step = n.indices(l)
741
inds = xrange(start,stop,step)
742
k = len(inds)
743
# fast exit
744
if k==0:
745
return P.vector(0)
746
# fast call, beware pari is one based
747
if pari_type == t_VEC:
748
if step==1:
749
return self.vecextract('"'+str(start+1)+".."+str(stop)+'"')
750
if step==-1:
751
return self.vecextract('"'+str(start+1)+".."+str(stop+2)+'"')
752
# slow call
753
v = P.vector(k)
754
for i,j in enumerate(inds):
755
v[i] = self[j]
756
return v
757
758
## there are no "out of bounds" problems
759
## for a polynomial or power series, so these go before
760
## bounds testing
761
if pari_type == t_POL:
762
return self.polcoeff(n)
763
764
elif pari_type == t_SER:
765
bound = valp(self.g) + lg(self.g) - 2
766
if n >= bound:
767
raise IndexError, "index out of bounds"
768
return self.polcoeff(n)
769
770
elif pari_type in (t_INT, t_REAL, t_PADIC, t_QUAD):
771
# these are definitely scalar!
772
raise TypeError, "unindexable object"
773
774
elif n < 0 or n >= glength(self.g):
775
raise IndexError, "index out of bounds"
776
777
elif pari_type == t_VEC or pari_type == t_MAT:
778
#t_VEC : row vector [ code ] [ x_1 ] ... [ x_k ]
779
#t_MAT : matrix [ code ] [ col_1 ] ... [ col_k ]
780
if self.refers_to is not None and n in self.refers_to:
781
return self.refers_to[n]
782
else:
783
## In this case, we're being asked to return
784
## a GEN that has no gen pointing to it, so
785
## we need to create such a gen, add it to
786
## self.refers_to, and return it.
787
val = P.new_ref(gel(self.g, n+1), self)
788
if self.refers_to is None:
789
self.refers_to = {n: val}
790
else:
791
self.refers_to[n] = val
792
return val
793
794
elif pari_type == t_VECSMALL:
795
#t_VECSMALL: vec. small ints [ code ] [ x_1 ] ... [ x_k ]
796
return self.g[n+1]
797
798
elif pari_type == t_STR:
799
#t_STR : string [ code ] [ man_1 ] ... [ man_k ]
800
return chr( (<char *>(self.g+1))[n] )
801
802
elif pari_type == t_LIST:
803
#t_LIST : list [ code ] [ n ] [ nmax ][ vec ]
804
return self.component(n+1)
805
#code from previous version, now segfaults:
806
#return P.new_ref(gel(self.g,n+2), self)
807
808
elif pari_type in (t_INTMOD, t_POLMOD):
809
#t_INTMOD : integermods [ code ] [ mod ] [ integer ]
810
#t_POLMOD : poly mod [ code ] [ mod ] [ polynomial ]
811
812
# if we keep going we would get:
813
# [0] = modulus
814
# [1] = lift to t_INT or t_POL
815
# do we want this? maybe the other way around?
816
raise TypeError, "unindexable object"
817
818
#elif pari_type in (t_FRAC, t_RFRAC):
819
# generic code gives us:
820
# [0] = numerator
821
# [1] = denominator
822
823
#elif pari_type == t_COMPLEX:
824
# generic code gives us
825
# [0] = real part
826
# [1] = imag part
827
828
#elif type(self.g) in (t_QFR, t_QFI):
829
# generic code works ok
830
831
else:
832
## generic code, which currently handles cases
833
## as mentioned above
834
return P.new_ref(gel(self.g,n+1), self)
835
836
def __setitem__(gen self, n, y):
837
r"""
838
Set the nth entry to a reference to y.
839
840
841
- The indexing is 0-based, like everywhere else in Python, but
842
*unlike* in PARI/GP.
843
844
- Assignment sets the nth entry to a reference to y, assuming y is
845
an object of type gen. This is the same as in Python, but
846
*different* than what happens in the gp interpreter, where
847
assignment makes a copy of y.
848
849
- Because setting creates references it is *possible* to make
850
circular references, unlike in GP. Do *not* do this (see the
851
example below). If you need circular references, work at the Python
852
level (where they work well), not the PARI object level.
853
854
855
856
EXAMPLES::
857
858
sage: v = pari(range(10))
859
sage: v
860
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
861
sage: v[0] = 10
862
sage: w = pari([5,8,-20])
863
sage: v
864
[10, 1, 2, 3, 4, 5, 6, 7, 8, 9]
865
sage: v[1] = w
866
sage: v
867
[10, [5, 8, -20], 2, 3, 4, 5, 6, 7, 8, 9]
868
sage: w[0] = -30
869
sage: v
870
[10, [-30, 8, -20], 2, 3, 4, 5, 6, 7, 8, 9]
871
sage: t = v[1]; t[1] = 10 ; v
872
[10, [-30, 10, -20], 2, 3, 4, 5, 6, 7, 8, 9]
873
sage: v[1][0] = 54321 ; v
874
[10, [54321, 10, -20], 2, 3, 4, 5, 6, 7, 8, 9]
875
sage: w
876
[54321, 10, -20]
877
sage: v = pari([[[[0,1],2],3],4]) ; v[0][0][0][1] = 12 ; v
878
[[[[0, 12], 2], 3], 4]
879
sage: m = pari(matrix(2,2,range(4))) ; l = pari([5,6]) ; n = pari(matrix(2,2,[7,8,9,0])) ; m[1,0] = l ; l[1] = n ; m[1,0][1][1,1] = 1111 ; m
880
[0, 1; [5, [7, 8; 9, 1111]], 3]
881
sage: m = pari("[[1,2;3,4],5,6]") ; m[0][1,1] = 11 ; m
882
[[1, 2; 3, 11], 5, 6]
883
884
Finally, we create a circular reference::
885
886
sage: v = pari([0])
887
sage: w = pari([v])
888
sage: v
889
[0]
890
sage: w
891
[[0]]
892
sage: v[0] = w
893
894
Now there is a circular reference. Accessing v[0] will crash Sage.
895
896
::
897
898
sage: s=pari.vector(2,[0,0])
899
sage: s[:1]
900
[0]
901
sage: s[:1]=[1]
902
sage: s
903
[1, 0]
904
sage: type(s[0])
905
<type 'sage.libs.pari.gen.gen'>
906
sage: s = pari(range(20)) ; s
907
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
908
sage: s[0:10:2] = range(50,55) ; s
909
[50, 1, 51, 3, 52, 5, 53, 7, 54, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
910
sage: s[10:20:3] = range(100,150) ; s
911
[50, 1, 51, 3, 52, 5, 53, 7, 54, 9, 100, 11, 12, 101, 14, 15, 102, 17, 18, 103]
912
913
TESTS::
914
915
sage: v = pari(xrange(10)) ; v
916
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
917
sage: v[:] = [20..29]
918
sage: v
919
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
920
sage: type(v[0])
921
<type 'sage.libs.pari.gen.gen'>
922
"""
923
cdef int i, j
924
cdef gen x = objtogen(y)
925
cdef long l
926
cdef Py_ssize_t ii, jj, step
927
928
pari_catch_sig_on()
929
try:
930
if isinstance(n, tuple):
931
if typ(self.g) != t_MAT:
932
raise TypeError, "cannot index PARI type %s by tuple"%typ(self.g)
933
934
if len(n) != 2:
935
raise ValueError, "matrix index must be of the form [row, column]"
936
937
i = int(n[0])
938
j = int(n[1])
939
ind = (i,j)
940
941
if i < 0 or i >= glength(<GEN>(self.g[1])):
942
raise IndexError, "row i(=%s) must be between 0 and %s"%(i,self.nrows()-1)
943
if j < 0 or j >= glength(self.g):
944
raise IndexError, "column j(=%s) must be between 0 and %s"%(j,self.ncols()-1)
945
if self.refers_to is None:
946
self.refers_to = {ind: x}
947
else:
948
self.refers_to[ind] = x
949
950
(<GEN>(self.g)[j+1])[i+1] = <long>(x.g)
951
return
952
953
elif isinstance(n, slice):
954
l = glength(self.g)
955
inds = xrange(*n.indices(l))
956
k = len(inds)
957
if k > len(y):
958
raise ValueError, "attempt to assign sequence of size %s to slice of size %s"%(len(y), k)
959
960
# actually set the values
961
for i,j in enumerate(inds):
962
self[j] = y[i]
963
return
964
965
i = int(n)
966
967
if i < 0 or i >= glength(self.g):
968
raise IndexError, "index (%s) must be between 0 and %s"%(i,glength(self.g)-1)
969
970
# so python memory manager will work correctly
971
# and not free x if PARI part of self is the
972
# only thing pointing to it.
973
if self.refers_to is None:
974
self.refers_to = {i: x}
975
else:
976
self.refers_to[i] = x
977
978
## correct indexing for t_POLs
979
if typ(self.g) == t_POL:
980
i = i + 1
981
982
## actually set the value
983
(self.g)[i+1] = <long>(x.g)
984
return
985
finally:
986
pari_catch_sig_off()
987
988
def __len__(gen self):
989
return glength(self.g)
990
991
992
993
###########################################
994
# comparisons
995
# I had to rewrite PARI's compare, since
996
# otherwise trapping signals and other horrible,
997
# memory-leaking and slow stuff occurs.
998
###########################################
999
1000
def __richcmp__(left, right, int op):
1001
return (<Element>left)._richcmp(right, op)
1002
1003
cdef int _cmp_c_impl(left, Element right) except -2:
1004
"""
1005
Comparisons
1006
1007
First uses PARI's cmp routine; if it decides the objects are not
1008
comparable, it then compares the underlying strings (since in
1009
Python all objects are supposed to be comparable).
1010
1011
EXAMPLES::
1012
1013
sage: a = pari(5)
1014
sage: b = 10
1015
sage: a < b
1016
True
1017
sage: a <= b
1018
True
1019
sage: a <= 5
1020
True
1021
sage: a > b
1022
False
1023
sage: a >= b
1024
False
1025
sage: a >= pari(10)
1026
False
1027
sage: a == 5
1028
True
1029
sage: a is 5
1030
False
1031
1032
::
1033
1034
sage: pari(2.5) > None
1035
True
1036
sage: pari(3) == pari(3)
1037
True
1038
sage: pari('x^2 + 1') == pari('I-1')
1039
False
1040
sage: pari(I) == pari(I)
1041
True
1042
"""
1043
return gcmp_sage(left.g, (<gen>right).g)
1044
1045
def __copy__(gen self):
1046
pari_catch_sig_on()
1047
return P.new_gen(gcopy(self.g))
1048
1049
###########################################
1050
# Conversion --> Python
1051
# Try to convert to a meaningful python object
1052
# in various ways
1053
###########################################
1054
1055
def list_str(gen self):
1056
"""
1057
Return str that might correctly evaluate to a Python-list.
1058
"""
1059
s = str(self)
1060
if s[:4] == "Mat(":
1061
s = "[" + s[4:-1] + "]"
1062
s = s.replace("~","")
1063
if s.find(";") != -1:
1064
s = s.replace(";","], [")
1065
s = "[" + s + "]"
1066
return eval(s)
1067
else:
1068
return eval(s)
1069
1070
def __hex__(gen self):
1071
"""
1072
Return the hexadecimal digits of self in lower case.
1073
1074
EXAMPLES::
1075
1076
sage: print hex(pari(0))
1077
0
1078
sage: print hex(pari(15))
1079
f
1080
sage: print hex(pari(16))
1081
10
1082
sage: print hex(pari(16938402384092843092843098243))
1083
36bb1e3929d1a8fe2802f083
1084
sage: print hex(long(16938402384092843092843098243))
1085
0x36bb1e3929d1a8fe2802f083L
1086
sage: print hex(pari(-16938402384092843092843098243))
1087
-36bb1e3929d1a8fe2802f083
1088
"""
1089
cdef GEN x
1090
cdef long lx, *xp
1091
cdef long w
1092
cdef char *s, *sp
1093
cdef char *hexdigits
1094
hexdigits = "0123456789abcdef"
1095
cdef int i, j
1096
cdef int size
1097
x = self.g
1098
if typ(x) != t_INT:
1099
raise TypeError, "gen must be of PARI type t_INT"
1100
if not signe(x):
1101
return "0"
1102
lx = lgefint(x)-2 # number of words
1103
size = lx*2*sizeof(long)
1104
s = <char *>sage_malloc(size+2) # 1 char for sign, 1 char for '\0'
1105
sp = s + size+1
1106
sp[0] = 0
1107
xp = int_LSW(x)
1108
for i from 0 <= i < lx:
1109
w = xp[0]
1110
for j from 0 <= j < 2*sizeof(long):
1111
sp = sp-1
1112
sp[0] = hexdigits[w & 15]
1113
w = w>>4
1114
xp = int_nextW(xp)
1115
# remove leading zeros!
1116
while sp[0] == c'0':
1117
sp = sp+1
1118
if signe(x) < 0:
1119
sp = sp-1
1120
sp[0] = c'-'
1121
k = <object>sp
1122
sage_free(s)
1123
return k
1124
1125
def __int__(gen self):
1126
"""
1127
Convert ``self`` to a Python integer.
1128
1129
If the number is too large to fit into a Pyhon ``int``, a
1130
Python ``long`` is returned instead.
1131
1132
EXAMPLES::
1133
1134
sage: int(pari(0))
1135
0
1136
sage: int(pari(10))
1137
10
1138
sage: int(pari(-10))
1139
-10
1140
sage: int(pari(123456789012345678901234567890))
1141
123456789012345678901234567890L
1142
sage: int(pari(-123456789012345678901234567890))
1143
-123456789012345678901234567890L
1144
sage: int(pari(2^31-1))
1145
2147483647
1146
sage: int(pari(-2^31))
1147
-2147483648
1148
sage: int(pari("Pol(10)"))
1149
10
1150
sage: int(pari("Mod(2, 7)"))
1151
2
1152
sage: int(pari(RealField(63)(2^63-1)))
1153
9223372036854775807L # 32-bit
1154
9223372036854775807 # 64-bit
1155
sage: int(pari(RealField(63)(2^63+2)))
1156
9223372036854775810L
1157
1158
"""
1159
global Integer
1160
if Integer is None:
1161
import sage.rings.integer
1162
Integer = sage.rings.integer.Integer
1163
return int(Integer(self))
1164
1165
def python_list_small(gen self):
1166
"""
1167
Return a Python list of the PARI gens. This object must be of type
1168
t_VECSMALL, and the resulting list contains python 'int's.
1169
1170
EXAMPLES::
1171
1172
sage: v=pari([1,2,3,10,102,10]).Vecsmall()
1173
sage: w = v.python_list_small()
1174
sage: w
1175
[1, 2, 3, 10, 102, 10]
1176
sage: type(w[0])
1177
<type 'int'>
1178
"""
1179
cdef long n, m
1180
if typ(self.g) != t_VECSMALL:
1181
raise TypeError, "Object (=%s) must be of type t_VECSMALL."%self
1182
V = []
1183
m = glength(self.g)
1184
for n from 0 <= n < m:
1185
V.append(self.g[n+1])
1186
return V
1187
1188
def python_list(gen self):
1189
"""
1190
Return a Python list of the PARI gens. This object must be of type
1191
t_VEC.
1192
1193
INPUT: None
1194
1195
OUTPUT:
1196
1197
- ``list`` - Python list whose elements are the
1198
elements of the input gen.
1199
1200
1201
EXAMPLES::
1202
1203
sage: v=pari([1,2,3,10,102,10])
1204
sage: w = v.python_list()
1205
sage: w
1206
[1, 2, 3, 10, 102, 10]
1207
sage: type(w[0])
1208
<type 'sage.libs.pari.gen.gen'>
1209
sage: pari("[1,2,3]").python_list()
1210
[1, 2, 3]
1211
"""
1212
cdef long n, m
1213
cdef gen t
1214
1215
if typ(self.g) != t_VEC:
1216
raise TypeError, "Object (=%s) must be of type t_VEC."%self
1217
m = glength(self.g)
1218
V = []
1219
for n from 0 <= n < m:
1220
V.append(self.__getitem__(n))
1221
return V
1222
1223
def python(self, locals=None):
1224
"""
1225
Return Python eval of self.
1226
1227
Note: is self is a real (type t_REAL) the result will be a
1228
RealField element of the equivalent precision; if self is a complex
1229
(type t_COMPLEX) the result will be a ComplexField element of
1230
precision the minimum precision of the real and imaginary parts.
1231
1232
EXAMPLES::
1233
1234
sage: pari('389/17').python()
1235
389/17
1236
sage: f = pari('(2/3)*x^3 + x - 5/7 + y'); f
1237
2/3*x^3 + x + (y - 5/7)
1238
sage: var('x,y')
1239
(x, y)
1240
sage: f.python({'x':x, 'y':y})
1241
2/3*x^3 + x + y - 5/7
1242
1243
You can also use .sage, which is a psynonym::
1244
1245
sage: f.sage({'x':x, 'y':y})
1246
2/3*x^3 + x + y - 5/7
1247
"""
1248
import sage.libs.pari.gen_py
1249
return sage.libs.pari.gen_py.python(self, locals=locals)
1250
1251
sage = python
1252
1253
_sage_ = _eval_ = python
1254
1255
def __long__(gen self):
1256
"""
1257
Convert ``self`` to a Python ``long``.
1258
1259
EXAMPLES::
1260
1261
sage: long(pari(0))
1262
0L
1263
sage: long(pari(10))
1264
10L
1265
sage: long(pari(-10))
1266
-10L
1267
sage: long(pari(123456789012345678901234567890))
1268
123456789012345678901234567890L
1269
sage: long(pari(-123456789012345678901234567890))
1270
-123456789012345678901234567890L
1271
sage: long(pari(2^31-1))
1272
2147483647L
1273
sage: long(pari(-2^31))
1274
-2147483648L
1275
sage: long(pari("Pol(10)"))
1276
10L
1277
sage: long(pari("Mod(2, 7)"))
1278
2L
1279
"""
1280
global Integer
1281
if Integer is None:
1282
import sage.rings.integer
1283
Integer = sage.rings.integer.Integer
1284
return long(Integer(self))
1285
1286
def __float__(gen self):
1287
"""
1288
Return Python float.
1289
"""
1290
cdef double d
1291
pari_catch_sig_on()
1292
d = gtodouble(self.g)
1293
pari_catch_sig_off()
1294
return d
1295
1296
def __complex__(self):
1297
r"""
1298
Return ``self`` as a Python ``complex``
1299
value.
1300
1301
EXAMPLES::
1302
1303
sage: g = pari(-1.0)^(1/5); g
1304
0.809016994374947 + 0.587785252292473*I
1305
sage: g.__complex__()
1306
(0.8090169943749475+0.5877852522924731j)
1307
sage: complex(g)
1308
(0.8090169943749475+0.5877852522924731j)
1309
1310
::
1311
1312
sage: g = pari(Integers(5)(3)); g
1313
Mod(3, 5)
1314
sage: complex(g)
1315
Traceback (most recent call last):
1316
...
1317
PariError: incorrect type in greal/gimag
1318
"""
1319
cdef double re, im
1320
pari_catch_sig_on()
1321
re = gtodouble(greal(self.g))
1322
im = gtodouble(gimag(self.g))
1323
pari_catch_sig_off()
1324
return complex(re, im)
1325
1326
def __nonzero__(self):
1327
"""
1328
EXAMPLES::
1329
1330
sage: pari('1').__nonzero__()
1331
True
1332
sage: pari('x').__nonzero__()
1333
True
1334
sage: bool(pari(0))
1335
False
1336
sage: a = pari('Mod(0,3)')
1337
sage: a.__nonzero__()
1338
False
1339
"""
1340
return not gequal0(self.g)
1341
1342
1343
###########################################
1344
# Comparisons (from PARI)
1345
###########################################
1346
1347
def gequal(gen a, b):
1348
r"""
1349
Check whether `a` and `b` are equal using PARI's ``gequal``.
1350
1351
EXAMPLES::
1352
1353
sage: a = pari(1); b = pari(1.0); c = pari('"some_string"')
1354
sage: a.gequal(a)
1355
True
1356
sage: b.gequal(b)
1357
True
1358
sage: c.gequal(c)
1359
True
1360
sage: a.gequal(b)
1361
True
1362
sage: a.gequal(c)
1363
False
1364
1365
WARNING: this relation is not transitive::
1366
1367
sage: a = pari('[0]'); b = pari(0); c = pari('[0,0]')
1368
sage: a.gequal(b)
1369
True
1370
sage: b.gequal(c)
1371
True
1372
sage: a.gequal(c)
1373
False
1374
"""
1375
cdef gen t0 = objtogen(b)
1376
pari_catch_sig_on()
1377
cdef int ret = gequal(a.g, t0.g)
1378
pari_catch_sig_off()
1379
return ret != 0
1380
1381
def gequal0(gen a):
1382
r"""
1383
Check whether `a` is equal to zero.
1384
1385
EXAMPLES::
1386
1387
sage: pari(0).gequal0()
1388
True
1389
sage: pari(1).gequal0()
1390
False
1391
sage: pari(1e-100).gequal0()
1392
False
1393
sage: pari("0.0 + 0.0*I").gequal0()
1394
True
1395
sage: pari(GF(3^20,'t')(0)).gequal0()
1396
True
1397
"""
1398
pari_catch_sig_on()
1399
cdef int ret = gequal0(a.g)
1400
pari_catch_sig_off()
1401
return ret != 0
1402
1403
def gequal_long(gen a, long b):
1404
r"""
1405
Check whether `a` is equal to the ``long int`` `b` using PARI's ``gequalsg``.
1406
1407
EXAMPLES::
1408
1409
sage: a = pari(1); b = pari(2.0); c = pari('3*matid(3)')
1410
sage: a.gequal_long(1)
1411
True
1412
sage: a.gequal_long(-1)
1413
False
1414
sage: a.gequal_long(0)
1415
False
1416
sage: b.gequal_long(2)
1417
True
1418
sage: b.gequal_long(-2)
1419
False
1420
sage: c.gequal_long(3)
1421
True
1422
sage: c.gequal_long(-3)
1423
False
1424
"""
1425
pari_catch_sig_on()
1426
cdef int ret = gequalsg(b, a.g)
1427
pari_catch_sig_off()
1428
return ret != 0
1429
1430
1431
###########################################
1432
# arith1.c
1433
###########################################
1434
def isprime(gen self, long flag=0):
1435
"""
1436
isprime(x, flag=0): Returns True if x is a PROVEN prime number, and
1437
False otherwise.
1438
1439
INPUT:
1440
1441
1442
- ``flag`` - int 0 (default): use a combination of
1443
algorithms. 1: certify primality using the Pocklington-Lehmer Test.
1444
2: certify primality using the APRCL test.
1445
1446
1447
OUTPUT:
1448
1449
1450
- ``bool`` - True or False
1451
1452
1453
EXAMPLES::
1454
1455
sage: pari(9).isprime()
1456
False
1457
sage: pari(17).isprime()
1458
True
1459
sage: n = pari(561) # smallest Carmichael number
1460
sage: n.isprime() # not just a pseudo-primality test!
1461
False
1462
sage: n.isprime(1)
1463
False
1464
sage: n.isprime(2)
1465
False
1466
"""
1467
pari_catch_sig_on()
1468
cdef long t = signe(gisprime(self.g, flag))
1469
P.clear_stack()
1470
return t != 0
1471
1472
def qfbhclassno(gen n):
1473
r"""
1474
Computes the Hurwitz-Kronecker class number of `n`.
1475
1476
INPUT:
1477
1478
- `n` (gen) -- a non-negative integer
1479
1480
.. note::
1481
1482
If `n` is large (more than `5*10^5`), the result is
1483
conditional upon GRH.
1484
1485
EXAMPLES:
1486
1487
The Hurwitx class number is 0 is n is congruent to 1 or 2 modulo 4::
1488
sage: pari(-10007).qfbhclassno()
1489
0
1490
sage: pari(-2).qfbhclassno()
1491
0
1492
1493
It is -1/12 for n=0::
1494
1495
sage: pari(0).qfbhclassno()
1496
-1/12
1497
1498
Otherwise it is the number of classes of positive definite
1499
binary quadratic forms with discriminant `-n`, weighted by
1500
`1/m` where `m` is the number of automorphisms of the form::
1501
1502
sage: pari(4).qfbhclassno()
1503
1/2
1504
sage: pari(3).qfbhclassno()
1505
1/3
1506
sage: pari(23).qfbhclassno()
1507
3
1508
1509
"""
1510
pari_catch_sig_on()
1511
return P.new_gen(hclassno(n.g))
1512
1513
def ispseudoprime(gen self, long flag=0):
1514
"""
1515
ispseudoprime(x, flag=0): Returns True if x is a pseudo-prime
1516
number, and False otherwise.
1517
1518
INPUT:
1519
1520
1521
- ``flag`` - int 0 (default): checks whether x is a
1522
Baillie-Pomerance-Selfridge-Wagstaff pseudo prime (strong
1523
Rabin-Miller pseudo prime for base 2, followed by strong Lucas test
1524
for the sequence (P,-1), P smallest positive integer such that
1525
`P^2 - 4` is not a square mod x). 0: checks whether x is a
1526
strong Miller-Rabin pseudo prime for flag randomly chosen bases
1527
(with end-matching to catch square roots of -1).
1528
1529
1530
OUTPUT:
1531
1532
1533
- ``bool`` - True or False
1534
1535
1536
EXAMPLES::
1537
1538
sage: pari(9).ispseudoprime()
1539
False
1540
sage: pari(17).ispseudoprime()
1541
True
1542
sage: n = pari(561) # smallest Carmichael number
1543
sage: n.ispseudoprime(2)
1544
False
1545
"""
1546
pari_catch_sig_on()
1547
cdef long t = ispseudoprime(self.g, flag)
1548
pari_catch_sig_off()
1549
return t != 0
1550
1551
def ispower(gen self, k=None):
1552
r"""
1553
Determine whether or not self is a perfect k-th power. If k is not
1554
specified, find the largest k so that self is a k-th power.
1555
1556
INPUT:
1557
1558
1559
- ``k`` - int (optional)
1560
1561
1562
OUTPUT:
1563
1564
1565
- ``power`` - int, what power it is
1566
1567
- ``g`` - what it is a power of
1568
1569
1570
EXAMPLES::
1571
1572
sage: pari(9).ispower()
1573
(2, 3)
1574
sage: pari(17).ispower()
1575
(1, 17)
1576
sage: pari(17).ispower(2)
1577
(False, None)
1578
sage: pari(17).ispower(1)
1579
(1, 17)
1580
sage: pari(2).ispower()
1581
(1, 2)
1582
"""
1583
cdef int n
1584
cdef GEN x
1585
cdef gen t0
1586
1587
if k is None:
1588
pari_catch_sig_on()
1589
n = gisanypower(self.g, &x)
1590
if n == 0:
1591
pari_catch_sig_off()
1592
return 1, self
1593
else:
1594
return n, P.new_gen(x)
1595
else:
1596
t0 = objtogen(k)
1597
pari_catch_sig_on()
1598
n = ispower(self.g, t0.g, &x)
1599
if n == 0:
1600
pari_catch_sig_off()
1601
return False, None
1602
else:
1603
return k, P.new_gen(x)
1604
1605
###########################################
1606
# 1: Standard monadic or dyadic OPERATORS
1607
###########################################
1608
def divrem(gen x, y, var=-1):
1609
"""
1610
divrem(x, y, v): Euclidean division of x by y giving as a
1611
2-dimensional column vector the quotient and the remainder, with
1612
respect to v (to main variable if v is omitted).
1613
"""
1614
cdef gen t0 = objtogen(y)
1615
pari_catch_sig_on()
1616
return P.new_gen(divrem(x.g, t0.g, P.get_var(var)))
1617
1618
def lex(gen x, y):
1619
"""
1620
lex(x,y): Compare x and y lexicographically (1 if xy, 0 if x==y, -1
1621
if xy)
1622
"""
1623
cdef gen t0 = objtogen(y)
1624
pari_catch_sig_on()
1625
r = lexcmp(x.g, t0.g)
1626
pari_catch_sig_off()
1627
return r
1628
1629
def max(gen x, y):
1630
"""
1631
max(x,y): Return the maximum of x and y.
1632
"""
1633
cdef gen t0 = objtogen(y)
1634
pari_catch_sig_on()
1635
return P.new_gen(gmax(x.g, t0.g))
1636
1637
def min(gen x, y):
1638
"""
1639
min(x,y): Return the minimum of x and y.
1640
"""
1641
cdef gen t0 = objtogen(y)
1642
pari_catch_sig_on()
1643
return P.new_gen(gmin(x.g, t0.g))
1644
1645
def shift(gen x, long n):
1646
"""
1647
shift(x,n): shift x left n bits if n=0, right -n bits if n0.
1648
"""
1649
pari_catch_sig_on()
1650
return P.new_gen(gshift(x.g, n))
1651
1652
def shiftmul(gen x, long n):
1653
"""
1654
shiftmul(x,n): Return the product of x by `2^n`.
1655
"""
1656
pari_catch_sig_on()
1657
return P.new_gen(gmul2n(x.g, n))
1658
1659
def moebius(gen x):
1660
"""
1661
moebius(x): Moebius function of x.
1662
"""
1663
pari_catch_sig_on()
1664
return P.new_gen(gmoebius(x.g))
1665
1666
def sign(gen x):
1667
"""
1668
Return the sign of x, where x is of type integer, real or
1669
fraction.
1670
1671
EXAMPLES::
1672
1673
sage: pari(pi).sign()
1674
1
1675
sage: pari(0).sign()
1676
0
1677
sage: pari(-1/2).sign()
1678
-1
1679
1680
PARI throws an error if you attempt to take the sign of a
1681
complex number::
1682
1683
sage: pari(I).sign()
1684
Traceback (most recent call last):
1685
...
1686
PariError: incorrect type in gsigne
1687
1688
"""
1689
pari_catch_sig_on()
1690
r = gsigne(x.g)
1691
pari_catch_sig_off()
1692
return r
1693
1694
def vecmax(gen x):
1695
"""
1696
vecmax(x): Return the maximum of the elements of the vector/matrix
1697
x.
1698
"""
1699
pari_catch_sig_on()
1700
return P.new_gen(vecmax(x.g))
1701
1702
1703
def vecmin(gen x):
1704
"""
1705
vecmin(x): Return the maximum of the elements of the vector/matrix
1706
x.
1707
"""
1708
pari_catch_sig_on()
1709
return P.new_gen(vecmin(x.g))
1710
1711
1712
1713
###########################################
1714
# 2: CONVERSIONS and similar elementary functions
1715
###########################################
1716
1717
def Col(gen x, long n = 0):
1718
"""
1719
Transform the object `x` into a column vector with minimal size `|n|`.
1720
1721
INPUT:
1722
1723
- ``x`` -- gen
1724
1725
- ``n`` -- Make the column vector of minimal length `|n|`. If `n > 0`,
1726
append zeros; if `n < 0`, prepend zeros.
1727
1728
OUTPUT:
1729
1730
A PARI column vector (type ``t_COL``)
1731
1732
EXAMPLES::
1733
1734
sage: pari(1.5).Col()
1735
[1.50000000000000]~
1736
sage: pari([1,2,3,4]).Col()
1737
[1, 2, 3, 4]~
1738
sage: pari('[1,2; 3,4]').Col()
1739
[[1, 2], [3, 4]]~
1740
sage: pari('"Sage"').Col()
1741
["S", "a", "g", "e"]~
1742
sage: pari('x + 3*x^3').Col()
1743
[3, 0, 1, 0]~
1744
sage: pari('x + 3*x^3 + O(x^5)').Col()
1745
[1, 0, 3, 0]~
1746
1747
We demonstate the `n` argument::
1748
1749
sage: pari([1,2,3,4]).Col(2)
1750
[1, 2, 3, 4]~
1751
sage: pari([1,2,3,4]).Col(-2)
1752
[1, 2, 3, 4]~
1753
sage: pari([1,2,3,4]).Col(6)
1754
[1, 2, 3, 4, 0, 0]~
1755
sage: pari([1,2,3,4]).Col(-6)
1756
[0, 0, 1, 2, 3, 4]~
1757
1758
See also :meth:`Vec` (create a row vector) for more examples
1759
and :meth:`Colrev` (create a column in reversed order).
1760
"""
1761
pari_catch_sig_on()
1762
return P.new_gen(_Vec_append(gtocol(x.g), gen_0, n))
1763
1764
def Colrev(gen x, long n = 0):
1765
"""
1766
Transform the object `x` into a column vector with minimal size `|n|`.
1767
The order of the resulting vector is reversed compared to :meth:`Col`.
1768
1769
INPUT:
1770
1771
- ``x`` -- gen
1772
1773
- ``n`` -- Make the vector of minimal length `|n|`. If `n > 0`,
1774
prepend zeros; if `n < 0`, append zeros.
1775
1776
OUTPUT:
1777
1778
A PARI column vector (type ``t_COL``)
1779
1780
EXAMPLES::
1781
1782
sage: pari(1.5).Colrev()
1783
[1.50000000000000]~
1784
sage: pari([1,2,3,4]).Colrev()
1785
[4, 3, 2, 1]~
1786
sage: pari('[1,2; 3,4]').Colrev()
1787
[[3, 4], [1, 2]]~
1788
sage: pari('x + 3*x^3').Colrev()
1789
[0, 1, 0, 3]~
1790
1791
We demonstate the `n` argument::
1792
1793
sage: pari([1,2,3,4]).Colrev(2)
1794
[4, 3, 2, 1]~
1795
sage: pari([1,2,3,4]).Colrev(-2)
1796
[4, 3, 2, 1]~
1797
sage: pari([1,2,3,4]).Colrev(6)
1798
[0, 0, 4, 3, 2, 1]~
1799
sage: pari([1,2,3,4]).Colrev(-6)
1800
[4, 3, 2, 1, 0, 0]~
1801
"""
1802
pari_catch_sig_on()
1803
# Create a non-reversed column vector
1804
cdef GEN v = _Vec_append(gtocol(x.g), gen_0, n)
1805
# Reverse it in-place
1806
cdef GEN L = v + 1
1807
cdef GEN R = v + (lg(v)-1)
1808
cdef long t
1809
while (L < R):
1810
t = L[0]
1811
L[0] = R[0]
1812
R[0] = t
1813
L += 1
1814
R -= 1
1815
return P.new_gen(v)
1816
1817
def List(gen x):
1818
"""
1819
List(x): transforms the PARI vector or list x into a list.
1820
1821
EXAMPLES::
1822
1823
sage: v = pari([1,2,3])
1824
sage: v
1825
[1, 2, 3]
1826
sage: v.type()
1827
't_VEC'
1828
sage: w = v.List()
1829
sage: w
1830
List([1, 2, 3])
1831
sage: w.type()
1832
't_LIST'
1833
"""
1834
pari_catch_sig_on()
1835
return P.new_gen(gtolist(x.g))
1836
1837
def Mat(gen x):
1838
"""
1839
Mat(x): Returns the matrix defined by x.
1840
1841
- If x is already a matrix, a copy of x is created and returned.
1842
1843
- If x is not a vector or a matrix, this function returns a 1x1
1844
matrix.
1845
1846
- If x is a row (resp. column) vector, this functions returns
1847
a 1-row (resp. 1-column) matrix, *unless* all elements are
1848
column (resp. row) vectors of the same length, in which case
1849
the vectors are concatenated sideways and the associated big
1850
matrix is returned.
1851
1852
INPUT:
1853
1854
1855
- ``x`` - gen
1856
1857
1858
OUTPUT:
1859
1860
1861
- ``gen`` - a PARI matrix
1862
1863
1864
EXAMPLES::
1865
1866
sage: x = pari(5)
1867
sage: x.type()
1868
't_INT'
1869
sage: y = x.Mat()
1870
sage: y
1871
Mat(5)
1872
sage: y.type()
1873
't_MAT'
1874
sage: x = pari('[1,2;3,4]')
1875
sage: x.type()
1876
't_MAT'
1877
sage: x = pari('[1,2,3,4]')
1878
sage: x.type()
1879
't_VEC'
1880
sage: y = x.Mat()
1881
sage: y
1882
Mat([1, 2, 3, 4])
1883
sage: y.type()
1884
't_MAT'
1885
1886
::
1887
1888
sage: v = pari('[1,2;3,4]').Vec(); v
1889
[[1, 3]~, [2, 4]~]
1890
sage: v.Mat()
1891
[1, 2; 3, 4]
1892
sage: v = pari('[1,2;3,4]').Col(); v
1893
[[1, 2], [3, 4]]~
1894
sage: v.Mat()
1895
[1, 2; 3, 4]
1896
"""
1897
pari_catch_sig_on()
1898
return P.new_gen(gtomat(x.g))
1899
1900
def Mod(gen x, y):
1901
"""
1902
Mod(x, y): Returns the object x modulo y, denoted Mod(x, y).
1903
1904
The input y must be a an integer or a polynomial:
1905
1906
- If y is an INTEGER, x must also be an integer, a rational
1907
number, or a p-adic number compatible with the modulus y.
1908
1909
- If y is a POLYNOMIAL, x must be a scalar (which is not a
1910
polmod), a polynomial, a rational function, or a power
1911
series.
1912
1913
.. warning::
1914
1915
This function is not the same as ``x % y`` which is an
1916
integer or a polynomial.
1917
1918
INPUT:
1919
1920
1921
- ``x`` - gen
1922
1923
- ``y`` - integer or polynomial
1924
1925
1926
OUTPUT:
1927
1928
1929
- ``gen`` - intmod or polmod
1930
1931
1932
EXAMPLES::
1933
1934
sage: z = pari(3)
1935
sage: x = z.Mod(pari(7))
1936
sage: x
1937
Mod(3, 7)
1938
sage: x^2
1939
Mod(2, 7)
1940
sage: x^100
1941
Mod(4, 7)
1942
sage: x.type()
1943
't_INTMOD'
1944
1945
::
1946
1947
sage: f = pari("x^2 + x + 1")
1948
sage: g = pari("x")
1949
sage: a = g.Mod(f)
1950
sage: a
1951
Mod(x, x^2 + x + 1)
1952
sage: a*a
1953
Mod(-x - 1, x^2 + x + 1)
1954
sage: a.type()
1955
't_POLMOD'
1956
"""
1957
cdef gen t0 = objtogen(y)
1958
pari_catch_sig_on()
1959
return P.new_gen(gmodulo(x.g, t0.g))
1960
1961
def Pol(self, v=-1):
1962
"""
1963
Pol(x, v): convert x into a polynomial with main variable v and
1964
return the result.
1965
1966
- If x is a scalar, returns a constant polynomial.
1967
1968
- If x is a power series, the effect is identical to
1969
``truncate``, i.e. it chops off the `O(X^k)`.
1970
1971
- If x is a vector, this function creates the polynomial whose
1972
coefficients are given in x, with x[0] being the leading
1973
coefficient (which can be zero).
1974
1975
.. warning::
1976
1977
This is *not* a substitution function. It will not
1978
transform an object containing variables of higher priority
1979
than v::
1980
1981
sage: pari('x+y').Pol('y')
1982
Traceback (most recent call last):
1983
...
1984
PariError: variable must have higher priority in gtopoly
1985
1986
INPUT:
1987
1988
1989
- ``x`` - gen
1990
1991
- ``v`` - (optional) which variable, defaults to 'x'
1992
1993
1994
OUTPUT:
1995
1996
1997
- ``gen`` - a polynomial
1998
1999
2000
EXAMPLES::
2001
2002
sage: v = pari("[1,2,3,4]")
2003
sage: f = v.Pol()
2004
sage: f
2005
x^3 + 2*x^2 + 3*x + 4
2006
sage: f*f
2007
x^6 + 4*x^5 + 10*x^4 + 20*x^3 + 25*x^2 + 24*x + 16
2008
2009
::
2010
2011
sage: v = pari("[1,2;3,4]")
2012
sage: v.Pol()
2013
[1, 3]~*x + [2, 4]~
2014
"""
2015
pari_catch_sig_on()
2016
return P.new_gen(gtopoly(self.g, P.get_var(v)))
2017
2018
def Polrev(self, v=-1):
2019
"""
2020
Polrev(x, v): Convert x into a polynomial with main variable v and
2021
return the result. This is the reverse of Pol if x is a vector,
2022
otherwise it is identical to Pol. By "reverse" we mean that the
2023
coefficients are reversed.
2024
2025
INPUT:
2026
2027
- ``x`` - gen
2028
2029
OUTPUT:
2030
2031
- ``gen`` - a polynomial
2032
2033
EXAMPLES::
2034
2035
sage: v = pari("[1,2,3,4]")
2036
sage: f = v.Polrev()
2037
sage: f
2038
4*x^3 + 3*x^2 + 2*x + 1
2039
sage: v.Pol()
2040
x^3 + 2*x^2 + 3*x + 4
2041
sage: v.Polrev('y')
2042
4*y^3 + 3*y^2 + 2*y + 1
2043
2044
Note that Polrev does *not* reverse the coefficients of a
2045
polynomial! ::
2046
2047
sage: f
2048
4*x^3 + 3*x^2 + 2*x + 1
2049
sage: f.Polrev()
2050
4*x^3 + 3*x^2 + 2*x + 1
2051
sage: v = pari("[1,2;3,4]")
2052
sage: v.Polrev()
2053
[2, 4]~*x + [1, 3]~
2054
"""
2055
pari_catch_sig_on()
2056
return P.new_gen(gtopolyrev(self.g, P.get_var(v)))
2057
2058
def Qfb(gen a, b, c, D=0, unsigned long precision=0):
2059
"""
2060
Qfb(a,b,c,D=0.): Returns the binary quadratic form
2061
2062
.. math::
2063
2064
ax^2 + bxy + cy^2.
2065
2066
2067
The optional D is 0 by default and initializes Shank's distance if
2068
`b^2 - 4ac > 0`. The discriminant of the quadratic form must not
2069
be a perfect square.
2070
2071
.. note::
2072
2073
Negative definite forms are not implemented, so use their
2074
positive definite counterparts instead. (I.e., if f is a
2075
negative definite quadratic form, then -f is positive
2076
definite.)
2077
2078
INPUT:
2079
2080
2081
- ``a`` - gen
2082
2083
- ``b`` - gen
2084
2085
- ``c`` - gen
2086
2087
- ``D`` - gen (optional, defaults to 0)
2088
2089
2090
OUTPUT:
2091
2092
2093
- ``gen`` - binary quadratic form
2094
2095
2096
EXAMPLES::
2097
2098
sage: pari(3).Qfb(7, 1)
2099
Qfb(3, 7, 1, 0.E-19)
2100
sage: pari(3).Qfb(7, 2) # discriminant is 25
2101
Traceback (most recent call last):
2102
...
2103
PariError: square discriminant in Qfb
2104
"""
2105
cdef gen t0 = objtogen(b)
2106
cdef gen t1 = objtogen(c)
2107
cdef gen t2 = objtogen(D)
2108
pari_catch_sig_on()
2109
return P.new_gen(Qfb0(a.g, t0.g, t1.g, t2.g, prec_bits_to_words(precision)))
2110
2111
2112
def Ser(gen x, v=-1, long seriesprecision=16):
2113
"""
2114
Ser(x,v=x): Create a power series from x with main variable v and
2115
return the result.
2116
2117
- If x is a scalar, this gives a constant power series with
2118
precision given by the default series precision, as returned
2119
by get_series_precision().
2120
2121
- If x is a polynomial, the precision is the greatest of
2122
get_series_precision() and the degree of the polynomial.
2123
2124
- If x is a vector, the precision is similarly given, and the
2125
coefficients of the vector are understood to be the
2126
coefficients of the power series starting from the constant
2127
term (i.e. the reverse of the function Pol).
2128
2129
.. warning::
2130
2131
This is *not* a substitution function. It will not
2132
transform an object containing variables of higher priority
2133
than v.
2134
2135
INPUT:
2136
2137
2138
- ``x`` - gen
2139
2140
- ``v`` - PARI variable (default: x)
2141
2142
2143
OUTPUT:
2144
2145
2146
- ``gen`` - PARI object of PARI type t_SER
2147
2148
2149
EXAMPLES::
2150
2151
sage: pari(2).Ser()
2152
2 + O(x^16)
2153
sage: x = pari([1,2,3,4,5])
2154
sage: x.Ser()
2155
1 + 2*x + 3*x^2 + 4*x^3 + 5*x^4 + O(x^5)
2156
sage: f = x.Ser('v'); print f
2157
1 + 2*v + 3*v^2 + 4*v^3 + 5*v^4 + O(v^5)
2158
sage: pari(1)/f
2159
1 - 2*v + v^2 + O(v^5)
2160
sage: pari('x^5').Ser(seriesprecision=20)
2161
x^5 + O(x^25)
2162
sage: pari('1/x').Ser(seriesprecision=1)
2163
x^-1 + O(x^0)
2164
"""
2165
pari_catch_sig_on()
2166
return P.new_gen(gtoser(x.g, P.get_var(v), seriesprecision))
2167
2168
2169
def Set(gen x):
2170
"""
2171
Set(x): convert x into a set, i.e. a row vector of strings in
2172
increasing lexicographic order.
2173
2174
INPUT:
2175
2176
2177
- ``x`` - gen
2178
2179
2180
OUTPUT:
2181
2182
2183
- ``gen`` - a vector of strings in increasing
2184
lexicographic order.
2185
2186
2187
EXAMPLES::
2188
2189
sage: pari([1,5,2]).Set()
2190
["1", "2", "5"]
2191
sage: pari([]).Set() # the empty set
2192
[]
2193
sage: pari([1,1,-1,-1,3,3]).Set()
2194
["-1", "1", "3"]
2195
sage: pari(1).Set()
2196
["1"]
2197
sage: pari('1/(x*y)').Set()
2198
["1/(y*x)"]
2199
sage: pari('["bc","ab","bc"]').Set()
2200
["\"ab\"", "\"bc\""]
2201
"""
2202
pari_catch_sig_on()
2203
return P.new_gen(gtoset(x.g))
2204
2205
2206
def Str(self):
2207
"""
2208
Str(self): Return the print representation of self as a PARI
2209
object.
2210
2211
INPUT:
2212
2213
2214
- ``self`` - gen
2215
2216
2217
OUTPUT:
2218
2219
2220
- ``gen`` - a PARI gen of type t_STR, i.e., a PARI
2221
string
2222
2223
2224
EXAMPLES::
2225
2226
sage: pari([1,2,['abc',1]]).Str()
2227
"[1, 2, [abc, 1]]"
2228
sage: pari([1,1, 1.54]).Str()
2229
"[1, 1, 1.54000000000000]"
2230
sage: pari(1).Str() # 1 is automatically converted to string rep
2231
"1"
2232
sage: x = pari('x') # PARI variable "x"
2233
sage: x.Str() # is converted to string rep.
2234
"x"
2235
sage: x.Str().type()
2236
't_STR'
2237
"""
2238
cdef char* c
2239
pari_catch_sig_on()
2240
# Use sig_block(), which is needed because GENtostr() uses
2241
# malloc(), which is dangerous inside sig_on()
2242
sig_block()
2243
c = GENtostr(self.g)
2244
sig_unblock()
2245
v = P.new_gen(strtoGENstr(c))
2246
pari_free(c)
2247
return v
2248
2249
2250
def Strchr(gen x):
2251
"""
2252
Strchr(x): converts x to a string, translating each integer into a
2253
character (in ASCII).
2254
2255
.. note::
2256
2257
:meth:`.Vecsmall` is (essentially) the inverse to :meth:`.Strchr`.
2258
2259
INPUT:
2260
2261
2262
- ``x`` - PARI vector of integers
2263
2264
2265
OUTPUT:
2266
2267
2268
- ``gen`` - a PARI string
2269
2270
2271
EXAMPLES::
2272
2273
sage: pari([65,66,123]).Strchr()
2274
"AB{"
2275
sage: pari('"Sage"').Vecsmall() # pari('"Sage"') --> PARI t_STR
2276
Vecsmall([83, 97, 103, 101])
2277
sage: _.Strchr()
2278
"Sage"
2279
sage: pari([83, 97, 103, 101]).Strchr()
2280
"Sage"
2281
"""
2282
pari_catch_sig_on()
2283
return P.new_gen(Strchr(x.g))
2284
2285
def Strexpand(gen x):
2286
"""
2287
Strexpand(x): Concatenate the entries of the vector x into a single
2288
string, performing tilde expansion.
2289
2290
.. note::
2291
2292
I have no clue what the point of this function is. - William
2293
"""
2294
if typ(x.g) != t_VEC:
2295
raise TypeError, "x must be of type t_VEC."
2296
pari_catch_sig_on()
2297
return P.new_gen(Strexpand(x.g))
2298
2299
2300
def Strtex(gen x):
2301
r"""
2302
Strtex(x): Translates the vector x of PARI gens to TeX format and
2303
returns the resulting concatenated strings as a PARI t_STR.
2304
2305
INPUT:
2306
2307
2308
- ``x`` - gen
2309
2310
2311
OUTPUT:
2312
2313
2314
- ``gen`` - PARI t_STR (string)
2315
2316
2317
EXAMPLES::
2318
2319
sage: v=pari('x^2')
2320
sage: v.Strtex()
2321
"x^2"
2322
sage: v=pari(['1/x^2','x'])
2323
sage: v.Strtex()
2324
"\\frac{1}{x^2}x"
2325
sage: v=pari(['1 + 1/x + 1/(y+1)','x-1'])
2326
sage: v.Strtex()
2327
"\\frac{ \\left(y\n + 2\\right) x\n + \\left(y\n + 1\\right) }{ \\left(y\n + 1\\right) x}x\n - 1"
2328
"""
2329
if typ(x.g) != t_VEC:
2330
x = P.vector(1, [x])
2331
pari_catch_sig_on()
2332
return P.new_gen(Strtex(x.g))
2333
2334
def printtex(gen x):
2335
return x.Strtex()
2336
2337
def Vec(gen x, long n = 0):
2338
"""
2339
Transform the object `x` into a vector with minimal size `|n|`.
2340
2341
INPUT:
2342
2343
- ``x`` -- gen
2344
2345
- ``n`` -- Make the vector of minimal length `|n|`. If `n > 0`,
2346
append zeros; if `n < 0`, prepend zeros.
2347
2348
OUTPUT:
2349
2350
A PARI vector (type ``t_VEC``)
2351
2352
EXAMPLES::
2353
2354
sage: pari(1).Vec()
2355
[1]
2356
sage: pari('x^3').Vec()
2357
[1, 0, 0, 0]
2358
sage: pari('x^3 + 3*x - 2').Vec()
2359
[1, 0, 3, -2]
2360
sage: pari([1,2,3]).Vec()
2361
[1, 2, 3]
2362
sage: pari('[1, 2; 3, 4]').Vec()
2363
[[1, 3]~, [2, 4]~]
2364
sage: pari('"Sage"').Vec()
2365
["S", "a", "g", "e"]
2366
sage: pari('2*x^2 + 3*x^3 + O(x^5)').Vec()
2367
[2, 3, 0]
2368
sage: pari('2*x^-2 + 3*x^3 + O(x^5)').Vec()
2369
[2, 0, 0, 0, 0, 3, 0]
2370
2371
Note the different term ordering for polynomials and series::
2372
2373
sage: pari('1 + x + 3*x^3 + O(x^5)').Vec()
2374
[1, 1, 0, 3, 0]
2375
sage: pari('1 + x + 3*x^3').Vec()
2376
[3, 0, 1, 1]
2377
2378
We demonstate the `n` argument::
2379
2380
sage: pari([1,2,3,4]).Vec(2)
2381
[1, 2, 3, 4]
2382
sage: pari([1,2,3,4]).Vec(-2)
2383
[1, 2, 3, 4]
2384
sage: pari([1,2,3,4]).Vec(6)
2385
[1, 2, 3, 4, 0, 0]
2386
sage: pari([1,2,3,4]).Vec(-6)
2387
[0, 0, 1, 2, 3, 4]
2388
2389
See also :meth:`Col` (create a column vector) and :meth:`Vecrev`
2390
(create a vector in reversed order).
2391
"""
2392
pari_catch_sig_on()
2393
return P.new_gen(_Vec_append(gtovec(x.g), gen_0, n))
2394
2395
def Vecrev(gen x, long n = 0):
2396
"""
2397
Transform the object `x` into a vector with minimal size `|n|`.
2398
The order of the resulting vector is reversed compared to :meth:`Vec`.
2399
2400
INPUT:
2401
2402
- ``x`` -- gen
2403
2404
- ``n`` -- Make the vector of minimal length `|n|`. If `n > 0`,
2405
prepend zeros; if `n < 0`, append zeros.
2406
2407
OUTPUT:
2408
2409
A PARI vector (type ``t_VEC``)
2410
2411
EXAMPLES::
2412
2413
sage: pari(1).Vecrev()
2414
[1]
2415
sage: pari('x^3').Vecrev()
2416
[0, 0, 0, 1]
2417
sage: pari('x^3 + 3*x - 2').Vecrev()
2418
[-2, 3, 0, 1]
2419
sage: pari([1, 2, 3]).Vecrev()
2420
[3, 2, 1]
2421
sage: pari('Col([1, 2, 3])').Vecrev()
2422
[3, 2, 1]
2423
sage: pari('[1, 2; 3, 4]').Vecrev()
2424
[[2, 4]~, [1, 3]~]
2425
sage: pari('"Sage"').Vecrev()
2426
["e", "g", "a", "S"]
2427
2428
We demonstate the `n` argument::
2429
2430
sage: pari([1,2,3,4]).Vecrev(2)
2431
[4, 3, 2, 1]
2432
sage: pari([1,2,3,4]).Vecrev(-2)
2433
[4, 3, 2, 1]
2434
sage: pari([1,2,3,4]).Vecrev(6)
2435
[0, 0, 4, 3, 2, 1]
2436
sage: pari([1,2,3,4]).Vecrev(-6)
2437
[4, 3, 2, 1, 0, 0]
2438
"""
2439
pari_catch_sig_on()
2440
return P.new_gen(_Vec_append(gtovecrev(x.g), gen_0, -n))
2441
2442
def Vecsmall(gen x, long n = 0):
2443
"""
2444
Transform the object `x` into a ``t_VECSMALL`` with minimal size `|n|`.
2445
2446
INPUT:
2447
2448
- ``x`` -- gen
2449
2450
- ``n`` -- Make the vector of minimal length `|n|`. If `n > 0`,
2451
append zeros; if `n < 0`, prepend zeros.
2452
2453
OUTPUT:
2454
2455
A PARI vector of small integers (type ``t_VECSMALL``)
2456
2457
EXAMPLES::
2458
2459
sage: pari([1,2,3]).Vecsmall()
2460
Vecsmall([1, 2, 3])
2461
sage: pari('"Sage"').Vecsmall()
2462
Vecsmall([83, 97, 103, 101])
2463
sage: pari(1234).Vecsmall()
2464
Vecsmall([1234])
2465
sage: pari('x^2 + 2*x + 3').Vecsmall()
2466
Traceback (most recent call last):
2467
...
2468
PariError: incorrect type in vectosmall
2469
2470
We demonstate the `n` argument::
2471
2472
sage: pari([1,2,3]).Vecsmall(2)
2473
Vecsmall([1, 2, 3])
2474
sage: pari([1,2,3]).Vecsmall(-2)
2475
Vecsmall([1, 2, 3])
2476
sage: pari([1,2,3]).Vecsmall(6)
2477
Vecsmall([1, 2, 3, 0, 0, 0])
2478
sage: pari([1,2,3]).Vecsmall(-6)
2479
Vecsmall([0, 0, 0, 1, 2, 3])
2480
"""
2481
pari_catch_sig_on()
2482
return P.new_gen(_Vec_append(gtovecsmall(x.g), <GEN>0, n))
2483
2484
def binary(gen x):
2485
"""
2486
binary(x): gives the vector formed by the binary digits of abs(x),
2487
where x is of type t_INT.
2488
2489
INPUT:
2490
2491
2492
- ``x`` - gen of type t_INT
2493
2494
2495
OUTPUT:
2496
2497
2498
- ``gen`` - of type t_VEC
2499
2500
2501
EXAMPLES::
2502
2503
sage: pari(0).binary()
2504
[0]
2505
sage: pari(-5).binary()
2506
[1, 0, 1]
2507
sage: pari(5).binary()
2508
[1, 0, 1]
2509
sage: pari(2005).binary()
2510
[1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1]
2511
2512
::
2513
2514
sage: pari('"2"').binary()
2515
Traceback (most recent call last):
2516
...
2517
TypeError: x (="2") must be of type t_INT, but is of type t_STR.
2518
"""
2519
if typ(x.g) != t_INT:
2520
raise TypeError, "x (=%s) must be of type t_INT, but is of type %s."%(x,x.type())
2521
pari_catch_sig_on()
2522
return P.new_gen(binaire(x.g))
2523
2524
def bitand(gen x, y):
2525
"""
2526
bitand(x,y): Bitwise and of two integers x and y. Negative numbers
2527
behave as if modulo some large power of 2.
2528
2529
INPUT:
2530
2531
2532
- ``x`` - gen (of type t_INT)
2533
2534
- ``y`` - coercible to gen (of type t_INT)
2535
2536
2537
OUTPUT:
2538
2539
2540
- ``gen`` - of type type t_INT
2541
2542
2543
EXAMPLES::
2544
2545
sage: pari(8).bitand(4)
2546
0
2547
sage: pari(8).bitand(8)
2548
8
2549
sage: pari(6).binary()
2550
[1, 1, 0]
2551
sage: pari(7).binary()
2552
[1, 1, 1]
2553
sage: pari(6).bitand(7)
2554
6
2555
sage: pari(19).bitand(-1)
2556
19
2557
sage: pari(-1).bitand(-1)
2558
-1
2559
"""
2560
cdef gen t0 = objtogen(y)
2561
pari_catch_sig_on()
2562
return P.new_gen(gbitand(x.g, t0.g))
2563
2564
2565
def bitneg(gen x, long n=-1):
2566
r"""
2567
bitneg(x,n=-1): Bitwise negation of the integer x truncated to n
2568
bits. n=-1 (the default) represents an infinite sequence of the bit
2569
1. Negative numbers behave as if modulo some large power of 2.
2570
2571
With n=-1, this function returns -n-1. With n = 0, it returns a
2572
number a such that `a\cong -n-1 \pmod{2^n}`.
2573
2574
INPUT:
2575
2576
2577
- ``x`` - gen (t_INT)
2578
2579
- ``n`` - long, default = -1
2580
2581
2582
OUTPUT:
2583
2584
2585
- ``gen`` - t_INT
2586
2587
2588
EXAMPLES::
2589
2590
sage: pari(10).bitneg()
2591
-11
2592
sage: pari(1).bitneg()
2593
-2
2594
sage: pari(-2).bitneg()
2595
1
2596
sage: pari(-1).bitneg()
2597
0
2598
sage: pari(569).bitneg()
2599
-570
2600
sage: pari(569).bitneg(10)
2601
454
2602
sage: 454 % 2^10
2603
454
2604
sage: -570 % 2^10
2605
454
2606
"""
2607
pari_catch_sig_on()
2608
return P.new_gen(gbitneg(x.g,n))
2609
2610
2611
def bitnegimply(gen x, y):
2612
"""
2613
bitnegimply(x,y): Bitwise negated imply of two integers x and y, in
2614
other words, x BITAND BITNEG(y). Negative numbers behave as if
2615
modulo big power of 2.
2616
2617
INPUT:
2618
2619
2620
- ``x`` - gen (of type t_INT)
2621
2622
- ``y`` - coercible to gen (of type t_INT)
2623
2624
2625
OUTPUT:
2626
2627
2628
- ``gen`` - of type type t_INT
2629
2630
2631
EXAMPLES::
2632
2633
sage: pari(14).bitnegimply(0)
2634
14
2635
sage: pari(8).bitnegimply(8)
2636
0
2637
sage: pari(8+4).bitnegimply(8)
2638
4
2639
"""
2640
cdef gen t0 = objtogen(y)
2641
pari_catch_sig_on()
2642
return P.new_gen(gbitnegimply(x.g, t0.g))
2643
2644
2645
def bitor(gen x, y):
2646
"""
2647
bitor(x,y): Bitwise or of two integers x and y. Negative numbers
2648
behave as if modulo big power of 2.
2649
2650
INPUT:
2651
2652
2653
- ``x`` - gen (of type t_INT)
2654
2655
- ``y`` - coercible to gen (of type t_INT)
2656
2657
2658
OUTPUT:
2659
2660
2661
- ``gen`` - of type type t_INT
2662
2663
2664
EXAMPLES::
2665
2666
sage: pari(14).bitor(0)
2667
14
2668
sage: pari(8).bitor(4)
2669
12
2670
sage: pari(12).bitor(1)
2671
13
2672
sage: pari(13).bitor(1)
2673
13
2674
"""
2675
cdef gen t0 = objtogen(y)
2676
pari_catch_sig_on()
2677
return P.new_gen(gbitor(x.g, t0.g))
2678
2679
2680
def bittest(gen x, long n):
2681
"""
2682
bittest(x, long n): Returns bit number n (coefficient of
2683
`2^n` in binary) of the integer x. Negative numbers behave
2684
as if modulo a big power of 2.
2685
2686
INPUT:
2687
2688
2689
- ``x`` - gen (pari integer)
2690
2691
2692
OUTPUT:
2693
2694
2695
- ``bool`` - a Python bool
2696
2697
2698
EXAMPLES::
2699
2700
sage: x = pari(6)
2701
sage: x.bittest(0)
2702
False
2703
sage: x.bittest(1)
2704
True
2705
sage: x.bittest(2)
2706
True
2707
sage: x.bittest(3)
2708
False
2709
sage: pari(-3).bittest(0)
2710
True
2711
sage: pari(-3).bittest(1)
2712
False
2713
sage: [pari(-3).bittest(n) for n in range(10)]
2714
[True, False, True, True, True, True, True, True, True, True]
2715
"""
2716
pari_catch_sig_on()
2717
cdef long b = bittest(x.g, n)
2718
pari_catch_sig_off()
2719
return b != 0
2720
2721
def bitxor(gen x, y):
2722
"""
2723
bitxor(x,y): Bitwise exclusive or of two integers x and y. Negative
2724
numbers behave as if modulo big power of 2.
2725
2726
INPUT:
2727
2728
2729
- ``x`` - gen (of type t_INT)
2730
2731
- ``y`` - coercible to gen (of type t_INT)
2732
2733
2734
OUTPUT:
2735
2736
2737
- ``gen`` - of type type t_INT
2738
2739
2740
EXAMPLES::
2741
2742
sage: pari(6).bitxor(4)
2743
2
2744
sage: pari(0).bitxor(4)
2745
4
2746
sage: pari(6).bitxor(0)
2747
6
2748
"""
2749
cdef gen t0 = objtogen(y)
2750
pari_catch_sig_on()
2751
return P.new_gen(gbitxor(x.g, t0.g))
2752
2753
2754
def ceil(gen x):
2755
"""
2756
For real x: return the smallest integer = x. For rational
2757
functions: the quotient of numerator by denominator. For lists:
2758
apply componentwise.
2759
2760
INPUT:
2761
2762
2763
- ``x`` - gen
2764
2765
2766
OUTPUT:
2767
2768
2769
- ``gen`` - depends on type of x
2770
2771
2772
EXAMPLES::
2773
2774
sage: pari(1.4).ceil()
2775
2
2776
sage: pari(-1.4).ceil()
2777
-1
2778
sage: pari(3/4).ceil()
2779
1
2780
sage: pari(x).ceil()
2781
x
2782
sage: pari((x^2+x+1)/x).ceil()
2783
x + 1
2784
2785
This may be unexpected: but it is correct, treating the argument as
2786
a rational function in RR(x).
2787
2788
::
2789
2790
sage: pari(x^2+5*x+2.5).ceil()
2791
x^2 + 5*x + 2.50000000000000
2792
"""
2793
pari_catch_sig_on()
2794
return P.new_gen(gceil(x.g))
2795
2796
def centerlift(gen x, v=-1):
2797
"""
2798
centerlift(x,v): Centered lift of x. This function returns exactly
2799
the same thing as lift, except if x is an integer mod.
2800
2801
INPUT:
2802
2803
2804
- ``x`` - gen
2805
2806
- ``v`` - var (default: x)
2807
2808
2809
OUTPUT: gen
2810
2811
EXAMPLES::
2812
2813
sage: x = pari(-2).Mod(5)
2814
sage: x.centerlift()
2815
-2
2816
sage: x.lift()
2817
3
2818
sage: f = pari('x-1').Mod('x^2 + 1')
2819
sage: f.centerlift()
2820
x - 1
2821
sage: f.lift()
2822
x - 1
2823
sage: f = pari('x-y').Mod('x^2+1')
2824
sage: f
2825
Mod(x - y, x^2 + 1)
2826
sage: f.centerlift('x')
2827
x - y
2828
sage: f.centerlift('y')
2829
Mod(x - y, x^2 + 1)
2830
"""
2831
pari_catch_sig_on()
2832
return P.new_gen(centerlift0(x.g, P.get_var(v)))
2833
2834
2835
def component(gen x, long n):
2836
"""
2837
component(x, long n): Return n'th component of the internal
2838
representation of x. This function is 1-based instead of 0-based.
2839
2840
.. note::
2841
2842
For vectors or matrices, it is simpler to use x[n-1]. For
2843
list objects such as is output by nfinit, it is easier to
2844
use member functions.
2845
2846
INPUT:
2847
2848
2849
- ``x`` - gen
2850
2851
- ``n`` - C long (coercible to)
2852
2853
2854
OUTPUT: gen
2855
2856
EXAMPLES::
2857
2858
sage: pari([0,1,2,3,4]).component(1)
2859
0
2860
sage: pari([0,1,2,3,4]).component(2)
2861
1
2862
sage: pari([0,1,2,3,4]).component(4)
2863
3
2864
sage: pari('x^3 + 2').component(1)
2865
2
2866
sage: pari('x^3 + 2').component(2)
2867
0
2868
sage: pari('x^3 + 2').component(4)
2869
1
2870
2871
::
2872
2873
sage: pari('x').component(0)
2874
Traceback (most recent call last):
2875
...
2876
PariError: nonexistent component
2877
"""
2878
pari_catch_sig_on()
2879
return P.new_gen(compo(x.g, n))
2880
2881
def conj(gen x):
2882
"""
2883
conj(x): Return the algebraic conjugate of x.
2884
2885
INPUT:
2886
2887
2888
- ``x`` - gen
2889
2890
2891
OUTPUT: gen
2892
2893
EXAMPLES::
2894
2895
sage: pari('x+1').conj()
2896
x + 1
2897
sage: pari('x+I').conj()
2898
x - I
2899
sage: pari('1/(2*x+3*I)').conj()
2900
1/(2*x - 3*I)
2901
sage: pari([1,2,'2-I','Mod(x,x^2+1)', 'Mod(x,x^2-2)']).conj()
2902
[1, 2, 2 + I, Mod(-x, x^2 + 1), Mod(-x, x^2 - 2)]
2903
sage: pari('Mod(x,x^2-2)').conj()
2904
Mod(-x, x^2 - 2)
2905
sage: pari('Mod(x,x^3-3)').conj()
2906
Traceback (most recent call last):
2907
...
2908
PariError: incorrect type in gconj
2909
"""
2910
pari_catch_sig_on()
2911
return P.new_gen(gconj(x.g))
2912
2913
def conjvec(gen x, unsigned long precision=0):
2914
"""
2915
conjvec(x): Returns the vector of all conjugates of the algebraic
2916
number x. An algebraic number is a polynomial over Q modulo an
2917
irreducible polynomial.
2918
2919
INPUT:
2920
2921
2922
- ``x`` - gen
2923
2924
2925
OUTPUT: gen
2926
2927
EXAMPLES::
2928
2929
sage: pari('Mod(1+x,x^2-2)').conjvec()
2930
[-0.414213562373095, 2.41421356237310]~
2931
sage: pari('Mod(x,x^3-3)').conjvec()
2932
[1.44224957030741, -0.721124785153704 + 1.24902476648341*I, -0.721124785153704 - 1.24902476648341*I]~
2933
sage: pari('Mod(1+x,x^2-2)').conjvec(precision=192)[0].sage()
2934
-0.414213562373095048801688724209698078569671875376948073177
2935
"""
2936
pari_catch_sig_on()
2937
return P.new_gen(conjvec(x.g, prec_bits_to_words(precision)))
2938
2939
def denominator(gen x):
2940
"""
2941
denominator(x): Return the denominator of x. When x is a vector,
2942
this is the least common multiple of the denominators of the
2943
components of x.
2944
2945
what about poly? INPUT:
2946
2947
2948
- ``x`` - gen
2949
2950
2951
OUTPUT: gen
2952
2953
EXAMPLES::
2954
2955
sage: pari('5/9').denominator()
2956
9
2957
sage: pari('(x+1)/(x-2)').denominator()
2958
x - 2
2959
sage: pari('2/3 + 5/8*x + 7/3*x^2 + 1/5*y').denominator()
2960
1
2961
sage: pari('2/3*x').denominator()
2962
1
2963
sage: pari('[2/3, 5/8, 7/3, 1/5]').denominator()
2964
120
2965
"""
2966
pari_catch_sig_on()
2967
return P.new_gen(denom(x.g))
2968
2969
def floor(gen x):
2970
"""
2971
For real x: return the largest integer = x. For rational functions:
2972
the quotient of numerator by denominator. For lists: apply
2973
componentwise.
2974
2975
INPUT:
2976
2977
2978
- ``x`` - gen
2979
2980
2981
OUTPUT: gen
2982
2983
EXAMPLES::
2984
2985
sage: pari(5/9).floor()
2986
0
2987
sage: pari(11/9).floor()
2988
1
2989
sage: pari(1.17).floor()
2990
1
2991
sage: pari([1.5,2.3,4.99]).floor()
2992
[1, 2, 4]
2993
sage: pari([[1.1,2.2],[3.3,4.4]]).floor()
2994
[[1, 2], [3, 4]]
2995
sage: pari(x).floor()
2996
x
2997
sage: pari((x^2+x+1)/x).floor()
2998
x + 1
2999
sage: pari(x^2+5*x+2.5).floor()
3000
x^2 + 5*x + 2.50000000000000
3001
3002
::
3003
3004
sage: pari('"hello world"').floor()
3005
Traceback (most recent call last):
3006
...
3007
PariError: incorrect type in gfloor
3008
"""
3009
pari_catch_sig_on()
3010
return P.new_gen(gfloor(x.g))
3011
3012
def frac(gen x):
3013
"""
3014
frac(x): Return the fractional part of x, which is x - floor(x).
3015
3016
INPUT:
3017
3018
3019
- ``x`` - gen
3020
3021
3022
OUTPUT: gen
3023
3024
EXAMPLES::
3025
3026
sage: pari(1.75).frac()
3027
0.750000000000000
3028
sage: pari(sqrt(2)).frac()
3029
0.414213562373095
3030
sage: pari('sqrt(-2)').frac()
3031
Traceback (most recent call last):
3032
...
3033
PariError: incorrect type in gfloor
3034
"""
3035
pari_catch_sig_on()
3036
return P.new_gen(gfrac(x.g))
3037
3038
def imag(gen x):
3039
"""
3040
imag(x): Return the imaginary part of x. This function also works
3041
component-wise.
3042
3043
INPUT:
3044
3045
3046
- ``x`` - gen
3047
3048
3049
OUTPUT: gen
3050
3051
EXAMPLES::
3052
3053
sage: pari('1+2*I').imag()
3054
2
3055
sage: pari(sqrt(-2)).imag()
3056
1.41421356237310
3057
sage: pari('x+I').imag()
3058
1
3059
sage: pari('x+2*I').imag()
3060
2
3061
sage: pari('(1+I)*x^2+2*I').imag()
3062
x^2 + 2
3063
sage: pari('[1,2,3] + [4*I,5,6]').imag()
3064
[4, 0, 0]
3065
"""
3066
pari_catch_sig_on()
3067
return P.new_gen(gimag(x.g))
3068
3069
def length(self):
3070
"""
3071
3072
"""
3073
return glength(self.g)
3074
3075
def lift(gen x, v=-1):
3076
"""
3077
lift(x,v): Returns the lift of an element of Z/nZ to Z or R[x]/(P)
3078
to R[x] for a type R if v is omitted. If v is given, lift only
3079
polymods with main variable v. If v does not occur in x, lift only
3080
intmods.
3081
3082
INPUT:
3083
3084
3085
- ``x`` - gen
3086
3087
- ``v`` - (optional) variable
3088
3089
3090
OUTPUT: gen
3091
3092
EXAMPLES::
3093
3094
sage: x = pari("x")
3095
sage: a = x.Mod('x^3 + 17*x + 3')
3096
sage: a
3097
Mod(x, x^3 + 17*x + 3)
3098
sage: b = a^4; b
3099
Mod(-17*x^2 - 3*x, x^3 + 17*x + 3)
3100
sage: b.lift()
3101
-17*x^2 - 3*x
3102
3103
??? more examples
3104
"""
3105
pari_catch_sig_on()
3106
if v == -1:
3107
return P.new_gen(lift(x.g))
3108
return P.new_gen(lift0(x.g, P.get_var(v)))
3109
3110
def numbpart(gen x):
3111
"""
3112
numbpart(x): returns the number of partitions of x.
3113
3114
EXAMPLES::
3115
3116
sage: pari(20).numbpart()
3117
627
3118
sage: pari(100).numbpart()
3119
190569292
3120
"""
3121
pari_catch_sig_on()
3122
return P.new_gen(numbpart(x.g))
3123
3124
def numerator(gen x):
3125
"""
3126
numerator(x): Returns the numerator of x.
3127
3128
INPUT:
3129
3130
3131
- ``x`` - gen
3132
3133
3134
OUTPUT: gen
3135
3136
EXAMPLES:
3137
"""
3138
pari_catch_sig_on()
3139
return P.new_gen(numer(x.g))
3140
3141
3142
def numtoperm(gen k, long n):
3143
"""
3144
numtoperm(k, n): Return the permutation number k (mod n!) of n
3145
letters, where n is an integer.
3146
3147
INPUT:
3148
3149
3150
- ``k`` - gen, integer
3151
3152
- ``n`` - int
3153
3154
3155
OUTPUT:
3156
3157
3158
- ``gen`` - vector (permutation of 1,...,n)
3159
3160
3161
EXAMPLES:
3162
"""
3163
pari_catch_sig_on()
3164
return P.new_gen(numtoperm(n, k.g))
3165
3166
3167
def padicprec(gen x, p):
3168
"""
3169
padicprec(x,p): Return the absolute p-adic precision of the object
3170
x.
3171
3172
INPUT:
3173
3174
3175
- ``x`` - gen
3176
3177
3178
OUTPUT: int
3179
3180
EXAMPLES::
3181
3182
sage: K = Qp(11,5)
3183
sage: x = K(11^-10 + 5*11^-7 + 11^-6)
3184
sage: y = pari(x)
3185
sage: y.padicprec(11)
3186
-5
3187
sage: y.padicprec(17)
3188
Traceback (most recent call last):
3189
...
3190
PariError: not the same prime in padicprec
3191
3192
This works for polynomials too::
3193
3194
sage: R.<t> = PolynomialRing(Zp(3))
3195
sage: pol = R([O(3^4), O(3^6), O(3^5)])
3196
sage: pari(pol).padicprec(3)
3197
4
3198
"""
3199
cdef gen t0 = objtogen(p)
3200
pari_catch_sig_on()
3201
cdef long prec = padicprec(x.g, t0.g)
3202
pari_catch_sig_off()
3203
return prec
3204
3205
def padicprime(gen x):
3206
"""
3207
The uniformizer of the p-adic ring this element lies in, as a t_INT.
3208
3209
INPUT:
3210
3211
- ``x`` - gen, of type t_PADIC
3212
3213
OUTPUT:
3214
3215
- ``p`` - gen, of type t_INT
3216
3217
EXAMPLES::
3218
3219
sage: K = Qp(11,5)
3220
sage: x = K(11^-10 + 5*11^-7 + 11^-6)
3221
sage: y = pari(x)
3222
sage: y.padicprime()
3223
11
3224
sage: y.padicprime().type()
3225
't_INT'
3226
"""
3227
pari_catch_sig_on()
3228
return P.new_gen(gel(x.g, 2))
3229
3230
def permtonum(gen x):
3231
"""
3232
permtonum(x): Return the ordinal (between 1 and n!) of permutation
3233
vector x. ??? Huh ??? say more. what is a perm vector. 0 to n-1 or
3234
1-n.
3235
3236
INPUT:
3237
3238
3239
- ``x`` - gen (vector of integers)
3240
3241
3242
OUTPUT:
3243
3244
3245
- ``gen`` - integer
3246
3247
3248
EXAMPLES:
3249
"""
3250
if typ(x.g) != t_VEC:
3251
raise TypeError, "x (=%s) must be of type t_VEC, but is of type %s."%(x,x.type())
3252
pari_catch_sig_on()
3253
return P.new_gen(permtonum(x.g))
3254
3255
def precision(gen x, long n=-1):
3256
"""
3257
precision(x,n): Change the precision of x to be n, where n is a
3258
C-integer). If n is omitted, output the real precision of x.
3259
3260
INPUT:
3261
3262
3263
- ``x`` - gen
3264
3265
- ``n`` - (optional) int
3266
3267
3268
OUTPUT: nothing or gen if n is omitted
3269
3270
EXAMPLES:
3271
"""
3272
if n <= -1:
3273
return precision(x.g)
3274
pari_catch_sig_on()
3275
return P.new_gen(precision0(x.g, n))
3276
3277
def random(gen N):
3278
r"""
3279
``random(N=2^31)``: Return a pseudo-random integer
3280
between 0 and `N-1`.
3281
3282
INPUT:
3283
3284
3285
-``N`` - gen, integer
3286
3287
3288
OUTPUT:
3289
3290
3291
- ``gen`` - integer
3292
3293
3294
EXAMPLES:
3295
"""
3296
if typ(N.g) != t_INT:
3297
raise TypeError, "x (=%s) must be of type t_INT, but is of type %s."%(N,N.type())
3298
pari_catch_sig_on()
3299
return P.new_gen(genrand(N.g))
3300
3301
def real(gen x):
3302
"""
3303
real(x): Return the real part of x.
3304
3305
INPUT:
3306
3307
3308
- ``x`` - gen
3309
3310
3311
OUTPUT: gen
3312
3313
EXAMPLES:
3314
"""
3315
pari_catch_sig_on()
3316
return P.new_gen(greal(x.g))
3317
3318
def round(gen x, estimate=False):
3319
"""
3320
round(x,estimate=False): If x is a real number, returns x rounded
3321
to the nearest integer (rounding up). If the optional argument
3322
estimate is True, also returns the binary exponent e of the
3323
difference between the original and the rounded value (the
3324
"fractional part") (this is the integer ceiling of log_2(error)).
3325
3326
When x is a general PARI object, this function returns the result
3327
of rounding every coefficient at every level of PARI object. Note
3328
that this is different than what the truncate function does (see
3329
the example below).
3330
3331
One use of round is to get exact results after a long approximate
3332
computation, when theory tells you that the coefficients must be
3333
integers.
3334
3335
INPUT:
3336
3337
3338
- ``x`` - gen
3339
3340
- ``estimate`` - (optional) bool, False by default
3341
3342
3343
OUTPUT:
3344
3345
- if estimate is False, return a single gen.
3346
3347
- if estimate is True, return rounded version of x and error
3348
estimate in bits, both as gens.
3349
3350
EXAMPLES::
3351
3352
sage: pari('1.5').round()
3353
2
3354
sage: pari('1.5').round(True)
3355
(2, -1)
3356
sage: pari('1.5 + 2.1*I').round()
3357
2 + 2*I
3358
sage: pari('1.0001').round(True)
3359
(1, -14)
3360
sage: pari('(2.4*x^2 - 1.7)/x').round()
3361
(2*x^2 - 2)/x
3362
sage: pari('(2.4*x^2 - 1.7)/x').truncate()
3363
2.40000000000000*x
3364
"""
3365
cdef int n
3366
cdef long e
3367
cdef gen y
3368
pari_catch_sig_on()
3369
if not estimate:
3370
return P.new_gen(ground(x.g))
3371
y = P.new_gen(grndtoi(x.g, &e))
3372
return y, e
3373
3374
def simplify(gen x):
3375
"""
3376
simplify(x): Simplify the object x as much as possible, and return
3377
the result.
3378
3379
A complex or quadratic number whose imaginary part is an exact 0
3380
(i.e., not an approximate one such as O(3) or 0.E-28) is converted
3381
to its real part, and a a polynomial of degree 0 is converted to
3382
its constant term. Simplification occurs recursively.
3383
3384
This function is useful before using arithmetic functions, which
3385
expect integer arguments:
3386
3387
EXAMPLES::
3388
3389
sage: y = pari('y')
3390
sage: x = pari('9') + y - y
3391
sage: x
3392
9
3393
sage: x.type()
3394
't_POL'
3395
sage: x.factor()
3396
matrix(0,2)
3397
sage: pari('9').factor()
3398
Mat([3, 2])
3399
sage: x.simplify()
3400
9
3401
sage: x.simplify().factor()
3402
Mat([3, 2])
3403
sage: x = pari('1.5 + 0*I')
3404
sage: x.type()
3405
't_REAL'
3406
sage: x.simplify()
3407
1.50000000000000
3408
sage: y = x.simplify()
3409
sage: y.type()
3410
't_REAL'
3411
"""
3412
pari_catch_sig_on()
3413
return P.new_gen(simplify(x.g))
3414
3415
def sizeword(gen x):
3416
"""
3417
Return the total number of machine words occupied by the
3418
complete tree of the object x. A machine word is 32 or
3419
64 bits, depending on the computer.
3420
3421
INPUT:
3422
3423
- ``x`` - gen
3424
3425
OUTPUT: int (a Python int)
3426
3427
EXAMPLES::
3428
3429
sage: pari('0').sizeword()
3430
2
3431
sage: pari('1').sizeword()
3432
3
3433
sage: pari('1000000').sizeword()
3434
3
3435
sage: pari('10^100').sizeword()
3436
13 # 32-bit
3437
8 # 64-bit
3438
sage: pari(RDF(1.0)).sizeword()
3439
4 # 32-bit
3440
3 # 64-bit
3441
sage: pari('x').sizeword()
3442
9
3443
sage: pari('x^20').sizeword()
3444
66
3445
sage: pari('[x, I]').sizeword()
3446
20
3447
"""
3448
return gsizeword(x.g)
3449
3450
def sizebyte(gen x):
3451
"""
3452
Return the total number of bytes occupied by the complete tree
3453
of the object x. Note that this number depends on whether the
3454
computer is 32-bit or 64-bit.
3455
3456
INPUT:
3457
3458
- ``x`` - gen
3459
3460
OUTPUT: int (a Python int)
3461
3462
EXAMPLE::
3463
3464
sage: pari('1').sizebyte()
3465
12 # 32-bit
3466
24 # 64-bit
3467
"""
3468
return gsizebyte(x.g)
3469
3470
def sizedigit(gen x):
3471
"""
3472
sizedigit(x): Return a quick estimate for the maximal number of
3473
decimal digits before the decimal point of any component of x.
3474
3475
INPUT:
3476
3477
3478
- ``x`` - gen
3479
3480
3481
OUTPUT:
3482
3483
3484
- ``int`` - Python integer
3485
3486
3487
EXAMPLES::
3488
3489
sage: x = pari('10^100')
3490
sage: x.Str().length()
3491
101
3492
sage: x.sizedigit()
3493
101
3494
3495
Note that digits after the decimal point are ignored.
3496
3497
::
3498
3499
sage: x = pari('1.234')
3500
sage: x
3501
1.23400000000000
3502
sage: x.sizedigit()
3503
1
3504
3505
The estimate can be one too big::
3506
3507
sage: pari('7234.1').sizedigit()
3508
4
3509
sage: pari('9234.1').sizedigit()
3510
5
3511
"""
3512
return sizedigit(x.g)
3513
3514
def truncate(gen x, estimate=False):
3515
"""
3516
truncate(x,estimate=False): Return the truncation of x. If estimate
3517
is True, also return the number of error bits.
3518
3519
When x is in the real numbers, this means that the part after the
3520
decimal point is chopped away, e is the binary exponent of the
3521
difference between the original and truncated value (the
3522
"fractional part"). If x is a rational function, the result is the
3523
integer part (Euclidean quotient of numerator by denominator) and
3524
if requested the error estimate is 0.
3525
3526
When truncate is applied to a power series (in X), it transforms it
3527
into a polynomial or a rational function with denominator a power
3528
of X, by chopping away the `O(X^k)`. Similarly, when
3529
applied to a p-adic number, it transforms it into an integer or a
3530
rational number by chopping away the `O(p^k)`.
3531
3532
INPUT:
3533
3534
3535
- ``x`` - gen
3536
3537
- ``estimate`` - (optional) bool, which is False by
3538
default
3539
3540
3541
OUTPUT:
3542
3543
- if estimate is False, return a single gen.
3544
3545
- if estimate is True, return rounded version of x and error
3546
estimate in bits, both as gens.
3547
3548
EXAMPLES::
3549
3550
sage: pari('(x^2+1)/x').round()
3551
(x^2 + 1)/x
3552
sage: pari('(x^2+1)/x').truncate()
3553
x
3554
sage: pari('1.043').truncate()
3555
1
3556
sage: pari('1.043').truncate(True)
3557
(1, -5)
3558
sage: pari('1.6').truncate()
3559
1
3560
sage: pari('1.6').round()
3561
2
3562
sage: pari('1/3 + 2 + 3^2 + O(3^3)').truncate()
3563
34/3
3564
sage: pari('sin(x+O(x^10))').truncate()
3565
1/362880*x^9 - 1/5040*x^7 + 1/120*x^5 - 1/6*x^3 + x
3566
sage: pari('sin(x+O(x^10))').round() # each coefficient has abs < 1
3567
x + O(x^10)
3568
"""
3569
cdef long e
3570
cdef gen y
3571
pari_catch_sig_on()
3572
if not estimate:
3573
return P.new_gen(gtrunc(x.g))
3574
y = P.new_gen(gcvtoi(x.g, &e))
3575
return y, e
3576
3577
def valuation(gen x, p):
3578
"""
3579
valuation(x,p): Return the valuation of x with respect to p.
3580
3581
The valuation is the highest exponent of p dividing x.
3582
3583
- If p is an integer, x must be an integer, an intmod whose
3584
modulus is divisible by p, a rational number, a p-adic
3585
number, or a polynomial or power series in which case the
3586
valuation is the minimum of the valuations of the
3587
coefficients.
3588
3589
- If p is a polynomial, x must be a polynomial or a rational
3590
function. If p is a monomial then x may also be a power
3591
series.
3592
3593
- If x is a vector, complex or quadratic number, then the
3594
valuation is the minimum of the component valuations.
3595
3596
- If x = 0, the result is `2^31-1` on 32-bit machines or
3597
`2^63-1` on 64-bit machines if x is an exact
3598
object. If x is a p-adic number or power series, the result
3599
is the exponent of the zero.
3600
3601
INPUT:
3602
3603
3604
- ``x`` - gen
3605
3606
- ``p`` - coercible to gen
3607
3608
3609
OUTPUT:
3610
3611
3612
- ``gen`` - integer
3613
3614
3615
EXAMPLES::
3616
3617
sage: pari(9).valuation(3)
3618
2
3619
sage: pari(9).valuation(9)
3620
1
3621
sage: x = pari(9).Mod(27); x.valuation(3)
3622
2
3623
sage: pari('5/3').valuation(3)
3624
-1
3625
sage: pari('9 + 3*x + 15*x^2').valuation(3)
3626
1
3627
sage: pari([9,3,15]).valuation(3)
3628
1
3629
sage: pari('9 + 3*x + 15*x^2 + O(x^5)').valuation(3)
3630
1
3631
3632
::
3633
3634
sage: pari('x^2*(x+1)^3').valuation(pari('x+1'))
3635
3
3636
sage: pari('x + O(x^5)').valuation('x')
3637
1
3638
sage: pari('2*x^2 + O(x^5)').valuation('x')
3639
2
3640
3641
::
3642
3643
sage: pari(0).valuation(3)
3644
2147483647 # 32-bit
3645
9223372036854775807 # 64-bit
3646
"""
3647
cdef gen t0 = objtogen(p)
3648
pari_catch_sig_on()
3649
v = ggval(x.g, t0.g)
3650
pari_catch_sig_off()
3651
return v
3652
3653
def _valp(gen x):
3654
"""
3655
Return the valuation of x where x is a p-adic number (t_PADIC)
3656
or a laurent series (t_SER). If x is a different type, this
3657
will give a bogus number.
3658
3659
EXAMPLES::
3660
3661
sage: pari('1/x^2 + O(x^10)')._valp()
3662
-2
3663
sage: pari('O(x^10)')._valp()
3664
10
3665
sage: pari('(1145234796 + O(3^10))/771966234')._valp()
3666
-2
3667
sage: pari('O(2^10)')._valp()
3668
10
3669
sage: pari('x')._valp() # random
3670
-35184372088832
3671
"""
3672
# This is a simple macro, so we don't need pari_catch_sig_on()
3673
return valp(x.g)
3674
3675
def variable(gen x):
3676
"""
3677
variable(x): Return the main variable of the object x, or p if x is
3678
a p-adic number.
3679
3680
This function raises a TypeError exception on scalars, i.e., on
3681
objects with no variable associated to them.
3682
3683
INPUT:
3684
3685
3686
- ``x`` - gen
3687
3688
3689
OUTPUT: gen
3690
3691
EXAMPLES::
3692
3693
sage: pari('x^2 + x -2').variable()
3694
x
3695
sage: pari('1+2^3 + O(2^5)').variable()
3696
2
3697
sage: pari('x+y0').variable()
3698
x
3699
sage: pari('y0+z0').variable()
3700
y0
3701
"""
3702
pari_catch_sig_on()
3703
return P.new_gen(gpolvar(x.g))
3704
3705
3706
###########################################
3707
# 3: TRANSCENDENTAL functions
3708
# AUTHORS: Pyrex Code, docs -- Justin Walker ([email protected])
3709
# Examples, docs -- William Stein
3710
###########################################
3711
3712
def abs(gen x, unsigned long precision=0):
3713
"""
3714
Returns the absolute value of x (its modulus, if x is complex).
3715
Rational functions are not allowed. Contrary to most transcendental
3716
functions, an exact argument is not converted to a real number
3717
before applying abs and an exact result is returned if possible.
3718
3719
EXAMPLES::
3720
3721
sage: x = pari("-27.1")
3722
sage: x.abs()
3723
27.1000000000000
3724
sage: pari('1 + I').abs(precision=128).sage()
3725
1.4142135623730950488016887242096980786
3726
3727
If x is a polynomial, returns -x if the leading coefficient is real
3728
and negative else returns x. For a power series, the constant
3729
coefficient is considered instead.
3730
3731
EXAMPLES::
3732
3733
sage: pari('x-1.2*x^2').abs()
3734
1.20000000000000*x^2 - x
3735
sage: pari('-2 + t + O(t^2)').abs()
3736
2 - t + O(t^2)
3737
"""
3738
pari_catch_sig_on()
3739
return P.new_gen(gabs(x.g, prec_bits_to_words(precision)))
3740
3741
def acos(gen x, unsigned long precision=0):
3742
r"""
3743
The principal branch of `\cos^{-1}(x)`, so that
3744
`\RR e(\mathrm{acos}(x))` belongs to `[0,Pi]`. If `x`
3745
is real and `|x| > 1`, then `\mathrm{acos}(x)` is complex.
3746
3747
If `x` is an exact argument, it is first converted to a
3748
real or complex number using the optional parameter precision (in
3749
bits). If `x` is inexact (e.g. real), its own precision is
3750
used in the computation, and the parameter precision is ignored.
3751
3752
EXAMPLES::
3753
3754
sage: pari(0.5).acos()
3755
1.04719755119660
3756
sage: pari(1/2).acos()
3757
1.04719755119660
3758
sage: pari(1.1).acos()
3759
0.443568254385115*I
3760
sage: C.<i> = ComplexField()
3761
sage: pari(1.1+i).acos()
3762
0.849343054245252 - 1.09770986682533*I
3763
"""
3764
pari_catch_sig_on()
3765
return P.new_gen(gacos(x.g, prec_bits_to_words(precision)))
3766
3767
def acosh(gen x, unsigned long precision=0):
3768
r"""
3769
The principal branch of `\cosh^{-1}(x)`, so that
3770
`\Im(\mathrm{acosh}(x))` belongs to `[0,Pi]`. If
3771
`x` is real and `x < 1`, then
3772
`\mathrm{acosh}(x)` is complex.
3773
3774
If `x` is an exact argument, it is first converted to a
3775
real or complex number using the optional parameter precision (in
3776
bits). If `x` is inexact (e.g. real), its own precision is
3777
used in the computation, and the parameter precision is ignored.
3778
3779
EXAMPLES::
3780
3781
sage: pari(2).acosh()
3782
1.31695789692482
3783
sage: pari(0).acosh()
3784
1.57079632679490*I
3785
sage: C.<i> = ComplexField()
3786
sage: pari(i).acosh()
3787
0.881373587019543 + 1.57079632679490*I
3788
"""
3789
pari_catch_sig_on()
3790
return P.new_gen(gach(x.g, prec_bits_to_words(precision)))
3791
3792
def agm(gen x, y, unsigned long precision=0):
3793
r"""
3794
The arithmetic-geometric mean of x and y. In the case of complex or
3795
negative numbers, the principal square root is always chosen.
3796
p-adic or power series arguments are also allowed. Note that a
3797
p-adic AGM exists only if x/y is congruent to 1 modulo p (modulo 16
3798
for p=2). x and y cannot both be vectors or matrices.
3799
3800
If any of `x` or `y` is an exact argument, it is
3801
first converted to a real or complex number using the optional
3802
parameter precision (in bits). If the arguments are inexact (e.g.
3803
real), the smallest of their two precisions is used in the
3804
computation, and the parameter precision is ignored.
3805
3806
EXAMPLES::
3807
3808
sage: pari(2).agm(2)
3809
2.00000000000000
3810
sage: pari(0).agm(1)
3811
0
3812
sage: pari(1).agm(2)
3813
1.45679103104691
3814
sage: C.<i> = ComplexField()
3815
sage: pari(1+i).agm(-3)
3816
-0.964731722290876 + 1.15700282952632*I
3817
"""
3818
cdef gen t0 = objtogen(y)
3819
pari_catch_sig_on()
3820
return P.new_gen(agm(x.g, t0.g, prec_bits_to_words(precision)))
3821
3822
def arg(gen x, unsigned long precision=0):
3823
r"""
3824
arg(x): argument of x,such that `-\pi < \arg(x) \leq \pi`.
3825
3826
If `x` is an exact argument, it is first converted to a
3827
real or complex number using the optional parameter precision (in
3828
bits). If `x` is inexact (e.g. real), its own precision is
3829
used in the computation, and the parameter precision is ignored.
3830
3831
EXAMPLES::
3832
3833
sage: C.<i> = ComplexField()
3834
sage: pari(2+i).arg()
3835
0.463647609000806
3836
"""
3837
pari_catch_sig_on()
3838
return P.new_gen(garg(x.g, prec_bits_to_words(precision)))
3839
3840
def asin(gen x, unsigned long precision=0):
3841
r"""
3842
The principal branch of `\sin^{-1}(x)`, so that
3843
`\RR e(\mathrm{asin}(x))` belongs to `[-\pi/2,\pi/2]`. If
3844
`x` is real and `|x| > 1` then `\mathrm{asin}(x)`
3845
is complex.
3846
3847
If `x` is an exact argument, it is first converted to a
3848
real or complex number using the optional parameter precision (in
3849
bits). If `x` is inexact (e.g. real), its own precision is
3850
used in the computation, and the parameter precision is ignored.
3851
3852
EXAMPLES::
3853
3854
sage: pari(pari(0.5).sin()).asin()
3855
0.500000000000000
3856
sage: pari(2).asin()
3857
1.57079632679490 - 1.31695789692482*I
3858
"""
3859
pari_catch_sig_on()
3860
return P.new_gen(gasin(x.g, prec_bits_to_words(precision)))
3861
3862
def asinh(gen x, unsigned long precision=0):
3863
r"""
3864
The principal branch of `\sinh^{-1}(x)`, so that
3865
`\Im(\mathrm{asinh}(x))` belongs to `[-\pi/2,\pi/2]`.
3866
3867
If `x` is an exact argument, it is first converted to a
3868
real or complex number using the optional parameter precision (in
3869
bits). If `x` is inexact (e.g. real), its own precision is
3870
used in the computation, and the parameter precision is ignored.
3871
3872
EXAMPLES::
3873
3874
sage: pari(2).asinh()
3875
1.44363547517881
3876
sage: C.<i> = ComplexField()
3877
sage: pari(2+i).asinh()
3878
1.52857091948100 + 0.427078586392476*I
3879
"""
3880
pari_catch_sig_on()
3881
return P.new_gen(gash(x.g, prec_bits_to_words(precision)))
3882
3883
def atan(gen x, unsigned long precision=0):
3884
r"""
3885
The principal branch of `\tan^{-1}(x)`, so that
3886
`\RR e(\mathrm{atan}(x))` belongs to `]-\pi/2, \pi/2[`.
3887
3888
If `x` is an exact argument, it is first converted to a
3889
real or complex number using the optional parameter precision (in
3890
bits). If `x` is inexact (e.g. real), its own precision is
3891
used in the computation, and the parameter precision is ignored.
3892
3893
EXAMPLES::
3894
3895
sage: pari(1).atan()
3896
0.785398163397448
3897
sage: C.<i> = ComplexField()
3898
sage: pari(1.5+i).atan()
3899
1.10714871779409 + 0.255412811882995*I
3900
"""
3901
pari_catch_sig_on()
3902
return P.new_gen(gatan(x.g, prec_bits_to_words(precision)))
3903
3904
def atanh(gen x, unsigned long precision=0):
3905
r"""
3906
The principal branch of `\tanh^{-1}(x)`, so that
3907
`\Im(\mathrm{atanh}(x))` belongs to `]-\pi/2,\pi/2]`. If
3908
`x` is real and `|x| > 1` then `\mathrm{atanh}(x)`
3909
is complex.
3910
3911
If `x` is an exact argument, it is first converted to a
3912
real or complex number using the optional parameter precision (in
3913
bits). If `x` is inexact (e.g. real), its own precision is
3914
used in the computation, and the parameter precision is ignored.
3915
3916
EXAMPLES::
3917
3918
sage: pari(0).atanh()
3919
0.E-19
3920
sage: pari(2).atanh()
3921
0.549306144334055 - 1.57079632679490*I
3922
"""
3923
pari_catch_sig_on()
3924
return P.new_gen(gath(x.g, prec_bits_to_words(precision)))
3925
3926
def bernfrac(gen x):
3927
r"""
3928
The Bernoulli number `B_x`, where `B_0 = 1`,
3929
`B_1 = -1/2`, `B_2 = 1/6,\ldots,` expressed as a
3930
rational number. The argument `x` should be of type
3931
integer.
3932
3933
EXAMPLES::
3934
3935
sage: pari(18).bernfrac()
3936
43867/798
3937
sage: [pari(n).bernfrac() for n in range(10)]
3938
[1, -1/2, 1/6, 0, -1/30, 0, 1/42, 0, -1/30, 0]
3939
"""
3940
pari_catch_sig_on()
3941
return P.new_gen(bernfrac(x))
3942
3943
def bernreal(gen x, unsigned long precision=0):
3944
r"""
3945
The Bernoulli number `B_x`, as for the function bernfrac,
3946
but `B_x` is returned as a real number (with the current
3947
precision).
3948
3949
EXAMPLES::
3950
3951
sage: pari(18).bernreal()
3952
54.9711779448622
3953
sage: pari(18).bernreal(precision=192).sage()
3954
54.9711779448621553884711779448621553884711779448621553885
3955
"""
3956
pari_catch_sig_on()
3957
return P.new_gen(bernreal(x, prec_bits_to_words(precision)))
3958
3959
def bernvec(gen x):
3960
r"""
3961
Creates a vector containing, as rational numbers, the Bernoulli
3962
numbers `B_0, B_2,\ldots, B_{2x}`. This routine is
3963
obsolete. Use bernfrac instead each time you need a Bernoulli
3964
number in exact form.
3965
3966
Note: this routine is implemented using repeated independent calls
3967
to bernfrac, which is faster than the standard recursion in exact
3968
arithmetic.
3969
3970
EXAMPLES::
3971
3972
sage: pari(8).bernvec()
3973
[1, 1/6, -1/30, 1/42, -1/30, 5/66, -691/2730, 7/6, -3617/510]
3974
sage: [pari(2*n).bernfrac() for n in range(9)]
3975
[1, 1/6, -1/30, 1/42, -1/30, 5/66, -691/2730, 7/6, -3617/510]
3976
"""
3977
pari_catch_sig_on()
3978
return P.new_gen(bernvec(x))
3979
3980
def besselh1(gen nu, x, unsigned long precision=0):
3981
r"""
3982
The `H^1`-Bessel function of index `\nu` and
3983
argument `x`.
3984
3985
If `nu` or `x` is an exact argument, it is first
3986
converted to a real or complex number using the optional parameter
3987
precision (in bits). If the arguments are inexact (e.g. real), the
3988
smallest of their precisions is used in the computation, and the
3989
parameter precision is ignored.
3990
3991
EXAMPLES::
3992
3993
sage: pari(2).besselh1(3)
3994
0.486091260585891 - 0.160400393484924*I
3995
"""
3996
cdef gen t0 = objtogen(x)
3997
pari_catch_sig_on()
3998
return P.new_gen(hbessel1(nu.g, t0.g, prec_bits_to_words(precision)))
3999
4000
def besselh2(gen nu, x, unsigned long precision=0):
4001
r"""
4002
The `H^2`-Bessel function of index `\nu` and
4003
argument `x`.
4004
4005
If `nu` or `x` is an exact argument, it is first
4006
converted to a real or complex number using the optional parameter
4007
precision (in bits). If the arguments are inexact (e.g. real), the
4008
smallest of their precisions is used in the computation, and the
4009
parameter precision is ignored.
4010
4011
EXAMPLES::
4012
4013
sage: pari(2).besselh2(3)
4014
0.486091260585891 + 0.160400393484924*I
4015
"""
4016
cdef gen t0 = objtogen(x)
4017
pari_catch_sig_on()
4018
return P.new_gen(hbessel2(nu.g, t0.g, prec_bits_to_words(precision)))
4019
4020
def besselj(gen nu, x, unsigned long precision=0):
4021
r"""
4022
Bessel J function (Bessel function of the first kind), with index
4023
`\nu` and argument `x`. If `x` converts to
4024
a power series, the initial factor
4025
`(x/2)^{\nu}/\Gamma(\nu+1)` is omitted (since it cannot be
4026
represented in PARI when `\nu` is not integral).
4027
4028
If `nu` or `x` is an exact argument, it is first
4029
converted to a real or complex number using the optional parameter
4030
precision (in bits). If the arguments are inexact (e.g. real), the
4031
smallest of their precisions is used in the computation, and the
4032
parameter precision is ignored.
4033
4034
EXAMPLES::
4035
4036
sage: pari(2).besselj(3)
4037
0.486091260585891
4038
"""
4039
cdef gen t0 = objtogen(x)
4040
pari_catch_sig_on()
4041
return P.new_gen(jbessel(nu.g, t0.g, prec_bits_to_words(precision)))
4042
4043
def besseljh(gen nu, x, unsigned long precision=0):
4044
"""
4045
J-Bessel function of half integral index (Spherical Bessel
4046
function of the first kind). More precisely, besseljh(n,x) computes
4047
`J_{n+1/2}(x)` where n must an integer, and x is any
4048
complex value. In the current implementation (PARI, version
4049
2.2.11), this function is not very accurate when `x` is
4050
small.
4051
4052
If `nu` or `x` is an exact argument, it is first
4053
converted to a real or complex number using the optional parameter
4054
precision (in bits). If the arguments are inexact (e.g. real), the
4055
smallest of their precisions is used in the computation, and the
4056
parameter precision is ignored.
4057
4058
EXAMPLES::
4059
4060
sage: pari(2).besseljh(3)
4061
0.4127100324 # 32-bit
4062
0.412710032209716 # 64-bit
4063
"""
4064
cdef gen t0 = objtogen(x)
4065
pari_catch_sig_on()
4066
return P.new_gen(jbesselh(nu.g, t0.g, prec_bits_to_words(precision)))
4067
4068
def besseli(gen nu, x, unsigned long precision=0):
4069
r"""
4070
Bessel I function (Bessel function of the second kind), with index
4071
`\nu` and argument `x`. If `x` converts to
4072
a power series, the initial factor
4073
`(x/2)^{\nu}/\Gamma(\nu+1)` is omitted (since it cannot be
4074
represented in PARI when `\nu` is not integral).
4075
4076
If `nu` or `x` is an exact argument, it is first
4077
converted to a real or complex number using the optional parameter
4078
precision (in bits). If the arguments are inexact (e.g. real), the
4079
smallest of their precisions is used in the computation, and the
4080
parameter precision is ignored.
4081
4082
EXAMPLES::
4083
4084
sage: pari(2).besseli(3)
4085
2.24521244092995
4086
sage: C.<i> = ComplexField()
4087
sage: pari(2).besseli(3+i)
4088
1.12539407613913 + 2.08313822670661*I
4089
"""
4090
cdef gen t0 = objtogen(x)
4091
pari_catch_sig_on()
4092
return P.new_gen(ibessel(nu.g, t0.g, prec_bits_to_words(precision)))
4093
4094
def besselk(gen nu, x, long flag=0, unsigned long precision=0):
4095
"""
4096
nu.besselk(x, flag=0): K-Bessel function (modified Bessel function
4097
of the second kind) of index nu, which can be complex, and argument
4098
x.
4099
4100
If `nu` or `x` is an exact argument, it is first
4101
converted to a real or complex number using the optional parameter
4102
precision (in bits). If the arguments are inexact (e.g. real), the
4103
smallest of their precisions is used in the computation, and the
4104
parameter precision is ignored.
4105
4106
INPUT:
4107
4108
4109
- ``nu`` - a complex number
4110
4111
- ``x`` - real number (positive or negative)
4112
4113
- ``flag`` - default: 0 or 1: use hyperu (hyperu is
4114
much slower for small x, and doesn't work for negative x).
4115
4116
4117
EXAMPLES::
4118
4119
sage: C.<i> = ComplexField()
4120
sage: pari(2+i).besselk(3)
4121
0.0455907718407551 + 0.0289192946582081*I
4122
4123
::
4124
4125
sage: pari(2+i).besselk(-3)
4126
-4.34870874986752 - 5.38744882697109*I
4127
4128
::
4129
4130
sage: pari(2+i).besselk(300, flag=1)
4131
3.74224603319728 E-132 + 2.49071062641525 E-134*I
4132
"""
4133
cdef gen t0 = objtogen(x)
4134
pari_catch_sig_on()
4135
return P.new_gen(kbessel(nu.g, t0.g, prec_bits_to_words(precision)))
4136
4137
def besseln(gen nu, x, unsigned long precision=0):
4138
"""
4139
nu.besseln(x): Bessel N function (Spherical Bessel function of the
4140
second kind) of index nu and argument x.
4141
4142
If `nu` or `x` is an exact argument, it is first
4143
converted to a real or complex number using the optional parameter
4144
precision (in bits). If the arguments are inexact (e.g. real), the
4145
smallest of their precisions is used in the computation, and the
4146
parameter precision is ignored.
4147
4148
EXAMPLES::
4149
4150
sage: C.<i> = ComplexField()
4151
sage: pari(2+i).besseln(3)
4152
-0.280775566958244 - 0.486708533223726*I
4153
"""
4154
cdef gen t0 = objtogen(x)
4155
pari_catch_sig_on()
4156
return P.new_gen(nbessel(nu.g, t0.g, prec_bits_to_words(precision)))
4157
4158
def cos(gen x, unsigned long precision=0):
4159
"""
4160
The cosine function.
4161
4162
If `x` is an exact argument, it is first converted to a
4163
real or complex number using the optional parameter precision (in
4164
bits). If `x` is inexact (e.g. real), its own precision is
4165
used in the computation, and the parameter precision is ignored.
4166
4167
EXAMPLES::
4168
4169
sage: pari(1.5).cos()
4170
0.0707372016677029
4171
sage: C.<i> = ComplexField()
4172
sage: pari(1+i).cos()
4173
0.833730025131149 - 0.988897705762865*I
4174
sage: pari('x+O(x^8)').cos()
4175
1 - 1/2*x^2 + 1/24*x^4 - 1/720*x^6 + 1/40320*x^8 + O(x^9)
4176
"""
4177
pari_catch_sig_on()
4178
return P.new_gen(gcos(x.g, prec_bits_to_words(precision)))
4179
4180
def cosh(gen x, unsigned long precision=0):
4181
"""
4182
The hyperbolic cosine function.
4183
4184
If `x` is an exact argument, it is first converted to a
4185
real or complex number using the optional parameter precision (in
4186
bits). If `x` is inexact (e.g. real), its own precision is
4187
used in the computation, and the parameter precision is ignored.
4188
4189
EXAMPLES::
4190
4191
sage: pari(1.5).cosh()
4192
2.35240961524325
4193
sage: C.<i> = ComplexField()
4194
sage: pari(1+i).cosh()
4195
0.833730025131149 + 0.988897705762865*I
4196
sage: pari('x+O(x^8)').cosh()
4197
1 + 1/2*x^2 + 1/24*x^4 + 1/720*x^6 + O(x^8)
4198
"""
4199
pari_catch_sig_on()
4200
return P.new_gen(gch(x.g, prec_bits_to_words(precision)))
4201
4202
def cotan(gen x, unsigned long precision=0):
4203
"""
4204
The cotangent of x.
4205
4206
If `x` is an exact argument, it is first converted to a
4207
real or complex number using the optional parameter precision (in
4208
bits). If `x` is inexact (e.g. real), its own precision is
4209
used in the computation, and the parameter precision is ignored.
4210
4211
EXAMPLES::
4212
4213
sage: pari(5).cotan()
4214
-0.295812915532746
4215
4216
Computing the cotangent of `\pi` doesn't raise an error,
4217
but instead just returns a very large (positive or negative)
4218
number.
4219
4220
::
4221
4222
sage: x = RR(pi)
4223
sage: pari(x).cotan() # random
4224
-8.17674825 E15
4225
"""
4226
pari_catch_sig_on()
4227
return P.new_gen(gcotan(x.g, prec_bits_to_words(precision)))
4228
4229
def dilog(gen x, unsigned long precision=0):
4230
r"""
4231
The principal branch of the dilogarithm of `x`, i.e. the
4232
analytic continuation of the power series
4233
`\log_2(x) = \sum_{n>=1} x^n/n^2`.
4234
4235
If `x` is an exact argument, it is first converted to a
4236
real or complex number using the optional parameter precision (in
4237
bits). If `x` is inexact (e.g. real), its own precision is
4238
used in the computation, and the parameter precision is ignored.
4239
4240
EXAMPLES::
4241
4242
sage: pari(1).dilog()
4243
1.64493406684823
4244
sage: C.<i> = ComplexField()
4245
sage: pari(1+i).dilog()
4246
0.616850275068085 + 1.46036211675312*I
4247
"""
4248
pari_catch_sig_on()
4249
return P.new_gen(dilog(x.g, prec_bits_to_words(precision)))
4250
4251
def eint1(gen x, long n=0, unsigned long precision=0):
4252
r"""
4253
x.eint1(n): exponential integral E1(x):
4254
4255
.. math::
4256
4257
\int_{x}^{\infty} \frac{e^{-t}}{t} dt
4258
4259
4260
If n is present, output the vector [eint1(x), eint1(2\*x), ...,
4261
eint1(n\*x)]. This is faster than repeatedly calling eint1(i\*x).
4262
4263
If `x` is an exact argument, it is first converted to a
4264
real or complex number using the optional parameter precision (in
4265
bits). If `x` is inexact (e.g. real), its own precision is
4266
used in the computation, and the parameter precision is ignored.
4267
4268
REFERENCE:
4269
4270
- See page 262, Prop 5.6.12, of Cohen's book "A Course in
4271
Computational Algebraic Number Theory".
4272
4273
EXAMPLES:
4274
"""
4275
pari_catch_sig_on()
4276
if n <= 0:
4277
return P.new_gen(eint1(x.g, prec_bits_to_words(precision)))
4278
else:
4279
return P.new_gen(veceint1(x.g, stoi(n), prec_bits_to_words(precision)))
4280
4281
def erfc(gen x, unsigned long precision=0):
4282
r"""
4283
Return the complementary error function:
4284
4285
.. math::
4286
4287
(2/\sqrt{\pi}) \int_{x}^{\infty} e^{-t^2} dt.
4288
4289
4290
4291
If `x` is an exact argument, it is first converted to a
4292
real or complex number using the optional parameter precision (in
4293
bits). If `x` is inexact (e.g. real), its own precision is
4294
used in the computation, and the parameter precision is ignored.
4295
4296
EXAMPLES::
4297
4298
sage: pari(1).erfc()
4299
0.157299207050285
4300
"""
4301
pari_catch_sig_on()
4302
return P.new_gen(gerfc(x.g, prec_bits_to_words(precision)))
4303
4304
def eta(gen x, long flag=0, unsigned long precision=0):
4305
r"""
4306
x.eta(flag=0): if flag=0, `\eta` function without the
4307
`q^{1/24}`; otherwise `\eta` of the complex number
4308
`x` in the upper half plane intelligently computed using
4309
`\mathrm{SL}(2,\ZZ)` transformations.
4310
4311
DETAILS: This functions computes the following. If the input
4312
`x` is a complex number with positive imaginary part, the
4313
result is `\prod_{n=1}^{\infty} (q-1^n)`, where
4314
`q=e^{2 i \pi x}`. If `x` is a power series
4315
(or can be converted to a power series) with positive valuation,
4316
the result is `\prod_{n=1}^{\infty} (1-x^n)`.
4317
4318
If `x` is an exact argument, it is first converted to a
4319
real or complex number using the optional parameter precision (in
4320
bits). If `x` is inexact (e.g. real), its own precision is
4321
used in the computation, and the parameter precision is ignored.
4322
4323
EXAMPLES::
4324
4325
sage: C.<i> = ComplexField()
4326
sage: pari(i).eta()
4327
0.998129069925959
4328
"""
4329
pari_catch_sig_on()
4330
if flag == 1:
4331
return P.new_gen(trueeta(x.g, prec_bits_to_words(precision)))
4332
return P.new_gen(eta(x.g, prec_bits_to_words(precision)))
4333
4334
def exp(gen self, unsigned long precision=0):
4335
"""
4336
x.exp(): exponential of x.
4337
4338
If `x` is an exact argument, it is first converted to a
4339
real or complex number using the optional parameter precision (in
4340
bits). If `x` is inexact (e.g. real), its own precision is
4341
used in the computation, and the parameter precision is ignored.
4342
4343
EXAMPLES::
4344
4345
sage: pari(0).exp()
4346
1.00000000000000
4347
sage: pari(1).exp()
4348
2.71828182845905
4349
sage: pari('x+O(x^8)').exp()
4350
1 + x + 1/2*x^2 + 1/6*x^3 + 1/24*x^4 + 1/120*x^5 + 1/720*x^6 + 1/5040*x^7 + O(x^8)
4351
"""
4352
pari_catch_sig_on()
4353
return P.new_gen(gexp(self.g, prec_bits_to_words(precision)))
4354
4355
def gamma(gen s, unsigned long precision=0):
4356
"""
4357
s.gamma(precision): Gamma function at s.
4358
4359
If `s` is an exact argument, it is first converted to a
4360
real or complex number using the optional parameter precision (in
4361
bits). If `s` is inexact (e.g. real), its own precision is
4362
used in the computation, and the parameter precision is ignored.
4363
4364
EXAMPLES::
4365
4366
sage: pari(2).gamma()
4367
1.00000000000000
4368
sage: pari(5).gamma()
4369
24.0000000000000
4370
sage: C.<i> = ComplexField()
4371
sage: pari(1+i).gamma()
4372
0.498015668118356 - 0.154949828301811*I
4373
4374
TESTS::
4375
4376
sage: pari(-1).gamma()
4377
Traceback (most recent call last):
4378
...
4379
PariError: non-positive integer argument in ggamma
4380
"""
4381
pari_catch_sig_on()
4382
return P.new_gen(ggamma(s.g, prec_bits_to_words(precision)))
4383
4384
def gammah(gen s, unsigned long precision=0):
4385
"""
4386
s.gammah(): Gamma function evaluated at the argument x+1/2.
4387
4388
If `s` is an exact argument, it is first converted to a
4389
real or complex number using the optional parameter precision (in
4390
bits). If `s` is inexact (e.g. real), its own precision is
4391
used in the computation, and the parameter precision is ignored.
4392
4393
EXAMPLES::
4394
4395
sage: pari(2).gammah()
4396
1.32934038817914
4397
sage: pari(5).gammah()
4398
52.3427777845535
4399
sage: C.<i> = ComplexField()
4400
sage: pari(1+i).gammah()
4401
0.575315188063452 + 0.0882106775440939*I
4402
"""
4403
pari_catch_sig_on()
4404
return P.new_gen(ggamd(s.g, prec_bits_to_words(precision)))
4405
4406
def hyperu(gen a, b, x, unsigned long precision=0):
4407
r"""
4408
a.hyperu(b,x): U-confluent hypergeometric function.
4409
4410
If `a`, `b`, or `x` is an exact argument,
4411
it is first converted to a real or complex number using the
4412
optional parameter precision (in bits). If the arguments are
4413
inexact (e.g. real), the smallest of their precisions is used in
4414
the computation, and the parameter precision is ignored.
4415
4416
EXAMPLES::
4417
4418
sage: pari(1).hyperu(2,3)
4419
0.333333333333333
4420
"""
4421
cdef gen t0 = objtogen(b)
4422
cdef gen t1 = objtogen(x)
4423
pari_catch_sig_on()
4424
return P.new_gen(hyperu(a.g, t0.g, t1.g, prec_bits_to_words(precision)))
4425
4426
def incgam(gen s, x, y=None, unsigned long precision=0):
4427
r"""
4428
s.incgam(x, y, precision): incomplete gamma function. y is optional
4429
and is the precomputed value of gamma(s).
4430
4431
If `s` is an exact argument, it is first converted to a
4432
real or complex number using the optional parameter precision (in
4433
bits). If `s` is inexact (e.g. real), its own precision is
4434
used in the computation, and the parameter precision is ignored.
4435
4436
EXAMPLES::
4437
4438
sage: C.<i> = ComplexField()
4439
sage: pari(1+i).incgam(3-i)
4440
-0.0458297859919946 + 0.0433696818726677*I
4441
"""
4442
cdef gen t0 = objtogen(x)
4443
cdef gen t1
4444
if y is None:
4445
pari_catch_sig_on()
4446
return P.new_gen(incgam(s.g, t0.g, prec_bits_to_words(precision)))
4447
else:
4448
t1 = objtogen(y)
4449
pari_catch_sig_on()
4450
return P.new_gen(incgam0(s.g, t0.g, t1.g, prec_bits_to_words(precision)))
4451
4452
def incgamc(gen s, x, unsigned long precision=0):
4453
r"""
4454
s.incgamc(x): complementary incomplete gamma function.
4455
4456
The arguments `x` and `s` are complex numbers such
4457
that `s` is not a pole of `\Gamma` and
4458
`|x|/(|s|+1)` is not much larger than `1`
4459
(otherwise, the convergence is very slow). The function returns the
4460
value of the integral
4461
`\int_{0}^{x} e^{-t} t^{s-1} dt.`
4462
4463
If `s` or `x` is an exact argument, it is first
4464
converted to a real or complex number using the optional parameter
4465
precision (in bits). If the arguments are inexact (e.g. real), the
4466
smallest of their precisions is used in the computation, and the
4467
parameter precision is ignored.
4468
4469
EXAMPLES::
4470
4471
sage: pari(1).incgamc(2)
4472
0.864664716763387
4473
"""
4474
cdef gen t0 = objtogen(x)
4475
pari_catch_sig_on()
4476
return P.new_gen(incgamc(s.g, t0.g, prec_bits_to_words(precision)))
4477
4478
def log(gen x, unsigned long precision=0):
4479
r"""
4480
x.log(): natural logarithm of x.
4481
4482
This function returns the principal branch of the natural logarithm
4483
of `x`, i.e., the branch such that
4484
`\Im(\log(x)) \in ]-\pi, \pi].` The result is
4485
complex (with imaginary part equal to `\pi`) if
4486
`x\in \RR` and `x<0`. In general, the algorithm uses
4487
the formula
4488
4489
.. math::
4490
4491
\log(x) \simeq \frac{\pi}{2{\rm agm}(1,4/s)} - m\log(2),
4492
4493
4494
if `s=x 2^m` is large enough. (The result is exact to
4495
`B` bits provided that `s>2^{B/2}`.) At low
4496
accuracies, this function computes `\log` using the series
4497
expansion near `1`.
4498
4499
If `x` is an exact argument, it is first converted to a
4500
real or complex number using the optional parameter precision (in
4501
bits). If `x` is inexact (e.g. real), its own precision is
4502
used in the computation, and the parameter precision is ignored.
4503
4504
Note that `p`-adic arguments can also be given as input,
4505
with the convention that `\log(p)=0`. Hence, in particular,
4506
`\exp(\log(x))/x` is not in general equal to `1`
4507
but instead to a `(p-1)`-st root of unity (or
4508
`\pm 1` if `p=2`) times a power of `p`.
4509
4510
EXAMPLES::
4511
4512
sage: pari(5).log()
4513
1.60943791243410
4514
sage: C.<i> = ComplexField()
4515
sage: pari(i).log()
4516
0.E-19 + 1.57079632679490*I
4517
"""
4518
pari_catch_sig_on()
4519
return P.new_gen(glog(x.g, prec_bits_to_words(precision)))
4520
4521
def lngamma(gen x, unsigned long precision=0):
4522
r"""
4523
This method is deprecated, please use :meth:`.log_gamma` instead.
4524
4525
See the :meth:`.log_gamma` method for documentation and examples.
4526
4527
EXAMPLES::
4528
4529
sage: pari(100).lngamma()
4530
doctest:...: DeprecationWarning: The method lngamma() is deprecated. Use log_gamma() instead.
4531
See http://trac.sagemath.org/6992 for details.
4532
359.134205369575
4533
"""
4534
from sage.misc.superseded import deprecation
4535
deprecation(6992, "The method lngamma() is deprecated. Use log_gamma() instead.")
4536
return x.log_gamma(precision)
4537
4538
def log_gamma(gen x, unsigned long precision=0):
4539
r"""
4540
Logarithm of the gamma function of x.
4541
4542
This function returns the principal branch of the logarithm of the
4543
gamma function of `x`. The function
4544
`\log(\Gamma(x))` is analytic on the complex plane with
4545
non-positive integers removed. This function can have much larger
4546
inputs than `\Gamma` itself.
4547
4548
The `p`-adic analogue of this function is unfortunately not
4549
implemented.
4550
4551
If `x` is an exact argument, it is first converted to a
4552
real or complex number using the optional parameter precision (in
4553
bits). If `x` is inexact (e.g. real), its own precision is
4554
used in the computation, and the parameter precision is ignored.
4555
4556
EXAMPLES::
4557
4558
sage: pari(100).log_gamma()
4559
359.134205369575
4560
"""
4561
pari_catch_sig_on()
4562
return P.new_gen(glngamma(x.g, prec_bits_to_words(precision)))
4563
4564
def polylog(gen x, long m, long flag=0, unsigned long precision=0):
4565
"""
4566
x.polylog(m,flag=0): m-th polylogarithm of x. flag is optional, and
4567
can be 0: default, 1: D_m -modified m-th polylog of x, 2:
4568
D_m-modified m-th polylog of x, 3: P_m-modified m-th polylog of
4569
x.
4570
4571
If `x` is an exact argument, it is first converted to a
4572
real or complex number using the optional parameter precision (in
4573
bits). If `x` is inexact (e.g. real), its own precision is
4574
used in the computation, and the parameter precision is ignored.
4575
4576
TODO: Add more explanation, copied from the PARI manual.
4577
4578
EXAMPLES::
4579
4580
sage: pari(10).polylog(3)
4581
5.64181141475134 - 8.32820207698027*I
4582
sage: pari(10).polylog(3,0)
4583
5.64181141475134 - 8.32820207698027*I
4584
sage: pari(10).polylog(3,1)
4585
0.523778453502411
4586
sage: pari(10).polylog(3,2)
4587
-0.400459056163451
4588
"""
4589
pari_catch_sig_on()
4590
return P.new_gen(polylog0(m, x.g, flag, prec_bits_to_words(precision)))
4591
4592
def psi(gen x, unsigned long precision=0):
4593
r"""
4594
x.psi(): psi-function at x.
4595
4596
Return the `\psi`-function of `x`, i.e., the
4597
logarithmic derivative `\Gamma'(x)/\Gamma(x)`.
4598
4599
If `x` is an exact argument, it is first converted to a
4600
real or complex number using the optional parameter precision (in
4601
bits). If `x` is inexact (e.g. real), its own precision is
4602
used in the computation, and the parameter precision is ignored.
4603
4604
EXAMPLES::
4605
4606
sage: pari(1).psi()
4607
-0.577215664901533
4608
"""
4609
pari_catch_sig_on()
4610
return P.new_gen(gpsi(x.g, prec_bits_to_words(precision)))
4611
4612
def sin(gen x, unsigned long precision=0):
4613
"""
4614
x.sin(): The sine of x.
4615
4616
If `x` is an exact argument, it is first converted to a
4617
real or complex number using the optional parameter precision (in
4618
bits). If `x` is inexact (e.g. real), its own precision is
4619
used in the computation, and the parameter precision is ignored.
4620
4621
EXAMPLES::
4622
4623
sage: pari(1).sin()
4624
0.841470984807897
4625
sage: C.<i> = ComplexField()
4626
sage: pari(1+i).sin()
4627
1.29845758141598 + 0.634963914784736*I
4628
"""
4629
pari_catch_sig_on()
4630
return P.new_gen(gsin(x.g, prec_bits_to_words(precision)))
4631
4632
def sinh(gen x, unsigned long precision=0):
4633
"""
4634
The hyperbolic sine function.
4635
4636
If `x` is an exact argument, it is first converted to a
4637
real or complex number using the optional parameter precision (in
4638
bits). If `x` is inexact (e.g. real), its own precision is
4639
used in the computation, and the parameter precision is ignored.
4640
4641
EXAMPLES::
4642
4643
sage: pari(0).sinh()
4644
0.E-19
4645
sage: C.<i> = ComplexField()
4646
sage: pari(1+i).sinh()
4647
0.634963914784736 + 1.29845758141598*I
4648
"""
4649
pari_catch_sig_on()
4650
return P.new_gen(gsh(x.g, prec_bits_to_words(precision)))
4651
4652
def sqr(gen x):
4653
"""
4654
x.sqr(): square of x. Faster than, and most of the time (but not
4655
always - see the examples) identical to x\*x.
4656
4657
EXAMPLES::
4658
4659
sage: pari(2).sqr()
4660
4
4661
4662
For `2`-adic numbers, x.sqr() may not be identical to x\*x
4663
(squaring a `2`-adic number increases its precision)::
4664
4665
sage: pari("1+O(2^5)").sqr()
4666
1 + O(2^6)
4667
sage: pari("1+O(2^5)")*pari("1+O(2^5)")
4668
1 + O(2^5)
4669
4670
However::
4671
4672
sage: x = pari("1+O(2^5)"); x*x
4673
1 + O(2^6)
4674
"""
4675
pari_catch_sig_on()
4676
return P.new_gen(gsqr(x.g))
4677
4678
4679
def sqrt(gen x, unsigned long precision=0):
4680
"""
4681
x.sqrt(precision): The square root of x.
4682
4683
If `x` is an exact argument, it is first converted to a
4684
real or complex number using the optional parameter precision (in
4685
bits). If `x` is inexact (e.g. real), its own precision is
4686
used in the computation, and the parameter precision is ignored.
4687
4688
EXAMPLES::
4689
4690
sage: pari(2).sqrt()
4691
1.41421356237310
4692
"""
4693
pari_catch_sig_on()
4694
return P.new_gen(gsqrt(x.g, prec_bits_to_words(precision)))
4695
4696
def sqrtn(gen x, n, unsigned long precision=0):
4697
r"""
4698
x.sqrtn(n): return the principal branch of the n-th root of x,
4699
i.e., the one such that
4700
`\arg(\sqrt(x)) \in ]-\pi/n, \pi/n]`. Also returns a second
4701
argument which is a suitable root of unity allowing one to recover
4702
all the other roots. If it was not possible to find such a number,
4703
then this second return value is 0. If the argument is present and
4704
no square root exists, return 0 instead of raising an error.
4705
4706
If `x` is an exact argument, it is first converted to a
4707
real or complex number using the optional parameter precision (in
4708
bits). If `x` is inexact (e.g. real), its own precision is
4709
used in the computation, and the parameter precision is ignored.
4710
4711
.. note::
4712
4713
intmods (modulo a prime) and `p`-adic numbers are
4714
allowed as arguments.
4715
4716
INPUT:
4717
4718
4719
- ``x`` - gen
4720
4721
- ``n`` - integer
4722
4723
4724
OUTPUT:
4725
4726
4727
- ``gen`` - principal n-th root of x
4728
4729
- ``gen`` - root of unity z that gives the other
4730
roots
4731
4732
4733
EXAMPLES::
4734
4735
sage: s, z = pari(2).sqrtn(5)
4736
sage: z
4737
0.309016994374947 + 0.951056516295154*I
4738
sage: s
4739
1.14869835499704
4740
sage: s^5
4741
2.00000000000000
4742
sage: z^5
4743
1.00000000000000 + 5.42101086 E-19*I # 32-bit
4744
1.00000000000000 + 5.96311194867027 E-19*I # 64-bit
4745
sage: (s*z)^5
4746
2.00000000000000 + 1.409462824 E-18*I # 32-bit
4747
2.00000000000000 + 9.21571846612679 E-19*I # 64-bit
4748
"""
4749
# TODO: ??? lots of good examples in the PARI docs ???
4750
cdef GEN zetan
4751
cdef gen t0 = objtogen(n)
4752
pari_catch_sig_on()
4753
ans = P.new_gen_noclear(gsqrtn(x.g, t0.g, &zetan, prec_bits_to_words(precision)))
4754
return ans, P.new_gen(zetan)
4755
4756
def tan(gen x, unsigned long precision=0):
4757
"""
4758
x.tan() - tangent of x
4759
4760
If `x` is an exact argument, it is first converted to a
4761
real or complex number using the optional parameter precision (in
4762
bits). If `x` is inexact (e.g. real), its own precision is
4763
used in the computation, and the parameter precision is ignored.
4764
4765
EXAMPLES::
4766
4767
sage: pari(2).tan()
4768
-2.18503986326152
4769
sage: C.<i> = ComplexField()
4770
sage: pari(i).tan()
4771
0.E-19 + 0.761594155955765*I
4772
"""
4773
pari_catch_sig_on()
4774
return P.new_gen(gtan(x.g, prec_bits_to_words(precision)))
4775
4776
def tanh(gen x, unsigned long precision=0):
4777
"""
4778
x.tanh() - hyperbolic tangent of x
4779
4780
If `x` is an exact argument, it is first converted to a
4781
real or complex number using the optional parameter precision (in
4782
bits). If `x` is inexact (e.g. real), its own precision is
4783
used in the computation, and the parameter precision is ignored.
4784
4785
EXAMPLES::
4786
4787
sage: pari(1).tanh()
4788
0.761594155955765
4789
sage: C.<i> = ComplexField()
4790
sage: z = pari(i); z
4791
0.E-19 + 1.00000000000000*I
4792
sage: result = z.tanh()
4793
sage: result.real() <= 1e-18
4794
True
4795
sage: result.imag()
4796
1.55740772465490
4797
"""
4798
pari_catch_sig_on()
4799
return P.new_gen(gth(x.g, prec_bits_to_words(precision)))
4800
4801
def teichmuller(gen x):
4802
r"""
4803
teichmuller(x): teichmuller character of p-adic number x.
4804
4805
This is the unique `(p-1)`-st root of unity congruent to
4806
`x/p^{v_p(x)}` modulo `p`.
4807
4808
EXAMPLES::
4809
4810
sage: pari('2+O(7^5)').teichmuller()
4811
2 + 4*7 + 6*7^2 + 3*7^3 + O(7^5)
4812
"""
4813
pari_catch_sig_on()
4814
return P.new_gen(teich(x.g))
4815
4816
def theta(gen q, z, unsigned long precision=0):
4817
"""
4818
q.theta(z): Jacobi sine theta-function.
4819
4820
If `q` or `z` is an exact argument, it is first
4821
converted to a real or complex number using the optional parameter
4822
precision (in bits). If the arguments are inexact (e.g. real), the
4823
smallest of their precisions is used in the computation, and the
4824
parameter precision is ignored.
4825
4826
EXAMPLES::
4827
4828
sage: pari(0.5).theta(2)
4829
1.63202590295260
4830
"""
4831
cdef gen t0 = objtogen(z)
4832
pari_catch_sig_on()
4833
return P.new_gen(theta(q.g, t0.g, prec_bits_to_words(precision)))
4834
4835
def thetanullk(gen q, long k, unsigned long precision=0):
4836
"""
4837
q.thetanullk(k): return the k-th derivative at z=0 of theta(q,z).
4838
4839
If `q` is an exact argument, it is first converted to a
4840
real or complex number using the optional parameter precision (in
4841
bits). If `q` is inexact (e.g. real), its own precision is
4842
used in the computation, and the parameter precision is ignored.
4843
4844
EXAMPLES::
4845
4846
sage: pari(0.5).thetanullk(1)
4847
0.548978532560341
4848
"""
4849
pari_catch_sig_on()
4850
return P.new_gen(thetanullk(q.g, k, prec_bits_to_words(precision)))
4851
4852
def weber(gen x, long flag=0, unsigned long precision=0):
4853
r"""
4854
x.weber(flag=0): One of Weber's f functions of x. flag is optional,
4855
and can be 0: default, function
4856
f(x)=exp(-i\*Pi/24)\*eta((x+1)/2)/eta(x) such that
4857
`j=(f^{24}-16)^3/f^{24}`, 1: function f1(x)=eta(x/2)/eta(x)
4858
such that `j=(f1^24+16)^3/f2^{24}`, 2: function
4859
f2(x)=sqrt(2)\*eta(2\*x)/eta(x) such that
4860
`j=(f2^{24}+16)^3/f2^{24}`.
4861
4862
If `x` is an exact argument, it is first converted to a
4863
real or complex number using the optional parameter precision (in
4864
bits). If `x` is inexact (e.g. real), its own precision is
4865
used in the computation, and the parameter precision is ignored.
4866
4867
TODO: Add further explanation from PARI manual.
4868
4869
EXAMPLES::
4870
4871
sage: C.<i> = ComplexField()
4872
sage: pari(i).weber()
4873
1.18920711500272 + 0.E-19*I # 32-bit
4874
1.18920711500272 + 2.71050543121376 E-20*I # 64-bit
4875
sage: pari(i).weber(1)
4876
1.09050773266526 + 0.E-19*I
4877
sage: pari(i).weber(2)
4878
1.09050773266526
4879
"""
4880
pari_catch_sig_on()
4881
return P.new_gen(weber0(x.g, flag, prec_bits_to_words(precision)))
4882
4883
def zeta(gen s, unsigned long precision=0):
4884
"""
4885
zeta(s): zeta function at s with s a complex or a p-adic number.
4886
4887
If `s` is a complex number, this is the Riemann zeta
4888
function `\zeta(s)=\sum_{n\geq 1} n^{-s}`, computed either
4889
using the Euler-Maclaurin summation formula (if `s` is not
4890
an integer), or using Bernoulli numbers (if `s` is a
4891
negative integer or an even nonnegative integer), or using modular
4892
forms (if `s` is an odd nonnegative integer).
4893
4894
If `s` is a `p`-adic number, this is the
4895
Kubota-Leopoldt zeta function, i.e. the unique continuous
4896
`p`-adic function on the `p`-adic integers that
4897
interpolates the values of `(1-p^{-k})\zeta(k)` at negative
4898
integers `k` such that `k\equiv 1\pmod{p-1}` if
4899
`p` is odd, and at odd `k` if `p=2`.
4900
4901
If `x` is an exact argument, it is first converted to a
4902
real or complex number using the optional parameter precision (in
4903
bits). If `x` is inexact (e.g. real), its own precision is
4904
used in the computation, and the parameter precision is ignored.
4905
4906
INPUT:
4907
4908
4909
- ``s`` - gen (real, complex, or p-adic number)
4910
4911
4912
OUTPUT:
4913
4914
4915
- ``gen`` - value of zeta at s.
4916
4917
4918
EXAMPLES::
4919
4920
sage: pari(2).zeta()
4921
1.64493406684823
4922
sage: x = RR(pi)^2/6
4923
sage: pari(x)
4924
1.64493406684823
4925
sage: pari(3).zeta()
4926
1.20205690315959
4927
sage: pari('1+5*7+2*7^2+O(7^3)').zeta()
4928
4*7^-2 + 5*7^-1 + O(7^0)
4929
"""
4930
pari_catch_sig_on()
4931
return P.new_gen(gzeta(s.g, prec_bits_to_words(precision)))
4932
4933
###########################################
4934
# 4: NUMBER THEORETICAL functions
4935
###########################################
4936
4937
def bezout(gen x, y):
4938
cdef gen u, v, g
4939
cdef GEN U, V, G
4940
cdef gen t0 = objtogen(y)
4941
pari_catch_sig_on()
4942
G = gbezout(x.g, t0.g, &U, &V)
4943
g = P.new_gen_noclear(G)
4944
u = P.new_gen_noclear(U)
4945
v = P.new_gen(V)
4946
return g, u, v
4947
4948
def binomial(gen x, long k):
4949
"""
4950
binomial(x, k): return the binomial coefficient "x choose k".
4951
4952
INPUT:
4953
4954
4955
- ``x`` - any PARI object (gen)
4956
4957
- ``k`` - integer
4958
4959
4960
EXAMPLES::
4961
4962
sage: pari(6).binomial(2)
4963
15
4964
sage: pari('x+1').binomial(3)
4965
1/6*x^3 - 1/6*x
4966
sage: pari('2+x+O(x^2)').binomial(3)
4967
1/3*x + O(x^2)
4968
"""
4969
pari_catch_sig_on()
4970
return P.new_gen(binomial(x.g, k))
4971
4972
def contfrac(gen x, b=0, long lmax=0):
4973
"""
4974
contfrac(x,b,lmax): continued fraction expansion of x (x rational,
4975
real or rational function). b and lmax are both optional, where b
4976
is the vector of numerators of the continued fraction, and lmax is
4977
a bound for the number of terms in the continued fraction
4978
expansion.
4979
"""
4980
cdef gen t0 = objtogen(b)
4981
pari_catch_sig_on()
4982
return P.new_gen(contfrac0(x.g, t0.g, lmax))
4983
4984
def contfracpnqn(gen x, b=0, long lmax=0):
4985
"""
4986
contfracpnqn(x): [p_n,p_n-1; q_n,q_n-1] corresponding to the
4987
continued fraction x.
4988
"""
4989
pari_catch_sig_on()
4990
return P.new_gen(pnqn(x.g))
4991
4992
def ffgen(gen T, v=-1):
4993
r"""
4994
Return the generator `g=x \bmod T` of the finite field defined
4995
by the polynomial `T`.
4996
4997
INPUT:
4998
4999
- ``T`` -- a gen of type t_POL with coefficients of type t_INTMOD:
5000
a polynomial over a prime finite field
5001
5002
- ``v`` -- string: a variable name or -1 (optional)
5003
5004
If `v` is a string, then `g` will be a polynomial in `v`, else the
5005
variable of the polynomial `T` is used.
5006
5007
EXAMPLES::
5008
5009
sage: x = GF(2)['x'].gen()
5010
sage: pari(x^2+x+2).ffgen()
5011
x
5012
sage: pari(x^2+x+1).ffgen('a')
5013
a
5014
"""
5015
pari_catch_sig_on()
5016
return P.new_gen(ffgen(T.g, P.get_var(v)))
5017
5018
def ffinit(gen p, long n, v=-1):
5019
r"""
5020
Return a monic irreducible polynomial `g` of degree `n` over the
5021
finite field of `p` elements.
5022
5023
INPUT:
5024
5025
- ``p`` -- a gen of type t_INT: a prime number
5026
5027
- ``n`` -- integer: the degree of the polynomial
5028
5029
- ``v`` -- string: a variable name or -1 (optional)
5030
5031
If `v \geq 0', then `g` will be a polynomial in `v`, else the
5032
variable `x` is used.
5033
5034
EXAMPLES::
5035
5036
sage: pari(7).ffinit(11)
5037
Mod(1, 7)*x^11 + Mod(1, 7)*x^10 + Mod(4, 7)*x^9 + Mod(5, 7)*x^8 + Mod(1, 7)*x^7 + Mod(1, 7)*x^2 + Mod(1, 7)*x + Mod(6, 7)
5038
sage: pari(2003).ffinit(3)
5039
Mod(1, 2003)*x^3 + Mod(1, 2003)*x^2 + Mod(1993, 2003)*x + Mod(1995, 2003)
5040
"""
5041
pari_catch_sig_on()
5042
return P.new_gen(ffinit(p.g, n, P.get_var(v)))
5043
5044
def fibonacci(gen x):
5045
r"""
5046
Return the Fibonacci number of index x.
5047
5048
EXAMPLES::
5049
5050
sage: pari(18).fibonacci()
5051
2584
5052
sage: [pari(n).fibonacci() for n in range(10)]
5053
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
5054
"""
5055
pari_catch_sig_on()
5056
return P.new_gen(fibo(long(x)))
5057
5058
def gcd(gen x, y=None):
5059
"""
5060
Return the greatest common divisor of `x` and `y`.
5061
5062
If `y` is ``None``, then `x` must be a list or tuple, and the
5063
greatest common divisor of its components is returned.
5064
5065
EXAMPLES::
5066
5067
sage: pari(10).gcd(15)
5068
5
5069
sage: pari([5, 'y']).gcd()
5070
1
5071
sage: pari(['x', x^2]).gcd()
5072
x
5073
5074
"""
5075
cdef gen t0
5076
if y is None:
5077
pari_catch_sig_on()
5078
return P.new_gen(ggcd0(x.g, NULL))
5079
else:
5080
t0 = objtogen(y)
5081
pari_catch_sig_on()
5082
return P.new_gen(ggcd0(x.g, t0.g))
5083
5084
def issquare(gen x, find_root=False):
5085
"""
5086
issquare(x,n): ``True`` if x is a square, ``False`` if not. If
5087
``find_root`` is given, also returns the exact square root.
5088
"""
5089
cdef GEN G
5090
cdef long t
5091
cdef gen g
5092
pari_catch_sig_on()
5093
if find_root:
5094
t = itos(gissquareall(x.g, &G))
5095
if t:
5096
return True, P.new_gen(G)
5097
else:
5098
P.clear_stack()
5099
return False, None
5100
else:
5101
t = itos(gissquare(x.g))
5102
pari_catch_sig_off()
5103
return t != 0
5104
5105
def issquarefree(gen self):
5106
"""
5107
EXAMPLES::
5108
5109
sage: pari(10).issquarefree()
5110
True
5111
sage: pari(20).issquarefree()
5112
False
5113
"""
5114
pari_catch_sig_on()
5115
cdef long t = issquarefree(self.g)
5116
pari_catch_sig_off()
5117
return t != 0
5118
5119
def lcm(gen x, y=None):
5120
"""
5121
Return the least common multiple of `x` and `y`.
5122
5123
If `y` is ``None``, then `x` must be a list or tuple, and the
5124
least common multiple of its components is returned.
5125
5126
EXAMPLES::
5127
5128
sage: pari(10).lcm(15)
5129
30
5130
sage: pari([5, 'y']).lcm()
5131
5*y
5132
sage: pari([10, 'x', x^2]).lcm()
5133
10*x^2
5134
5135
"""
5136
cdef gen t0
5137
if y is None:
5138
pari_catch_sig_on()
5139
return P.new_gen(glcm0(x.g, NULL))
5140
else:
5141
t0 = objtogen(y)
5142
pari_catch_sig_on()
5143
return P.new_gen(glcm0(x.g, t0.g))
5144
5145
def numdiv(gen n):
5146
"""
5147
Return the number of divisors of the integer n.
5148
5149
EXAMPLES::
5150
5151
sage: pari(10).numdiv()
5152
4
5153
"""
5154
pari_catch_sig_on()
5155
return P.new_gen(gnumbdiv(n.g))
5156
5157
def phi(gen n):
5158
"""
5159
Return the Euler phi function of n. EXAMPLES::
5160
5161
sage: pari(10).phi()
5162
4
5163
"""
5164
pari_catch_sig_on()
5165
return P.new_gen(geulerphi(n.g))
5166
5167
def primepi(gen self):
5168
"""
5169
Return the number of primes less than or equal to self.
5170
5171
EXAMPLES::
5172
5173
sage: pari(7).primepi()
5174
4
5175
sage: pari(100).primepi()
5176
25
5177
sage: pari(1000).primepi()
5178
168
5179
sage: pari(100000).primepi()
5180
9592
5181
sage: pari(0).primepi()
5182
0
5183
sage: pari(-15).primepi()
5184
0
5185
sage: pari(500509).primepi()
5186
41581
5187
"""
5188
pari_catch_sig_on()
5189
if self > P._primelimit():
5190
P.init_primes(self + 10)
5191
if signe(self.g) != 1:
5192
pari_catch_sig_off()
5193
return P.PARI_ZERO
5194
return P.new_gen(primepi(self.g))
5195
5196
def sumdiv(gen n):
5197
"""
5198
Return the sum of the divisors of `n`.
5199
5200
EXAMPLES::
5201
5202
sage: pari(10).sumdiv()
5203
18
5204
"""
5205
pari_catch_sig_on()
5206
return P.new_gen(sumdiv(n.g))
5207
5208
def sumdivk(gen n, long k):
5209
"""
5210
Return the sum of the k-th powers of the divisors of n.
5211
5212
EXAMPLES::
5213
5214
sage: pari(10).sumdivk(2)
5215
130
5216
"""
5217
pari_catch_sig_on()
5218
return P.new_gen(sumdivk(n.g, k))
5219
5220
def xgcd(gen x, y):
5221
"""
5222
Returns u,v,d such that d=gcd(x,y) and u\*x+v\*y=d.
5223
5224
EXAMPLES::
5225
5226
sage: pari(10).xgcd(15)
5227
(5, -1, 1)
5228
"""
5229
return x.bezout(y)
5230
5231
def Zn_issquare(gen self, n):
5232
"""
5233
Return ``True`` if ``self`` is a square modulo `n`, ``False``
5234
if not.
5235
5236
INPUT:
5237
5238
- ``self`` -- integer
5239
5240
- ``n`` -- integer or factorisation matrix
5241
5242
EXAMPLES::
5243
5244
sage: pari(3).Zn_issquare(4)
5245
False
5246
sage: pari(4).Zn_issquare(30.factor())
5247
True
5248
5249
"""
5250
cdef gen t0 = objtogen(n)
5251
pari_catch_sig_on()
5252
cdef long t = Zn_issquare(self.g, t0.g)
5253
pari_catch_sig_off()
5254
return t != 0
5255
5256
def Zn_sqrt(gen self, n):
5257
"""
5258
Return a square root of ``self`` modulo `n`, if such a square
5259
root exists; otherwise, raise a ``ValueError``.
5260
5261
INPUT:
5262
5263
- ``self`` -- integer
5264
5265
- ``n`` -- integer or factorisation matrix
5266
5267
EXAMPLES::
5268
5269
sage: pari(3).Zn_sqrt(4)
5270
Traceback (most recent call last):
5271
...
5272
ValueError: 3 is not a square modulo 4
5273
sage: pari(4).Zn_sqrt(30.factor())
5274
22
5275
5276
"""
5277
cdef gen t0 = objtogen(n)
5278
cdef GEN s
5279
pari_catch_sig_on()
5280
s = Zn_sqrt(self.g, t0.g)
5281
if s == NULL:
5282
pari_catch_sig_off()
5283
raise ValueError("%s is not a square modulo %s" % (self, n))
5284
return P.new_gen(s)
5285
5286
5287
##################################################
5288
# 5: Elliptic curve functions
5289
##################################################
5290
5291
def ellinit(self, long flag=0, unsigned long precision=0):
5292
"""
5293
Return the PARI elliptic curve object with Weierstrass coefficients
5294
given by self, a list with 5 elements.
5295
5296
INPUT:
5297
5298
5299
- ``self`` - a list of 5 coefficients
5300
5301
- ``flag (optional, default: 0)`` - if 0, ask for a PARI ell
5302
structure with 19 components; if 1, ask for a shorted PARI
5303
sell structure with only the first 13 components.
5304
5305
- ``precision (optional, default: 0)`` - the real
5306
precision to be used in the computation of the components of the
5307
PARI (s)ell structure; if 0, use the default 64 bits.
5308
5309
.. note::
5310
5311
The parameter ``precision`` in ``ellinit`` controls not
5312
only the real precision of the resulting (s)ell structure,
5313
but in some cases also the precision of most subsequent
5314
computations with this elliptic curve (if those rely on
5315
the precomputations done by ``ellinit``). You should
5316
therefore set the precision from the start to the value
5317
you require.
5318
5319
OUTPUT:
5320
5321
5322
- ``gen`` - either a PARI ell structure with 19 components
5323
(if flag=0), or a PARI sell structure with 13 components
5324
(if flag=1).
5325
5326
5327
EXAMPLES: An elliptic curve with integer coefficients::
5328
5329
sage: e = pari([0,1,0,1,0]).ellinit(); e
5330
[0, 1, 0, 1, 0, 4, 2, 0, -1, -32, 224, -48, 2048/3, [0.E-28, -0.500000000000000 - 0.866025403784439*I, -0.500000000000000 + 0.866025403784439*I]~, 3.37150070962519, -1.68575035481260 - 2.15651564749964*I, 1.37451455785745 - 1.084202173 E-19*I, -0.687257278928726 + 0.984434956803824*I, 7.27069403586288] # 32-bit
5331
[0, 1, 0, 1, 0, 4, 2, 0, -1, -32, 224, -48, 2048/3, [0.E-38, -0.500000000000000 - 0.866025403784439*I, -0.500000000000000 + 0.866025403784439*I]~, 3.37150070962519, -1.68575035481260 - 2.15651564749964*I, 1.37451455785745 - 5.42101086242752 E-19*I, -0.687257278928726 + 0.984434956803824*I, 7.27069403586288] # 64-bit
5332
5333
Its inexact components have the default precision of 53 bits::
5334
5335
sage: RR(e[14])
5336
3.37150070962519
5337
5338
We can compute this to higher precision::
5339
5340
sage: R = RealField(150)
5341
sage: e = pari([0,1,0,1,0]).ellinit(precision=150)
5342
sage: R(e[14])
5343
3.3715007096251920857424073155981539790016018
5344
5345
Using flag=1 returns a short elliptic curve PARI object::
5346
5347
sage: pari([0,1,0,1,0]).ellinit(flag=1)
5348
[0, 1, 0, 1, 0, 4, 2, 0, -1, -32, 224, -48, 2048/3]
5349
5350
The coefficients can be any ring elements that convert to PARI::
5351
5352
sage: pari([0,1/2,0,-3/4,0]).ellinit(flag=1)
5353
[0, 1/2, 0, -3/4, 0, 2, -3/2, 0, -9/16, 40, -116, 117/4, 256000/117]
5354
sage: pari([0,0.5,0,-0.75,0]).ellinit(flag=1)
5355
[0, 0.500000000000000, 0, -0.750000000000000, 0, 2.00000000000000, -1.50000000000000, 0, -0.562500000000000, 40.0000000000000, -116.000000000000, 29.2500000000000, 2188.03418803419]
5356
sage: pari([0,I,0,1,0]).ellinit(flag=1)
5357
[0, I, 0, 1, 0, 4*I, 2, 0, -1, -64, 352*I, -80, 16384/5]
5358
sage: pari([0,x,0,2*x,1]).ellinit(flag=1)
5359
[0, x, 0, 2*x, 1, 4*x, 4*x, 4, -4*x^2 + 4*x, 16*x^2 - 96*x, -64*x^3 + 576*x^2 - 864, 64*x^4 - 576*x^3 + 576*x^2 - 432, (256*x^6 - 4608*x^5 + 27648*x^4 - 55296*x^3)/(4*x^4 - 36*x^3 + 36*x^2 - 27)]
5360
"""
5361
pari_catch_sig_on()
5362
return P.new_gen(ellinit0(self.g, flag, prec_bits_to_words(precision)))
5363
5364
def ellglobalred(self):
5365
"""
5366
e.ellglobalred(): return information related to the global minimal
5367
model of the elliptic curve e.
5368
5369
INPUT:
5370
5371
5372
- ``e`` - elliptic curve (returned by ellinit)
5373
5374
5375
OUTPUT:
5376
5377
5378
- ``gen`` - the (arithmetic) conductor of e
5379
5380
- ``gen`` - a vector giving the coordinate change over
5381
Q from e to its minimal integral model (see also ellminimalmodel)
5382
5383
- ``gen`` - the product of the local Tamagawa numbers
5384
of e
5385
5386
5387
EXAMPLES::
5388
5389
sage: e = pari([0, 5, 2, -1, 1]).ellinit()
5390
sage: e.ellglobalred()
5391
[20144, [1, -2, 0, -1], 1]
5392
sage: e = pari(EllipticCurve('17a').a_invariants()).ellinit()
5393
sage: e.ellglobalred()
5394
[17, [1, 0, 0, 0], 4]
5395
"""
5396
pari_catch_sig_on()
5397
return P.new_gen(ellglobalred(self.g))
5398
5399
def elladd(self, z0, z1):
5400
"""
5401
e.elladd(z0, z1): return the sum of the points z0 and z1 on this
5402
elliptic curve.
5403
5404
INPUT:
5405
5406
5407
- ``e`` - elliptic curve E
5408
5409
- ``z0`` - point on E
5410
5411
- ``z1`` - point on E
5412
5413
5414
OUTPUT: point on E
5415
5416
EXAMPLES: First we create an elliptic curve::
5417
5418
sage: e = pari([0, 1, 1, -2, 0]).ellinit()
5419
sage: str(e)[:65] # first part of output
5420
'[0, 1, 1, -2, 0, 4, -4, 1, -3, 112, -856, 389, 1404928/389, [0.90'
5421
5422
Next we add two points on the elliptic curve. Notice that the
5423
Python lists are automatically converted to PARI objects so you
5424
don't have to do that explicitly in your code.
5425
5426
::
5427
5428
sage: e.elladd([1,0], [-1,1])
5429
[-3/4, -15/8]
5430
"""
5431
cdef gen t0 = objtogen(z0)
5432
cdef gen t1 = objtogen(z1)
5433
pari_catch_sig_on()
5434
return P.new_gen(addell(self.g, t0.g, t1.g))
5435
5436
def ellak(self, n):
5437
r"""
5438
e.ellak(n): Returns the coefficient `a_n` of the
5439
`L`-function of the elliptic curve e, i.e. the
5440
`n`-th Fourier coefficient of the weight 2 newform
5441
associated to e (according to Shimura-Taniyama).
5442
5443
The curve `e` *must* be a medium or long vector of the type
5444
given by ellinit. For this function to work for every n and not
5445
just those prime to the conductor, e must be a minimal Weierstrass
5446
equation. If this is not the case, use the function ellminimalmodel
5447
first before using ellak (or you will get INCORRECT RESULTS!)
5448
5449
5450
INPUT:
5451
5452
5453
- ``e`` - a PARI elliptic curve.
5454
5455
- ``n`` - integer.
5456
5457
5458
EXAMPLES::
5459
5460
sage: e = pari([0, -1, 1, -10, -20]).ellinit()
5461
sage: e.ellak(6)
5462
2
5463
sage: e.ellak(2005)
5464
2
5465
sage: e.ellak(-1)
5466
0
5467
sage: e.ellak(0)
5468
0
5469
"""
5470
cdef gen t0 = objtogen(n)
5471
pari_catch_sig_on()
5472
return P.new_gen(akell(self.g, t0.g))
5473
5474
5475
def ellan(self, long n, python_ints=False):
5476
"""
5477
Return the first `n` Fourier coefficients of the modular
5478
form attached to this elliptic curve. See ellak for more details.
5479
5480
INPUT:
5481
5482
5483
- ``n`` - a long integer
5484
5485
- ``python_ints`` - bool (default is False); if True,
5486
return a list of Python ints instead of a PARI gen wrapper.
5487
5488
5489
EXAMPLES::
5490
5491
sage: e = pari([0, -1, 1, -10, -20]).ellinit()
5492
sage: e.ellan(3)
5493
[1, -2, -1]
5494
sage: e.ellan(20)
5495
[1, -2, -1, 2, 1, 2, -2, 0, -2, -2, 1, -2, 4, 4, -1, -4, -2, 4, 0, 2]
5496
sage: e.ellan(-1)
5497
[]
5498
sage: v = e.ellan(10, python_ints=True); v
5499
[1, -2, -1, 2, 1, 2, -2, 0, -2, -2]
5500
sage: type(v)
5501
<type 'list'>
5502
sage: type(v[0])
5503
<type 'int'>
5504
"""
5505
pari_catch_sig_on()
5506
cdef GEN g
5507
if python_ints:
5508
g = anell(self.g, n)
5509
v = [gtolong(<GEN> g[i+1]) for i in range(glength(g))]
5510
P.clear_stack()
5511
return v
5512
else:
5513
return P.new_gen(anell(self.g, n))
5514
5515
def ellanalyticrank(self, unsigned long precision=0):
5516
r"""
5517
Returns a 2-component vector with the order of vanishing at
5518
`s = 1` of the L-function of the elliptic curve and the value
5519
of the first non-zero derivative.
5520
5521
EXAMPLE::
5522
5523
sage: E = EllipticCurve('389a1')
5524
sage: pari(E).ellanalyticrank()
5525
[2, 1.51863300057685]
5526
"""
5527
pari_catch_sig_on()
5528
return P.new_gen(ellanalyticrank(self.g, <GEN>0, prec_bits_to_words(precision)))
5529
5530
def ellap(self, p):
5531
r"""
5532
e.ellap(p): Returns the prime-indexed coefficient `a_p` of the
5533
`L`-function of the elliptic curve `e`, i.e. the `p`-th Fourier
5534
coefficient of the newform attached to e.
5535
5536
The computation uses the Shanks--Mestre method, or the SEA
5537
algorithm.
5538
5539
.. WARNING::
5540
5541
For this function to work for every n and not just those prime
5542
to the conductor, e must be a minimal Weierstrass equation.
5543
If this is not the case, use the function ellminimalmodel first
5544
before using ellap (or you will get INCORRECT RESULTS!)
5545
5546
5547
INPUT:
5548
5549
5550
- ``e`` - a PARI elliptic curve.
5551
5552
- ``p`` - prime integer
5553
5554
5555
EXAMPLES::
5556
5557
sage: e = pari([0, -1, 1, -10, -20]).ellinit()
5558
sage: e.ellap(2)
5559
-2
5560
sage: e.ellap(2003)
5561
4
5562
sage: e.ellak(-1)
5563
0
5564
"""
5565
cdef gen t0 = objtogen(p)
5566
pari_catch_sig_on()
5567
return P.new_gen(ellap(self.g, t0.g))
5568
5569
5570
def ellaplist(self, long n, python_ints=False):
5571
r"""
5572
e.ellaplist(n): Returns a PARI list of all the prime-indexed
5573
coefficients `a_p` (up to n) of the `L`-function
5574
of the elliptic curve `e`, i.e. the Fourier coefficients of
5575
the newform attached to `e`.
5576
5577
INPUT:
5578
5579
- ``self`` -- an elliptic curve
5580
5581
- ``n`` -- a long integer
5582
5583
- ``python_ints`` -- bool (default is False); if True,
5584
return a list of Python ints instead of a PARI gen wrapper.
5585
5586
.. WARNING::
5587
5588
The curve e must be a medium or long vector of the type given by
5589
ellinit. For this function to work for every n and not just those
5590
prime to the conductor, e must be a minimal Weierstrass equation.
5591
If this is not the case, use the function ellminimalmodel first
5592
before using ellaplist (or you will get INCORRECT RESULTS!)
5593
5594
EXAMPLES::
5595
5596
sage: e = pari([0, -1, 1, -10, -20]).ellinit()
5597
sage: v = e.ellaplist(10); v
5598
[-2, -1, 1, -2]
5599
sage: type(v)
5600
<type 'sage.libs.pari.gen.gen'>
5601
sage: v.type()
5602
't_VEC'
5603
sage: e.ellan(10)
5604
[1, -2, -1, 2, 1, 2, -2, 0, -2, -2]
5605
sage: v = e.ellaplist(10, python_ints=True); v
5606
[-2, -1, 1, -2]
5607
sage: type(v)
5608
<type 'list'>
5609
sage: type(v[0])
5610
<type 'int'>
5611
5612
TESTS::
5613
5614
sage: v = e.ellaplist(1)
5615
sage: print v, type(v)
5616
[] <type 'sage.libs.pari.gen.gen'>
5617
sage: v = e.ellaplist(1, python_ints=True)
5618
sage: print v, type(v)
5619
[] <type 'list'>
5620
"""
5621
if python_ints:
5622
return [int(x) for x in self.ellaplist(n)]
5623
5624
if n < 2:
5625
pari_catch_sig_on()
5626
return P.new_gen(zerovec(0))
5627
5628
# 1. Make a table of primes up to n.
5629
P.init_primes(n+1)
5630
cdef gen t0 = objtogen(n)
5631
pari_catch_sig_on()
5632
cdef GEN g = primes(gtolong(primepi(t0.g)))
5633
5634
# 2. Replace each prime in the table by ellap of it.
5635
cdef long i
5636
for i from 0 <= i < glength(g):
5637
set_gel(g, i + 1, ellap(self.g, gel(g, i + 1)))
5638
return P.new_gen(g)
5639
5640
def ellbil(self, z0, z1, unsigned long precision=0):
5641
"""
5642
e.ellbil(z0, z1): return the value of the canonical bilinear form
5643
on z0 and z1.
5644
5645
INPUT:
5646
5647
5648
- ``e`` - elliptic curve (assumed integral given by a
5649
minimal model, as returned by ellminimalmodel)
5650
5651
- ``z0, z1`` - rational points on e
5652
5653
5654
EXAMPLES::
5655
5656
sage: e = pari([0,1,1,-2,0]).ellinit().ellminimalmodel()[0]
5657
sage: e.ellbil([1, 0], [-1, 1])
5658
0.418188984498861
5659
"""
5660
cdef gen t0 = objtogen(z0)
5661
cdef gen t1 = objtogen(z1)
5662
pari_catch_sig_on()
5663
return P.new_gen(bilhell(self.g, t0.g, t1.g, prec_bits_to_words(precision)))
5664
5665
def ellchangecurve(self, ch):
5666
"""
5667
e.ellchangecurve(ch): return the new model (equation) for the
5668
elliptic curve e given by the change of coordinates ch.
5669
5670
The change of coordinates is specified by a vector ch=[u,r,s,t]; if
5671
`x'` and `y'` are the new coordinates, then
5672
`x = u^2 x' + r` and `y = u^3 y' + su^2 x' + t`.
5673
5674
INPUT:
5675
5676
5677
- ``e`` - elliptic curve
5678
5679
- ``ch`` - change of coordinates vector with 4
5680
entries
5681
5682
5683
EXAMPLES::
5684
5685
sage: e = pari([1,2,3,4,5]).ellinit()
5686
sage: e.ellglobalred()
5687
[10351, [1, -1, 0, -1], 1]
5688
sage: f = e.ellchangecurve([1,-1,0,-1])
5689
sage: f[:5]
5690
[1, -1, 0, 4, 3]
5691
"""
5692
cdef gen t0 = objtogen(ch)
5693
pari_catch_sig_on()
5694
return P.new_gen(ellchangecurve(self.g, t0.g))
5695
5696
def elleta(self, unsigned long precision=0):
5697
"""
5698
e.elleta(): return the vector [eta1,eta2] of quasi-periods
5699
associated with the period lattice e.omega() of the elliptic curve
5700
e.
5701
5702
EXAMPLES::
5703
5704
sage: e = pari([0,0,0,-82,0]).ellinit()
5705
sage: e.elleta()
5706
[3.60546360143265, 3.60546360143265*I]
5707
sage: w1,w2 = e.omega()
5708
sage: eta1, eta2 = e.elleta()
5709
sage: w1*eta2-w2*eta1
5710
6.28318530717959*I
5711
sage: w1*eta2-w2*eta1 == pari(2*pi*I)
5712
True
5713
sage: pari([0,0,0,-82,0]).ellinit(flag=1).elleta()
5714
Traceback (most recent call last):
5715
...
5716
PariError: incorrect type in elleta
5717
"""
5718
pari_catch_sig_on()
5719
return P.new_gen(elleta(self.g, prec_bits_to_words(precision)))
5720
5721
def ellheight(self, a, long flag=2, unsigned long precision=0):
5722
"""
5723
e.ellheight(a, flag=2): return the global Neron-Tate height of the
5724
point a on the elliptic curve e.
5725
5726
INPUT:
5727
5728
5729
- ``e`` - elliptic curve over `\QQ`,
5730
assumed to be in a standard minimal integral model (as given by
5731
ellminimalmodel)
5732
5733
- ``a`` - rational point on e
5734
5735
- ``flag (optional)`` - specifies which algorithm to
5736
be used for computing the archimedean local height:
5737
5738
- ``0`` - uses sigma- and theta-functions and a trick
5739
due to J. Silverman
5740
5741
- ``1`` - uses Tate's `4^n` algorithm
5742
5743
- ``2`` - uses Mestre's AGM algorithm (this is the
5744
default, being faster than the other two)
5745
5746
- ``precision (optional)`` - the precision of the
5747
result, in bits.
5748
5749
EXAMPLES::
5750
5751
sage: e = pari([0,1,1,-2,0]).ellinit().ellminimalmodel()[0]
5752
sage: e.ellheight([1,0])
5753
0.476711659343740
5754
sage: e.ellheight([1,0], flag=0)
5755
0.476711659343740
5756
sage: e.ellheight([1,0], flag=1)
5757
0.476711659343740
5758
sage: e.ellheight([1,0], precision=128).sage()
5759
0.47671165934373953737948605888465305932
5760
"""
5761
cdef gen t0 = objtogen(a)
5762
pari_catch_sig_on()
5763
return P.new_gen(ellheight0(self.g, t0.g, flag, prec_bits_to_words(precision)))
5764
5765
def ellheightmatrix(self, x, unsigned long precision=0):
5766
"""
5767
e.ellheightmatrix(x): return the height matrix for the vector x of
5768
points on the elliptic curve e.
5769
5770
In other words, it returns the Gram matrix of x with respect to the
5771
height bilinear form on e (see ellbil).
5772
5773
INPUT:
5774
5775
5776
- ``e`` - elliptic curve over `\QQ`,
5777
assumed to be in a standard minimal integral model (as given by
5778
ellminimalmodel)
5779
5780
- ``x`` - vector of rational points on e
5781
5782
5783
EXAMPLES::
5784
5785
sage: e = pari([0,1,1,-2,0]).ellinit().ellminimalmodel()[0]
5786
sage: e.ellheightmatrix([[1,0], [-1,1]])
5787
[0.476711659343740, 0.418188984498861; 0.418188984498861, 0.686667083305587]
5788
5789
It is allowed to call :meth:`ellinit` with ``flag=1``::
5790
5791
sage: E = pari([0,1,1,-2,0]).ellinit(flag=1)
5792
sage: E.ellheightmatrix([[1,0], [-1,1]], precision=128).sage()
5793
[0.47671165934373953737948605888465305932 0.41818898449886058562988945821587638244]
5794
[0.41818898449886058562988945821587638244 0.68666708330558658572355210295409678904]
5795
"""
5796
cdef gen t0 = objtogen(x)
5797
pari_catch_sig_on()
5798
return P.new_gen(mathell(self.g, t0.g, prec_bits_to_words(precision)))
5799
5800
def ellisoncurve(self, x):
5801
"""
5802
e.ellisoncurve(x): return True if the point x is on the elliptic
5803
curve e, False otherwise.
5804
5805
If the point or the curve have inexact coefficients, an attempt is
5806
made to take this into account.
5807
5808
EXAMPLES::
5809
5810
sage: e = pari([0,1,1,-2,0]).ellinit()
5811
sage: e.ellisoncurve([1,0])
5812
True
5813
sage: e.ellisoncurve([1,1])
5814
False
5815
sage: e.ellisoncurve([1,0.00000000000000001])
5816
False
5817
sage: e.ellisoncurve([1,0.000000000000000001])
5818
True
5819
sage: e.ellisoncurve([0])
5820
True
5821
"""
5822
cdef gen t0 = objtogen(x)
5823
pari_catch_sig_on()
5824
cdef int t = oncurve(self.g, t0.g)
5825
pari_catch_sig_off()
5826
return t != 0
5827
5828
def elllocalred(self, p):
5829
r"""
5830
e.elllocalred(p): computes the data of local reduction at the prime
5831
p on the elliptic curve e
5832
5833
For more details on local reduction and Kodaira types, see IV.8 and
5834
IV.9 in J. Silverman's book "Advanced topics in the arithmetic of
5835
elliptic curves".
5836
5837
INPUT:
5838
5839
5840
- ``e`` - elliptic curve with coefficients in `\ZZ`
5841
5842
- ``p`` - prime number
5843
5844
5845
OUTPUT:
5846
5847
5848
- ``gen`` - the exponent of p in the arithmetic
5849
conductor of e
5850
5851
- ``gen`` - the Kodaira type of e at p, encoded as an
5852
integer:
5853
5854
- ``1`` - type `I_0`: good reduction,
5855
nonsingular curve of genus 1
5856
5857
- ``2`` - type `II`: rational curve with a
5858
cusp
5859
5860
- ``3`` - type `III`: two nonsingular rational
5861
curves intersecting tangentially at one point
5862
5863
- ``4`` - type `IV`: three nonsingular
5864
rational curves intersecting at one point
5865
5866
- ``5`` - type `I_1`: rational curve with a
5867
node
5868
5869
- ``6 or larger`` - think of it as `4+v`, then
5870
it is type `I_v`: `v` nonsingular rational curves
5871
arranged as a `v`-gon
5872
5873
- ``-1`` - type `I_0^*`: nonsingular rational
5874
curve of multiplicity two with four nonsingular rational curves of
5875
multiplicity one attached
5876
5877
- ``-2`` - type `II^*`: nine nonsingular
5878
rational curves in a special configuration
5879
5880
- ``-3`` - type `III^*`: eight nonsingular
5881
rational curves in a special configuration
5882
5883
- ``-4`` - type `IV^*`: seven nonsingular
5884
rational curves in a special configuration
5885
5886
- ``-5 or smaller`` - think of it as `-4-v`,
5887
then it is type `I_v^*`: chain of `v+1`
5888
nonsingular rational curves of multiplicity two, with two
5889
nonsingular rational curves of multiplicity one attached at either
5890
end
5891
5892
- ``gen`` - a vector with 4 components, giving the
5893
coordinate changes done during the local reduction; if the first
5894
component is 1, then the equation for e was already minimal at p
5895
5896
- ``gen`` - the local Tamagawa number `c_p`
5897
5898
5899
EXAMPLES:
5900
5901
Type `I_0`::
5902
5903
sage: e = pari([0,0,0,0,1]).ellinit()
5904
sage: e.elllocalred(7)
5905
[0, 1, [1, 0, 0, 0], 1]
5906
5907
Type `II`::
5908
5909
sage: e = pari(EllipticCurve('27a3').a_invariants()).ellinit()
5910
sage: e.elllocalred(3)
5911
[3, 2, [1, -1, 0, 1], 1]
5912
5913
Type `III`::
5914
5915
sage: e = pari(EllipticCurve('24a4').a_invariants()).ellinit()
5916
sage: e.elllocalred(2)
5917
[3, 3, [1, 1, 0, 1], 2]
5918
5919
Type `IV`::
5920
5921
sage: e = pari(EllipticCurve('20a2').a_invariants()).ellinit()
5922
sage: e.elllocalred(2)
5923
[2, 4, [1, 1, 0, 1], 3]
5924
5925
Type `I_1`::
5926
5927
sage: e = pari(EllipticCurve('11a2').a_invariants()).ellinit()
5928
sage: e.elllocalred(11)
5929
[1, 5, [1, 0, 0, 0], 1]
5930
5931
Type `I_2`::
5932
5933
sage: e = pari(EllipticCurve('14a4').a_invariants()).ellinit()
5934
sage: e.elllocalred(2)
5935
[1, 6, [1, 0, 0, 0], 2]
5936
5937
Type `I_6`::
5938
5939
sage: e = pari(EllipticCurve('14a1').a_invariants()).ellinit()
5940
sage: e.elllocalred(2)
5941
[1, 10, [1, 0, 0, 0], 2]
5942
5943
Type `I_0^*`::
5944
5945
sage: e = pari(EllipticCurve('32a3').a_invariants()).ellinit()
5946
sage: e.elllocalred(2)
5947
[5, -1, [1, 1, 1, 0], 1]
5948
5949
Type `II^*`::
5950
5951
sage: e = pari(EllipticCurve('24a5').a_invariants()).ellinit()
5952
sage: e.elllocalred(2)
5953
[3, -2, [1, 2, 1, 4], 1]
5954
5955
Type `III^*`::
5956
5957
sage: e = pari(EllipticCurve('24a2').a_invariants()).ellinit()
5958
sage: e.elllocalred(2)
5959
[3, -3, [1, 2, 1, 4], 2]
5960
5961
Type `IV^*`::
5962
5963
sage: e = pari(EllipticCurve('20a1').a_invariants()).ellinit()
5964
sage: e.elllocalred(2)
5965
[2, -4, [1, 0, 1, 2], 3]
5966
5967
Type `I_1^*`::
5968
5969
sage: e = pari(EllipticCurve('24a1').a_invariants()).ellinit()
5970
sage: e.elllocalred(2)
5971
[3, -5, [1, 0, 1, 2], 4]
5972
5973
Type `I_6^*`::
5974
5975
sage: e = pari(EllipticCurve('90c2').a_invariants()).ellinit()
5976
sage: e.elllocalred(3)
5977
[2, -10, [1, 96, 1, 316], 4]
5978
"""
5979
cdef gen t0 = objtogen(p)
5980
pari_catch_sig_on()
5981
return P.new_gen(elllocalred(self.g, t0.g))
5982
5983
def elllseries(self, s, A=1, unsigned long precision=0):
5984
"""
5985
e.elllseries(s, A=1): return the value of the `L`-series of
5986
the elliptic curve e at the complex number s.
5987
5988
This uses an `O(N^{1/2})` algorithm in the conductor N of
5989
e, so it is impractical for large conductors (say greater than
5990
`10^{12}`).
5991
5992
INPUT:
5993
5994
5995
- ``e`` - elliptic curve defined over `\QQ`
5996
5997
- ``s`` - complex number
5998
5999
- ``A (optional)`` - cutoff point for the integral,
6000
which must be chosen close to 1 for best speed.
6001
6002
6003
EXAMPLES::
6004
6005
sage: e = pari([0,1,1,-2,0]).ellinit()
6006
sage: e.elllseries(2.1)
6007
0.402838047956645
6008
sage: e.elllseries(1, precision=128)
6009
2.87490929644255 E-38
6010
sage: e.elllseries(1, precision=256)
6011
3.00282377034977 E-77
6012
sage: e.elllseries(-2)
6013
0
6014
sage: e.elllseries(2.1, A=1.1)
6015
0.402838047956645
6016
"""
6017
cdef gen t0 = objtogen(s)
6018
cdef gen t1 = objtogen(A)
6019
pari_catch_sig_on()
6020
return P.new_gen(elllseries(self.g, t0.g, t1.g, prec_bits_to_words(precision)))
6021
6022
def ellminimalmodel(self):
6023
"""
6024
ellminimalmodel(e): return the standard minimal integral model of
6025
the rational elliptic curve e and the corresponding change of
6026
variables. INPUT:
6027
6028
6029
- ``e`` - gen (that defines an elliptic curve)
6030
6031
6032
OUTPUT:
6033
6034
6035
- ``gen`` - minimal model
6036
6037
- ``gen`` - change of coordinates
6038
6039
6040
EXAMPLES::
6041
6042
sage: e = pari([1,2,3,4,5]).ellinit()
6043
sage: F, ch = e.ellminimalmodel()
6044
sage: F[:5]
6045
[1, -1, 0, 4, 3]
6046
sage: ch
6047
[1, -1, 0, -1]
6048
sage: e.ellchangecurve(ch)[:5]
6049
[1, -1, 0, 4, 3]
6050
"""
6051
cdef GEN x, y
6052
cdef gen model, change
6053
cdef pari_sp t
6054
pari_catch_sig_on()
6055
x = ellminimalmodel(self.g, &y)
6056
change = P.new_gen_noclear(y)
6057
model = P.new_gen(x)
6058
return model, change
6059
6060
def ellorder(self, x):
6061
"""
6062
e.ellorder(x): return the order of the point x on the elliptic
6063
curve e (return 0 if x is not a torsion point)
6064
6065
INPUT:
6066
6067
6068
- ``e`` - elliptic curve defined over `\QQ`
6069
6070
- ``x`` - point on e
6071
6072
6073
EXAMPLES::
6074
6075
sage: e = pari(EllipticCurve('65a1').a_invariants()).ellinit()
6076
6077
A point of order two::
6078
6079
sage: e.ellorder([0,0])
6080
2
6081
6082
And a point of infinite order::
6083
6084
sage: e.ellorder([1,0])
6085
0
6086
"""
6087
cdef gen t0 = objtogen(x)
6088
pari_catch_sig_on()
6089
return P.new_gen(orderell(self.g, t0.g))
6090
6091
def ellordinate(self, x, unsigned long precision=0):
6092
"""
6093
e.ellordinate(x): return the `y`-coordinates of the points
6094
on the elliptic curve e having x as `x`-coordinate.
6095
6096
INPUT:
6097
6098
6099
- ``e`` - elliptic curve
6100
6101
- ``x`` - x-coordinate (can be a complex or p-adic
6102
number, or a more complicated object like a power series)
6103
6104
6105
EXAMPLES::
6106
6107
sage: e = pari([0,1,1,-2,0]).ellinit()
6108
sage: e.ellordinate(0)
6109
[0, -1]
6110
sage: e.ellordinate(I)
6111
[0.582203589721741 - 1.38606082464177*I, -1.58220358972174 + 1.38606082464177*I]
6112
sage: e.ellordinate(I, precision=128)[0].sage()
6113
0.58220358972174117723338947874993600727 - 1.3860608246417697185311834209833653345*I
6114
sage: e.ellordinate(1+3*5^1+O(5^3))
6115
[4*5 + 5^2 + O(5^3), 4 + 3*5^2 + O(5^3)]
6116
sage: e.ellordinate('z+2*z^2+O(z^4)')
6117
[-2*z - 7*z^2 - 23*z^3 + O(z^4), -1 + 2*z + 7*z^2 + 23*z^3 + O(z^4)]
6118
6119
The field in which PARI looks for the point depends on the
6120
input field::
6121
6122
sage: e.ellordinate(5)
6123
[]
6124
sage: e.ellordinate(5.0)
6125
[11.3427192823270, -12.3427192823270]
6126
sage: e.ellordinate(RR(-3))
6127
[-1/2 + 3.42782730020052*I, -1/2 - 3.42782730020052*I]
6128
"""
6129
cdef gen t0 = objtogen(x)
6130
pari_catch_sig_on()
6131
return P.new_gen(ellordinate(self.g, t0.g, prec_bits_to_words(precision)))
6132
6133
def ellpointtoz(self, pt, unsigned long precision=0):
6134
"""
6135
e.ellpointtoz(pt): return the complex number (in the fundamental
6136
parallelogram) corresponding to the point ``pt`` on the elliptic curve
6137
e, under the complex uniformization of e given by the Weierstrass
6138
p-function.
6139
6140
The complex number z returned by this function lies in the
6141
parallelogram formed by the real and complex periods of e, as given
6142
by e.omega().
6143
6144
EXAMPLES::
6145
6146
sage: e = pari([0,0,0,1,0]).ellinit()
6147
sage: e.ellpointtoz([0,0])
6148
1.85407467730137
6149
6150
The point at infinity is sent to the complex number 0::
6151
6152
sage: e.ellpointtoz([0])
6153
0
6154
"""
6155
cdef gen t0 = objtogen(pt)
6156
pari_catch_sig_on()
6157
return P.new_gen(zell(self.g, t0.g, prec_bits_to_words(precision)))
6158
6159
def ellpow(self, z, n):
6160
"""
6161
e.ellpow(z, n): return `n` times the point `z` on the elliptic
6162
curve `e`.
6163
6164
INPUT:
6165
6166
6167
- ``e`` - elliptic curve
6168
6169
- ``z`` - point on `e`
6170
6171
- ``n`` - integer, or a complex quadratic integer of complex
6172
multiplication for `e`. Complex multiplication currently
6173
only works if `e` is defined over `Q`.
6174
6175
6176
EXAMPLES: We consider a curve with CM by `Z[i]`::
6177
6178
sage: e = pari([0,0,0,3,0]).ellinit()
6179
sage: p = [1,2] # Point of infinite order
6180
6181
Multiplication by two::
6182
6183
sage: e.ellpow([0,0], 2)
6184
[0]
6185
sage: e.ellpow(p, 2)
6186
[1/4, -7/8]
6187
6188
Complex multiplication::
6189
6190
sage: q = e.ellpow(p, 1+I); q
6191
[-2*I, 1 + I]
6192
sage: e.ellpow(q, 1-I)
6193
[1/4, -7/8]
6194
6195
TESTS::
6196
6197
sage: for D in [-7, -8, -11, -12, -16, -19, -27, -28]: # long time (1s)
6198
....: hcpol = hilbert_class_polynomial(D)
6199
....: j = hcpol.roots(multiplicities=False)[0]
6200
....: t = (1728-j)/(27*j)
6201
....: E = EllipticCurve([4*t,16*t^2])
6202
....: P = E.point([0, 4*t])
6203
....: assert(E.j_invariant() == j)
6204
....: #
6205
....: # Compute some CM number and its minimal polynomial
6206
....: #
6207
....: cm = pari('cm = (3*quadgen(%s)+2)'%D)
6208
....: cm_minpoly = pari('minpoly(cm)')
6209
....: #
6210
....: # Evaluate cm_minpoly(cm)(P), which should be zero
6211
....: #
6212
....: e = pari(E) # Convert E to PARI
6213
....: P2 = e.ellpow(P, cm_minpoly[2]*cm + cm_minpoly[1])
6214
....: P0 = e.elladd(e.ellpow(P, cm_minpoly[0]), e.ellpow(P2, cm))
6215
....: assert(P0 == E(0))
6216
"""
6217
cdef gen t0 = objtogen(z)
6218
cdef gen t1 = objtogen(n)
6219
pari_catch_sig_on()
6220
return P.new_gen(powell(self.g, t0.g, t1.g))
6221
6222
def ellrootno(self, p=1):
6223
"""
6224
e.ellrootno(p): return the (local or global) root number of the
6225
`L`-series of the elliptic curve e
6226
6227
If p is a prime number, the local root number at p is returned. If
6228
p is 1, the global root number is returned. Note that the global
6229
root number is the sign of the functional equation of the
6230
`L`-series, and therefore conjecturally equal to the parity
6231
of the rank of e.
6232
6233
INPUT:
6234
6235
6236
- ``e`` - elliptic curve over `\QQ`
6237
6238
- ``p (default = 1)`` - 1 or a prime number
6239
6240
6241
OUTPUT: 1 or -1
6242
6243
EXAMPLES: Here is a curve of rank 3::
6244
6245
sage: e = pari([0,0,0,-82,0]).ellinit()
6246
sage: e.ellrootno()
6247
-1
6248
sage: e.ellrootno(2)
6249
1
6250
sage: e.ellrootno(1009)
6251
1
6252
"""
6253
cdef gen t0 = objtogen(p)
6254
pari_catch_sig_on()
6255
rootno = ellrootno(self.g, t0.g)
6256
pari_catch_sig_off()
6257
return rootno
6258
6259
def ellsigma(self, z, long flag=0, unsigned long precision=0):
6260
"""
6261
e.ellsigma(z, flag=0): return the value at the complex point z of
6262
the Weierstrass `\sigma` function associated to the
6263
elliptic curve e.
6264
6265
EXAMPLES::
6266
6267
sage: e = pari([0,0,0,1,0]).ellinit()
6268
sage: C.<i> = ComplexField()
6269
sage: e.ellsigma(2+i)
6270
1.43490215804166 + 1.80307856719256*I
6271
"""
6272
cdef gen t0 = objtogen(z)
6273
pari_catch_sig_on()
6274
return P.new_gen(ellsigma(self.g, t0.g, flag, prec_bits_to_words(precision)))
6275
6276
def ellsub(self, z0, z1):
6277
"""
6278
e.ellsub(z0, z1): return z0-z1 on this elliptic curve.
6279
6280
INPUT:
6281
6282
6283
- ``e`` - elliptic curve E
6284
6285
- ``z0`` - point on E
6286
6287
- ``z1`` - point on E
6288
6289
6290
OUTPUT: point on E
6291
6292
EXAMPLES::
6293
6294
sage: e = pari([0, 1, 1, -2, 0]).ellinit()
6295
sage: e.ellsub([1,0], [-1,1])
6296
[0, 0]
6297
"""
6298
cdef gen t0 = objtogen(z0)
6299
cdef gen t1 = objtogen(z1)
6300
pari_catch_sig_on()
6301
return P.new_gen(subell(self.g, t0.g, t1.g))
6302
6303
def elltaniyama(self):
6304
pari_catch_sig_on()
6305
return P.new_gen(taniyama(self.g))
6306
6307
def elltors(self, long flag=0):
6308
"""
6309
e.elltors(flag = 0): return information about the torsion subgroup
6310
of the elliptic curve e
6311
6312
INPUT:
6313
6314
6315
- ``e`` - elliptic curve over `\QQ`
6316
6317
- ``flag (optional)`` - specify which algorithm to
6318
use:
6319
6320
- ``0 (default)`` - use Doud's algorithm: bound
6321
torsion by computing the cardinality of e(GF(p)) for small primes
6322
of good reduction, then look for torsion points using Weierstrass
6323
parametrization and Mazur's classification
6324
6325
- ``1`` - use algorithm given by the Nagell-Lutz
6326
theorem (this is much slower)
6327
6328
6329
OUTPUT:
6330
6331
6332
- ``gen`` - the order of the torsion subgroup, a.k.a.
6333
the number of points of finite order
6334
6335
- ``gen`` - vector giving the structure of the torsion
6336
subgroup as a product of cyclic groups, sorted in non-increasing
6337
order
6338
6339
- ``gen`` - vector giving points on e generating these
6340
cyclic groups
6341
6342
6343
EXAMPLES::
6344
6345
sage: e = pari([1,0,1,-19,26]).ellinit()
6346
sage: e.elltors()
6347
[12, [6, 2], [[-2, 8], [3, -2]]]
6348
"""
6349
pari_catch_sig_on()
6350
return P.new_gen(elltors0(self.g, flag))
6351
6352
def ellzeta(self, z, unsigned long precision=0):
6353
"""
6354
e.ellzeta(z): return the value at the complex point z of the
6355
Weierstrass `\zeta` function associated with the elliptic
6356
curve e.
6357
6358
.. note::
6359
6360
This function has infinitely many poles (one of which is at
6361
z=0); attempting to evaluate it too close to one of the
6362
poles will result in a PariError.
6363
6364
INPUT:
6365
6366
6367
- ``e`` - elliptic curve
6368
6369
- ``z`` - complex number
6370
6371
6372
EXAMPLES::
6373
6374
sage: e = pari([0,0,0,1,0]).ellinit()
6375
sage: e.ellzeta(1)
6376
1.06479841295883 + 0.E-19*I # 32-bit
6377
1.06479841295883 + 5.42101086242752 E-20*I # 64-bit
6378
sage: C.<i> = ComplexField()
6379
sage: e.ellzeta(i-1)
6380
-0.350122658523049 - 0.350122658523049*I
6381
"""
6382
cdef gen t0 = objtogen(z)
6383
pari_catch_sig_on()
6384
return P.new_gen(ellzeta(self.g, t0.g, prec_bits_to_words(precision)))
6385
6386
def ellztopoint(self, z, unsigned long precision=0):
6387
"""
6388
e.ellztopoint(z): return the point on the elliptic curve e
6389
corresponding to the complex number z, under the usual complex
6390
uniformization of e by the Weierstrass p-function.
6391
6392
INPUT:
6393
6394
6395
- ``e`` - elliptic curve
6396
6397
- ``z`` - complex number
6398
6399
6400
OUTPUT point on e
6401
6402
EXAMPLES::
6403
6404
sage: e = pari([0,0,0,1,0]).ellinit()
6405
sage: C.<i> = ComplexField()
6406
sage: e.ellztopoint(1+i)
6407
[0.E-19 - 1.02152286795670*I, -0.149072813701096 - 0.149072813701096*I] # 32-bit
6408
[7.96075508054992 E-21 - 1.02152286795670*I, -0.149072813701096 - 0.149072813701096*I] # 64-bit
6409
6410
Complex numbers belonging to the period lattice of e are of course
6411
sent to the point at infinity on e::
6412
6413
sage: e.ellztopoint(0)
6414
[0]
6415
"""
6416
cdef gen t0 = objtogen(z)
6417
pari_catch_sig_on()
6418
return P.new_gen(pointell(self.g, t0.g, prec_bits_to_words(precision)))
6419
6420
def omega(self):
6421
"""
6422
e.omega(): return basis for the period lattice of the elliptic
6423
curve e.
6424
6425
EXAMPLES::
6426
6427
sage: e = pari([0, -1, 1, -10, -20]).ellinit()
6428
sage: e.omega()
6429
[1.26920930427955, -0.634604652139777 - 1.45881661693850*I]
6430
"""
6431
return self[14:16]
6432
6433
def disc(self):
6434
"""
6435
e.disc(): return the discriminant of the elliptic curve e.
6436
6437
EXAMPLES::
6438
6439
sage: e = pari([0, -1, 1, -10, -20]).ellinit()
6440
sage: e.disc()
6441
-161051
6442
sage: _.factor()
6443
[-1, 1; 11, 5]
6444
"""
6445
return self[11]
6446
6447
def j(self):
6448
"""
6449
e.j(): return the j-invariant of the elliptic curve e.
6450
6451
EXAMPLES::
6452
6453
sage: e = pari([0, -1, 1, -10, -20]).ellinit()
6454
sage: e.j()
6455
-122023936/161051
6456
sage: _.factor()
6457
[-1, 1; 2, 12; 11, -5; 31, 3]
6458
"""
6459
return self[12]
6460
6461
def ellj(self, unsigned long precision=0):
6462
"""
6463
Elliptic `j`-invariant of ``self``.
6464
6465
EXAMPLES::
6466
6467
sage: pari(I).ellj()
6468
1728.00000000000
6469
sage: pari(3*I).ellj()
6470
153553679.396729
6471
sage: pari('quadgen(-3)').ellj()
6472
0.E-54
6473
sage: pari('quadgen(-7)').ellj(precision=256).sage()
6474
-3375.000000000000000000000000000000000000000000000000000000000000000000000000
6475
sage: pari(-I).ellj()
6476
Traceback (most recent call last):
6477
...
6478
PariError: argument '-I' does not belong to upper half-plane
6479
"""
6480
pari_catch_sig_on()
6481
return P.new_gen(jell(self.g, prec_bits_to_words(precision)))
6482
6483
6484
###########################################
6485
# 6: Functions related to NUMBER FIELDS
6486
###########################################
6487
def bnfcertify(self):
6488
r"""
6489
``bnf`` being as output by ``bnfinit``, checks whether the result is
6490
correct, i.e. whether the calculation of the contents of ``self``
6491
are correct without assuming the Generalized Riemann Hypothesis.
6492
If it is correct, the answer is 1. If not, the program may output
6493
some error message or loop indefinitely.
6494
6495
For more information about PARI and the Generalized Riemann
6496
Hypothesis, see [PariUsers], page 120.
6497
6498
REFERENCES:
6499
6500
.. [PariUsers] User's Guide to PARI/GP,
6501
http://pari.math.u-bordeaux.fr/pub/pari/manuals/2.5.1/users.pdf
6502
"""
6503
pari_catch_sig_on()
6504
n = bnfcertify(self.g)
6505
pari_catch_sig_off()
6506
return n
6507
6508
def bnfinit(self, long flag=0, tech=None, unsigned long precision=0):
6509
cdef gen t0
6510
if tech is None:
6511
pari_catch_sig_on()
6512
return P.new_gen(bnfinit0(self.g, flag, NULL, prec_bits_to_words(precision)))
6513
else:
6514
t0 = objtogen(tech)
6515
pari_catch_sig_on()
6516
return P.new_gen(bnfinit0(self.g, flag, t0.g, prec_bits_to_words(precision)))
6517
6518
def bnfisintnorm(self, x):
6519
cdef gen t0 = objtogen(x)
6520
pari_catch_sig_on()
6521
return P.new_gen(bnfisintnorm(self.g, t0.g))
6522
6523
def bnfisnorm(self, x, long flag=0):
6524
cdef gen t0 = objtogen(x)
6525
pari_catch_sig_on()
6526
return P.new_gen(bnfisnorm(self.g, t0.g, flag))
6527
6528
def bnfisprincipal(self, x, long flag=1):
6529
cdef gen t0 = objtogen(x)
6530
pari_catch_sig_on()
6531
return P.new_gen(bnfisprincipal0(self.g, t0.g, flag))
6532
6533
def bnfnarrow(self):
6534
pari_catch_sig_on()
6535
return P.new_gen(buchnarrow(self.g))
6536
6537
def bnfsunit(self, S, unsigned long precision=0):
6538
cdef gen t0 = objtogen(S)
6539
pari_catch_sig_on()
6540
return P.new_gen(bnfsunit(self.g, t0.g, prec_bits_to_words(precision)))
6541
6542
def bnfunit(self):
6543
pari_catch_sig_on()
6544
return P.new_gen(bnf_get_fu(self.g))
6545
6546
def bnfisunit(self, x):
6547
cdef gen t0 = objtogen(x)
6548
pari_catch_sig_on()
6549
return P.new_gen(bnfisunit(self.g, t0.g))
6550
6551
def bnrclassno(self, I):
6552
r"""
6553
Return the order of the ray class group of self modulo ``I``.
6554
6555
INPUT:
6556
6557
- ``self``: a pari "BNF" object representing a number field
6558
- ``I``: a pari "BID" object representing an ideal of self
6559
6560
OUTPUT: integer
6561
6562
TESTS::
6563
6564
sage: K.<z> = QuadraticField(-23)
6565
sage: p = K.primes_above(3)[0]
6566
sage: K.pari_bnf().bnrclassno(p._pari_bid_())
6567
3
6568
"""
6569
cdef gen t0 = objtogen(I)
6570
pari_catch_sig_on()
6571
return P.new_gen(bnrclassno(self.g, t0.g))
6572
6573
def bnfissunit(self, sunit_data, x):
6574
cdef gen t0 = objtogen(x)
6575
cdef gen t1 = objtogen(sunit_data)
6576
pari_catch_sig_on()
6577
return P.new_gen(bnfissunit(self.g, t1.g, t0.g))
6578
6579
def dirzetak(self, n):
6580
cdef gen t0 = objtogen(n)
6581
pari_catch_sig_on()
6582
return P.new_gen(dirzetak(self.g, t0.g))
6583
6584
def galoisapply(self, aut, x):
6585
cdef gen t0 = objtogen(aut)
6586
cdef gen t1 = objtogen(x)
6587
pari_catch_sig_on()
6588
return P.new_gen(galoisapply(self.g, t0.g, t1.g))
6589
6590
def galoisinit(self, den=None):
6591
"""
6592
galoisinit(K{,den}): calculate Galois group of number field K; see PARI manual
6593
for meaning of den
6594
"""
6595
cdef gen t0
6596
if den is None:
6597
pari_catch_sig_on()
6598
return P.new_gen(galoisinit(self.g, NULL))
6599
else:
6600
t0 = objtogen(den)
6601
pari_catch_sig_on()
6602
return P.new_gen(galoisinit(self.g, t0.g))
6603
6604
def galoispermtopol(self, perm):
6605
cdef gen t0 = objtogen(perm)
6606
pari_catch_sig_on()
6607
return P.new_gen(galoispermtopol(self.g, t0.g))
6608
6609
def galoisfixedfield(self, perm, long flag=0, v=-1):
6610
cdef gen t0 = objtogen(perm)
6611
pari_catch_sig_on()
6612
return P.new_gen(galoisfixedfield(self.g, t0.g, flag, P.get_var(v)))
6613
6614
def idealred(self, I, vdir=0):
6615
cdef gen t0 = objtogen(I)
6616
cdef gen t1 = objtogen(vdir)
6617
pari_catch_sig_on()
6618
return P.new_gen(idealred0(self.g, t0.g, t1.g if vdir else NULL))
6619
6620
def idealadd(self, x, y):
6621
cdef gen t0 = objtogen(x)
6622
cdef gen t1 = objtogen(y)
6623
pari_catch_sig_on()
6624
return P.new_gen(idealadd(self.g, t0.g, t1.g))
6625
6626
def idealaddtoone(self, x, y):
6627
cdef gen t0 = objtogen(x)
6628
cdef gen t1 = objtogen(y)
6629
pari_catch_sig_on()
6630
return P.new_gen(idealaddtoone0(self.g, t0.g, t1.g))
6631
6632
def idealappr(self, x, long flag=0):
6633
cdef gen t0 = objtogen(x)
6634
pari_catch_sig_on()
6635
return P.new_gen(idealappr0(self.g, t0.g, flag))
6636
6637
def idealcoprime(self, x, y):
6638
"""
6639
Given two integral ideals x and y of a pari number field self,
6640
return an element a of the field (expressed in the integral
6641
basis of self) such that a*x is an integral ideal coprime to
6642
y.
6643
6644
EXAMPLES::
6645
6646
sage: F = NumberField(x^3-2, 'alpha')
6647
sage: nf = F._pari_()
6648
sage: x = pari('[1, -1, 2]~')
6649
sage: y = pari('[1, -1, 3]~')
6650
sage: nf.idealcoprime(x, y)
6651
[1, 0, 0]~
6652
6653
sage: y = pari('[2, -2, 4]~')
6654
sage: nf.idealcoprime(x, y)
6655
[5/43, 9/43, -1/43]~
6656
"""
6657
cdef gen t0 = objtogen(x)
6658
cdef gen t1 = objtogen(y)
6659
pari_catch_sig_on()
6660
return P.new_gen(idealcoprime(self.g, t0.g, t1.g))
6661
6662
def idealdiv(self, x, y, long flag=0):
6663
cdef gen t0 = objtogen(x)
6664
cdef gen t1 = objtogen(y)
6665
pari_catch_sig_on()
6666
return P.new_gen(idealdiv0(self.g, t0.g, t1.g, flag))
6667
6668
def idealfactor(self, x):
6669
cdef gen t0 = objtogen(x)
6670
pari_catch_sig_on()
6671
return P.new_gen(idealfactor(self.g, t0.g))
6672
6673
def idealhnf(self, a, b=None):
6674
cdef gen t0 = objtogen(a)
6675
cdef gen t1
6676
if b is None:
6677
pari_catch_sig_on()
6678
return P.new_gen(idealhnf(self.g, t0.g))
6679
else:
6680
t1 = objtogen(b)
6681
pari_catch_sig_on()
6682
return P.new_gen(idealhnf0(self.g, t0.g, t1.g))
6683
6684
def idealintersection(self, x, y):
6685
cdef gen t0 = objtogen(x)
6686
cdef gen t1 = objtogen(y)
6687
pari_catch_sig_on()
6688
return P.new_gen(idealintersect(self.g, t0.g, t1.g))
6689
6690
def ideallist(self, long bound, long flag = 4):
6691
"""
6692
Vector of vectors `L` of all idealstar of all ideals of `norm <= bound`.
6693
6694
The binary digits of flag mean:
6695
6696
- 1: give generators;
6697
- 2: add units;
6698
- 4: (default) give only the ideals and not the bid.
6699
6700
EXAMPLES::
6701
6702
sage: R.<x> = PolynomialRing(QQ)
6703
sage: K.<a> = NumberField(x^2 + 1)
6704
sage: L = K.pari_nf().ideallist(100)
6705
6706
Now we have our list `L`. Entry `L[n-1]` contains all ideals of
6707
norm `n`::
6708
6709
sage: L[0] # One ideal of norm 1.
6710
[[1, 0; 0, 1]]
6711
sage: L[64] # 4 ideals of norm 65.
6712
[[65, 8; 0, 1], [65, 47; 0, 1], [65, 18; 0, 1], [65, 57; 0, 1]]
6713
"""
6714
pari_catch_sig_on()
6715
return P.new_gen(ideallist0(self.g, bound, flag))
6716
6717
def ideallog(self, x, bid):
6718
"""
6719
Return the discrete logarithm of the unit x in (ring of integers)/bid.
6720
6721
INPUT:
6722
6723
- ``self`` - a pari number field
6724
6725
- ``bid`` - a big ideal structure (corresponding to an ideal I
6726
of self) output by idealstar
6727
6728
- ``x`` - an element of self with valuation zero at all
6729
primes dividing I
6730
6731
OUTPUT:
6732
6733
- the discrete logarithm of x on the generators given in bid[2]
6734
6735
EXAMPLE::
6736
6737
sage: F = NumberField(x^3-2, 'alpha')
6738
sage: nf = F._pari_()
6739
sage: I = pari('[1, -1, 2]~')
6740
sage: bid = nf.idealstar(I)
6741
sage: x = pari('5')
6742
sage: nf.ideallog(x, bid)
6743
[25]~
6744
"""
6745
cdef gen t0 = objtogen(x)
6746
cdef gen t1 = objtogen(bid)
6747
pari_catch_sig_on()
6748
return P.new_gen(ideallog(self.g, t0.g, t1.g))
6749
6750
def idealmul(self, x, y, long flag=0):
6751
cdef gen t0 = objtogen(x)
6752
cdef gen t1 = objtogen(y)
6753
pari_catch_sig_on()
6754
if flag == 0:
6755
return P.new_gen(idealmul(self.g, t0.g, t1.g))
6756
else:
6757
return P.new_gen(idealmulred(self.g, t0.g, t1.g))
6758
6759
def idealnorm(self, x):
6760
cdef gen t0 = objtogen(x)
6761
pari_catch_sig_on()
6762
return P.new_gen(idealnorm(self.g, t0.g))
6763
6764
def idealprimedec(nf, p):
6765
"""
6766
Prime ideal decomposition of the prime number `p` in the number
6767
field `nf` as a vector of 5 component vectors `[p,a,e,f,b]`
6768
representing the prime ideals `p O_K + a O_K`, `e` ,`f` as usual,
6769
`a` as vector of components on the integral basis, `b` Lenstra's
6770
constant.
6771
6772
EXAMPLES::
6773
6774
sage: K.<i> = QuadraticField(-1)
6775
sage: F = pari(K).idealprimedec(5); F
6776
[[5, [-2, 1]~, 1, 1, [2, 1]~], [5, [2, 1]~, 1, 1, [-2, 1]~]]
6777
sage: F[0].pr_get_p()
6778
5
6779
"""
6780
cdef gen t0 = objtogen(p)
6781
pari_catch_sig_on()
6782
return P.new_gen(idealprimedec(nf.g, t0.g))
6783
6784
def idealstar(self, I, long flag=1):
6785
"""
6786
Return the big ideal (bid) structure of modulus I.
6787
6788
INPUT:
6789
6790
- ``self`` - a pari number field
6791
6792
- ``I`` -- an ideal of self, or a row vector whose first
6793
component is an ideal and whose second component
6794
is a row vector of r_1 0 or 1.
6795
6796
- ``flag`` - determines the amount of computation and the shape
6797
of the output:
6798
6799
- ``1`` (default): return a bid structure without
6800
generators
6801
6802
- ``2``: return a bid structure with generators (slower)
6803
6804
- ``0`` (deprecated): only outputs units of (ring of integers/I)
6805
as an abelian group, i.e as a 3-component
6806
vector [h,d,g]: h is the order, d is the vector
6807
of SNF cyclic components and g the corresponding
6808
generators. This flag is deprecated: it is in
6809
fact slightly faster to compute a true bid
6810
structure, which contains much more information.
6811
6812
EXAMPLE::
6813
6814
sage: F = NumberField(x^3-2, 'alpha')
6815
sage: nf = F._pari_()
6816
sage: I = pari('[1, -1, 2]~')
6817
sage: nf.idealstar(I)
6818
[[[43, 9, 5; 0, 1, 0; 0, 0, 1], [0]], [42, [42]], Mat([[43, [9, 1, 0]~, 1, 1, [-5, -9, 1]~], 1]), [[[[42], [[3, 0, 0]~], [[3, 0, 0]~], [Vecsmall([])], 1]], [[], [], []]], Mat(1)]
6819
"""
6820
cdef gen t0 = objtogen(I)
6821
pari_catch_sig_on()
6822
return P.new_gen(idealstar0(self.g, t0.g, flag))
6823
6824
def idealtwoelt(self, x, a=None):
6825
cdef gen t0 = objtogen(x)
6826
cdef gen t1
6827
if a is None:
6828
pari_catch_sig_on()
6829
return P.new_gen(idealtwoelt0(self.g, t0.g, NULL))
6830
else:
6831
t1 = objtogen(a)
6832
pari_catch_sig_on()
6833
return P.new_gen(idealtwoelt0(self.g, t0.g, t1.g))
6834
6835
def idealval(self, x, p):
6836
cdef gen t0 = objtogen(x)
6837
cdef gen t1 = objtogen(p)
6838
pari_catch_sig_on()
6839
v = idealval(self.g, t0.g, t1.g)
6840
pari_catch_sig_off()
6841
return v
6842
6843
def elementval(self, x, p):
6844
cdef gen t0 = objtogen(x)
6845
cdef gen t1 = objtogen(p)
6846
pari_catch_sig_on()
6847
v = nfval(self.g, t0.g, t1.g)
6848
pari_catch_sig_off()
6849
return v
6850
6851
def modreverse(self):
6852
"""
6853
modreverse(x): reverse polymod of the polymod x, if it exists.
6854
6855
EXAMPLES:
6856
"""
6857
pari_catch_sig_on()
6858
return P.new_gen(modreverse(self.g))
6859
6860
def nfbasis(self, long flag=0, fa=None):
6861
"""
6862
nfbasis(x, flag, fa): integral basis of the field QQ[a], where ``a`` is
6863
a root of the polynomial x.
6864
6865
Binary digits of ``flag`` mean:
6866
6867
- 1: assume that no square of a prime>primelimit divides the
6868
discriminant of ``x``.
6869
- 2: use round 2 algorithm instead of round 4.
6870
6871
If present, ``fa`` provides the matrix of a partial factorization of
6872
the discriminant of ``x``, useful if one wants only an order maximal at
6873
certain primes only.
6874
6875
EXAMPLES::
6876
6877
sage: pari('x^3 - 17').nfbasis()
6878
[1, x, 1/3*x^2 - 1/3*x + 1/3]
6879
6880
We test ``flag`` = 1, noting it gives a wrong result when the
6881
discriminant (-4 * `p`^2 * `q` in the example below) has a big square
6882
factor::
6883
6884
sage: p = next_prime(10^10); q = next_prime(p)
6885
sage: x = polygen(QQ); f = x^2 + p^2*q
6886
sage: pari(f).nfbasis(1) # Wrong result
6887
[1, x]
6888
sage: pari(f).nfbasis() # Correct result
6889
[1, 1/10000000019*x]
6890
sage: pari(f).nfbasis(fa = "[2,2; %s,2]"%p) # Correct result and faster
6891
[1, 1/10000000019*x]
6892
6893
TESTS:
6894
6895
``flag`` = 2 should give the same result::
6896
6897
sage: pari('x^3 - 17').nfbasis(flag = 2)
6898
[1, x, 1/3*x^2 - 1/3*x + 1/3]
6899
"""
6900
cdef gen t0
6901
if not fa:
6902
pari_catch_sig_on()
6903
return P.new_gen(nfbasis0(self.g, flag, NULL))
6904
else:
6905
t0 = objtogen(fa)
6906
pari_catch_sig_on()
6907
return P.new_gen(nfbasis0(self.g, flag, t0.g))
6908
6909
def nfbasis_d(self, long flag=0, fa=None):
6910
"""
6911
nfbasis_d(x): Return a basis of the number field defined over QQ
6912
by x and its discriminant.
6913
6914
EXAMPLES::
6915
6916
sage: F = NumberField(x^3-2,'alpha')
6917
sage: F._pari_()[0].nfbasis_d()
6918
([1, y, y^2], -108)
6919
6920
::
6921
6922
sage: G = NumberField(x^5-11,'beta')
6923
sage: G._pari_()[0].nfbasis_d()
6924
([1, y, y^2, y^3, y^4], 45753125)
6925
6926
::
6927
6928
sage: pari([-2,0,0,1]).Polrev().nfbasis_d()
6929
([1, x, x^2], -108)
6930
"""
6931
cdef gen t0
6932
cdef GEN disc
6933
if not fa:
6934
pari_catch_sig_on()
6935
B = P.new_gen_noclear(nfbasis(self.g, &disc, flag, NULL))
6936
else:
6937
t0 = objtogen(fa)
6938
pari_catch_sig_on()
6939
B = P.new_gen_noclear(nfbasis(self.g, &disc, flag, t0.g))
6940
D = P.new_gen(disc)
6941
return B, D
6942
6943
def nfbasistoalg(nf, x):
6944
r"""
6945
Transforms the column vector ``x`` on the integral basis into an
6946
algebraic number.
6947
6948
INPUT:
6949
6950
- ``nf`` -- a number field
6951
- ``x`` -- a column of rational numbers of length equal to the
6952
degree of ``nf`` or a single rational number
6953
6954
OUTPUT:
6955
6956
- A POLMOD representing the element of ``nf`` whose coordinates
6957
are ``x`` in the Z-basis of ``nf``.
6958
6959
EXAMPLES::
6960
6961
sage: x = polygen(QQ)
6962
sage: K.<a> = NumberField(x^3 - 17)
6963
sage: Kpari = K.pari_nf()
6964
sage: Kpari.getattr('zk')
6965
[1, 1/3*y^2 - 1/3*y + 1/3, y]
6966
sage: Kpari.nfbasistoalg(42)
6967
Mod(42, y^3 - 17)
6968
sage: Kpari.nfbasistoalg("[3/2, -5, 0]~")
6969
Mod(-5/3*y^2 + 5/3*y - 1/6, y^3 - 17)
6970
sage: Kpari.getattr('zk') * pari("[3/2, -5, 0]~")
6971
-5/3*y^2 + 5/3*y - 1/6
6972
"""
6973
cdef gen t0 = objtogen(x)
6974
pari_catch_sig_on()
6975
return P.new_gen(basistoalg(nf.g, t0.g))
6976
6977
def nfbasistoalg_lift(nf, x):
6978
r"""
6979
Transforms the column vector ``x`` on the integral basis into a
6980
polynomial representing the algebraic number.
6981
6982
INPUT:
6983
6984
- ``nf`` -- a number field
6985
- ``x`` -- a column of rational numbers of length equal to the
6986
degree of ``nf`` or a single rational number
6987
6988
OUTPUT:
6989
6990
- ``nf.nfbasistoalg(x).lift()``
6991
6992
EXAMPLES::
6993
6994
sage: x = polygen(QQ)
6995
sage: K.<a> = NumberField(x^3 - 17)
6996
sage: Kpari = K.pari_nf()
6997
sage: Kpari.getattr('zk')
6998
[1, 1/3*y^2 - 1/3*y + 1/3, y]
6999
sage: Kpari.nfbasistoalg_lift(42)
7000
42
7001
sage: Kpari.nfbasistoalg_lift("[3/2, -5, 0]~")
7002
-5/3*y^2 + 5/3*y - 1/6
7003
sage: Kpari.getattr('zk') * pari("[3/2, -5, 0]~")
7004
-5/3*y^2 + 5/3*y - 1/6
7005
"""
7006
cdef gen t0 = objtogen(x)
7007
pari_catch_sig_on()
7008
return P.new_gen(gel(basistoalg(nf.g, t0.g), 2))
7009
7010
def nfdisc(self, long flag=0, p=0):
7011
"""
7012
nfdisc(x): Return the discriminant of the number field defined over
7013
QQ by x.
7014
7015
EXAMPLES::
7016
7017
sage: F = NumberField(x^3-2,'alpha')
7018
sage: F._pari_()[0].nfdisc()
7019
-108
7020
7021
::
7022
7023
sage: G = NumberField(x^5-11,'beta')
7024
sage: G._pari_()[0].nfdisc()
7025
45753125
7026
7027
::
7028
7029
sage: f = x^3-2
7030
sage: f._pari_()
7031
x^3 - 2
7032
sage: f._pari_().nfdisc()
7033
-108
7034
"""
7035
cdef gen _p
7036
cdef GEN g
7037
if p != 0:
7038
_p = self.pari(p)
7039
g = _p.g
7040
else:
7041
g = <GEN>NULL
7042
pari_catch_sig_on()
7043
return P.new_gen(nfdisc0(self.g, flag, g))
7044
7045
def nfeltdiveuc(self, x, y):
7046
"""
7047
Given `x` and `y` in the number field ``self``, return `q` such
7048
that `x - q y` is "small".
7049
7050
EXAMPLES::
7051
7052
sage: k.<a> = NumberField(x^2 + 5)
7053
sage: x = 10
7054
sage: y = a + 1
7055
sage: pari(k).nfeltdiveuc(pari(x), pari(y))
7056
[2, -2]~
7057
"""
7058
cdef gen t0 = objtogen(x)
7059
cdef gen t1 = objtogen(y)
7060
pari_catch_sig_on()
7061
return P.new_gen(nfdiveuc(self.g, t0.g, t1.g))
7062
7063
def nfeltreduce(self, x, I):
7064
"""
7065
Given an ideal I in Hermite normal form and an element x of the pari
7066
number field self, finds an element r in self such that x-r belongs
7067
to the ideal and r is small.
7068
7069
EXAMPLES::
7070
7071
sage: k.<a> = NumberField(x^2 + 5)
7072
sage: I = k.ideal(a)
7073
sage: kp = pari(k)
7074
sage: kp.nfeltreduce(12, I.pari_hnf())
7075
[2, 0]~
7076
sage: 12 - k(kp.nfeltreduce(12, I.pari_hnf())) in I
7077
True
7078
"""
7079
cdef gen t0 = objtogen(x)
7080
cdef gen t1 = objtogen(I)
7081
pari_catch_sig_on()
7082
return P.new_gen(nfreduce(self.g, t0.g, t1.g))
7083
7084
def nffactor(self, x):
7085
cdef gen t0 = objtogen(x)
7086
pari_catch_sig_on()
7087
return P.new_gen(nffactor(self.g, t0.g))
7088
7089
def nfgenerator(self):
7090
f = self[0]
7091
x = f.variable()
7092
return x.Mod(f)
7093
7094
def nfhilbert(self, a, b, p=None):
7095
"""
7096
nfhilbert(nf,a,b,{p}): if p is omitted, global Hilbert symbol (a,b)
7097
in nf, that is 1 if X^2-aY^2-bZ^2 has a non-trivial solution (X,Y,Z)
7098
in nf, -1 otherwise. Otherwise compute the local symbol modulo the
7099
prime ideal p.
7100
7101
EXAMPLES::
7102
7103
sage: x = polygen(QQ)
7104
sage: K.<t> = NumberField(x^3 - x + 1)
7105
sage: pari(K).nfhilbert(t, t + 2)
7106
-1
7107
sage: P = K.ideal(t^2 + t - 2) # Prime ideal above 5
7108
sage: pari(K).nfhilbert(t, t + 2, P.pari_prime())
7109
-1
7110
sage: P = K.ideal(t^2 + 3*t - 1) # Prime ideal above 23, ramified
7111
sage: pari(K).nfhilbert(t, t + 2, P.pari_prime())
7112
1
7113
"""
7114
cdef gen t0 = objtogen(a)
7115
cdef gen t1 = objtogen(b)
7116
cdef gen t2
7117
if p:
7118
t2 = objtogen(p)
7119
pari_catch_sig_on()
7120
r = nfhilbert0(self.g, t0.g, t1.g, t2.g)
7121
else:
7122
pari_catch_sig_on()
7123
r = nfhilbert(self.g, t0.g, t1.g)
7124
pari_catch_sig_off()
7125
return r
7126
7127
7128
def nfhnf(self,x):
7129
"""
7130
nfhnf(nf,x) : given a pseudo-matrix (A, I) or an integral pseudo-matrix (A,I,J), finds a
7131
pseudo-basis in Hermite normal form of the module it generates.
7132
7133
A pseudo-matrix is a 2-component row vector (A, I) where A is a relative m x n matrix and
7134
I an ideal list of length n. An integral pseudo-matrix is a 3-component row vector (A, I, J).
7135
7136
.. NOTE::
7137
7138
The definition of a pseudo-basis ([Cohen]_):
7139
Let M be a finitely generated, torsion-free R-module, and set V = KM. If `\mathfrak{a}_i` are
7140
fractional ideals of R and `w_i` are elements of V, we say that
7141
`(w_i, \mathfrak{a}_k)_{1 \leq i \leq k}`
7142
is a pseudo-basis of M if
7143
`M = \mathfrak{a}_1 w_1 \oplus \cdots \oplus \mathfrak{a}_k w_k.`
7144
7145
REFERENCES:
7146
7147
.. [Cohen] Cohen, "Advanced Topics in Computational Number Theory"
7148
7149
EXAMPLES::
7150
7151
sage: F.<a> = NumberField(x^2-x-1)
7152
sage: Fp = pari(F)
7153
sage: A = matrix(F,[[1,2,a,3],[3,0,a+2,0],[0,0,a,2],[3+a,a,0,1]])
7154
sage: I = [F.ideal(-2*a+1),F.ideal(7), F.ideal(3),F.ideal(1)]
7155
sage: Fp.nfhnf([pari(A),[pari(P) for P in I]])
7156
[[1, [-969/5, -1/15]~, [15, -2]~, [-1938, -3]~; 0, 1, 0, 0; 0, 0, 1, 0;
7157
0, 0, 0, 1], [[3997, 1911; 0, 7], [15, 6; 0, 3], [1, 0; 0, 1], [1, 0; 0,
7158
1]]]
7159
sage: K.<b> = NumberField(x^3-2)
7160
sage: Kp = pari(K)
7161
sage: A = matrix(K,[[1,0,0,5*b],[1,2*b^2,b,57],[0,2,1,b^2-3],[2,0,0,b]])
7162
sage: I = [K.ideal(2),K.ideal(3+b^2),K.ideal(1),K.ideal(1)]
7163
sage: Kp.nfhnf([pari(A),[pari(P) for P in I]])
7164
[[1, -225, 72, -31; 0, 1, [0, -1, 0]~, [0, 0, -1/2]~; 0, 0, 1, [0, 0,
7165
-1/2]~; 0, 0, 0, 1], [[1116, 756, 612; 0, 18, 0; 0, 0, 18], [2, 0, 0; 0,
7166
2, 0; 0, 0, 2], [1, 0, 0; 0, 1, 0; 0, 0, 1], [2, 0, 0; 0, 1, 0; 0, 0,
7167
1]]]
7168
7169
An example where the ring of integers of the number field is not a PID::
7170
7171
sage: K.<b> = NumberField(x^2+5)
7172
sage: Kp = pari(K)
7173
sage: A = matrix(K,[[1,0,0,5*b],[1,2*b^2,b,57],[0,2,1,b^2-3],[2,0,0,b]])
7174
sage: I = [K.ideal(2),K.ideal(3+b^2),K.ideal(1),K.ideal(1)]
7175
sage: Kp.nfhnf([pari(A),[pari(P) for P in I]])
7176
[[1, [15, 6]~, [0, -54]~, [113, 72]~; 0, 1, [-4, -1]~, [0, -1]~; 0, 0,
7177
1, 0; 0, 0, 0, 1], [[360, 180; 0, 180], [6, 4; 0, 2], [1, 0; 0, 1], [1,
7178
0; 0, 1]]]
7179
sage: A = matrix(K,[[1,0,0,5*b],[1,2*b,b,57],[0,2,1,b-3],[2,0,b,b]])
7180
sage: I = [K.ideal(2).factor()[0][0],K.ideal(3+b),K.ideal(1),K.ideal(1)]
7181
sage: Kp.nfhnf([pari(A),[pari(P) for P in I]])
7182
[[1, [7605, 4]~, [5610, 5]~, [7913, -6]~; 0, 1, 0, -1; 0, 0, 1, 0; 0, 0,
7183
0, 1], [[19320, 13720; 0, 56], [2, 1; 0, 1], [1, 0; 0, 1], [1, 0; 0,
7184
1]]]
7185
7186
AUTHORS:
7187
7188
- Aly Deines (2012-09-19)
7189
"""
7190
cdef gen t0 = objtogen(x)
7191
pari_catch_sig_on()
7192
return P.new_gen(nfhnf(self.g, t0.g))
7193
7194
7195
def nfinit(self, long flag=0, unsigned long precision=0):
7196
"""
7197
nfinit(pol, {flag=0}): ``pol`` being a nonconstant irreducible
7198
polynomial, gives a vector containing all the data necessary for PARI
7199
to compute in this number field.
7200
7201
``flag`` is optional and can be set to:
7202
- 0: default
7203
- 1: do not compute different
7204
- 2: first use polred to find a simpler polynomial
7205
- 3: outputs a two-element vector [nf,Mod(a,P)], where nf is as in 2
7206
and Mod(a,P) is a polmod equal to Mod(x,pol) and P=nf.pol
7207
7208
EXAMPLES::
7209
7210
sage: pari('x^3 - 17').nfinit()
7211
[x^3 - 17, [1, 1], -867, 3, [[1, 1.68006..., 2.57128...; 1, -0.340034... + 2.65083...*I, -1.28564... - 2.22679...*I], [1, 1.68006..., 2.57128...; 1, 2.31080..., -3.51243...; 1, -2.99087..., 0.941154...], [1, 2, 3; 1, 2, -4; 1, -3, 1], [3, 1, 0; 1, -11, 17; 0, 17, 0], [51, 0, 16; 0, 17, 3; 0, 0, 1], [17, 0, -1; 0, 0, 3; -1, 3, 2], [51, [-17, 6, -1; 0, -18, 3; 1, 0, -16]]], [2.57128..., -1.28564... - 2.22679...*I], [1, 1/3*x^2 - 1/3*x + 1/3, x], [1, 0, -1; 0, 0, 3; 0, 1, 1], [1, 0, 0, 0, -4, 6, 0, 6, -1; 0, 1, 0, 1, 1, -1, 0, -1, 3; 0, 0, 1, 0, 2, 0, 1, 0, 1]]
7212
7213
TESTS:
7214
7215
This example only works after increasing precision::
7216
7217
sage: pari('x^2 + 10^100 + 1').nfinit(precision=64)
7218
Traceback (most recent call last):
7219
...
7220
PariError: precision too low in floorr (precision loss in truncation)
7221
sage: pari('x^2 + 10^100 + 1').nfinit()
7222
[...]
7223
7224
Throw a PARI error which is not of type ``precer``::
7225
7226
sage: pari('1.0').nfinit()
7227
Traceback (most recent call last):
7228
...
7229
PariError: incorrect type in checknf
7230
"""
7231
# If explicit precision is given, use only that
7232
if precision:
7233
pari_catch_sig_on()
7234
return P.new_gen(nfinit0(self.g, flag, prec_bits_to_words(precision)))
7235
7236
# Otherwise, start with 64 bits of precision and increase as needed:
7237
precision = 64
7238
while True:
7239
try:
7240
return self.nfinit(flag, precision)
7241
except PariError as err:
7242
if err.errnum() == precer:
7243
precision *= 2
7244
else:
7245
raise
7246
7247
def nfisisom(self, gen other):
7248
"""
7249
nfisisom(x, y): Determine if the number fields defined by x and y
7250
are isomorphic. According to the PARI documentation, this is much
7251
faster if at least one of x or y is a number field. If they are
7252
isomorphic, it returns an embedding for the generators. If not,
7253
returns 0.
7254
7255
EXAMPLES::
7256
7257
sage: F = NumberField(x^3-2,'alpha')
7258
sage: G = NumberField(x^3-2,'beta')
7259
sage: F._pari_().nfisisom(G._pari_())
7260
[y]
7261
7262
::
7263
7264
sage: GG = NumberField(x^3-4,'gamma')
7265
sage: F._pari_().nfisisom(GG._pari_())
7266
[1/2*y^2]
7267
7268
::
7269
7270
sage: F._pari_().nfisisom(GG.pari_nf())
7271
[1/2*y^2]
7272
7273
::
7274
7275
sage: F.pari_nf().nfisisom(GG._pari_()[0])
7276
[y^2]
7277
7278
::
7279
7280
sage: H = NumberField(x^2-2,'alpha')
7281
sage: F._pari_().nfisisom(H._pari_())
7282
0
7283
"""
7284
pari_catch_sig_on()
7285
return P.new_gen(nfisisom(self.g, other.g))
7286
7287
def nfrootsof1(self):
7288
"""
7289
nf.nfrootsof1()
7290
7291
number of roots of unity and primitive root of unity in the number
7292
field nf.
7293
7294
EXAMPLES::
7295
7296
sage: nf = pari('x^2 + 1').nfinit()
7297
sage: nf.nfrootsof1()
7298
[4, -x]
7299
"""
7300
pari_catch_sig_on()
7301
return P.new_gen(rootsof1(self.g))
7302
7303
def nfsubfields(self, long d=0):
7304
"""
7305
Find all subfields of degree d of number field nf (all subfields if
7306
d is null or omitted). Result is a vector of subfields, each being
7307
given by [g,h], where g is an absolute equation and h expresses one
7308
of the roots of g in terms of the root x of the polynomial defining
7309
nf.
7310
7311
INPUT:
7312
7313
7314
- ``self`` - nf number field
7315
7316
- ``d`` - C long integer
7317
"""
7318
pari_catch_sig_on()
7319
return P.new_gen(nfsubfields(self.g, d))
7320
7321
def rnfcharpoly(self, T, a, v='x'):
7322
cdef gen t0 = objtogen(T)
7323
cdef gen t1 = objtogen(a)
7324
cdef gen t2 = objtogen(v)
7325
pari_catch_sig_on()
7326
return P.new_gen(rnfcharpoly(self.g, t0.g, t1.g, gvar(t2.g)))
7327
7328
def rnfdisc(self, x):
7329
cdef gen t0 = objtogen(x)
7330
pari_catch_sig_on()
7331
return P.new_gen(rnfdiscf(self.g, t0.g))
7332
7333
def rnfeltabstorel(self, x):
7334
cdef gen t0 = objtogen(x)
7335
pari_catch_sig_on()
7336
return P.new_gen(rnfelementabstorel(self.g, t0.g))
7337
7338
def rnfeltreltoabs(self, x):
7339
cdef gen t0 = objtogen(x)
7340
pari_catch_sig_on()
7341
return P.new_gen(rnfelementreltoabs(self.g, t0.g))
7342
7343
def rnfequation(self, poly, long flag=0):
7344
cdef gen t0 = objtogen(poly)
7345
pari_catch_sig_on()
7346
return P.new_gen(rnfequation0(self.g, t0.g, flag))
7347
7348
def rnfidealabstorel(self, x):
7349
cdef gen t0 = objtogen(x)
7350
pari_catch_sig_on()
7351
return P.new_gen(rnfidealabstorel(self.g, t0.g))
7352
7353
def rnfidealdown(self, x):
7354
r"""
7355
rnfidealdown(rnf,x): finds the intersection of the ideal x with the base field.
7356
7357
EXAMPLES:
7358
sage: x = ZZ['xx1'].0; pari(x)
7359
xx1
7360
sage: y = ZZ['yy1'].0; pari(y)
7361
yy1
7362
sage: nf = pari(y^2 - 6*y + 24).nfinit()
7363
sage: rnf = nf.rnfinit(x^2 - pari(y))
7364
7365
This is the relative HNF of the inert ideal (2) in rnf::
7366
7367
sage: P = pari('[[[1, 0]~, [0, 0]~; [0, 0]~, [1, 0]~], [[2, 0; 0, 2], [2, 0; 0, 1/2]]]')
7368
7369
And this is the HNF of the inert ideal (2) in nf:
7370
7371
sage: rnf.rnfidealdown(P)
7372
[2, 0; 0, 2]
7373
"""
7374
cdef gen t0 = objtogen(x)
7375
pari_catch_sig_on()
7376
return P.new_gen(rnfidealdown(self.g, t0.g))
7377
7378
def rnfidealhnf(self, x):
7379
cdef gen t0 = objtogen(x)
7380
pari_catch_sig_on()
7381
return P.new_gen(rnfidealhermite(self.g, t0.g))
7382
7383
def rnfidealnormrel(self, x):
7384
cdef gen t0 = objtogen(x)
7385
pari_catch_sig_on()
7386
return P.new_gen(rnfidealnormrel(self.g, t0.g))
7387
7388
def rnfidealreltoabs(self, x):
7389
cdef gen t0 = objtogen(x)
7390
pari_catch_sig_on()
7391
return P.new_gen(rnfidealreltoabs(self.g, t0.g))
7392
7393
def rnfidealtwoelt(self, x):
7394
cdef gen t0 = objtogen(x)
7395
pari_catch_sig_on()
7396
return P.new_gen(rnfidealtwoelement(self.g, t0.g))
7397
7398
def rnfinit(self, poly):
7399
"""
7400
EXAMPLES: We construct a relative number field.
7401
7402
::
7403
7404
sage: f = pari('y^3+y+1')
7405
sage: K = f.nfinit()
7406
sage: x = pari('x'); y = pari('y')
7407
sage: g = x^5 - x^2 + y
7408
sage: L = K.rnfinit(g)
7409
"""
7410
cdef gen t0 = objtogen(poly)
7411
pari_catch_sig_on()
7412
return P.new_gen(rnfinit(self.g, t0.g))
7413
7414
def rnfisfree(self, poly):
7415
cdef gen t0 = objtogen(poly)
7416
pari_catch_sig_on()
7417
r = rnfisfree(self.g, t0.g)
7418
pari_catch_sig_off()
7419
return r
7420
7421
def quadhilbert(self):
7422
r"""
7423
Returns a polynomial over `\QQ` whose roots generate the
7424
Hilbert class field of the quadratic field of discriminant
7425
``self`` (which must be fundamental).
7426
7427
EXAMPLES::
7428
7429
sage: pari(-23).quadhilbert()
7430
x^3 - x^2 + 1
7431
sage: pari(145).quadhilbert()
7432
x^4 - x^3 - 3*x^2 + x + 1
7433
sage: pari(-12).quadhilbert() # Not fundamental
7434
Traceback (most recent call last):
7435
...
7436
PariError: quadray needs a fundamental discriminant
7437
"""
7438
pari_catch_sig_on()
7439
# Precision argument is only used for real quadratic extensions
7440
# and will be automatically increased by PARI if needed.
7441
return P.new_gen(quadhilbert(self.g, DEFAULTPREC))
7442
7443
7444
##################################################
7445
# 7: POLYNOMIALS and power series
7446
##################################################
7447
def reverse(self):
7448
"""
7449
Return the polynomial obtained by reversing the coefficients of
7450
this polynomial.
7451
"""
7452
return self.Vec().Polrev()
7453
7454
def content(self):
7455
"""
7456
Greatest common divisor of all the components of ``self``.
7457
7458
EXAMPLES::
7459
7460
sage: R.<x> = PolynomialRing(ZZ)
7461
sage: pari(2*x^2 + 2).content()
7462
2
7463
sage: pari("4*x^3 - 2*x/3 + 2/5").content()
7464
2/15
7465
"""
7466
pari_catch_sig_on()
7467
return P.new_gen(content(self.g))
7468
7469
def deriv(self, v=-1):
7470
pari_catch_sig_on()
7471
return P.new_gen(deriv(self.g, P.get_var(v)))
7472
7473
def eval(self, *args, **kwds):
7474
"""
7475
Evaluate ``self`` with the given arguments.
7476
7477
This is currently implemented in 3 cases:
7478
7479
- univariate polynomials (using a single unnamed argument or
7480
keyword arguments),
7481
- any PARI object supporting the PARI function ``substvec``
7482
(in particular, multivariate polynomials) using keyword
7483
arguments,
7484
- objects of type ``t_CLOSURE`` (functions in GP bytecode form)
7485
using unnamed arguments.
7486
7487
In no case is mixing unnamed and keyword arguments allowed.
7488
7489
EXAMPLES::
7490
7491
sage: f = pari('x^2 + 1')
7492
sage: f.type()
7493
't_POL'
7494
sage: f.eval(I)
7495
0
7496
sage: f.eval(x=2)
7497
5
7498
7499
The notation ``f(x)`` is an alternative for ``f.eval(x)``::
7500
7501
sage: f(3) == f.eval(3)
7502
True
7503
7504
Evaluating multivariate polynomials::
7505
7506
sage: f = pari('y^2 + x^3')
7507
sage: f(1) # Dangerous, depends on PARI variable ordering
7508
y^2 + 1
7509
sage: f(x=1) # Safe
7510
y^2 + 1
7511
sage: f(y=1)
7512
x^3 + 1
7513
sage: f(1, 2)
7514
Traceback (most recent call last):
7515
...
7516
TypeError: evaluating a polynomial takes exactly 1 argument (2 given)
7517
sage: f(y='x', x='2*y')
7518
x^2 + 8*y^3
7519
sage: f()
7520
x^3 + y^2
7521
7522
It's not an error to substitute variables which do not appear::
7523
7524
sage: f.eval(z=37)
7525
x^3 + y^2
7526
sage: pari(42).eval(t=0)
7527
42
7528
7529
We can define and evaluate closures as follows::
7530
7531
sage: T = pari('n -> n + 2')
7532
sage: T.type()
7533
't_CLOSURE'
7534
sage: T.eval(3)
7535
5
7536
7537
sage: T = pari('() -> 42')
7538
sage: T()
7539
42
7540
7541
sage: pr = pari('s -> print(s)')
7542
sage: pr.eval('"hello world"')
7543
hello world
7544
7545
sage: f = pari('myfunc(x,y) = x*y')
7546
sage: f.eval(5, 6)
7547
30
7548
7549
Default arguments work, missing arguments are treated as zero
7550
(like in GP)::
7551
7552
sage: f = pari("(x, y, z=1.0) -> [x, y, z]")
7553
sage: f(1, 2, 3)
7554
[1, 2, 3]
7555
sage: f(1, 2)
7556
[1, 2, 1.00000000000000]
7557
sage: f(1)
7558
[1, 0, 1.00000000000000]
7559
sage: f()
7560
[0, 0, 1.00000000000000]
7561
7562
Using keyword arguments, we can substitute in more complicated
7563
objects, for example a number field::
7564
7565
sage: K.<a> = NumberField(x^2 + 1)
7566
sage: nf = K._pari_()
7567
sage: nf
7568
[y^2 + 1, [0, 1], -4, 1, [Mat([1, 0.E-19 - 1.00000000000000*I]), [1, -1.00000000000000; 1, 1.00000000000000], [1, -1; 1, 1], [2, 0; 0, -2], [2, 0; 0, 2], [1, 0; 0, -1], [1, [0, -1; 1, 0]]], [0.E-19 - 1.00000000000000*I], [1, y], [1, 0; 0, 1], [1, 0, 0, -1; 0, 1, 1, 0]]
7569
sage: nf(y='x')
7570
[x^2 + 1, [0, 1], -4, 1, [Mat([1, 0.E-19 - 1.00000000000000*I]), [1, -1.00000000000000; 1, 1.00000000000000], [1, -1; 1, 1], [2, 0; 0, -2], [2, 0; 0, 2], [1, 0; 0, -1], [1, [0, -1; 1, 0]]], [0.E-19 - 1.00000000000000*I], [1, x], [1, 0; 0, 1], [1, 0, 0, -1; 0, 1, 1, 0]]
7571
"""
7572
cdef long t = typ(self.g)
7573
cdef gen t0
7574
cdef GEN result
7575
cdef long arity
7576
cdef long nargs = len(args)
7577
cdef long nkwds = len(kwds)
7578
7579
# Closure must be evaluated using *args
7580
if t == t_CLOSURE:
7581
if nkwds > 0:
7582
raise TypeError("cannot evaluate a PARI closure using keyword arguments")
7583
# XXX: use undocumented internals to get arity of closure
7584
# (In PARI 2.6, there is closure_arity() which does this)
7585
arity = self.g[1]
7586
if nargs > arity:
7587
raise TypeError("PARI closure takes at most %d argument%s (%d given)"%(
7588
arity, "s" if (arity!=1) else "", nargs))
7589
t0 = objtogen(args)
7590
pari_catch_sig_on()
7591
result = closure_callgenvec(self.g, t0.g)
7592
if result == gnil:
7593
P.clear_stack()
7594
return None
7595
return P.new_gen(result)
7596
7597
# Evaluate univariate polynomial using *args
7598
if nargs > 0:
7599
if nkwds > 0:
7600
raise TypeError("mixing unnamed and keyword arguments not allowed when evaluating a PARI object")
7601
if t == t_POL:
7602
# evaluate univariate polynomial
7603
if nargs != 1:
7604
raise TypeError("evaluating a polynomial takes exactly 1 argument (%d given)"%nargs)
7605
t0 = objtogen(args[0])
7606
pari_catch_sig_on()
7607
return P.new_gen(poleval(self.g, t0.g))
7608
raise TypeError("cannot evaluate %s using unnamed arguments"%self.type())
7609
7610
# Call substvec() using **kwds
7611
vstr = kwds.keys() # Variables as Python strings
7612
t0 = objtogen(kwds.values()) # Replacements
7613
7614
pari_catch_sig_on()
7615
cdef GEN v = cgetg(nkwds+1, t_VEC) # Variables as PARI polynomials
7616
cdef long i
7617
for i in range(nkwds):
7618
set_gel(v, i+1, pol_x(P.get_var(vstr[i])))
7619
return P.new_gen(gsubstvec(self.g, v, t0.g))
7620
7621
7622
def __call__(self, *args, **kwds):
7623
"""
7624
Evaluate ``self`` with the given arguments.
7625
7626
This has the same effect as :meth:`eval`.
7627
7628
EXAMPLES::
7629
7630
sage: R.<x> = GF(3)[]
7631
sage: f = (x^2 + x + 1)._pari_()
7632
sage: f.type()
7633
't_POL'
7634
sage: f(2)
7635
Mod(1, 3)
7636
7637
TESTS::
7638
7639
sage: T = pari('n -> 1/n')
7640
sage: T.type()
7641
't_CLOSURE'
7642
sage: T(0)
7643
Traceback (most recent call last):
7644
...
7645
PariError: _/_: division by zero
7646
sage: pari('() -> 42')(1,2,3)
7647
Traceback (most recent call last):
7648
...
7649
TypeError: PARI closure takes at most 0 arguments (3 given)
7650
sage: pari('n -> n')(n=2)
7651
Traceback (most recent call last):
7652
...
7653
TypeError: cannot evaluate a PARI closure using keyword arguments
7654
sage: pari('x + y')(4, y=1)
7655
Traceback (most recent call last):
7656
...
7657
TypeError: mixing unnamed and keyword arguments not allowed when evaluating a PARI object
7658
sage: pari("12345")(4)
7659
Traceback (most recent call last):
7660
...
7661
TypeError: cannot evaluate t_INT using unnamed arguments
7662
"""
7663
return self.eval(*args, **kwds)
7664
7665
def factornf(self, t):
7666
"""
7667
Factorization of the polynomial ``self`` over the number field
7668
defined by the polynomial ``t``. This does not require that `t`
7669
is integral, nor that the discriminant of the number field can be
7670
factored.
7671
7672
EXAMPLES::
7673
7674
sage: x = polygen(QQ)
7675
sage: K.<a> = NumberField(x^2 - 1/8)
7676
sage: pari(x^2 - 2).factornf(K.pari_polynomial("a"))
7677
[x + Mod(-4*a, 8*a^2 - 1), 1; x + Mod(4*a, 8*a^2 - 1), 1]
7678
"""
7679
cdef gen t0 = objtogen(t)
7680
pari_catch_sig_on()
7681
return P.new_gen(polfnf(self.g, t0.g))
7682
7683
def factorpadic(self, p, long r=20, long flag=0):
7684
"""
7685
self.factorpadic(p,r=20,flag=0): p-adic factorization of the
7686
polynomial x to precision r. flag is optional and may be set to 0
7687
(use round 4) or 1 (use Buchmann-Lenstra)
7688
"""
7689
cdef gen t0 = objtogen(p)
7690
pari_catch_sig_on()
7691
return P.new_gen(factorpadic0(self.g, t0.g, r, flag))
7692
7693
def factormod(self, p, long flag=0):
7694
"""
7695
x.factormod(p,flag=0): factorization mod p of the polynomial x
7696
using Berlekamp. flag is optional, and can be 0: default or 1:
7697
simple factormod, same except that only the degrees of the
7698
irreducible factors are given.
7699
"""
7700
cdef gen t0 = objtogen(p)
7701
pari_catch_sig_on()
7702
return P.new_gen(factormod0(self.g, t0.g, flag))
7703
7704
def intformal(self, y=-1):
7705
"""
7706
x.intformal(y): formal integration of x with respect to the main
7707
variable of y, or to the main variable of x if y is omitted
7708
"""
7709
pari_catch_sig_on()
7710
return P.new_gen(integ(self.g, P.get_var(y)))
7711
7712
def padicappr(self, a):
7713
"""
7714
x.padicappr(a): p-adic roots of the polynomial x congruent to a mod
7715
p
7716
"""
7717
cdef gen t0 = objtogen(a)
7718
pari_catch_sig_on()
7719
return P.new_gen(padicappr(self.g, t0.g))
7720
7721
def newtonpoly(self, p):
7722
"""
7723
x.newtonpoly(p): Newton polygon of polynomial x with respect to the
7724
prime p.
7725
7726
EXAMPLES::
7727
7728
sage: x = pari('y^8+6*y^6-27*y^5+1/9*y^2-y+1')
7729
sage: x.newtonpoly(3)
7730
[1, 1, -1/3, -1/3, -1/3, -1/3, -1/3, -1/3]
7731
"""
7732
cdef gen t0 = objtogen(p)
7733
pari_catch_sig_on()
7734
return P.new_gen(newtonpoly(self.g, t0.g))
7735
7736
def polcoeff(self, long n, var=-1):
7737
"""
7738
EXAMPLES::
7739
7740
sage: f = pari("x^2 + y^3 + x*y")
7741
sage: f
7742
x^2 + y*x + y^3
7743
sage: f.polcoeff(1)
7744
y
7745
sage: f.polcoeff(3)
7746
0
7747
sage: f.polcoeff(3, "y")
7748
1
7749
sage: f.polcoeff(1, "y")
7750
x
7751
"""
7752
pari_catch_sig_on()
7753
return P.new_gen(polcoeff0(self.g, n, P.get_var(var)))
7754
7755
def polcompositum(self, pol2, long flag=0):
7756
cdef gen t0 = objtogen(pol2)
7757
pari_catch_sig_on()
7758
return P.new_gen(polcompositum0(self.g, t0.g, flag))
7759
7760
def poldegree(self, var=-1):
7761
"""
7762
f.poldegree(var=x): Return the degree of this polynomial.
7763
"""
7764
pari_catch_sig_on()
7765
n = poldegree(self.g, P.get_var(var))
7766
pari_catch_sig_off()
7767
return n
7768
7769
def poldisc(self, var=-1):
7770
"""
7771
Return the discriminant of this polynomial.
7772
7773
EXAMPLES::
7774
7775
sage: pari("x^2 + 1").poldisc()
7776
-4
7777
7778
Before :trac:`15654`, this used to take a very long time.
7779
Now it takes much less than a second::
7780
7781
sage: pari.allocatemem(200000)
7782
PARI stack size set to 200000 bytes
7783
sage: x = polygen(ZpFM(3,10))
7784
sage: pol = ((x-1)^50 + x)
7785
sage: pari(pol).poldisc()
7786
2*3 + 3^4 + 2*3^6 + 3^7 + 2*3^8 + 2*3^9 + O(3^10)
7787
"""
7788
pari_catch_sig_on()
7789
return P.new_gen(poldisc0(self.g, P.get_var(var)))
7790
7791
def poldiscreduced(self):
7792
pari_catch_sig_on()
7793
return P.new_gen(reduceddiscsmith(self.g))
7794
7795
def polgalois(self, unsigned long precision=0):
7796
"""
7797
f.polgalois(): Galois group of the polynomial f
7798
"""
7799
pari_catch_sig_on()
7800
return P.new_gen(polgalois(self.g, prec_bits_to_words(precision)))
7801
7802
def nfgaloisconj(self, long flag=0, denom=None, unsigned long precision=0):
7803
r"""
7804
Edited from the pari documentation:
7805
7806
nfgaloisconj(nf): list of conjugates of a root of the
7807
polynomial x=nf.pol in the same number field.
7808
7809
Uses a combination of Allombert's algorithm and nfroots.
7810
7811
EXAMPLES::
7812
7813
sage: x = QQ['x'].0; nf = pari(x^2 + 2).nfinit()
7814
sage: nf.nfgaloisconj()
7815
[-x, x]~
7816
sage: nf = pari(x^3 + 2).nfinit()
7817
sage: nf.nfgaloisconj()
7818
[x]~
7819
sage: nf = pari(x^4 + 2).nfinit()
7820
sage: nf.nfgaloisconj()
7821
[-x, x]~
7822
"""
7823
cdef gen t0
7824
if denom is None:
7825
pari_catch_sig_on()
7826
return P.new_gen(galoisconj0(self.g, flag, NULL, prec_bits_to_words(precision)))
7827
else:
7828
t0 = objtogen(denom)
7829
pari_catch_sig_on()
7830
return P.new_gen(galoisconj0(self.g, flag, t0.g, prec_bits_to_words(precision)))
7831
7832
def nfroots(self, poly):
7833
r"""
7834
Return the roots of `poly` in the number field self without
7835
multiplicity.
7836
7837
EXAMPLES::
7838
7839
sage: y = QQ['yy'].0; _ = pari(y) # pari has variable ordering rules
7840
sage: x = QQ['zz'].0; nf = pari(x^2 + 2).nfinit()
7841
sage: nf.nfroots(y^2 + 2)
7842
[Mod(-zz, zz^2 + 2), Mod(zz, zz^2 + 2)]
7843
sage: nf = pari(x^3 + 2).nfinit()
7844
sage: nf.nfroots(y^3 + 2)
7845
[Mod(zz, zz^3 + 2)]
7846
sage: nf = pari(x^4 + 2).nfinit()
7847
sage: nf.nfroots(y^4 + 2)
7848
[Mod(-zz, zz^4 + 2), Mod(zz, zz^4 + 2)]
7849
"""
7850
cdef gen t0 = objtogen(poly)
7851
pari_catch_sig_on()
7852
return P.new_gen(nfroots(self.g, t0.g))
7853
7854
def polhensellift(self, y, p, long e):
7855
"""
7856
self.polhensellift(y, p, e): lift the factorization y of self
7857
modulo p to a factorization modulo `p^e` using Hensel lift.
7858
The factors in y must be pairwise relatively prime modulo p.
7859
"""
7860
cdef gen t0 = objtogen(y)
7861
cdef gen t1 = objtogen(p)
7862
pari_catch_sig_on()
7863
return P.new_gen(polhensellift(self.g, t0.g, t1.g, e))
7864
7865
def polisirreducible(self):
7866
"""
7867
f.polisirreducible(): Returns True if f is an irreducible
7868
non-constant polynomial, or False if f is reducible or constant.
7869
"""
7870
pari_catch_sig_on()
7871
cdef long t = itos(gisirreducible(self.g))
7872
P.clear_stack()
7873
return t != 0
7874
7875
def pollead(self, v=-1):
7876
"""
7877
self.pollead(v): leading coefficient of polynomial or series self,
7878
or self itself if self is a scalar. Error otherwise. With respect
7879
to the main variable of self if v is omitted, with respect to the
7880
variable v otherwise
7881
"""
7882
pari_catch_sig_on()
7883
return P.new_gen(pollead(self.g, P.get_var(v)))
7884
7885
def polrecip(self):
7886
pari_catch_sig_on()
7887
return P.new_gen(polrecip(self.g))
7888
7889
def polred(self, long flag=0, fa=None):
7890
cdef gen t0
7891
if fa is None:
7892
pari_catch_sig_on()
7893
return P.new_gen(polred0(self.g, flag, NULL))
7894
else:
7895
t0 = objtogen(fa)
7896
pari_catch_sig_on()
7897
return P.new_gen(polred0(self.g, flag, t0.g))
7898
7899
def polredabs(self, long flag=0):
7900
pari_catch_sig_on()
7901
return P.new_gen(polredabs0(self.g, flag))
7902
7903
def polredbest(self, long flag=0):
7904
pari_catch_sig_on()
7905
return P.new_gen(polredbest(self.g, flag))
7906
7907
def polresultant(self, y, var=-1, long flag=0):
7908
cdef gen t0 = objtogen(y)
7909
pari_catch_sig_on()
7910
return P.new_gen(polresultant0(self.g, t0.g, P.get_var(var), flag))
7911
7912
def polroots(self, long flag=0, unsigned long precision=0):
7913
"""
7914
polroots(x,flag=0): complex roots of the polynomial x. flag is
7915
optional, and can be 0: default, uses Schonhage's method modified
7916
by Gourdon, or 1: uses a modified Newton method.
7917
"""
7918
pari_catch_sig_on()
7919
return P.new_gen(roots0(self.g, flag, prec_bits_to_words(precision)))
7920
7921
def polrootsmod(self, p, long flag=0):
7922
cdef gen t0 = objtogen(p)
7923
pari_catch_sig_on()
7924
return P.new_gen(rootmod0(self.g, t0.g, flag))
7925
7926
def polrootspadic(self, p, r=20):
7927
cdef gen t0 = objtogen(p)
7928
pari_catch_sig_on()
7929
return P.new_gen(rootpadic(self.g, t0.g, r))
7930
7931
def polrootspadicfast(self, p, r=20):
7932
cdef gen t0 = objtogen(p)
7933
pari_catch_sig_on()
7934
return P.new_gen(rootpadicfast(self.g, t0.g, r))
7935
7936
def polsturm(self, a, b):
7937
cdef gen t0 = objtogen(a)
7938
cdef gen t1 = objtogen(b)
7939
pari_catch_sig_on()
7940
n = sturmpart(self.g, t0.g, t1.g)
7941
pari_catch_sig_off()
7942
return n
7943
7944
def polsturm_full(self):
7945
pari_catch_sig_on()
7946
n = sturmpart(self.g, NULL, NULL)
7947
pari_catch_sig_off()
7948
return n
7949
7950
def polsylvestermatrix(self, g):
7951
cdef gen t0 = objtogen(g)
7952
pari_catch_sig_on()
7953
return P.new_gen(sylvestermatrix(self.g, t0.g))
7954
7955
def polsym(self, long n):
7956
pari_catch_sig_on()
7957
return P.new_gen(polsym(self.g, n))
7958
7959
def serconvol(self, g):
7960
cdef gen t0 = objtogen(g)
7961
pari_catch_sig_on()
7962
return P.new_gen(convol(self.g, t0.g))
7963
7964
def serlaplace(self):
7965
pari_catch_sig_on()
7966
return P.new_gen(laplace(self.g))
7967
7968
def serreverse(self):
7969
"""
7970
serreverse(f): reversion of the power series f.
7971
7972
If f(t) is a series in t with valuation 1, find the series g(t)
7973
such that g(f(t)) = t.
7974
7975
EXAMPLES::
7976
7977
sage: f = pari('x+x^2+x^3+O(x^4)'); f
7978
x + x^2 + x^3 + O(x^4)
7979
sage: g = f.serreverse(); g
7980
x - x^2 + x^3 + O(x^4)
7981
sage: f.subst('x',g)
7982
x + O(x^4)
7983
sage: g.subst('x',f)
7984
x + O(x^4)
7985
"""
7986
pari_catch_sig_on()
7987
return P.new_gen(recip(self.g))
7988
7989
def thueinit(self, long flag=0, unsigned long precision=0):
7990
pari_catch_sig_on()
7991
return P.new_gen(thueinit(self.g, flag, prec_bits_to_words(precision)))
7992
7993
7994
def rnfisnorminit(self, polrel, long flag=2):
7995
cdef gen t0 = objtogen(polrel)
7996
pari_catch_sig_on()
7997
return P.new_gen(rnfisnorminit(self.g, t0.g, flag))
7998
7999
def rnfisnorm(self, T, long flag=0):
8000
cdef gen t0 = objtogen(T)
8001
pari_catch_sig_on()
8002
return P.new_gen(rnfisnorm(t0.g, self.g, flag))
8003
8004
###########################################
8005
# 8: Vectors, matrices, LINEAR ALGEBRA and sets
8006
###########################################
8007
8008
def vecextract(self, y, z=None):
8009
r"""
8010
self.vecextract(y,z): extraction of the components of the matrix or
8011
vector x according to y and z. If z is omitted, y designates
8012
columns, otherwise y corresponds to rows and z to columns. y and z
8013
can be vectors (of indices), strings (indicating ranges as
8014
in"1..10") or masks (integers whose binary representation indicates
8015
the indices to extract, from left to right 1, 2, 4, 8, etc.)
8016
8017
.. note::
8018
8019
This function uses the PARI row and column indexing, so the
8020
first row or column is indexed by 1 instead of 0.
8021
"""
8022
cdef gen t0 = objtogen(y)
8023
cdef gen t1
8024
if z is None:
8025
pari_catch_sig_on()
8026
return P.new_gen(shallowextract(self.g, t0.g))
8027
else:
8028
t1 = objtogen(z)
8029
pari_catch_sig_on()
8030
return P.new_gen(extract0(self.g, t0.g, t1.g))
8031
8032
def ncols(self):
8033
"""
8034
Return the number of columns of self.
8035
8036
EXAMPLES::
8037
8038
sage: pari('matrix(19,8)').ncols()
8039
8
8040
"""
8041
cdef long n
8042
pari_catch_sig_on()
8043
n = glength(self.g)
8044
pari_catch_sig_off()
8045
return n
8046
8047
def nrows(self):
8048
"""
8049
Return the number of rows of self.
8050
8051
EXAMPLES::
8052
8053
sage: pari('matrix(19,8)').nrows()
8054
19
8055
"""
8056
cdef long n
8057
pari_catch_sig_on()
8058
# if this matrix has no columns
8059
# then it has no rows.
8060
if self.ncols() == 0:
8061
pari_catch_sig_off()
8062
return 0
8063
n = glength(<GEN>(self.g[1]))
8064
pari_catch_sig_off()
8065
return n
8066
8067
def mattranspose(self):
8068
"""
8069
Transpose of the matrix self.
8070
8071
EXAMPLES::
8072
8073
sage: pari('[1,2,3; 4,5,6; 7,8,9]').mattranspose()
8074
[1, 4, 7; 2, 5, 8; 3, 6, 9]
8075
"""
8076
pari_catch_sig_on()
8077
return P.new_gen(gtrans(self.g)).Mat()
8078
8079
def matadjoint(self):
8080
"""
8081
matadjoint(x): adjoint matrix of x.
8082
8083
EXAMPLES::
8084
8085
sage: pari('[1,2,3; 4,5,6; 7,8,9]').matadjoint()
8086
[-3, 6, -3; 6, -12, 6; -3, 6, -3]
8087
sage: pari('[a,b,c; d,e,f; g,h,i]').matadjoint()
8088
[(i*e - h*f), (-i*b + h*c), (f*b - e*c); (-i*d + g*f), i*a - g*c, -f*a + d*c; (h*d - g*e), -h*a + g*b, e*a - d*b]
8089
"""
8090
pari_catch_sig_on()
8091
return P.new_gen(adj(self.g)).Mat()
8092
8093
def qflll(self, long flag=0):
8094
"""
8095
qflll(x,flag=0): LLL reduction of the vectors forming the matrix x
8096
(gives the unimodular transformation matrix). The columns of x must
8097
be linearly independent, unless specified otherwise below. flag is
8098
optional, and can be 0: default, 1: assumes x is integral, columns
8099
may be dependent, 2: assumes x is integral, returns a partially
8100
reduced basis, 4: assumes x is integral, returns [K,I] where K is
8101
the integer kernel of x and I the LLL reduced image, 5: same as 4
8102
but x may have polynomial coefficients, 8: same as 0 but x may have
8103
polynomial coefficients.
8104
"""
8105
pari_catch_sig_on()
8106
return P.new_gen(qflll0(self.g,flag)).Mat()
8107
8108
def qflllgram(self, long flag=0):
8109
"""
8110
qflllgram(x,flag=0): LLL reduction of the lattice whose gram matrix
8111
is x (gives the unimodular transformation matrix). flag is optional
8112
and can be 0: default,1: lllgramint algorithm for integer matrices,
8113
4: lllgramkerim giving the kernel and the LLL reduced image, 5:
8114
lllgramkerimgen same when the matrix has polynomial coefficients,
8115
8: lllgramgen, same as qflllgram when the coefficients are
8116
polynomials.
8117
"""
8118
pari_catch_sig_on()
8119
return P.new_gen(qflllgram0(self.g,flag)).Mat()
8120
8121
def lllgram(self):
8122
return self.qflllgram(0)
8123
8124
def lllgramint(self):
8125
return self.qflllgram(1)
8126
8127
def qfminim(self, b=None, m=None, long flag=0, unsigned long precision=0):
8128
"""
8129
Return vectors with bounded norm for this quadratic form.
8130
8131
INPUT:
8132
8133
- ``self`` -- a quadratic form
8134
- ``b`` -- a bound on vector norm (finds minimal non-zero
8135
vectors if b=0)
8136
- ``m`` -- maximum number of vectors to return. If ``None``
8137
(default), return all vectors of norm at most B
8138
- flag (optional) --
8139
8140
- 0: default;
8141
- 1: return only the first minimal vector found (ignore ``max``);
8142
- 2: as 0 but uses a more robust, slower implementation,
8143
valid for non integral quadratic forms.
8144
8145
OUTPUT:
8146
8147
A triple consisting of
8148
8149
- the number of vectors of norm <= b,
8150
- the actual maximum norm of vectors listed
8151
- a matrix whose columns are vectors with norm less than or
8152
equal to b for the definite quadratic form. Only one of `v`
8153
and `-v` is returned and the zero vector is never returned.
8154
8155
.. note::
8156
8157
If max is specified then only max vectors will be output,
8158
but all vectors withing the given norm bound will be computed.
8159
8160
EXAMPLES::
8161
8162
sage: A = Matrix(3,3,[1,2,3,2,5,5,3,5,11])
8163
sage: A.is_positive_definite()
8164
True
8165
8166
The first 5 vectors of norm at most 10::
8167
8168
sage: pari(A).qfminim(10, 5).python()
8169
[
8170
[-17 -14 -15 -16 -13]
8171
[ 4 3 3 3 2]
8172
146, 10, [ 3 3 3 3 3]
8173
]
8174
8175
8176
All vectors of minimal norm::
8177
8178
sage: pari(A).qfminim(0).python()
8179
[
8180
[-5 -2 1]
8181
[ 1 1 0]
8182
6, 1, [ 1 0 0]
8183
]
8184
8185
Use flag=2 for non-integral input::
8186
8187
sage: pari(A.change_ring(RR)).qfminim(5, m=5, flag=2).python()
8188
[
8189
[ -5 -10 -2 -7 3]
8190
[ 1 2 1 2 0]
8191
10, 5.00000000023283..., [ 1 2 0 1 -1]
8192
]
8193
8194
"""
8195
cdef gen t0, t1
8196
cdef GEN g0, g1
8197
if b is None:
8198
g0 = NULL
8199
else:
8200
t0 = objtogen(b)
8201
g0 = t0.g
8202
if m is None:
8203
g1 = NULL
8204
else:
8205
t1 = objtogen(m)
8206
g1 = t1.g
8207
pari_catch_sig_on()
8208
# precision is only used when flag == 2
8209
return P.new_gen(qfminim0(self.g, g0, g1, flag, prec_bits_to_words(precision)))
8210
8211
def qfrep(self, B, long flag=0):
8212
"""
8213
qfrep(x,B,flag=0): vector of (half) the number of vectors of norms
8214
from 1 to B for the integral and definite quadratic form x. Binary
8215
digits of flag mean 1: count vectors of even norm from 1 to 2B, 2:
8216
return a t_VECSMALL instead of a t_VEC.
8217
"""
8218
cdef gen t0 = objtogen(B)
8219
pari_catch_sig_on()
8220
return P.new_gen(qfrep0(self.g, t0.g, flag))
8221
8222
def matsolve(self, B):
8223
"""
8224
matsolve(B): Solve the linear system Mx=B for an invertible matrix
8225
M
8226
8227
matsolve(B) uses Gaussian elimination to solve Mx=B, where M is
8228
invertible and B is a column vector.
8229
8230
The corresponding pari library routine is gauss. The gp-interface
8231
name matsolve has been given preference here.
8232
8233
INPUT:
8234
8235
8236
- ``B`` - a column vector of the same dimension as the
8237
square matrix self
8238
8239
8240
EXAMPLES::
8241
8242
sage: pari('[1,1;1,-1]').matsolve(pari('[1;0]'))
8243
[1/2; 1/2]
8244
"""
8245
cdef gen t0 = objtogen(B)
8246
pari_catch_sig_on()
8247
return P.new_gen(gauss(self.g, t0.g))
8248
8249
def matsolvemod(self, D, B, long flag = 0):
8250
r"""
8251
For column vectors `D=(d_i)` and `B=(b_i)`, find a small integer
8252
solution to the system of linear congruences
8253
8254
.. math::
8255
8256
R_ix=b_i\text{ (mod }d_i),
8257
8258
where `R_i` is the ith row of ``self``. If `d_i=0`, the equation is
8259
considered over the integers. The entries of ``self``, ``D``, and
8260
``B`` should all be integers (those of ``D`` should also be
8261
non-negative).
8262
8263
If ``flag`` is 1, the output is a two-component row vector whose first
8264
component is a solution and whose second component is a matrix whose
8265
columns form a basis of the solution set of the homogeneous system.
8266
8267
For either value of ``flag``, the output is 0 if there is no solution.
8268
8269
Note that if ``D`` or ``B`` is an integer, then it will be considered
8270
as a vector all of whose entries are that integer.
8271
8272
EXAMPLES::
8273
8274
sage: D = pari('[3,4]~')
8275
sage: B = pari('[1,2]~')
8276
sage: M = pari('[1,2;3,4]')
8277
sage: M.matsolvemod(D, B)
8278
[-2, 0]~
8279
sage: M.matsolvemod(3, 1)
8280
[-1, 1]~
8281
sage: M.matsolvemod(pari('[3,0]~'), pari('[1,2]~'))
8282
[6, -4]~
8283
sage: M2 = pari('[1,10;9,18]')
8284
sage: M2.matsolvemod(3, pari('[2,3]~'), 1)
8285
[[0, -1]~, [-1, -2; 1, -1]]
8286
sage: M2.matsolvemod(9, pari('[2,3]~'))
8287
0
8288
sage: M2.matsolvemod(9, pari('[2,45]~'), 1)
8289
[[1, 1]~, [-1, -4; 1, -5]]
8290
"""
8291
cdef gen t0 = objtogen(D)
8292
cdef gen t1 = objtogen(B)
8293
pari_catch_sig_on()
8294
return P.new_gen(matsolvemod0(self.g, t0.g, t1.g, flag))
8295
8296
def matker(self, long flag=0):
8297
"""
8298
Return a basis of the kernel of this matrix.
8299
8300
INPUT:
8301
8302
8303
- ``flag`` - optional; may be set to 0: default;
8304
non-zero: x is known to have integral entries.
8305
8306
8307
EXAMPLES::
8308
8309
sage: pari('[1,2,3;4,5,6;7,8,9]').matker()
8310
[1; -2; 1]
8311
8312
With algorithm 1, even if the matrix has integer entries the kernel
8313
need not be saturated (which is weird)::
8314
8315
sage: pari('[1,2,3;4,5,6;7,8,9]').matker(1)
8316
[3; -6; 3]
8317
sage: pari('matrix(3,3,i,j,i)').matker()
8318
[-1, -1; 1, 0; 0, 1]
8319
sage: pari('[1,2,3;4,5,6;7,8,9]*Mod(1,2)').matker()
8320
[Mod(1, 2); Mod(0, 2); Mod(1, 2)]
8321
"""
8322
pari_catch_sig_on()
8323
return P.new_gen(matker0(self.g, flag))
8324
8325
def matkerint(self, long flag=0):
8326
"""
8327
Return the integer kernel of a matrix.
8328
8329
This is the LLL-reduced Z-basis of the kernel of the matrix x with
8330
integral entries.
8331
8332
INPUT:
8333
8334
8335
- ``flag`` - optional, and may be set to 0: default,
8336
uses a modified LLL, 1: uses matrixqz.
8337
8338
8339
EXAMPLES::
8340
8341
sage: pari('[2,1;2,1]').matker()
8342
[-1/2; 1]
8343
sage: pari('[2,1;2,1]').matkerint()
8344
[1; -2]
8345
sage: pari('[2,1;2,1]').matkerint(1)
8346
[1; -2]
8347
"""
8348
pari_catch_sig_on()
8349
return P.new_gen(matkerint0(self.g, flag))
8350
8351
def matdet(self, long flag=0):
8352
"""
8353
Return the determinant of this matrix.
8354
8355
INPUT:
8356
8357
8358
- ``flag`` - (optional) flag 0: using Gauss-Bareiss.
8359
1: use classical Gaussian elimination (slightly better for integer
8360
entries)
8361
8362
8363
EXAMPLES::
8364
8365
sage: pari('[1,2; 3,4]').matdet(0)
8366
-2
8367
sage: pari('[1,2; 3,4]').matdet(1)
8368
-2
8369
"""
8370
pari_catch_sig_on()
8371
return P.new_gen(det0(self.g, flag))
8372
8373
def trace(self):
8374
"""
8375
Return the trace of this PARI object.
8376
8377
EXAMPLES::
8378
8379
sage: pari('[1,2; 3,4]').trace()
8380
5
8381
"""
8382
pari_catch_sig_on()
8383
return P.new_gen(gtrace(self.g))
8384
8385
def mathnf(self, long flag=0):
8386
"""
8387
A.mathnf(flag=0): (upper triangular) Hermite normal form of A,
8388
basis for the lattice formed by the columns of A.
8389
8390
INPUT:
8391
8392
8393
- ``flag`` - optional, value range from 0 to 4 (0 if
8394
omitted), meaning : 0: naive algorithm
8395
8396
- ``1: Use Batut's algorithm`` - output 2-component
8397
vector [H,U] such that H is the HNF of A, and U is a unimodular
8398
matrix such that xU=H. 3: Use Batut's algorithm. Output [H,U,P]
8399
where P is a permutation matrix such that P A U = H. 4: As 1, using
8400
a heuristic variant of LLL reduction along the way.
8401
8402
8403
EXAMPLES::
8404
8405
sage: pari('[1,2,3; 4,5,6; 7,8,9]').mathnf()
8406
[6, 1; 3, 1; 0, 1]
8407
"""
8408
pari_catch_sig_on()
8409
return P.new_gen(mathnf0(self.g, flag))
8410
8411
def mathnfmod(self, d):
8412
"""
8413
Returns the Hermite normal form if d is a multiple of the
8414
determinant
8415
8416
Beware that PARI's concept of a Hermite normal form is an upper
8417
triangular matrix with the same column space as the input matrix.
8418
8419
INPUT:
8420
8421
8422
- ``d`` - multiple of the determinant of self
8423
8424
8425
EXAMPLES::
8426
8427
sage: M=matrix([[1,2,3],[4,5,6],[7,8,11]])
8428
sage: d=M.det()
8429
sage: pari(M).mathnfmod(d)
8430
[6, 4, 3; 0, 1, 0; 0, 0, 1]
8431
8432
Note that d really needs to be a multiple of the discriminant, not
8433
just of the exponent of the cokernel::
8434
8435
sage: M=matrix([[1,0,0],[0,2,0],[0,0,6]])
8436
sage: pari(M).mathnfmod(6)
8437
[1, 0, 0; 0, 1, 0; 0, 0, 6]
8438
sage: pari(M).mathnfmod(12)
8439
[1, 0, 0; 0, 2, 0; 0, 0, 6]
8440
"""
8441
cdef gen t0 = objtogen(d)
8442
pari_catch_sig_on()
8443
return P.new_gen(hnfmod(self.g, t0.g))
8444
8445
def mathnfmodid(self, d):
8446
"""
8447
Returns the Hermite Normal Form of M concatenated with d\*Identity
8448
8449
Beware that PARI's concept of a Hermite normal form is a maximal
8450
rank upper triangular matrix with the same column space as the
8451
input matrix.
8452
8453
INPUT:
8454
8455
8456
- ``d`` - Determines
8457
8458
8459
EXAMPLES::
8460
8461
sage: M=matrix([[1,0,0],[0,2,0],[0,0,6]])
8462
sage: pari(M).mathnfmodid(6)
8463
[1, 0, 0; 0, 2, 0; 0, 0, 6]
8464
8465
This routine is not completely equivalent to mathnfmod::
8466
8467
sage: pari(M).mathnfmod(6)
8468
[1, 0, 0; 0, 1, 0; 0, 0, 6]
8469
"""
8470
cdef gen t0 = objtogen(d)
8471
pari_catch_sig_on()
8472
return P.new_gen(hnfmodid(self.g, t0.g))
8473
8474
def matsnf(self, long flag=0):
8475
"""
8476
x.matsnf(flag=0): Smith normal form (i.e. elementary divisors) of
8477
the matrix x, expressed as a vector d. Binary digits of flag mean
8478
1: returns [u,v,d] where d=u\*x\*v, otherwise only the diagonal d
8479
is returned, 2: allow polynomial entries, otherwise assume x is
8480
integral, 4: removes all information corresponding to entries equal
8481
to 1 in d.
8482
8483
EXAMPLES::
8484
8485
sage: pari('[1,2,3; 4,5,6; 7,8,9]').matsnf()
8486
[0, 3, 1]
8487
"""
8488
pari_catch_sig_on()
8489
return P.new_gen(matsnf0(self.g, flag))
8490
8491
def matfrobenius(self, long flag=0):
8492
r"""
8493
M.matfrobenius(flag=0): Return the Frobenius form of the square
8494
matrix M. If flag is 1, return only the elementary divisors (a list
8495
of polynomials). If flag is 2, return a two-components vector [F,B]
8496
where F is the Frobenius form and B is the basis change so that
8497
`M=B^{-1} F B`.
8498
8499
EXAMPLES::
8500
8501
sage: a = pari('[1,2;3,4]')
8502
sage: a.matfrobenius()
8503
[0, 2; 1, 5]
8504
sage: a.matfrobenius(flag=1)
8505
[x^2 - 5*x - 2]
8506
sage: a.matfrobenius(2)
8507
[[0, 2; 1, 5], [1, -1/3; 0, 1/3]]
8508
sage: v = a.matfrobenius(2)
8509
sage: v[0]
8510
[0, 2; 1, 5]
8511
sage: v[1]^(-1)*v[0]*v[1]
8512
[1, 2; 3, 4]
8513
8514
We let t be the matrix of `T_2` acting on modular symbols
8515
of level 43, which was computed using
8516
``ModularSymbols(43,sign=1).T(2).matrix()``::
8517
8518
sage: t = pari('[3, -2, 0, 0; 0, -2, 0, 1; 0, -1, -2, 2; 0, -2, 0, 2]')
8519
sage: t.matfrobenius()
8520
[0, 0, 0, -12; 1, 0, 0, -2; 0, 1, 0, 8; 0, 0, 1, 1]
8521
sage: t.charpoly('x')
8522
x^4 - x^3 - 8*x^2 + 2*x + 12
8523
sage: t.matfrobenius(1)
8524
[x^4 - x^3 - 8*x^2 + 2*x + 12]
8525
8526
AUTHORS:
8527
8528
- Martin Albrect (2006-04-02)
8529
"""
8530
pari_catch_sig_on()
8531
return P.new_gen(matfrobenius(self.g, flag, 0))
8532
8533
8534
###########################################
8535
# polarit2.c
8536
###########################################
8537
def factor(gen self, limit=-1, bint proof=1):
8538
"""
8539
Return the factorization of x.
8540
8541
INPUT:
8542
8543
- ``limit`` -- (default: -1) is optional and can be set
8544
whenever x is of (possibly recursive) rational type. If limit is
8545
set return partial factorization, using primes up to limit (up to
8546
primelimit if limit=0).
8547
8548
- ``proof`` -- (default: True) optional. If False (not the default),
8549
returned factors larger than `2^{64}` may only be pseudoprimes.
8550
8551
.. note::
8552
8553
In the standard PARI/GP interpreter and C-library the
8554
factor command *always* has proof=False, so beware!
8555
8556
EXAMPLES::
8557
8558
sage: pari('x^10-1').factor()
8559
[x - 1, 1; x + 1, 1; x^4 - x^3 + x^2 - x + 1, 1; x^4 + x^3 + x^2 + x + 1, 1]
8560
sage: pari(2^100-1).factor()
8561
[3, 1; 5, 3; 11, 1; 31, 1; 41, 1; 101, 1; 251, 1; 601, 1; 1801, 1; 4051, 1; 8101, 1; 268501, 1]
8562
sage: pari(2^100-1).factor(proof=False)
8563
[3, 1; 5, 3; 11, 1; 31, 1; 41, 1; 101, 1; 251, 1; 601, 1; 1801, 1; 4051, 1; 8101, 1; 268501, 1]
8564
8565
We illustrate setting a limit::
8566
8567
sage: pari(next_prime(10^50)*next_prime(10^60)*next_prime(10^4)).factor(10^5)
8568
[10007, 1; 100000000000000000000000000000000000000000000000151000000000700000000000000000000000000000000000000000000001057, 1]
8569
8570
PARI doesn't have an algorithm for factoring multivariate
8571
polynomials::
8572
8573
sage: pari('x^3 - y^3').factor()
8574
Traceback (most recent call last):
8575
...
8576
PariError: sorry, factor for general polynomials is not yet implemented
8577
"""
8578
cdef int r
8579
cdef GEN t0
8580
cdef GEN cutoff
8581
if limit == -1 and typ(self.g) == t_INT and proof:
8582
pari_catch_sig_on()
8583
# cutoff for checking true primality: 2^64 according to the
8584
# PARI documentation ??ispseudoprime.
8585
cutoff = mkintn(3, 1, 0, 0) # expansion of 2^64 in base 2^32: (1,0,0)
8586
r = factorint_withproof_sage(&t0, self.g, cutoff)
8587
z = P.new_gen(t0)
8588
if not r:
8589
return z
8590
else:
8591
return _factor_int_when_pari_factor_failed(self, z)
8592
pari_catch_sig_on()
8593
return P.new_gen(factor0(self.g, limit))
8594
8595
8596
###########################################
8597
# misc (classify when I know where they go)
8598
###########################################
8599
8600
def hilbert(x, y, p):
8601
cdef gen t0 = objtogen(y)
8602
cdef gen t1 = objtogen(p)
8603
pari_catch_sig_on()
8604
ret = hilbert0(x.g, t0.g, t1.g)
8605
pari_catch_sig_off()
8606
return ret
8607
8608
def chinese(self, y):
8609
cdef gen t0 = objtogen(y)
8610
pari_catch_sig_on()
8611
return P.new_gen(chinese(self.g, t0.g))
8612
8613
def order(self):
8614
pari_catch_sig_on()
8615
return P.new_gen(order(self.g))
8616
8617
def znprimroot(self):
8618
"""
8619
Return a primitive root modulo self, whenever it exists.
8620
8621
This is a generator of the group `(\ZZ/n\ZZ)^*`, whenever
8622
this group is cyclic, i.e. if `n=4` or `n=p^k` or
8623
`n=2p^k`, where `p` is an odd prime and `k`
8624
is a natural number.
8625
8626
INPUT:
8627
8628
8629
- ``self`` - positive integer equal to 4, or a power
8630
of an odd prime, or twice a power of an odd prime
8631
8632
8633
OUTPUT: gen
8634
8635
EXAMPLES::
8636
8637
sage: pari(4).znprimroot()
8638
Mod(3, 4)
8639
sage: pari(10007^3).znprimroot()
8640
Mod(5, 1002101470343)
8641
sage: pari(2*109^10).znprimroot()
8642
Mod(236736367459211723407, 473472734918423446802)
8643
"""
8644
pari_catch_sig_on()
8645
return P.new_gen(znprimroot0(self.g))
8646
8647
def __abs__(self):
8648
return self.abs()
8649
8650
def norm(gen self):
8651
pari_catch_sig_on()
8652
return P.new_gen(gnorm(self.g))
8653
8654
def nextprime(gen self, bint add_one=0):
8655
"""
8656
nextprime(x): smallest pseudoprime greater than or equal to `x`.
8657
If ``add_one`` is non-zero, return the smallest pseudoprime
8658
strictly greater than `x`.
8659
8660
EXAMPLES::
8661
8662
sage: pari(1).nextprime()
8663
2
8664
sage: pari(2).nextprime()
8665
2
8666
sage: pari(2).nextprime(add_one = 1)
8667
3
8668
sage: pari(2^100).nextprime()
8669
1267650600228229401496703205653
8670
"""
8671
pari_catch_sig_on()
8672
if add_one:
8673
return P.new_gen(gnextprime(gaddsg(1,self.g)))
8674
return P.new_gen(gnextprime(self.g))
8675
8676
def change_variable_name(self, var):
8677
"""
8678
In ``self``, which must be a ``t_POL`` or ``t_SER``, set the
8679
variable to ``var``. If the variable of ``self`` is already
8680
``var``, then return ``self``.
8681
8682
.. WARNING::
8683
8684
You should be careful with variable priorities when
8685
applying this on a polynomial or series of which the
8686
coefficients have polynomial components. To be safe, only
8687
use this function on polynomials with integer or rational
8688
coefficients. For a safer alternative, use :meth:`subst`.
8689
8690
EXAMPLES::
8691
8692
sage: f = pari('x^3 + 17*x + 3')
8693
sage: f.change_variable_name("y")
8694
y^3 + 17*y + 3
8695
sage: f = pari('1 + 2*y + O(y^10)')
8696
sage: f.change_variable_name("q")
8697
1 + 2*q + O(q^10)
8698
sage: f.change_variable_name("y") is f
8699
True
8700
8701
In PARI, ``I`` refers to the square root of -1, so it cannot be
8702
used as variable name. Note the difference with :meth:`subst`::
8703
8704
sage: f = pari('x^2 + 1')
8705
sage: f.change_variable_name("I")
8706
Traceback (most recent call last):
8707
...
8708
PariError: I already exists with incompatible valence
8709
sage: f.subst("x", "I")
8710
0
8711
"""
8712
pari_catch_sig_on()
8713
cdef long n = P.get_var(var)
8714
pari_catch_sig_off()
8715
if varn(self.g) == n:
8716
return self
8717
if typ(self.g) != t_POL and typ(self.g) != t_SER:
8718
raise TypeError, "set_variable() only works for polynomials or power series"
8719
# Copy self and then change the variable in place
8720
cdef gen newg = P.new_gen_noclear(self.g)
8721
setvarn(newg.g, n)
8722
return newg
8723
8724
def subst(self, var, z):
8725
"""
8726
In ``self``, replace the variable ``var`` by the expression `z`.
8727
8728
EXAMPLES::
8729
8730
sage: x = pari("x"); y = pari("y")
8731
sage: f = pari('x^3 + 17*x + 3')
8732
sage: f.subst(x, y)
8733
y^3 + 17*y + 3
8734
sage: f.subst(x, "z")
8735
z^3 + 17*z + 3
8736
sage: f.subst(x, "z")^2
8737
z^6 + 34*z^4 + 6*z^3 + 289*z^2 + 102*z + 9
8738
sage: f.subst(x, "x+1")
8739
x^3 + 3*x^2 + 20*x + 21
8740
sage: f.subst(x, "xyz")
8741
xyz^3 + 17*xyz + 3
8742
sage: f.subst(x, "xyz")^2
8743
xyz^6 + 34*xyz^4 + 6*xyz^3 + 289*xyz^2 + 102*xyz + 9
8744
"""
8745
cdef gen t0 = objtogen(z)
8746
pari_catch_sig_on()
8747
return P.new_gen(gsubst(self.g, P.get_var(var), t0.g))
8748
8749
def substpol(self, y, z):
8750
cdef gen t0 = objtogen(y)
8751
cdef gen t1 = objtogen(z)
8752
pari_catch_sig_on()
8753
return P.new_gen(gsubstpol(self.g, t0.g, t1.g))
8754
8755
def nf_subst(self, z):
8756
"""
8757
Given a PARI number field ``self``, return the same PARI
8758
number field but in the variable ``z``.
8759
8760
INPUT:
8761
8762
- ``self`` -- A PARI number field being the output of ``nfinit()``,
8763
``bnfinit()`` or ``bnrinit()``.
8764
8765
EXAMPLES::
8766
8767
sage: x = polygen(QQ)
8768
sage: K = NumberField(x^2 + 5, 'a')
8769
8770
We can substitute in a PARI ``nf`` structure::
8771
8772
sage: Kpari = K.pari_nf()
8773
sage: Kpari.nf_get_pol()
8774
y^2 + 5
8775
sage: Lpari = Kpari.nf_subst('a')
8776
sage: Lpari.nf_get_pol()
8777
a^2 + 5
8778
8779
We can also substitute in a PARI ``bnf`` structure::
8780
8781
sage: Kpari = K.pari_bnf()
8782
sage: Kpari.nf_get_pol()
8783
y^2 + 5
8784
sage: Kpari.bnf_get_cyc() # Structure of class group
8785
[2]
8786
sage: Lpari = Kpari.nf_subst('a')
8787
sage: Lpari.nf_get_pol()
8788
a^2 + 5
8789
sage: Lpari.bnf_get_cyc() # We still have a bnf after substituting
8790
[2]
8791
"""
8792
cdef gen t0 = objtogen(z)
8793
pari_catch_sig_on()
8794
return P.new_gen(gsubst(self.g, gvar(self.g), t0.g))
8795
8796
def taylor(self, v=-1):
8797
pari_catch_sig_on()
8798
return P.new_gen(tayl(self.g, P.get_var(v), precdl))
8799
8800
def thue(self, rhs, ne):
8801
cdef gen t0 = objtogen(rhs)
8802
cdef gen t1 = objtogen(ne)
8803
pari_catch_sig_on()
8804
return P.new_gen(thue(self.g, t0.g, t1.g))
8805
8806
def charpoly(self, var=-1, long flag=0):
8807
"""
8808
charpoly(A,v=x,flag=0): det(v\*Id-A) = characteristic polynomial of
8809
A using the comatrix. flag is optional and may be set to 1 (use
8810
Lagrange interpolation) or 2 (use Hessenberg form), 0 being the
8811
default.
8812
"""
8813
pari_catch_sig_on()
8814
return P.new_gen(charpoly0(self.g, P.get_var(var), flag))
8815
8816
8817
def kronecker(gen self, y):
8818
cdef gen t0 = objtogen(y)
8819
pari_catch_sig_on()
8820
return P.new_gen(gkronecker(self.g, t0.g))
8821
8822
8823
def type(gen self):
8824
"""
8825
Return the PARI type of self as a string.
8826
8827
.. note::
8828
8829
In Cython, it is much faster to simply use typ(self.g) for
8830
checking PARI types.
8831
8832
EXAMPLES::
8833
8834
sage: pari(7).type()
8835
't_INT'
8836
sage: pari('x').type()
8837
't_POL'
8838
"""
8839
# The following original code leaks memory:
8840
# return str(type_name(typ(self.g)))
8841
#
8842
# This code is the usual workaround:
8843
# cdef char* s= <char*>type_name(typ(self.g))
8844
# t=str(s)
8845
# free(s)
8846
# return(t)
8847
# However, it causes segfaults with t_INTs on some
8848
# machines, and errors about freeing non-aligned
8849
# pointers on others. So we settle for the following
8850
# fast but ugly code. Note that should the list of
8851
# valid PARI types ever be updated, this code would
8852
# need to be updated accordingly.
8853
#
8854
cdef long t = typ(self.g)
8855
8856
if t == t_INT: return 't_INT'
8857
elif t == t_REAL: return 't_REAL'
8858
elif t == t_INTMOD: return 't_INTMOD'
8859
elif t == t_FRAC: return 't_FRAC'
8860
elif t == t_FFELT: return 't_FFELT'
8861
elif t == t_COMPLEX: return 't_COMPLEX'
8862
elif t == t_PADIC: return 't_PADIC'
8863
elif t == t_QUAD: return 't_QUAD'
8864
elif t == t_POLMOD: return 't_POLMOD'
8865
elif t == t_POL: return 't_POL'
8866
elif t == t_SER: return 't_SER'
8867
elif t == t_RFRAC: return 't_RFRAC'
8868
elif t == t_QFR: return 't_QFR'
8869
elif t == t_QFI: return 't_QFI'
8870
elif t == t_VEC: return 't_VEC'
8871
elif t == t_COL: return 't_COL'
8872
elif t == t_MAT: return 't_MAT'
8873
elif t == t_LIST: return 't_LIST'
8874
elif t == t_STR: return 't_STR'
8875
elif t == t_VECSMALL: return 't_VECSMALL'
8876
elif t == t_CLOSURE: return 't_CLOSURE'
8877
else:
8878
raise TypeError, "Unknown PARI type: %s"%t
8879
8880
8881
def polinterpolate(self, ya, x):
8882
"""
8883
self.polinterpolate(ya,x,e): polynomial interpolation at x
8884
according to data vectors self, ya (i.e. return P such that
8885
P(self[i]) = ya[i] for all i). Also return an error estimate on the
8886
returned value.
8887
"""
8888
cdef gen t0 = objtogen(ya)
8889
cdef gen t1 = objtogen(x)
8890
cdef GEN dy, g
8891
pari_catch_sig_on()
8892
g = polint(self.g, t0.g, t1.g, &dy)
8893
dif = P.new_gen_noclear(dy)
8894
return P.new_gen(g), dif
8895
8896
def algdep(self, long n):
8897
"""
8898
EXAMPLES::
8899
8900
sage: n = pari.set_real_precision(210)
8901
sage: w1 = pari('z1=2-sqrt(26); (z1+I)/(z1-I)')
8902
sage: f = w1.algdep(12); f
8903
545*x^11 - 297*x^10 - 281*x^9 + 48*x^8 - 168*x^7 + 690*x^6 - 168*x^5 + 48*x^4 - 281*x^3 - 297*x^2 + 545*x
8904
sage: f(w1).abs() < 1.0e-200
8905
True
8906
sage: f.factor()
8907
[x, 1; x + 1, 2; x^2 + 1, 1; x^2 + x + 1, 1; 545*x^4 - 1932*x^3 + 2790*x^2 - 1932*x + 545, 1]
8908
sage: pari.set_real_precision(n)
8909
210
8910
"""
8911
pari_catch_sig_on()
8912
return P.new_gen(algdep(self.g, n))
8913
8914
def concat(self, y):
8915
cdef gen t0 = objtogen(y)
8916
pari_catch_sig_on()
8917
return P.new_gen(concat(self.g, t0.g))
8918
8919
def lindep(self, long flag=0):
8920
pari_catch_sig_on()
8921
return P.new_gen(lindep0(self.g, flag))
8922
8923
def listinsert(self, obj, long n):
8924
cdef gen t0 = objtogen(obj)
8925
pari_catch_sig_on()
8926
return P.new_gen(listinsert(self.g, t0.g, n))
8927
8928
def listput(self, obj, long n):
8929
cdef gen t0 = objtogen(obj)
8930
pari_catch_sig_on()
8931
return P.new_gen(listput(self.g, t0.g, n))
8932
8933
8934
8935
def elleisnum(self, long k, long flag=0, unsigned long precision=0):
8936
"""
8937
om.elleisnum(k, flag=0): om=[om1,om2] being a 2-component vector
8938
giving a basis of a lattice L and k an even positive integer,
8939
computes the numerical value of the Eisenstein series of weight k.
8940
When flag is non-zero and k=4 or 6, this gives g2 or g3 with the
8941
correct normalization.
8942
8943
INPUT:
8944
8945
8946
- ``om`` - gen, 2-component vector giving a basis of a
8947
lattice L
8948
8949
- ``k`` - int (even positive)
8950
8951
- ``flag`` - int (default 0)
8952
8953
8954
OUTPUT:
8955
8956
8957
- ``gen`` - numerical value of E_k
8958
8959
8960
EXAMPLES::
8961
8962
sage: e = pari([0,1,1,-2,0]).ellinit()
8963
sage: om = e.omega()
8964
sage: om
8965
[2.49021256085506, -1.97173770155165*I]
8966
sage: om.elleisnum(2) # was: -5.28864933965426
8967
10.0672605281120
8968
sage: om.elleisnum(4)
8969
112.000000000000
8970
sage: om.elleisnum(100)
8971
2.15314248576078 E50
8972
"""
8973
pari_catch_sig_on()
8974
return P.new_gen(elleisnum(self.g, k, flag, prec_bits_to_words(precision)))
8975
8976
def ellwp(gen self, z='z', long n=20, long flag=0, unsigned long precision=0):
8977
"""
8978
Return the value or the series expansion of the Weierstrass
8979
`P`-function at `z` on the lattice `self` (or the lattice
8980
defined by the elliptic curve `self`).
8981
8982
INPUT:
8983
8984
- ``self`` -- an elliptic curve created using ``ellinit`` or a
8985
list ``[om1, om2]`` representing generators for a lattice.
8986
8987
- ``z`` -- (default: 'z') a complex number or a variable name
8988
(as string or PARI variable).
8989
8990
- ``n`` -- (default: 20) if 'z' is a variable, compute the
8991
series expansion up to at least `O(z^n)`.
8992
8993
- ``flag`` -- (default = 0): If ``flag`` is 0, compute only
8994
`P(z)`. If ``flag`` is 1, compute `[P(z), P'(z)]`.
8995
8996
OUTPUT:
8997
8998
- `P(z)` (if ``flag`` is 0) or `[P(z), P'(z)]` (if ``flag`` is 1).
8999
numbers
9000
9001
EXAMPLES:
9002
9003
We first define the elliptic curve X_0(11)::
9004
9005
sage: E = pari([0,-1,1,-10,-20]).ellinit()
9006
9007
Compute P(1)::
9008
9009
sage: E.ellwp(1)
9010
13.9658695257485 + 0.E-18*I
9011
9012
Compute P(1+i), where i = sqrt(-1)::
9013
9014
sage: C.<i> = ComplexField()
9015
sage: E.ellwp(pari(1+i))
9016
-1.11510682565555 + 2.33419052307470*I
9017
sage: E.ellwp(1+i)
9018
-1.11510682565555 + 2.33419052307470*I
9019
9020
The series expansion, to the default `O(z^20)` precision::
9021
9022
sage: E.ellwp()
9023
z^-2 + 31/15*z^2 + 2501/756*z^4 + 961/675*z^6 + 77531/41580*z^8 + 1202285717/928746000*z^10 + 2403461/2806650*z^12 + 30211462703/43418875500*z^14 + 3539374016033/7723451736000*z^16 + 413306031683977/1289540602350000*z^18 + O(z^20)
9024
9025
Compute the series for wp to lower precision::
9026
9027
sage: E.ellwp(n=4)
9028
z^-2 + 31/15*z^2 + O(z^4)
9029
9030
Next we use the version where the input is generators for a
9031
lattice::
9032
9033
sage: pari([1.2692, 0.63 + 1.45*i]).ellwp(1)
9034
13.9656146936689 + 0.000644829272810...*I
9035
9036
With flag=1, compute the pair P(z) and P'(z)::
9037
9038
sage: E.ellwp(1, flag=1)
9039
[13.9658695257485 + 0.E-18*I, 50.5619300880073 ... E-18*I]
9040
"""
9041
cdef gen t0 = objtogen(z)
9042
pari_catch_sig_on()
9043
return P.new_gen(ellwp0(self.g, t0.g, flag, n+2, prec_bits_to_words(precision)))
9044
9045
def ellchangepoint(self, y):
9046
"""
9047
self.ellchangepoint(y): change data on point or vector of points
9048
self on an elliptic curve according to y=[u,r,s,t]
9049
9050
EXAMPLES::
9051
9052
sage: e = pari([0,1,1,-2,0]).ellinit()
9053
sage: x = pari([1,0])
9054
sage: e.ellisoncurve([1,4])
9055
False
9056
sage: e.ellisoncurve(x)
9057
True
9058
sage: f = e.ellchangecurve([1,2,3,-1])
9059
sage: f[:5] # show only first five entries
9060
[6, -2, -1, 17, 8]
9061
sage: x.ellchangepoint([1,2,3,-1])
9062
[-1, 4]
9063
sage: f.ellisoncurve([-1,4])
9064
True
9065
"""
9066
cdef gen t0 = objtogen(y)
9067
pari_catch_sig_on()
9068
return P.new_gen(ellchangepoint(self.g, t0.g))
9069
9070
def debug(gen self, long depth = -1):
9071
r"""
9072
Show the internal structure of self (like the ``\x`` command in gp).
9073
9074
EXAMPLE::
9075
9076
sage: pari('[1/2, 1.0*I]').debug() # random addresses
9077
[&=0000000004c5f010] VEC(lg=3):2200000000000003 0000000004c5eff8 0000000004c5efb0
9078
1st component = [&=0000000004c5eff8] FRAC(lg=3):0800000000000003 0000000004c5efe0 0000000004c5efc8
9079
num = [&=0000000004c5efe0] INT(lg=3):0200000000000003 (+,lgefint=3):4000000000000003 0000000000000001
9080
den = [&=0000000004c5efc8] INT(lg=3):0200000000000003 (+,lgefint=3):4000000000000003 0000000000000002
9081
2nd component = [&=0000000004c5efb0] COMPLEX(lg=3):0c00000000000003 00007fae8a2eb840 0000000004c5ef90
9082
real = gen_0
9083
imag = [&=0000000004c5ef90] REAL(lg=4):0400000000000004 (+,expo=0):6000000000000000 8000000000000000 0000000000000000
9084
"""
9085
pari_catch_sig_on()
9086
dbgGEN(self.g, depth)
9087
pari_catch_sig_off()
9088
return
9089
9090
9091
def init_pari_stack(s=8000000):
9092
"""
9093
Deprecated, use ``pari.allocatemem()`` instead.
9094
9095
EXAMPLES::
9096
9097
sage: from sage.libs.pari.gen import init_pari_stack
9098
sage: init_pari_stack()
9099
doctest:...: DeprecationWarning: init_pari_stack() is deprecated; use pari.allocatemem() instead.
9100
See http://trac.sagemath.org/10018 for details.
9101
sage: pari.stacksize()
9102
8000000
9103
"""
9104
from sage.misc.superseded import deprecation
9105
deprecation(10018, 'init_pari_stack() is deprecated; use pari.allocatemem() instead.')
9106
P.allocatemem(s, silent=True)
9107
9108
9109
cdef gen objtogen(s):
9110
"""Convert any Sage/Python object to a PARI gen"""
9111
cdef GEN g
9112
cdef Py_ssize_t length, i
9113
cdef mpz_t mpz_int
9114
cdef gen v
9115
9116
if isinstance(s, gen):
9117
return s
9118
try:
9119
return s._pari_()
9120
except AttributeError:
9121
pass
9122
9123
# Check basic Python types. Start with strings, which are a very
9124
# common case.
9125
if PyString_Check(s):
9126
pari_catch_sig_on()
9127
g = gp_read_str(PyString_AsString(s))
9128
if g == gnil:
9129
P.clear_stack()
9130
return None
9131
return P.new_gen(g)
9132
if PyInt_Check(s):
9133
pari_catch_sig_on()
9134
return P.new_gen(stoi(PyInt_AS_LONG(s)))
9135
if PyBool_Check(s):
9136
return P.PARI_ONE if s else P.PARI_ZERO
9137
if PyLong_Check(s):
9138
pari_catch_sig_on()
9139
mpz_init(mpz_int)
9140
mpz_set_pylong(mpz_int, s)
9141
g = P._new_GEN_from_mpz_t(mpz_int)
9142
mpz_clear(mpz_int)
9143
return P.new_gen(g)
9144
if PyFloat_Check(s):
9145
pari_catch_sig_on()
9146
return P.new_gen(dbltor(PyFloat_AS_DOUBLE(s)))
9147
if PyComplex_Check(s):
9148
pari_catch_sig_on()
9149
g = cgetg(3, t_COMPLEX)
9150
set_gel(g, 1, dbltor(PyComplex_RealAsDouble(s)))
9151
set_gel(g, 2, dbltor(PyComplex_ImagAsDouble(s)))
9152
return P.new_gen(g)
9153
9154
if isinstance(s, (types.ListType, types.XRangeType,
9155
types.TupleType, types.GeneratorType)):
9156
length = len(s)
9157
v = P._empty_vector(length)
9158
for i from 0 <= i < length:
9159
v[i] = objtogen(s[i])
9160
return v
9161
9162
# Simply use the string representation
9163
return objtogen(str(s))
9164
9165
9166
cdef GEN _Vec_append(GEN v, GEN a, long n):
9167
"""
9168
This implements appending zeros (or another constant GEN ``a``) to
9169
the result of :meth:`Vec` and similar functions.
9170
9171
This is a shallow function, copying ``a`` and entries of ``v`` to
9172
the result. The result is simply stored on the PARI stack.
9173
9174
INPUT:
9175
9176
- ``v`` -- GEN of type ``t_VEC`` or ``t_COL``
9177
9178
- ``a`` -- GEN which will be used for the added entries.
9179
Normally, this would be ``gen_0``.
9180
9181
- ``n`` -- Make the vector of minimal length `|n|`. If `n > 0`,
9182
append zeros; if `n < 0`, prepend zeros.
9183
9184
OUTPUT:
9185
9186
A GEN of the same type as ``v``.
9187
"""
9188
cdef long lenv = lg(v)-1
9189
cdef GEN w
9190
cdef long i
9191
# Do we need to extend the vector with zeros?
9192
if n > lenv:
9193
w = cgetg(n+1, typ(v))
9194
for i from 1 <= i <= lenv:
9195
set_gel(w, i, gel(v, i))
9196
for i from 1 <= i <= n-lenv:
9197
set_gel(w, i+lenv, a)
9198
return w
9199
elif n < -lenv:
9200
n = -n # Make n positive
9201
w = cgetg(n+1, typ(v))
9202
for i from 1 <= i <= lenv:
9203
set_gel(w, i+(n-lenv), gel(v, i))
9204
for i from 1 <= i <= n-lenv:
9205
set_gel(w, i, a)
9206
return w
9207
else:
9208
return v
9209
9210
9211
# We derive PariError from RuntimeError, for backward compatibility with
9212
# code that catches the latter.
9213
class PariError(RuntimeError):
9214
"""
9215
Error raised by PARI
9216
"""
9217
def errnum(self):
9218
r"""
9219
Return the PARI error number corresponding to this exception.
9220
9221
EXAMPLES::
9222
9223
sage: try:
9224
....: pari('1/0')
9225
....: except PariError as err:
9226
....: print err.errnum()
9227
27
9228
"""
9229
return self.args[0]
9230
9231
def errtext(self):
9232
"""
9233
Return the message output by PARI when this error occurred.
9234
9235
EXAMPLE::
9236
9237
sage: try:
9238
....: pari('pi()')
9239
....: except PariError as e:
9240
....: print e.errtext()
9241
....:
9242
*** at top-level: pi()
9243
*** ^----
9244
*** not a function in function call
9245
9246
"""
9247
return self.args[1]
9248
9249
def __repr__(self):
9250
r"""
9251
TESTS::
9252
9253
sage: PariError(11)
9254
PariError(11)
9255
"""
9256
return "PariError(%d)"%self.errnum()
9257
9258
def __str__(self):
9259
r"""
9260
Return a suitable message for displaying this exception.
9261
9262
This is the last line of ``self.errtext()``, with the leading
9263
``" *** "`` and trailing periods and colons (if any) removed.
9264
An exception is syntax errors, where the "syntax error" line is
9265
shown.
9266
9267
EXAMPLES::
9268
9269
sage: try:
9270
....: pari('1/0')
9271
....: except PariError as err:
9272
....: print err
9273
_/_: division by zero
9274
9275
A syntax error::
9276
9277
sage: pari('!@#$%^&*()')
9278
Traceback (most recent call last):
9279
...
9280
PariError: syntax error, unexpected $undefined: !@#$%^&*()
9281
"""
9282
lines = self.errtext().split('\n')
9283
if self.errnum() == syntaxer:
9284
for line in lines:
9285
if "syntax error" in line:
9286
return line.lstrip(" *").rstrip(" .:")
9287
return lines[-1].lstrip(" *").rstrip(" .:")
9288
9289
9290
cdef _factor_int_when_pari_factor_failed(x, failed_factorization):
9291
"""
9292
This is called by factor when PARI's factor tried to factor, got
9293
the failed_factorization, and it turns out that one of the factors
9294
in there is not proved prime. At this point, we don't care too much
9295
about speed (so don't write everything below using the PARI C
9296
library), since the probability this function ever gets called is
9297
infinitesimal. (That said, we of course did test this function by
9298
forcing a fake failure in the code in misc.h.)
9299
"""
9300
P = failed_factorization[0] # 'primes'
9301
E = failed_factorization[1] # exponents
9302
if len(P) == 1 and E[0] == 1:
9303
# Major problem -- factor can't split the integer at all, but it's composite. We're stuffed.
9304
print "BIG WARNING: The number %s wasn't split at all by PARI, but it's definitely composite."%(P[0])
9305
print "This is probably an infinite loop..."
9306
w = []
9307
for i in range(len(P)):
9308
p = P[i]
9309
e = E[i]
9310
if not p.isprime():
9311
# Try to factor further -- assume this works.
9312
F = p.factor(proof=True)
9313
for j in range(len(F[0])):
9314
w.append((F[0][j], F[1][j]))
9315
else:
9316
w.append((p, e))
9317
m = P.matrix(len(w), 2)
9318
for i in range(len(w)):
9319
m[i,0] = w[i][0]
9320
m[i,1] = w[i][1]
9321
return m
9322
9323
9324