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