Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

Testing latest pari + WASM + node.js... and it works?! Wow.

28495 views
License: GPL3
ubuntu2004
1
% Copyright (c) 2000 The PARI Group
2
%
3
% This file is part of the PARI/\kbd{gp} documentation
4
%
5
% Permission is granted to copy, distribute and/or modify this document
6
% under the terms of the GNU General Public License
7
8
% This should be compiled with plain TeX
9
\def\TITLE{A Tutorial for Pari/GP}
10
\input parimacro.tex
11
12
\chapno=0
13
\begintitle
14
\vskip2.5truecm
15
\centerline{\mine A Tutorial}
16
\vskip1.truecm
17
\centerline{\mine for}
18
\vskip1.truecm
19
\centerline{\mine PARI / GP}
20
\vskip1.truecm
21
\centerline{\sectiontitlebf (version \vers)}
22
\vskip1.truecm
23
\authors
24
\endtitle
25
26
\copyrightpage
27
\tableofcontents
28
29
\noindent This booklet is a guided tour and a tutorial to the \kbd{gp}
30
calculator. Many examples will be given, but each time a new function is
31
used, the reader should look at the appropriate section in the \emph{User's
32
Manual to PARI/GP} for detailed explanations. This chapter can be read
33
independently, for example to get acquainted with the possibilities of
34
\kbd{gp} without having to read the whole manual. At this point.
35
36
\section{Greetings!}
37
38
So you are sitting in front of your workstation (or terminal, or PC\dots),
39
and you type \kbd{gp} to get the program started (or click on the relevant
40
icon, or select some menu item). It says hello in its particular manner, and
41
then waits for you after its \kbd{prompt}, initially \kbd{?} (or something
42
like {\bf gp}~\kbd{>}). Type
43
\bprog
44
2 + 2
45
@eprog\noindent What happens? Maybe not what you expect. First of all, of
46
course, you should tell \kbd{gp} that your input is finished, and this is
47
done by hitting the \kbd{Return} (or \kbd{Newline}, or \kbd{Enter}) key. If
48
you do exactly this, you will get the expected answer. However some of you
49
may be used to other systems like Gap, Macsyma, Magma or Maple. In this case,
50
you will have subconsciously ended the line with a semicolon ``\kbd{;}''
51
before hitting \kbd{Return}, since this is how it is done on those systems.
52
In that case, you will simply see \kbd{gp} answering you with a smug
53
expression, i.e.~a new prompt and no answer! This is because a semicolon at
54
the end of a line tells \kbd{gp} not to print the result (it is still stored
55
in the result history). You will certainly want to use this feature if the
56
output is several pages long. Try
57
\bprog
58
27 * 37
59
@eprog\noindent Wow! even multiplication works. Actually, maybe those
60
spaces are not necessary after all. Let's try \kbd{27*37}. Seems to be ok. We
61
will still insert them in this document since it makes things easier to read,
62
but as \kbd{gp} does not care about them, you don't have to type them all.
63
64
Now this session is getting lengthy, so the second thing one needs to learn
65
is to quit. Each system has its quit signal. In \kbd{gp}, you can use
66
\kbd{quit} or \b{q} (backslash q), the \kbd{q} being of course for quit.
67
Try it.
68
69
Now you've done it! You're out of \kbd{gp}, so how do you want to continue
70
studying this tutorial? Get back in please.
71
72
Let's get to more serious stuff. I seem to remember that the decimal
73
expansion of $1/7$ has some interesting properties. Let's see what \kbd{gp}
74
has to say about this. Type
75
\bprog
76
1 / 7
77
@eprog\noindent
78
What? This computer is making fun of me, it just spits back to me my own
79
input, that's not what I want!
80
81
Now stop complaining, and think a little. Mathematically, $1/7$ is an element
82
of the field $\Q$ of rational numbers, so how else but $1/7$ can the computer
83
give the answer to you? Well maybe $2/14$ or $7^{-1}$, but why complicate
84
matters? Seriously, the basic point here is that PARI, hence \kbd{gp}, will
85
almost always try to give you a result which is as precise as possible (we
86
will see why ``almost'' later). Hence since here the result can be
87
represented exactly, that's what it gives you.
88
89
But I still want the decimal expansion of $1/7$. No problem. Type one of
90
the following:
91
\bprog
92
1./ 7
93
1 / 7.
94
1./ 7.
95
1 / 7 + 0.
96
@eprog\noindent
97
Immediately a number of decimals of this fraction appear, 38 on most systems,
98
28 on the others, and the repeating pattern is $142857$. The reason is that
99
you have included in the operations numbers like \kbd{0.}, \kbd{1.} or \kbd{7.}
100
which are \emph{imprecise} real numbers, hence \kbd{gp} cannot give you an
101
exact result.
102
103
Why 28 / 38 decimals by the way? Well, it is the default initial precision.
104
This has been chosen so that the computations are very fast, and gives
105
already 12 decimals more accuracy than conventional double precision floating
106
point operations. The precise value depends on a technical reason: if your
107
machine supports 64-bit integers (the standard C library can handle integers
108
up to $2^{64}$), the default precision is 38 decimals, and 28 otherwise.
109
For definiteness, we will assume the former henceforth. Of course, you can
110
extend the precision (almost) as much as you like as we will see in a moment.
111
112
I'm getting bored, why don't we get on with some more exciting stuff? Well,
113
try \kbd{exp(1)}. Presto, comes out the value of $e$ to 38 digits. Try
114
\kbd{log(exp(1))}. Well, we get a floating point number and not an exact $1$,
115
but pretty close! That's what you lose by working numerically.
116
117
What could we try now? Hum, \kbd{pi}? The answer is not that
118
enlightening. \kbd{Pi}? Ah. This works better. But let's remember that
119
\kbd{gp} distinguishes between uppercase and lowercase letters. \kbd{pi} was
120
as meaningless to it as \kbd{stupid garbage} would have been: in both cases
121
\kbd{gp} will just create a variable with that funny unknown name you just
122
used. Try it! Note that it is actually equivalent to type
123
\kbd{stupidgarbage}: all spaces are suppressed from the input. In the
124
\kbd{27~*~37} example it was not so conspicuous as we had an operator to
125
separate the two operands. This has important consequences for the writing of
126
\kbd{gp} scripts. More about this later.
127
128
By the way, you can ask \kbd{gp} about any identifier you think it might know
129
about: just type it, prepending a question mark ``\kbd{?}''. Try \kbd{?Pi}
130
and \kbd{?pi} for instance. On most systems, an extended online help should
131
be available: try doubling the question mark to check whether it's the case
132
on yours: \kbd{??Pi}. In fact the \kbd{gp} header already gave you that
133
information if it was the case, just before the copyright message. As well,
134
if it says something like ``\kbd{readline enabled}'' then you should have a
135
look at the \kbd{readline} introduction in the User's Manual before you go
136
on: it will be much easier to type in examples and correct typos after you've
137
done that.
138
139
Now try \kbd{exp(Pi * sqrt(163))}. Hmmm, we suspect that the last digit may
140
be wrong, can this really be an integer? This is the time to change
141
precision. Type \kbd{\b{p} 50}, then try \kbd{exp(Pi * sqrt(163))} again. We
142
were right to suspect that the last decimal was incorrect, since we get quite
143
a few nines in its place, but it is now convincingly clear that this is not
144
an integer. Maybe it's a bug in PARI, and the result is really an integer?
145
Type
146
\bprog
147
(log(%) / Pi)^2
148
@eprog\noindent
149
immediately after the preceding computation; \kbd{\%} means the result of the
150
last computed expression. More generally, the results are numbered \kbd{\%1,
151
\%2, \dots} \emph{including} the results
152
that you do not want to see printed by putting a semicolon at the end of the
153
line, and you can evidently use all these quantities in any further
154
computations. The result seems to be indistinguishable from $163$, hence it
155
does not seem to be a bug.
156
157
In fact, it is known that $\exp(\pi*\sqrt{n})$ not only is not an integer or
158
a rational number, but is even a transcendental number when $n$ is a nonzero
159
rational number.
160
161
So \kbd{gp} is just a fancy calculator, able to give me more decimals than I
162
will ever need? Not so, \kbd{gp} is incredibly more powerful than an ordinary
163
calculator, independently of its arbitrary precision possibilities.
164
165
\misctitle{Additional comments} (you are supposed to skip this at first,
166
and come back later)
167
168
1) If you are a PARI old timer, say the last version of PARI you used was
169
released around 1996, you have certainly noticed already that many many
170
things changed between the older 1.39.xx versions and this one.
171
Conspicuously, most function names have been changed. To know how a specific
172
function was changed, type \kbd{whatnow({\rm function})}.
173
174
2) It seems that the text implicitly says that as soon as an imprecise number
175
is entered, the result will be imprecise. Is this always true? There is a
176
unique exception: when you multiply an imprecise number by the exact number
177
0, you will get the exact 0. Compare \kbd{0 * 1.4} and \kbd{0.~*~1.4}.
178
\smallskip
179
%
180
3) Not only can the number of decimal places of real numbers be large, but
181
the number of digits of integers also. Try \kbd{1000!}. It is never necessary
182
to tell \kbd{gp} in advance the size of the integers that it will encounter.
183
The same is true for real numbers, although most computations with floating
184
point assume a default precision and truncate their results to this accuracy;
185
initially 38 decimal digits, but we may change that with \b{p} of course.
186
\smallskip
187
%
188
4) Come back to 38 digits of precision (\kbd{\b{p} 38}), and type
189
\kbd{exp(100)}. As you can see the result is printed in exponential format.
190
This is because \kbd{gp} never wants you to believe that a result is correct
191
when it is not. We are working with 38 digits of precision, but the integer
192
part of $\exp(100)$ has 44 decimal digits. Hence if \kbd{gp} had dutifully
193
printed out 44 digits, the last few digits would have been wrong. Hence
194
\kbd{gp} wants to print only 38 significant digits, but to do so it has to
195
print in exponential format. \smallskip
196
%
197
5) There are two ways to avoid this. One is of course to increase the
198
precision. Let's try it. To give it a wide margin, we set the precision to 50
199
decimals. Then we recall our last result (\kbd{\%}
200
or \kbd{\%n} where \kbd{n} is the number of the result). What? We still have
201
an exponential format! Do you understand why?
202
203
Again let's try to see what's happening. The number you recalled had been
204
computed only to 38 decimals, and even if you set the precision to 1000
205
decimals, \kbd{gp} knows that your number has only 38 digits of accuracy but
206
an integral part with 44 digits. So you haven't improved things by increasing
207
the precision. Or have you? What if we retype \kbd{exp(100)} now that we
208
have 50 digits? Try it. Now we no longer have an exponential format.
209
\medskip
210
%
211
6) What if I forget what the current precision is and I don't feel like
212
counting all the decimals? Well, you can type \b{p} by itself. You may also
213
learn about \kbd{gp} internal variables (and change them!) using
214
\kbd{default}. Type \kbd{default(realprecision)}, then
215
\kbd{default(realprecision, 38)}. Huh? In fact this last command is strictly
216
equivalent to \kbd{\b{p} 38}! (Admittedly more cumbersome to type.) There are
217
more ``defaults'' than just \kbd{format} and \kbd{realprecision}: type
218
\kbd{default} by itself now, they are all there. \smallskip
219
%
220
7) Note that the \kbd{default} command reacts differently according to the
221
number of input arguments. This is not an uncommon behavior for \kbd{gp}
222
functions. You can see this from the online help, or the complete description
223
in Chapter~3: any argument surrounded by braces \kbd{\obr\cbr} in the
224
function prototype is optional, which really means that a \emph{default}
225
argument will be supplied by \kbd{gp}. You can then check out from the text
226
what effect a given value will have, and in particular the default one.
227
\smallskip
228
%
229
8) Try the following: starting in precision 38, type first
230
\kbd{default(format, "e0.100")}, then \kbd{exp(1)}. Where are my 100
231
significant digits? Well, \kbd{default(format,)} only changes the output
232
format, but \emph{not} the default precision. On the other hand, the \b{p}
233
command changes both the precision and the output format.
234
235
\section{Warming up}
236
237
Another thing you better get used to pretty fast is error messages. Try
238
typing \kbd{1/0}. Could not be clearer. But why has the prompt
239
become funny, turning from \kbd{?} to \kbd{break>} ? When an error occurs, we
240
enter a so-called \emph{break loop}, where you get a chance, e.g to inspect
241
(and save!) values of variables before the prompt returns and all
242
computations so far are lost. In fact you can run an arbitrary command at
243
this point, and this mechanism is a tremendous help in debugging. To get out
244
of the break loop, type \kbd{break}, as instructed in the error message
245
last line.
246
247
\misctitle{Comment} You can enter the break loop at any time using
248
\kbd{Control-C}: this freezes the current computation and gets you a new
249
prompt so that you may e.g., increase debugging level, inspect or modify
250
variables (again, run arbitrary commands), before letting the program go
251
on.
252
\medskip
253
254
Now, back to our favorite example, in precision 38, type
255
\bprog
256
floor(exp(100))
257
@eprog\noindent
258
\kbd{floor} is the mathematician's integer part, not to be confused with
259
\kbd{truncate}, which is the computer scientist's: \kbd{floor(-3.4)} is equal
260
to $-4$ whereas \kbd{truncate(-3.4)} is equal to $-3$. You get a more
261
cryptic error message, which you would immediately understand if you had read
262
the additional comments of the preceding section. Since you were told not to
263
read them, here's the explanation: \kbd{gp} is unable to compute the
264
integer part of \kbd{exp(100)} given only 38 decimals of accuracy, since
265
it has 44 digits.
266
267
Some error messages are more cryptic and sometimes not so easy to understand.
268
For instance, try \kbd{log(x)}. It simply tells you that \kbd{gp} does not
269
understand what \kbd{log(x)} is, although it does know the \kbd{log}
270
function, as \kbd{?log} will readily tell us.
271
272
Now let's try \kbd{sqrt(-1)} to see what error message we get now. Haha!
273
\kbd{gp} even knows about complex numbers, so impossible to trick it that
274
way. Similarly, try typing \kbd{log(-2)}, \kbd{exp(I*Pi)}, \kbd{I\pow
275
I}\dots\ So we have a lot of real and complex analysis at our disposal.
276
There always is a specific branch of multivalued complex transcendental
277
functions which is taken, specified in the manual. Again, beware that
278
\kbd{I} and \kbd{i} are not the same thing. Compare \kbd{I\pow2} with
279
\kbd{i\pow2} for instance.
280
281
Just for fun, let's try \kbd{6*zeta(2) / Pi\pow2}. Pretty close, no?
282
283
\medskip
284
Now \kbd{gp} didn't seem to know what \kbd{log(x)} was, although it did know
285
how to compute numerical values of \kbd{log}. This is annoying. Maybe it
286
knows the exponential function? Let's give it a try. Type \kbd{exp(x)}.
287
What's this? If you had any experience with other computer algebra systems,
288
the answer should have simply been \kbd{exp(x)} again. But here the answer is
289
the Taylor expansion of the function around $\kbd{x}=0$, to 17 terms. Note
290
the \kbd{O(x\pow17)} which ends the series, and which is trademark of power
291
series in \kbd{gp}. It is the familiar ``big--oh'' notation of analysis.
292
Why 17 terms? This is governed by the \kbd{seriesprecision}, which
293
can be changed by typing \kbd{\b{ps} $n$} or \kbd{default(seriesprecision,
294
$n$)} where $n$ is the number of terms that you want in your power series
295
and is $16$ by default. Converting a polynomial or rational function to a
296
power series will yield 16 significant terms: so $x$ gets converted to $x +
297
O(x^{17})$; this is completely analogous to \kbd{realprecision} when an eact
298
integer or rational number is converted to a floating point real number.
299
Then we take the exponential of this new object and, since it has positive
300
valuation, we can actually deduce $17$ significant terms from the given $16$.
301
This is in keeping with PARI's philosophy of always returning a result which
302
is as precise as possible from a given input.
303
304
You thus automatically get the Taylor expansion of any function that can be
305
expanded around $0$, and incidentally this explains why we weren't able to do
306
anything with \kbd{log(x)} which is not defined at $0$. (In fact \kbd{gp}
307
knows about Laurent series, but \kbd{log(x)} is not meromorphic either at
308
$0$.) If we try \kbd{log(1+x)}, then it works, but this time we \emph{lose}
309
one significant term: the result is $x - 1/2*x^2 + \dots + 1/15*x^15 +
310
O(x^16))$. (Do you understand why ?)
311
312
But what if we wanted the expansion around a point different from 0? Well,
313
you're able to change $x$ into $x+a$, aren't you? So for instance you can
314
type \kbd{log(x+2)} to have the expansion of \kbd{log} around $\kbd{x}=2$. As
315
exercises you can try
316
\bprog
317
cos(x)
318
cos(x)^2 + sin(x)^2
319
exp(cos(x))
320
gamma(1 + x)
321
exp(exp(x) - 1)
322
1 / tan(x)
323
@eprog\noindent
324
for different values of \kbd{serieslength} (change it using \b{ps}
325
\var{newvalue}).
326
327
Let's try something else: type \kbd{(1 + x)\pow 3}. No \kbd{O(x)} here, since
328
the result is a polynomial. Haha, but I have learnt that if you do not take
329
exponents which are integers greater or equal to 0, you obtain a power series
330
with an infinite number of nonzero terms. Let's try. Type
331
\kbd{(1 + x)\pow (-3)} (the parentheses around \kbd{-3} are not necessary but
332
make things easier to read). Surprise! Contrary to what we expected, we don't
333
get a power series but a rational function. Again this is for the same reason
334
that \kbd{1 / 7} just gave you $1/7$: the result being exact, PARI doesn't see
335
any reason to make it inexact.
336
337
But I still want that power series. To obtain it, you can do as in the $1/7$
338
example and force a conversion using the $O(x^n)$ notation:
339
\bprog
340
(1 + x)^(-3) + O(x^16)
341
(1 + x)^(-3) * (1 + O(x^16))
342
(1 + x + O(x^16))^(-3)
343
@eprog\noindent
344
(Not on this example, but there is a difference between the first $2$
345
methods. Do you spot it?) Better yet, use the series constructor which
346
transforms any object into a power series, using the current
347
\kbd{seriesprecision}, and simply type
348
\bprog
349
Ser( (1 + x)^(-3) )
350
@eprog
351
352
Now try \kbd{(1 + x)\pow (1/2)}: we obtain a power series, since the
353
result is an object which PARI does not know how to represent exactly. (We
354
could teach PARI about algebraic functions, but then take \kbd{(1 + x)\pow Pi}
355
as another example.) This gives us still another solution to our preceding
356
exercise: we can type \kbd{(1 + x)\pow (-3.)}. Since \kbd{-3.} is not an exact
357
quantity, PARI has no means to know that we are dealing with a rational
358
function, and will instead give you the power series, this time with real
359
instead of integer coefficients.
360
\smallskip
361
362
To summarize, in this section we have seen that in addition to integers, real
363
numbers and rational numbers, PARI can handle complex numbers, polynomials,
364
rational functions and power series. A large number of functions exist which
365
handle these types, but in this tutorial we will only look at a few.
366
367
\misctitle{Additional comments} (as before, you are supposed to skip this
368
at first reading)
369
370
1) In almost all cases, there is no loss of information in PARI output: what
371
you see is all that PARI knows about the object, and you can happily
372
copy-paste it into another session. There are exceptions, though. Type
373
\kbd{n = 3 + 0*x}, then \kbd{n} is not the integer 3 but a constant polynomial
374
equal to $3 x^0$. Check it with \kbd{type(n)}.
375
376
However, it \emph{looks} like an integer without being one, and this may
377
cause some confusion in programs which actually expect integers. Hence if you
378
try to \kbd{factor(n)}, you obtain an empty factorization ! (Because, once
379
considered as a polynomial, \kbd{n} is a unit in $\Q[x]$.)
380
381
If you try to apply more general arithmetic functions, say the Euler totient
382
function (known as \kbd{eulerphi} to \kbd{gp}), you get an error message
383
worrying about integer arguments. You would have guessed yourself, but the
384
message is difficult to understand since 3 looks like a genuine integer!
385
Please make sure you understand the above, it is a common source of
386
incomprehension.
387
388
2) If you want the final expression to be in the simplest form possible (for
389
example before applying an arithmetic function, or simply because things will
390
go faster afterwards), apply the function \kbd{simplify} to the result.
391
This is done automatically at the end of a \kbd{gp} command, but
392
\emph{not} in intermediate expressions. Hence \kbd{n} above is not an
393
integer, but the final result stored in the output history is! So
394
if you type \kbd{type(\%)} instead of \kbd{type(n)} the answer is
395
\typ{INT}, adding to the confusion.
396
397
3) As already stated, power series expansions are always implicitly around
398
$\kbd{x} = 0$. When we wante them around $\kbd{x} = \kbd{a}$, we replace
399
\kbd{x} by \kbd{z + a} in the function we want to expand. For complicated
400
functions, it may be simpler to use the substitution function \kbd{subst}.
401
For example, if \kbd{p~= 1 / (x\pow 4 + 3*x\pow 3 + 5*x\pow 2 - 6*x + 7)},
402
you may not want to retype this, replacing \kbd{x} by \kbd{z~+ a}, so you can
403
write \kbd{subst(p, x, z+a)} (look up the exact description of the
404
\kbd{subst} function).
405
406
4) The valuation at $\kbd{x} = 0$ for a power series \kbd{p} is obtained
407
as \kbd{valuation(p, x)}.
408
409
\section{The Remaining PARI Types}
410
Let's talk some more about the basic PARI types.
411
412
Type \kbd{p = x * exp(-x)}. As expected, you get the power series expansion
413
to 17 terms (if you have not changed the default). Now type
414
\kbd{pr = serreverse(p)}. You are asking here for the \emph{reversion} of the
415
power series \kbd{p}, in other words the expansion of the inverse function.
416
This is possible only for power series whose first nonzero coefficient is
417
that of $x^1$. To check the correctness of the result, you can type
418
\kbd{subst(p, x, pr)} or \kbd{ subst(pr, x, p)} and you should get back
419
\kbd{x + O(x\pow 18)}.
420
421
Now the coefficients of \kbd{pr} obey a very simple formula. First, we would
422
like to multiply the coefficient of \kbd{x\pow n} by \kbd{n!} (in the case of
423
the exponential function, this would simplify things considerably!). The PARI
424
function \kbd{serlaplace} does just that. So type \kbd{ps = serlaplace(pr)}.
425
The coefficients now become integers, which can be immediately recognized by
426
inspection. The coefficient of $x^n$ is now equal to
427
$n^{n-1}$. In other words, we have
428
%
429
$$\kbd{pr} = \sum_{n\ge1}\dfrac{n^{n-1}}{n!} X^{n}.$$
430
%
431
Do you know how to prove this? (The proof is difficult.)
432
\smallskip
433
%
434
Of course PARI knows about vectors (rows and columns are distinguished, even
435
though mathematically there is no difference) and matrices. Type for example
436
\kbd{[1,2,3,4]}. This gives the row vector whose coordinates are 1, 2, 3 and
437
4. If you want a column vector, type \kbd{[1,2,3,4]\til}, the tilde meaning
438
of course transpose. You don't see much difference in the output, except for
439
the tilde at the end. However, now type \b{B}: lo and behold, the column
440
vector appears as a proper vertical thingy now. The \b{B} command is used
441
mainly for this purpose. The length of a vector is given by, well
442
\kbd{length} of course. The shorthand ``cardinality'' notation \kbd{\#v} for
443
\kbd{length(v)} is also available, for instance \kbd{v[\#v]} is the last
444
element of \kbd{v}.
445
446
Type \kbd{m = [a,b,c; d,e,f]}. You have just entered a matrix with 2 rows and
447
3 columns. Note that the matrix is entered by \emph{rows} and the rows are
448
separated by semicolons ``\kbd{;}''. The matrix is printed naturally in a
449
rectangle shape. If you want it printed horizontally just as you typed it,
450
type \b{a}, or if you want this type of printing to be the permanent default
451
type \kbd{default(output, 0)}. Type \kbd{default(output, 1)} if you want to
452
come back to the original output mode.
453
454
Now type \kbd{m[1,2]}, \kbd{m[1,]}, \kbd{m[,2]}. Are explanations necessary?
455
(In an expression such as \kbd{m[j,k]}, the \kbd{j} always refers to the
456
row number, and the \kbd{k} to the column number, and the first index is
457
always 1, never 0. This default cannot be changed.)
458
459
Even better, type \kbd{m[1,2] = 5; m}. The semicolon also allows us to put
460
several instructions on the same line; the final result is the output of
461
the last statement on the line. Now type \kbd{m[1,] = [15,-17,8]}. No
462
problem. Finally type \kbd{m[,2] = [j,k]}. You have an error message since you
463
have typed a row vector, while \kbd{m[,2]} is a column vector. If you type
464
instead \kbd{m[,2] = [j,k]\til} it works. \smallskip
465
%
466
\label{se:types}
467
Type now \kbd{h = mathilbert(20)}. You get the so-called ``Hilbert matrix''
468
whose coefficient of row $i$ and column $j$ is equal to $(i+j-1)^{-1}$.
469
Incidentally, the matrix \kbd{h} takes too much room. If you don't want to
470
see it, simply type a semi-colon ``\kbd{;}'' at the end of the line
471
(\kbd{h = mathilbert(20);}). This is an example of a ``precomputed'' matrix,
472
built into PARI. We will see a more general construction later.
473
474
What is interesting about Hilbert matrices is that first their inverses and
475
determinants can be computed explicitly (and the inverse has integer
476
coefficients), and second they are numerically very unstable, which make them
477
a severe test for linear algebra packages in numerical analysis. Of course
478
with PARI, no such problem can occur: since the coefficients are given as
479
rational numbers, the computation will be done exactly, so there cannot be
480
any numerical error. Try it. Type \kbd{d~=~matdet(h)}. The result is a
481
rational number (of course) of numerator equal to 1 and denominator having
482
226 digits. How do I know, by the way? Well, type \kbd{sizedigit(1/d)}. Or
483
\kbd{\#Str(1/d)}. (The length of the character string representing the
484
result.)
485
486
Now type \kbd{hr = 1.* h;} (do not forget the semicolon, we don't want to see
487
the result!), then \kbd{dr = matdet(hr)}. You notice two things. First the
488
computation, is much faster than in the rational case. (If your computer is
489
too fast for you to notice, try again with \kbd{h = mathilbert(40)}, or
490
even some larger value.) The reason for this is that PARI is handling real
491
numbers with 38 digits of accuracy, while in the rational case it is
492
handling integers having up to 226 decimal digits.
493
494
The second, more important, fact is that the result is terribly wrong. If you
495
compare with \kbd{1.$*$d} computed earlier, which is the correct answer, you
496
will see that few decimals agree! (None agree if you replaced 20 by 40 as
497
suggested above.) This catastrophic instability is as already mentioned one
498
of the characteristics of Hilbert matrices. In fact, the situation is
499
worse than that. Type \kbd{norml2(1/h - 1/hr)} (the function \kbd{norml2}
500
gives the square of the $L^2$ norm, i.e.~the sum of the squares of the
501
coefficients). The result is larger than $10^{32}$, showing that some
502
coefficients of \kbd{1/hr} are wrong by as much as $10^{16}$. To obtain the
503
correct result after rounding for the inverse, we have to use a default
504
precision of 57 digits (try it).
505
506
Although vectors and matrices can be entered manually, by typing explicitly
507
their elements, very often the elements satisfy a simple law and one uses a
508
different syntax. For example, assume that you want a vector whose $i$-th
509
coordinate is equal to $i^2$. No problem, type for example
510
\kbd{vector(10,i, i\pow 2)} if you want a vector of length 10. Similarly, if
511
you type
512
\bprog
513
matrix(5,5, i,j, 1 / (i+j-1))
514
@eprog\noindent
515
you will get the Hilbert matrix of order 5, hence the \kbd{mathilbert}
516
function is in fact redundant. The \kbd{i} and \kbd{j} represent dummy
517
variables which are used to number the rows and columns respectively (in
518
the case of a vector only one is present of course). You must not forget,
519
in addition to the dimensions of the vector or matrix, to indicate
520
explicitly the names of these variables. You may omit the variables and
521
the final expression to get zero entries, as in \kbd{matrix(10,20)}.
522
523
\misctitle{Warning} The letter \kbd{I} is reserved for the complex number
524
equal to the square root of $-1$. Hence it is forbidden to use it as a
525
variable. Try typing \kbd{vector(10,I, I\pow 2)}, the error message that you
526
get clearly indicates that \kbd{gp} does not consider \kbd{I} as a variable.
527
There are other reserved variable names: \kbd{Pi}, \kbd{Euler},
528
\kbd{Catalan} and \kbd{oo}. All function names are forbidden as well. On the
529
other hand there is nothing special about \kbd{i}, \kbd{pi}, \kbd{euler} or
530
\kbd{catalan}.
531
532
When creating vectors or matrices, it is often useful to use Boolean
533
operators and the \kbd{if()} statement. Indeed, an \kbd{if} expression has a
534
value, which is of course equal to the evaluated part of the \kbd{if}. So for
535
example you can type
536
\bprog
537
matrix(8,8, i,j, if ((i-j)%2, 1, 0))
538
@eprog\noindent
539
to get a checkerboard matrix of \kbd{1} and \kbd{0}. Note however
540
that a vector or matrix must be \emph{created} first before being used. For
541
example, it is possible to write
542
\bprog
543
v = vector(5);
544
for (i = 1, 5, v[i] = 1/i)
545
@eprog\noindent
546
but this would fail if the vector \kbd{v} had not been created beforehand.
547
Of course, the above example is better written as
548
\bprog
549
v = vector(5, i, 1/i);
550
@eprog
551
552
Another useful way to create vectors and matrices is to extract them from
553
larger ones. For instance, if \kbd{h} is the $20\times 20$ Hilbert matrix as above,
554
\bprog
555
h = mathilbert(20);
556
h[11..20, 11..20]
557
@eprog\noindent is its lower right quadrant.
558
559
\medskip The last PARI types which we have not yet played with are closely
560
linked to number theory. People not interested in number theory can skip
561
ahead.
562
563
The first is the type ``integer--modulo''. Let us see an example. Type
564
\bprog
565
n = 10^15 + 3
566
@eprog
567
We want to know whether this number is prime or not. Of course we could make
568
use of the built-in facilities of PARI, but let us do otherwise. We first
569
trial divide by the built-in table of primes. We slightly cheat here and use
570
a variant of the function \kbd{factor} which does exactly this. So type
571
\kbd{factor(n, 200000)}. The last argument tells \kbd{factor} to trial divide
572
up to the given bound and stop at this point. Set it to 0 to trial divide by
573
the full set of built-in primes, which goes up to $500000$ by default.
574
575
As for all factoring functions, the result is a 2 column matrix: the first
576
column gives the primes and the second their exponents. Here we get a single
577
row, telling us that if primes stopped at $200000$ as we made \kbd{factor}
578
believe, \kbd{n} would be prime. (Or is that a contradiction?) More
579
seriously, \kbd{n} is not divisible by any prime up to $200000$.
580
581
We could now trial divide further, or cheat and call the PARI function
582
\kbd{factor} without the optional second argument, but before we do this let
583
us see how to get an answer ourselves.
584
585
By Fermat's little theorem, if $n$ is prime we must have $a^{n-1}\equiv 1
586
\pmod{n}$ for all $a$ not divisible by $n$. Hence we could try this with $a=2$
587
for example. But $2^{n-1}$ is a number with approximately $3\cdot10^{14}$
588
digits, hence impossible to write down, let alone to compute. But instead type
589
\kbd{a = Mod(2,n)}. This creates the number $2$ considered now as an element
590
of the ring $R = \Z/\kbd{n}\Z$. The elements of $R$, called intmods, can
591
always be represented by numbers smaller than \kbd{n}, hence small. Fermat's
592
theorem can be rewritten
593
%
594
$\kbd{a}^{n-1} = \kbd{Mod(1,n)}$
595
%
596
in the ring $R$, and this can be computed very efficiently. Elements of $R$
597
may be lifted back to $\Z$ with either \kbd{lift} or \kbd{centerlift}. Type
598
\kbd{a\pow (n-1)}. The result is definitely \emph{not} equal to
599
\kbd{Mod(1,n)}, thus \emph{proving} that \kbd{n} is not a prime. If we had
600
obtained \kbd{Mod(1,n)} on the other hand, it would have given us a hint that
601
\kbd{n} is maybe prime, but not a proof.
602
603
To find the factors is another story. In this case, the integer $n$ is small
604
enough to let trial division run to completion. Type \kbd{\#} to turn on the
605
\kbd{gp} timer, then
606
\bprog
607
for (i = 2, ceil(sqrt(n)), if (n%i==0, print(i); break))
608
@eprog\noindent
609
This should take less than 5 seconds. In general, one must use less naive
610
techniques than trial division, or be very patient. Type \kbd{fa = factor(n)}
611
to let the factoring engine find all prime factors. You may stop the timer by
612
typing \kbd{\#} again.
613
614
Note that, as is the case with most ``prime''-producing functions, the
615
``prime'' factors given by \kbd{factor} are only strong pseudoprimes, and not
616
\emph{proven} primes. Use \kbd{isprime( fa[,1] )} to rigorously prove
617
primality of the factors. The latter command applies \kbd{isprime} to all
618
entries in the first column of \kbd{fa}, i.e to all pseudoprimes, and returns
619
the column vector of results: all equal to 1, so our pseudoprimes were
620
true primes. All arithmetic functions can be applied in this way to the entries
621
of a vector or matrix. In fact, it has been checked that the strong
622
pseudoprimes output by \kbd{factor} (Baillie-Pomerance-Selfridge-Wagstaff
623
pseudoprimes, without small divisors) are true primes at least up to
624
$2^{64}$, and no explicit counter-example is known.\smallskip
625
626
The second specifically number-theoretic type is the $p$-adic numbers. I have
627
no room for definitions, so please skip ahead if you have no use for such
628
beasts. A $p$-adic number is entered as a rational or integer valued
629
expression to which is added \kbd{O(p\pow n)}, or simply \kbd{O(p)} if
630
$\kbd{n}=1$, where \kbd{p} is the prime and \kbd{n} the $p$-adic precision.
631
Note that you have to explicitly type in \kbd{3\pow 2} for instance, \kbd{9}
632
will not do. Unless you want to cheat \kbd{gp} into believing that \kbd{9}
633
is prime, but you had better know what you are doing in this case: most
634
computations will yield a wrong result.
635
636
Apart from the usual arithmetic operations, you can apply a number of
637
transcendental functions. For example, type \kbd{n = 569 + O(7\pow 8)}, then
638
\kbd{s~=~sqrt(n)}, you obtain one of the square roots of \kbd{n}; to check
639
this, type \kbd{s\pow 2 - n}). Type now \kbd{s = log(n)}, then \kbd{e =
640
exp(s)}. If you know about $p$-adic logarithms, you will not be surprised
641
that \kbd{e} is not equal to \kbd{n}. Type \kbd{(n/e)\pow 6}: \kbd{e} is in
642
fact equal to \kbd{n} times the $(p-1)$-st root of unity \kbd{teichmuller(n)}.
643
644
Incidentally, if you want to get back the integer 569 from the $p$-adic
645
number \kbd{n}, type \kbd{lift(n)} or \kbd{truncate(n)}.
646
\smallskip
647
648
The third number-theoretic type is the type ``quadratic number''. This type
649
is specially tailored so that we can easily work in a quadratic extension of
650
a base field, usually $\Q$. It is a generalization of the type
651
``complex''. To start, we must specify which quadratic field we want to work
652
in. For this, we use the function \kbd{quadgen} applied to the
653
\emph{discriminant} \kbd{d} (as opposed to the radicand) of the quadratic
654
field. This returns a number equal to
655
$(\kbd{d}+a) / 2$ where $a$ is equal to 0 or 1 according to whether \kbd{d} is
656
even or odd. The function \kbd{quadgen} takes an extra parameter which is how
657
the number will be printed. To avoid confusion, this number should be
658
set to a variable of the same name, i.e. do \kbd{w = quadgen(d, 'w)}.
659
660
So type \kbd{w = quadgen(-163,'w)}, then \kbd{charpoly(w)} which asks for the
661
characteristic polynomial of \kbd{w}. The result shows what \kbd{w} will
662
represent. You may ask for \kbd{1.*w} to see which root of the quadratic has
663
been taken, but this is rarely necessary. We can now play in the field
664
$\Q(\sqrt{-163})$. Type for example \kbd{w\pow 10}, \kbd{norm(3 + 4*w)},
665
\kbd{1 / (4+w)}. More interesting, type \kbd{a = Mod(1,23) * w} then \kbd{b =
666
a\pow 264}. This is a generalization of Fermat's theorem to quadratic fields.
667
If you do not want to see the modulus 23 all the time, type \kbd{lift(b)}.
668
669
Another example: type \kbd{p = x\pow 2 + w*x + 5*w + 7}, then \kbd{norm(p)}. We
670
thus obtain the quartic equation over $\Q$ corresponding to the relative
671
quadratic extension over $\Q(\kbd{w})$ defined by \kbd{p}.
672
673
On the other hand, if you type \kbd{wr = sqrt(w\pow 2)}, do not expect to get
674
back \kbd{w}. Instead, you get the numerical value, the function \kbd{sqrt}
675
being considered as a ``transcendental'' function, even though it is
676
algebraic. Type \kbd{algdep(wr,2)}: this looks for algebraic relations
677
involving the powers of \kbd{w} up to degree 2. This is one way to get
678
\kbd{w} back. Similarly, type \kbd{algdep(sqrt(3*w + 5), 4)}. See the user's
679
manual for the function \kbd{algdep}.\smallskip
680
681
The fourth number-theoretic type is the type ``polynomial--modulo'', i.e.
682
polynomial modulo another polynomial. This type is used to work in general
683
algebraic extensions, for example elements of number fields (if the base
684
field is $\Q$), or elements of finite fields (if the base field is
685
$\Z/p\Z$ for a prime $p$). In a sense it is a generalization of the type
686
quadratic number. The syntax used is the same as for intmods. For example,
687
instead of typing \kbd{w = quadgen(-163,'w)}, you can type
688
\bprog
689
w = Mod(x, quadpoly(-163))
690
@eprog\noindent
691
Then, exactly as in the quadratic case, you can type \kbd{w\pow 10},
692
\kbd{norm(3 + 4*w)}, \kbd{1 / (4+w)}, \kbd{a = Mod(1,23)*w}, \kbd{b = a\pow
693
264}, obtaining of course the same results. (Type \kbd{lift(\dots)} if you
694
don't want to see the polynomial \kbd{x\pow 2 - x + 41} repeated all the
695
time.) Of course, you can work in any degree, not only quadratic. For the
696
latter, the corresponding elementary operations will be slower than
697
with quadratic numbers. Start the timer, then compare
698
\bprog
699
w = quadgen(-163,'w); W = Mod(x, quadpoly(-163));
700
a = 2 + w; A = 2 + W;
701
b = 3 + w; B = 3 + W;
702
for (i=1,10^5, a+b)
703
for (i=1,10^5, A+B)
704
for (i=1,10^5, a*b)
705
for (i=1,10^5, A*B)
706
for (i=1,10^5, a/b)
707
for (i=1,10^5, A/B)
708
@eprog\noindent
709
Don't retype everything, use the arrow keys!
710
711
There is however a slight difference in behavior. Keeping our polmod \kbd{w},
712
type \kbd{1.*w}. As you can see, the result is not the same. Type
713
\kbd{sqrt(w)}. Here, we obtain a vector with 2 components, the two components
714
being the principal branch of the square root of all the possible embeddings
715
of \kbd{w} in $\C$. More generally, if
716
\kbd{w} was of degree $n$, we would get an $n$-component vector, and similarly
717
for all transcendental functions.
718
719
We have at our disposal the usual arithmetic functions, plus a few others.
720
Type \kbd{a = Mod(x, x\pow 3 - x - 1)} defining a cubic extension. We can for
721
example ask for \kbd{b = a\pow 5}. Now assume we want to express \kbd{a}
722
as a polynomial in \kbd{b}. This is possible since \kbd{b} is also a
723
generator of the same field. No problem, type \kbd{modreverse(b)}. This gives
724
a new defining polynomial for the same field, i.e.~the characteristic
725
polynomial of \kbd{b}, and expresses \kbd{a} in terms of this new polmod,
726
i.e.~in terms of \kbd{a}. We will see this in more detail in the number
727
field section.
728
729
An important special case of the above construction allows to work in finite
730
fields, by choosing an irreducible polynomial $T$ of degree $f$ over $\F_p$
731
and considering $\F_p[t]/(T)$. As in
732
\bprog
733
T = ffinit(5, 6, 't); \\ @com degree 6, irreducible over $\F_5$
734
g = Mod(t, T)
735
@eprog\noindent Try a few elementary operations involving $g$, such as
736
$g^{100}$. This special case of \typ{POLMOD}s is in fact so important that we
737
now introduce a final dedicated number theoretical type \typ{FFELT}, for
738
``finite field element'', to simplify work with finite fields: \kbd{g =
739
ffgen(5\pow6, 't)} computes a suitable polynomial $T$ as above and returns
740
the generator $t \mod T(t)$. This has major advantages over the generic
741
\typ{POLMOD} solution: elements are printed in a simplified way (in lifted
742
form), and functions can assume that $T$ is indeed irreducible. A few dedicated
743
functions \kbd{ffprimroot} (analog of \kbd{znprimroot}), \kbd{fforder}
744
(analog of \kbd{znorder}), \kbd{fflog} (analog of \kbd{znlog}) are available.
745
Rational expressions in the variable $t$ can be mapped to such a finite
746
field by substituting $t$ by $g$, for instance
747
\bprog
748
? g = ffgen(5^6, 't);
749
? g.mod \\ @com irreducible over $\F_5$, defines $\F_{5^6}$
750
%2 = t^6 + t^5 + t^4 + t^3 + t^2 + t + 1
751
? Q = x^2 + t*x + 1
752
? factor(subst(Q,t,g))
753
%3 =
754
[ x + (t^5 + 3*t^4 + t^3 + 4*t + 1) 1]
755
756
[x + (4*t^5 + 2*t^4 + 4*t^3 + 2*t + 4) 1]
757
@eprog\noindent factors the polynomial $Q \in \F_{5^6}[x]$, where
758
$\F_{5^6} = \F_5[t]/(\kbd{g.mod})$.
759
760
\section{Elementary Arithmetic Functions}
761
762
Since PARI is aimed at number theorists, it is not surprising that there
763
exists a large number of arithmetic functions; see the list by typing
764
\kbd{?5}. We have already seen several, such as \kbd{factor}. Note that
765
\kbd{factor} handles not only integers, but also univariate polynomials.
766
Type for example \kbd{factor(x\pow 200 - 1)}. You can also ask to factor a
767
polynomial modulo a finite field or a number field !
768
769
Evidently, you have functions for computing GCD's (\kbd{gcd}), extended GCD's
770
(\kbd{bezout}), solving the Chinese remainder theorem (\kbd{chinese}) and so
771
on.
772
773
In addition to the factoring facilities, you have a few functions related to
774
primality testing such as \kbd{isprime}, \kbd{ispseudoprime},
775
\kbd{precprime}, and \kbd{nextprime}. As previously mentioned, only strong
776
pseudoprimes are produced by the latter two (they pass the
777
\kbd{ispseudoprime} test); the more sophisticated primality tests in
778
\kbd{isprime}, being so much slower, are not applied by default.
779
780
We also have the usual multiplicative arithmetic functions: the M\"obius $\mu$
781
function (\kbd{moebius}), the Euler $\phi$ function (\kbd{eulerphi}), the
782
$\omega$ and $\Omega$ functions (\kbd{omega} and \kbd{bigomega}), the
783
$\sigma_k$ functions (\kbd{sigma}), which compute sums of $k$-th powers of the
784
positive divisors of a given integer, etc\dots
785
786
You can compute continued fractions. For example, type \kbd{\b{p} 1000}, then
787
\kbd{contfrac(exp(1))}: you obtain the continued fraction of the base of
788
natural logarithms, which as you can see obeys a very simple pattern. Can
789
you prove it?
790
791
In many cases, one wants to perform some task only when an arithmetic
792
condition is satisfied. \kbd{gp} gives you the following functions: \kbd{isprime}
793
as mentioned above, \kbd{issquare}, \kbd{isfundamental} to test whether an
794
integer is a fundamental discriminant (i.e.~$1$ or the discriminant of a
795
quadratic field), and the \kbd{forprime}, \kbd{fordiv} and \kbd{sumdiv}
796
loops. Assume for example that we want to compute the product of all the
797
divisors of a positive integer \kbd{n}. The easiest way is to write
798
\bprog
799
p = 1; fordiv(n,d, p *= d); p
800
@eprog\noindent
801
(There is a simple formula for this product in terms of $n$ and the number of
802
its divisors: find and prove it!) The notation \kbd{p *= d} is just a
803
shorthand for \kbd{p = p * d}.
804
805
If we want to know the list of primes $p$ less than 1000 such that 2 is a
806
primitive root modulo $p$, one way would be to write:
807
\bprog
808
forprime(p=3,1000, if (znprimroot(p) == 2, print(p)))
809
@eprog\noindent
810
%
811
Note that this assumes that \kbd{znprimroot} returns the smallest primitive
812
root, and this is indeed the case. Had we not known about this, we could
813
have written
814
\bprog
815
forprime(p=3,1000, if (znorder(Mod(2,p)) == p-1, print(p)))
816
@eprog\noindent
817
%
818
(which is actually faster since we only compute the order of $2$ in $\Z/p\Z$,
819
instead of looking for a generator by trying successive elements whose orders
820
have to be computed as well.) Once we know a primitive root $g$, we can write
821
any nonzero element of $\Z/p\Z$ as $g^x$ for some unique $x$ in $\Z/(p-1)\Z$.
822
Computing such a discrete logarithm is a hard problem in general, performed
823
by the function \kbd{znlog}.
824
825
Arithmetic functions related to quadratic fields, binary quadratic forms and
826
general number fields will be seen in the next sections.
827
828
\section{Performing Linear Algebra}
829
The standard linear algebra routines are available: \kbd{matdet},
830
\kbd{mateigen} (eigenvectors), \kbd{matker}, \kbd{matimage}, \kbd{matrank},
831
\kbd{matsolve} (to solve a linear system), \kbd{charpoly} (characteristic
832
polynomial), to name a few. Bilinear algebra over $\R$ is also there:
833
\kbd{qfgaussred} (Gauss reduction), \kbd{qfsign} (signature). You may also
834
type \kbd{?7}. Can you guess what each of these do?
835
836
Let us see how this works. First, a vector space (or module) is given by a
837
generating set of vectors (often a basis) which are represented as
838
\emph{column} vectors. This set of vectors is in turn represented by the
839
columns of a matrix. Quadratic forms are represented by their Gram matrix.
840
The base field (or ring) can be any ring type PARI supports. However, certain
841
operations are specifically written for a real or complex base field, while
842
others are written for $\Z$ as the base ring.
843
844
We had some fun with Hilbert matrices and numerical instability a while back,
845
but most of the linear algebra routines are generic. If as before \kbd{h =
846
mathilbert(20)}, we may compute
847
\bprog
848
matdet(h * Mod(1,101))
849
matdet(h * (1 + O(101^100)))
850
@eprog\noindent
851
in $\Z/101\Z$ and the $p$-adic ring $\Z_{101}$ (to $100$ words of accuracy)
852
respectively. Let \kbd{H = 1/h} the inverse of \kbd{h}:
853
\bprog
854
H = 1/h; \\ @com integral
855
L = primes([10^5, 10^5 + 1000]); \\ @com pick a few primes
856
v = vector(#L, i, matdet(H * Mod(1,L[i])));
857
centerlift( chinese(v) )
858
@eprog\noindent
859
returns the determinant of \kbd{H}. (Assuming it is an integer
860
less than half the product of elements of \kbd{L} in absolute value, which
861
it is.)
862
In fact, we computed an homomorphic image of the determinant in a few small
863
finite fields, which admits a single integer representative given the size
864
constraints. We could also have made a single determinant computation modulo
865
a big prime (or pseudoprime) number, e.g \kbd{nextprime(2 * B)} if we know
866
that the determinant is less than \kbd{B} in absolute value.
867
(Why is that $2$ necessary?)
868
869
By the way, this is how you insert comments in a script: everything
870
following a double backslash, up to the first newline character, is ignored.
871
If you want comments which span many lines, you can brace them between
872
\kbd{/* ... */} pairs. Everything in between will be ignored as well. For
873
instance as a header for the script above you could insert the
874
following:
875
\bprog
876
/* Homomorphic imaging scheme to compute the determinant of a classical
877
* integral matrix.
878
* TODO: Look up the explicit formula
879
*/
880
@eprog\noindent
881
(I hope you did not waste your time copying this nonsense, did you?)
882
\medskip
883
884
In addition, linear algebra over $\Z$, i.e.~work on lattices, can also be
885
performed. Let us now consider the lattice $\Lambda$ generated by the columns
886
of \kbd{H} in $\Z^{20}\subset\R^{20}$. Since the determinant is nonzero, we
887
have in fact a basis. What is the structure of the finite abelian group
888
$\Z^{20}/\Lambda$? Type \kbd{matsnf(H)}. Wow, 20 cyclic factors.
889
890
891
There is a triangular basis for $\Lambda$ (triangular when expressed in
892
the canonical basis), perhaps it looks better than our initial one? Type
893
\kbd{mathnf(H)}. Hum, what if I also want the unimodular transformation
894
matrix? Simple : \kbd{z = mathnf(H, 1);} \kbd{z[1]} is the triangular HNF
895
basis, and \kbd{z[2]} is the base change matrix from the canonical basis to
896
the new one, with determinant $\pm 1$. Try \kbd{matdet(z[2])},
897
then \kbd{H * z[2] == z[1]}. Fine, it works. And \kbd{z[1]} indeed looks
898
better than \kbd{H}.
899
900
Can we do better? Perhaps, but then we'd better drop the requirement that
901
the basis be triangular, since the latter is essentially canonical. Type
902
\bprog
903
M = H * qflll(H)
904
@eprog
905
Its columns give an LLL-reduced basis for $\Lambda$ (\kbd{qflll(H)} itself
906
gives the base change matrix). The LLL algorithm outputs a nice basis for a
907
lattice given by an arbitrary basis, where nice means the basis vectors are
908
almost orthogonal and short, with precise guarantees on their relations to
909
the shortest vectors. Not really spectacular on this example, though.
910
911
Let us try something else, there should be an integer relation between
912
$\log 3$, $\log 5$ and $\log 15$. How to detect it?
913
\bprog
914
u = [log(15), log(5), log(3)];
915
m = matid(3); m[3,] = round(u * 10^25);
916
v = qflll(m)[,1] \\@com first vector of the LLL-reduced basis
917
u * v
918
@eprog\noindent
919
Pretty close. In fact, \kbd{lindep} automates this kind of search for integer
920
relations; try \kbd{lindep(u)}.
921
922
Let us come back to $\Lambda$ above, and our LLL basis in \kbd{M}. Type
923
\bprog
924
G = M~*M \\@com Gram matrix
925
m = qfminim(G, norml2(M[,1]), 100, 2);
926
@eprog\noindent
927
This enumerates the vectors in $\Lambda$ which are shorter than the first LLL
928
basis vector, at most 100 of them. The final argument $2$ instructs the
929
function to use a safe (slower) algorithm, since the matrix entries are
930
rather large; trying to remove it should produce an error, in this case.
931
There are $\kbd{m[1]} = 6$ such vectors, and \kbd{m[3]} gives half of them
932
(\kbd{-m[3]} would complete the lot): they are the first 3 basis vectors! So
933
these are optimally short, at least with respect to the Euclidean length. Let
934
us try
935
\bprog
936
m = qfminim(G, norml2(M[,4]), 100, 2);
937
@eprog\noindent
938
(The flag $2$ instructs \kbd{qfminim} to use a different enumeration
939
strategy, which is much faster when we expect more short vectors than we want
940
to store. Without the flag, this example requires several hours. This is an
941
exponential time algorithm, after all!) This time, we find a slew of short
942
vectors; \kbd{matrank(m[3])} says the 100 we have are all included in a
943
2-dimensional space. Let us try
944
\bprog
945
m = qfminim(G, norml2(M[,4]) - 1, 100000, 2);
946
@eprog\noindent
947
This time we find 50886 vectors of the requested length, spanning a
948
$4$-dimensional space, which is actually generated by \kbd{M[,1]},
949
\kbd{M[,2]} \kbd{M[,3]} and \kbd{M[,5]}.
950
951
\section{Using Transcendental Functions}
952
953
All the elementary transcendental functions and several higher transcendental
954
functions are provided: $\Gamma$ function, incomplete $\Gamma$ function, error
955
function, exponential integral, Bessel functions ($H^1$, $H^2$, $I$, $J$,
956
$K$, $N$), confluent hypergeometric functions, Riemann $\zeta$ function,
957
polylogarithms, Weber functions, theta functions. More will be written if the
958
need arises.
959
960
In this type of functions, the default precision plays an essential role.
961
In almost all cases transcendental functions work in the following way.
962
If the argument is exact, the result is computed using the current
963
default precision. If the argument is not exact, the precision of the
964
argument is used for the computation. A note of warning however: even in this
965
case the \emph{printed} value is the current real format, usually the
966
same as the default precision. In the present chapter we assume that your
967
machine works with 64-bit long integers. If it is not the case, we leave it
968
to you as a good exercise to make the necessary modifications.
969
970
Let's assume that we have 38 decimals of default precision (this is what we
971
get automatically at the start of a \kbd{gp} session on 64-bit machines). Type
972
\kbd{e = exp(1)}. We get the number $e=2.718\dots$ to 38 decimals. Let us check
973
how many correct decimals we really have. Change the precision to a
974
substantially higher value, for example by typing \kbd{\b{p} 100}. Then type
975
\kbd{e}, then \kbd{exp(1)} once again. This last value is the correct value
976
of the mathematical constant $e$ to 100 decimals, while the variable \kbd{e}
977
shows the value that was computed to 38 decimals. Clearly they coincide to
978
exactly 38 significant digits.
979
980
So 38 digits are printed, but how many significant digits are actually
981
contained in the variable \kbd{e}? Type \kbd{\#e} which indicates we have
982
exactly $2$ mantissa words. Since $2\ln(2^{64}) / \ln(10)\approx38.5$ we see
983
that we have 38 or 39 significant digits (on 64-bit machines).
984
985
\smallskip
986
Come back to 38 decimals (\kbd{\b{p} 38}). If we type \kbd{exp(1.)}
987
you can check that we also obtain 38 decimals. However, type
988
\kbd{f = exp(1 + 1E-40)}. Although the default precision is still 38,
989
you can check using the method above that we have in fact 96 significant
990
digits! The reason is that \kbd{1 + 1E-40} is computed according to the PARI
991
philosophy, i.e.~to the best possible precision. Since \kbd{1E-40} has 39
992
significant digits and 1 has ``infinite'' precision, the number \kbd{1 +
993
1E-40} will have at least $79=39+40$ significant digits, hence \kbd{f} also.
994
995
Now type \kbd{cos(1E-19)}. The result is printed as $1.0000\dots$, but
996
is of course not exactly equal to 1. Using \kbd{\#\%}, we see that the
997
result has 4 mantissa words, giving us the possibility of having 77
998
correct significant digits. PARI gives you as much as it can, and since 3
999
mantissa words would have given you only 57 digits, it uses 4. But why does
1000
it give so precise a result? Well, it is the same reason as before. When $x$
1001
is close to 1, $\cos(x)$ is close to $1-x^2/2$, hence the precision is going
1002
to be approximately the same as when computing this quantity, here
1003
$1-0.5*10^{-38}$ where $0.5*10^{-38}$ is considered with 38 significant digit
1004
accuracy. Hence the result will have approximately $38+38=76$ significant
1005
digits.
1006
1007
This philosophy cannot go too far. For example, when you type \kbd{cos(0)},
1008
\kbd{gp} should give you exactly 1. Since it is reasonable for a program to
1009
assume that a transcendental function never gives you an exact result,
1010
\kbd{gp} gives you $1.000\dots$ with as many mantissa word as the current
1011
precision.
1012
\medskip
1013
Let's see some more transcendental functions at work. Type
1014
\kbd{gamma(10)}. No problem (type \kbd{9!} to check). Type \kbd{gamma(100)}.
1015
The number is now written in exponential format because the default accuracy
1016
is too small to give the correct result. To get all digits, the most natural
1017
solution is to increase the precision; since \kbd{gamma(100)} has 156 decimal
1018
digits, type \kbd{\b{p} 170} to be on the safe side, then \kbd{gamma(100)}
1019
once again. Another one is to compute \kbd{99!} directly.
1020
1021
Try \kbd{gamma(1/2 + 10*I)}. No problem, we have the complex $\Gamma$ function.
1022
Now type
1023
\bprog
1024
t = 1000;
1025
z = gamma(1 + I*t) * t^(-1/2) * exp(Pi/2*t) / sqrt(2*Pi)
1026
norm(z)
1027
@eprog\noindent The latter is very close to 1, in accordance with the complex
1028
Stirling formula.
1029
\smallskip
1030
1031
Let's play now with the Riemann zeta function. First turn on the timer (type
1032
\kbd{\#}). Type \kbd{zeta(2)}, then \kbd{Pi\pow 2/6}. This seems correct. Type
1033
\kbd{zeta(3)}. All this takes essentially no time at all. However, type
1034
\kbd{zeta(3.1)}. You will notice that the time is substantially larger; if
1035
your machine is too fast to see the difference, increase the precision to
1036
\kbd{\b{p}1000}. This is because PARI uses special formulas to compute
1037
\kbd{zeta(n)} when \kbd{n} is an integer.
1038
1039
Type \kbd{zeta(1 + I)}. This also works. Now for fun, let us compute in a
1040
naive way the first complex zero of \kbd{zeta}. We know that it is
1041
of the form $1/2 + i*t$ with $t$ between 14 and 15. Thus, we can use the
1042
following series of instructions. But instead of typing them directly, write
1043
them into a file, say \kbd{zeta.gp}, then type \kbd{\b{r} zeta.gp} under
1044
\kbd{gp} to read it in:
1045
\bprog
1046
{
1047
t1 = 1/2 + 14*I;
1048
t2 = 1/2 + 15*I; eps = 1E-50;
1049
z1 = zeta(t1);
1050
until (norm(z2) < eps,
1051
z2 = zeta(t2);
1052
if (norm(z2) < norm(z1),
1053
t3 = t1; t1 = t2; t2 = t3; z1 = z2
1054
);
1055
t2 = (t1+t2) / 2.;
1056
print(t1 ": " z1)
1057
)
1058
}
1059
@eprog\noindent
1060
Don't forget the braces: they tell \kbd{gp} that a sequence of instructions
1061
is going to span many lines. We thus obtain the first zero to 25 significant
1062
digits.
1063
1064
By the way, you don't need to type in the suffix~\kbd{.gp} in the \b{r}
1065
command: it is supplied by \kbd{gp} if you forget it. The suffix is not
1066
mandatory either, but it is convenient to have all GP scripts labeled in the
1067
same distinctive way. Also, some text editors, e.g. Emacs or Vim, will
1068
recognize GP scripts as such by their suffix and load special colourful
1069
modes. \medskip
1070
%
1071
As mentioned at the beginning of this tutorial, some transcendental functions
1072
can also be applied to $p$-adic numbers. This is as good a time as any to
1073
familiarize yourself with them. Type
1074
\bprog
1075
a = exp(7 + O(7^10))
1076
log(a)
1077
@eprog\noindent All seems in order.
1078
\bprog
1079
b = log(5 + O(7^10))
1080
exp(b)
1081
@eprog\noindent Is something wrong? We don't recover the number we started
1082
with? This is normal: type
1083
\bprog
1084
exp(b) * teichmuller(5 + O(7^10))
1085
@eprog\noindent
1086
and we indeed recover our initial number. The Teichm\"uller
1087
character \kbd{teichmuller(x)} on $\Z_p^*$ is the unique \hbox{$(p-1)$-st}
1088
root of unity which is congruent to \kbd{x} modulo $p$, assuming that \kbd{x}
1089
is a $p$-adic unit.\smallskip
1090
%
1091
Let us come back to real numbers for the moment. Type \kbd{agm(1,sqrt(2))}.
1092
This gives the arithmetic-geometric mean of 1 and $\sqrt2$, and is the basic
1093
method for computing complete elliptic integrals. In fact, type
1094
1095
\kbd{Pi/2 / intnum(t=0,Pi/2, 1 / sqrt(1 + sin(t)\pow 2))},
1096
1097
\noindent and the result is the same. The elementary transformation
1098
\kbd{x = sin(t)} gives the mathematical equality
1099
$$\int_0^1 \dfrac{dx}{\sqrt{1-x^4}} = \dfrac{\pi}{2\text{AGM}(1,\sqrt2)}
1100
\enspace,$$
1101
which was one of Gauss's remarkable discoveries in his youth.
1102
1103
Now type \kbd{2 * agm(1,I) / (1+I)}. As you see, the complex AGM also works,
1104
although one must be careful with its definition. The result found is
1105
almost identical to the previous one. Do you see why?
1106
1107
Finally, type \kbd{agm(1, 1 + 7 + O(7\pow 10))}. So we also have $p$-adic
1108
AGM. Note however that since the square root of a $p$-adic number is not
1109
in general an element of the same $p$-adic field,
1110
only certain $p$-adic AGMs can be computed. In addition,
1111
when $p=2$, the congruence restriction is that \kbd{agm(a,b)} can be computed
1112
only when \kbd{a/b} is congruent to 1 modulo $16$, and not 8 as could be
1113
expected.\smallskip
1114
%
1115
Now type \kbd{?8}. This gives you the list of all transcendental functions.
1116
Instead of continuing with more examples, we suggest that you experiment
1117
yourself with this list. Try integer, real, complex and $p$-adic arguments.
1118
You will notice that some have not been implemented (or do not have a
1119
reasonable definition).
1120
1121
\section{Using Numerical Tools}
1122
1123
Although not written to be a numerical analysis package, PARI can
1124
nonetheless perform some numerical computations. Since linear algebra and
1125
polynomial computations are treated somewhere else, this section focuses on
1126
solving equations and various methods of summation.
1127
1128
You of course know the formula $\pi = 4(1-\dfrac13+\dfrac15-\dfrac17+\cdots)$
1129
which is deduced from the power series expansion of \kbd{atan(x)}. You also
1130
know that $\pi$ cannot be computed from this formula, since the convergence
1131
is so slow. Right? Wrong! Type
1132
\bprog
1133
\p 100
1134
4 * sumalt(k=0, (-1)^k/(2*k + 1))
1135
@eprog\noindent In a split second, we get $\pi$ to 100 significant digits
1136
(type \kbd{Pi} to check).
1137
1138
Similarly, try
1139
\bprog
1140
sumpos(k=1, k^-2)
1141
@eprog\noindent Although once again the convergence is slow, the summation is
1142
rather fast; compare with the exact result \kbd{Pi\pow 2/6}. This is less
1143
impressive because a bit slower than for alternating sums, but still useful.
1144
1145
Even better, \kbd{sumalt} can be used to sum divergent series! Type
1146
\bprog
1147
zet(s) = sumalt(k=1, (-1)^(k-1) / k^s) / (1 - 2^(1-s))
1148
@eprog\noindent
1149
Then for positive values of \kbd{s} different from 1, \kbd{zet(s)} is equal
1150
to \kbd{zeta(s)} and the series converges, albeit slowly; \kbd{sumalt}
1151
doesn't care however. For negative \kbd{s}, the series diverges, but
1152
\kbd{zet(s)} still gives the correct result! (Namely, the value of a suitable
1153
analytic continuation.) Try \kbd{zet(-1)}, \kbd{zet(-2)}, \kbd{zet(-1.5)},
1154
and compare with the corresponding values of \kbd{zeta}. You should not push
1155
the game too far: \kbd{zet(-100)}, for example, gives a completely wrong
1156
answer.
1157
1158
Try \kbd{zet(I)}, and compare with \kbd{zeta(I)}. Even (some) complex values
1159
work, although the sum is not alternating any more! Similarly, try
1160
\bprog
1161
sumalt(n=1, (-1)^n / (n+I))
1162
@eprog
1163
\medskip
1164
More traditional functions are the numerical integration functions. Try
1165
\kbd{intnum(t=1,2, 1/t)} and presto! you get 100 decimals of $\log(2)$. Look
1166
at Chapter 3 to see the available integration functions.
1167
1168
With PARI, however, you can go further since complex types are allowed.
1169
For example, assume that we want to know the location of the zeros of the
1170
function $h(z)=e^z-z$. We use Cauchy's theorem, which tells us that the
1171
number of zeros in a disk of radius $r$ centered around the origin is
1172
equal to
1173
$$\dfrac{1}{2i\pi}\int_{C_r}\dfrac{h'(z)}{h(z)}\,dz\enspace,$$
1174
where $C_r$ is the circle of radius $r$ centered at the origin.
1175
The function we want to integrate is
1176
\bprog
1177
fun(z) = my(u = exp(z)); (u-1) / (u-z)
1178
@eprog\noindent
1179
(Here \kbd{u} is a local variable to the function \kbd{f}: whenever
1180
a function is called, \kbd{gp} fills its argument list with the actual arguments
1181
given, and initializes the other declared parameters and local variables to
1182
0. It will then restore their former values upon exit. If we had not declared
1183
\kbd{u} in the function prototype, it would be considered as a global
1184
variable, whose value would be permanently changed. It is not mandatory to
1185
declare in this way all parameters, but beware of side effects!)
1186
1187
Type now:
1188
\bprog
1189
zero(r) = r/(2*Pi) * intnum(t=0, 2*Pi, real( fun(r*exp(I*t)) * exp(I*t) ))
1190
@eprog
1191
The function \kbd{zero(r)} will count the number of zeros of \kbd{fun}
1192
whose modulus is less than \kbd{r}: we simply made the change of variable
1193
$z = r*\exp(i*t)$, and took the real part to avoid integrating the
1194
imaginary part. Actually, there is a built-in function \kbd{intcirc}
1195
to integrate over a circle, yielding the much simpler:
1196
\bprog
1197
zero2(r) = intcirc(z=0, r, fun(z))
1198
@eprog
1199
(This is a little faster than the previous implementation, and no less
1200
accurate.)
1201
1202
We may type \kbd{\b{p} 9} since we know that the result is a small integer
1203
(but the computations should be instantaneous even at \b{p} 100 or so),
1204
then \kbd{zero(1)}, \kbd{zero(1.5)}. The result tells us that there are
1205
no zeros inside the unit disk, but that there are two (necessarily
1206
complex conjugate) in the annulus $1<|z|<1.5$. For the sake of
1207
completeness, let us compute them. Let $z = x+iy$ be such a zero, with
1208
$x$ and $y$ real. Then the equation $e^z-z=0$ implies, after elementary
1209
transformations, that $e^{2x}=x^2+y^2$ and that $e^x\cos(y)=x$. Hence
1210
$y=\pm\sqrt{e^{2x}-x^2}$ and hence $e^x\cos(\sqrt{e^{2x}-x^2})=x$.
1211
Therefore, type
1212
\bprog
1213
fun(x) = my(u = exp(x)); u * cos(sqrt(u^2 - x^2)) - x
1214
@eprog\noindent
1215
Then \kbd{fun(0)} is positive while \kbd{fun(1)} is negative. Come
1216
back to precision 38 and type
1217
\bprog
1218
x0 = solve(x=0,1, fun(x))
1219
z = x0 + I*sqrt(exp(2*x0) - x0^2)
1220
@eprog\noindent
1221
which is the required zero. As a check, type \kbd{exp(z) - z}.
1222
1223
Of course you can integrate over contours which are more complicated than
1224
circles, but you must perform yourself the variable changes, as we have done
1225
above to reduce the integral to a number of integrals on line segments.
1226
\smallskip
1227
%
1228
The example above also shows the use of the \kbd{solve} function. To use
1229
\kbd{solve} on functions of a complex variable, it is necessary to reduce the
1230
problem to a real one. For example, to find the first complex zero of the
1231
Riemann zeta function as above, we could try typing
1232
1233
\kbd{solve(t=14,15, real( zeta(1/2 + I*t) ))},
1234
1235
\noindent but this does not work because the real part is positive for
1236
$\kbd{t}=14$ and $15$. As it happens, the imaginary part works. Type
1237
1238
\kbd{solve(t=14,15, imag( zeta(1/2 + I*t) ))},
1239
1240
\noindent and this now works. We could also narrow the search interval and
1241
type for instance
1242
1243
\kbd{solve(t=14,14.2, real( zeta(1/2 + I*t) ))}
1244
1245
\noindent which would also work.
1246
1247
\section{Polynomials}
1248
1249
First a word of warning: it is essential to understand the difference between
1250
exact and inexact objects. Try
1251
\bprog
1252
gcd(x - Pi, x^2 - 6*zeta(2))
1253
@eprog\noindent
1254
We return a trivial GCD because the notion of GCD for inexact polynomials
1255
doesn't make much sense. A better quantitative approach is to use
1256
\bprog
1257
polresultant(x - Pi, x^2 - 6*zeta(2))
1258
@eprog\noindent
1259
A result close to zero shows that the GCD is nontrivial for small
1260
deformations of the inputs. Without telling us what it is, of course. This
1261
being said, we will mostly use polynomials (and power series) with exact
1262
coefficients in our examples.\smallskip
1263
1264
The simplest way to input a polynomial, is to simply write it down,
1265
or use an explicit formula for the coefficients and the function \kbd{sum}:
1266
\bprog
1267
T = 1 + x^2 + 27*x^10;
1268
T = sum(i = 1, 100, (i+1) * x^i);
1269
@eprog\noindent but it is in much more efficient to create a vector of
1270
coefficients then convert it to a polynomial using \kbd{Pol} or \kbd{Polrev}
1271
(\kbd{Pol([1,2])} is $x+2$, \kbd{Polrev([1,2]) is $2x + 1$}) :
1272
\bprog
1273
T = Polrev( vector(100, i, i) );
1274
1275
for (i=1, 10^4, Polrev( vector(100, i, i) ) ) \\@com time: 60ms
1276
for (i=1, 10^4, sum(i = 1, 100, (i+1) * x^i) ) \\@com time: 1,74ms
1277
@eprog\noindent The reason for the discrepancy is that the explicit summation
1278
(of densely encoded polynomials) is quadratic in the degree, whereas creating
1279
a vector of coefficients then converting it to a polynomial type is linear.
1280
1281
We also have a few built-in classical polynomial families. Consider the
1282
$15$-th cyclotomic polynomial,
1283
\bprog
1284
pol = polcyclo(15)
1285
@eprog\noindent
1286
which is of degree $\varphi(15)=8$. Now, type
1287
\bprog
1288
r = polroots(pol)
1289
@eprog\noindent We obtain the 8 complex roots of \kbd{pol}, given to 38
1290
significant digits. To see them better, type \b{B}: they are given as pairs
1291
of complex conjugate roots, in some order. In fact, the
1292
function \kbd{polroots} returns the real roots first, in increasing order,
1293
then the other roots by increasing absolute value of their imaginary parts
1294
(so that pairs of complex conjugate roots appear together).
1295
1296
The roots of \kbd{pol} are by definition the primitive $15$-th roots of unity.
1297
To check this, simply type \kbd{rc = r\pow 15}. Why, we get an error message!
1298
Fair enough, vectors cannot be multiplied, even less raised to a power.
1299
However, type
1300
\bprog
1301
rc = r^15.0
1302
@eprog\noindent without forgetting the `\kbd{.}' at the end. Now it works,
1303
because powering to a nonintegral exponent is a transcendental function and
1304
hence is applied termwise. Note that the fact that $15.0$ is a real number
1305
which is representable exactly as an integer has nothing to do with the
1306
problem.
1307
1308
We see that the components of the result are very close to 1. It is however
1309
tedious to look at all these real and imaginary parts. It would be impossible
1310
if we had many more. Let's do it automatically. Type
1311
\bprog
1312
rr = round(rc)
1313
exponent(rc - rr)
1314
@eprog\noindent We see that \kbd{rr} is indeed all 1's, and that the
1315
sup-norm of \kbd{rc - rr} is around $2^{-125}$, reasonable enough when we
1316
work with 128 bits of accuracy! In fact, \kbd{round} itself already provides
1317
a built-in rough approximation of the error:
1318
\bprog
1319
rr = round(rc, &e)
1320
@eprog\noindent Again, \kbd{e} contains the number of error bits when rounding
1321
\kbd{rc} to \kbd{rr}; in other words the sup norm of $\kbd{rc} - \kbd{rr}$
1322
is bounded by $2^{-\kbd{e}}$.
1323
%
1324
\smallskip
1325
Now type
1326
\bprog
1327
pol = x^5 + x^4 + 2*x^3 - 2*x^2 - 4*x - 3
1328
factor(pol)
1329
factor( poldisc(pol) )
1330
fun(p) = factor(pol, O(p^10));
1331
@eprog\noindent The polynomial \kbd{pol} factors over $\Q$ (or $\Z$) as a
1332
product of two factors, and the primes dividing its discriminant are
1333
$11$, $23$ and $37$. We also created a function \kbd{fun(p)} which factors
1334
\kbd{pol} over $\Q_p$ to $p$-adic precision 10. Type
1335
\bprog
1336
fun(5)
1337
fun(11)
1338
fun(23)
1339
fun(37)
1340
@eprog\noindent to see different splittings. You can use \kbd{lift} to
1341
convert $p$-adic numbers to neighbouring rational numbers.
1342
1343
Similarly, type
1344
\bprog
1345
lf(p) = lift( factor(pol, p) );
1346
lf(2)
1347
lf(11)
1348
lf(23)
1349
lf(37)
1350
@eprog\noindent which show the different factorizations, this time over
1351
$\F_p$. In fact, even better: type successively
1352
\bprog
1353
T = ffgen(3^3, 't) \\@com we want \kbd{t} to be a free variable
1354
factor(pol, t)
1355
@eprog\noindent
1356
The element $T$ is printed as \kbd{t} but is actually defined modulo the
1357
irreducible polynomial \kbd{t\pow 3 + 2t + 2} over $\F_{3}$ (see
1358
\kbd{t.mod}): it defines the finite field $\F_{27}$. Note that we introduced
1359
a new variable $t$ to express elements in this nonprime field.
1360
More generally, the generic \kbd{factor} function allows a second argument
1361
which describes the domain over which we want to factor, here $\F_{27}$
1362
(and, above, $\Q_p$ to $10$ digits of accuracy and $\F_p$).
1363
Typing \kbd{factor(pol)} directly would factor it over $\Q$, not what we
1364
wanted.
1365
1366
Similarly, type
1367
\bprog
1368
pol2 = x^4 - 4*x^2 + 16
1369
fn = lift( factor(pol2, t^2 + 1) )
1370
@eprog\noindent and we get the factorization of the polynomial \kbd{pol2}
1371
over the number field $\Q[t]/(t^2+1)$, i.e.~over $\Q(i)$. Without the
1372
\kbd{lift}, the result would involve number field elements as \typ{POLMOD}s
1373
of the form \kbd{Mod(1+t, t\pow2+1)}, which are more explicit but less
1374
readable.
1375
\smallskip
1376
1377
To summarize, in addition to being able to factor integers, you can factor
1378
polynomials over $\C$ using \kbd{polroots}, over $\R$ using
1379
\kbd{factor(,1.0)}, over finite fields using
1380
\kbd{factor(, p)}, over $\Q_p$ using \kbd{factor(, O(p\pow $n$))},
1381
over $\Q$ using \kbd{factor}, and over the number field $\Q[t]/(T)$ using
1382
\kbd{factor(, T)}.
1383
Note however that \kbd{factor} itself will guess intelligently over
1384
which ring you want to factor: try
1385
\bprog
1386
pol = x^2 + 1;
1387
factor(pol)
1388
factor(pol *1.)
1389
factor(pol * (1 + 0*I))
1390
factor(pol * (1 + 0.*I))
1391
factor(pol * Mod(1,2))
1392
factor(pol * Mod(1, Mod(1,3)*(t^2+1)))
1393
pol2 = x^2 + y^2;
1394
factor(pol2)
1395
factor(pol2 * Mod(1,5))
1396
@eprog\noindent
1397
In the present version \vers{}, it is not possible to factor over other
1398
base rings than the ones mentioned above, but multivariate polynomials over
1399
those rings are allowed as shown in the last examples. Other functions
1400
related to factoring are \kbd{padicappr}, \kbd{polrootsmod},
1401
\kbd{polrootspadic}, \kbd{polsturm}. Play with them a little.
1402
1403
Finally, type
1404
\bprog
1405
polsym(pol2, 20)
1406
@eprog\noindent where \kbd{pol2} was defined above. This gives the sum of the
1407
$k$-th powers of the roots of \kbd{pol2} up to $k=20$, of course computed
1408
using Newton's formula and not using \kbd{polroots}. You notice that every
1409
odd sum is zero (expected, since the polynomial is even), but also that
1410
the signs follow a regular pattern and that the (nonzero) absolute values
1411
are powers of 2. This is true: prove it, and more precisely find an explicit
1412
formula for the $k$-th symmetric power not involving (nonrational) algebraic
1413
numbers.
1414
1415
\section{Power Series}
1416
1417
Now let's play with power series as we have done at the beginning. Type
1418
\bprog
1419
N = 39;
1420
8*x + prod(n=1,N, if(n%4, 1 - x^n, 1), 1 + O(x^(N+1)))^8
1421
@eprog\noindent
1422
Apparently, only even powers of \kbd{x} appear. This is surprising, but can
1423
be proved using the theory of modular forms. Note that we initialize
1424
the product to \kbd{1 + O(x\pow (N+1))}, otherwise the whole computation would
1425
be done with polynomials; this would first have been slightly slower and also
1426
totally useless since the coefficients of \kbd{x\pow (N+1)} and above are
1427
irrelevant anyhow if we stop the product at $\kbd{n} = \kbd{N}$.
1428
1429
While we are on the subject of modular forms (which, together with Taylor
1430
series expansions are another great source of power series), type
1431
\bprog
1432
\ps 122 \\@com shortcut for \kbd{default(seriesprecision, 122)}
1433
d = x * eta(x)^24
1434
@eprog\noindent This gives the first 122 terms of the Fourier series
1435
expansion of the modular discriminant function $\Delta$ of Ramanujan. Its
1436
coefficients give by definition the Ramanujan $\tau$ function, which has a
1437
number of marvelous properties (look at any book on modular forms for
1438
explanations). We would like to see its properties modulo 2. Type \kbd{d\%2}.
1439
Hmm, apparently PARI doesn't like to reduce coefficients of power series, or
1440
polynomials for that matter, directly. Can we do it without writing a little
1441
program? No problem. Type instead
1442
\bprog
1443
lift(Mod(1,2) * d)
1444
centerlift(Mod(1,3) * d)
1445
@eprog\noindent and now this works like a charm. The pattern in the first
1446
result is clear; the pattern is less clear in the second result, but
1447
nonetheless there is one. Of course, it now remains to prove it (see Antwerp
1448
III or your resident modular forms guru).
1449
1450
\section{Working with Elliptic Curves}
1451
1452
Now we are getting to more complicated objects. Just as with number fields
1453
which we will meet later on, the first thing to do is to initialize them.
1454
That's because a lot of data will be needed repeatedly, and it's much more
1455
convenient to have it ready once and for all. Here, this is done with the
1456
function \kbd{ellinit}.
1457
1458
So type
1459
\bprog
1460
e0 = ellinit([6,-3,9,-16,-14])
1461
@eprog
1462
This computes a number of things
1463
about the elliptic curve defined by the affine equation
1464
%
1465
$$ y^2+6xy+9y = x^3-3x^2-16x-14\enspace. $$
1466
%
1467
It is not that clear what all these funny numbers mean, except that we
1468
recognize the first few of them as the coefficients we just input. To
1469
retrieve meaningful information from such complicated objects (and number
1470
fields will be much worse), one uses so-called \emph{member
1471
functions}. Type \kbd{?.} to get a complete list. Whenever \kbd{ell} appears
1472
in the right hand side, we can apply the corresponding function to an object
1473
output by \kbd{ellinit}. (I'm sure you know how the other \kbd{init} functions
1474
will be called now, don't you? Oh, by the way, neither \kbd{clgpinit} nor
1475
\kbd{pridinit} exist.)
1476
1477
Let's try it. The discriminant \kbd{e0.disc} is equal to 37, hence
1478
the conductor of the curve is 37. Of course in general it is not so
1479
trivial. In fact, although the equation of the curve is clearly
1480
minimal (since the discriminant is $12$th-power-free), it is not in
1481
standard reduced form, so type
1482
\bprog
1483
e = ellminimalmodel(e0)
1484
@eprog\noindent which
1485
gives the \kbd{ell} structure attached to the standard model,
1486
exactly as if we had used \kbd{ellinit} on a reduced equation. For
1487
some related data, type
1488
\bprog
1489
gr = ellglobalred(e0)
1490
@eprog\noindent The first
1491
component \kbd{gr[1]} tells us that the conductor is 37 as we already
1492
knew. The second component is a 4-component vector which allows us to
1493
get the minimal equation: in fact \kbd{e} is \kbd{ellchangecurve(e0, gr[2])}.
1494
Type
1495
\bprog
1496
q0 = [-2,2]
1497
ellisoncurve(e0, q0)
1498
q = ellchangepoint(q0,gr[2])
1499
ellisoncurve(e, q)
1500
@eprog\noindent
1501
The point \kbd{q0} is on the curve, as checked by \kbd{ellisoncurve}, and we
1502
transferred it onto the minimal model \kbd{e}, using \kbd{ellchangepoint} and
1503
the change of variable computed above. Note that \kbd{ellchangepoint()} is
1504
unusual among the elliptic curve functions in that it does not take an
1505
\kbd{ell} structure as its first argument: in \kbd{gp}, points do not
1506
``know'' which curve they are on, but to move a point from one model to
1507
another we only need to know the coordinates of the point and the
1508
transformation data here stored in \kbd{gr[2]}. Also, the point at infinity
1509
is represented as \kbd{[0]} on all elliptic curves; this is the identity for
1510
the group law.
1511
1512
Here, \kbd{q=[0,0]} obviously lies on \kbd{e}, which has equation
1513
$y^2+y = x^3-x$. Let us now play a little with points on \kbd{e}.
1514
The group law on an elliptic curve is implemented with the functions
1515
\kbd{elladd} for addition, \kbd{ellsub} for subtraction and
1516
\kbd{ellmul} for multiplication by an integer. For
1517
example, the negative of \kbd{q} is \kbd{ellsub(e,[0],q)}, and the
1518
double is obtained either as \kbd{ellmul(e,q,2)} or as
1519
\kbd{elladd(e,q,q)}.
1520
1521
Now \kbd{q} may be a torsion point. Type \kbd{ellheight(e, q)}, which
1522
computes the canonical Neron-Tate height of \kbd{q}. Note that
1523
\kbd{ellheight} does not assume that \kbd{e} is \emph{minimal}! (Although
1524
it is, making things a little faster.)
1525
This is nonzero, hence \kbd{q} is not torsion. To see this even better,
1526
type
1527
\bprog
1528
for(k = 1, 20, print(ellmul(e, q, k)))
1529
@eprog\noindent and we see the characteristic parabolic explosion of the size
1530
of the points. (And another proof that \kbd{q} is not torsion, assuming
1531
Mazur's bound on the size of the rational torsion.) We could can also type
1532
\kbd{ellorder(e, q)} which returns 0, telling us yet again that \kbd{q} is
1533
nontorsion. As a consistency check, type
1534
\bprog
1535
ellheight(e, ellmul(e, q,20)) / ellheight(e, q)
1536
@eprog\noindent
1537
We indeed find $400=20^2$ as it should be.
1538
1539
Notice how (almost) all those \kbd{ell}--prefixed functions take our
1540
elliptic curve as a first argument? This will be true with number
1541
fields as well: whatever object was initialized by an $ob$--\kbd{init}
1542
function will have to be used as a first argument of all the
1543
$ob$--prefixed functions. Conversely, you won't be able to use any
1544
such high-level function before you correctly initialize the relevant
1545
object. \smallskip
1546
1547
Ok, let's try another curve. Type
1548
\bprog
1549
E = ellinit([0,-1,1,0,0])
1550
q = [0,0]; ellheight(E, q)
1551
@eprog\noindent This corresponds to the equation $y^2+y = x^3-x^2$ and an
1552
obvious rational point on it. Again from the discriminant we see that the
1553
conductor is equal to 11, and if you type \kbd{ellminimalmodel(E)} you will
1554
see that the equation for \kbd{E} is minimal. This time the height is
1555
exactly zero, hence \kbd{q} must be a torsion point. Indeed, typing
1556
\bprog
1557
for(k=1, 5, print(ellmul(E, q,k)))
1558
ellorder(E, q) \\@com simpler
1559
@eprog\noindent
1560
we see in two different ways that \kbd{q} is a point of order 5. Moreover,
1561
typing
1562
\bprog
1563
elltors(E)
1564
@eprog\noindent shows that \kbd{q} generates all the torsion of \kbd{E},
1565
which is cyclic of order~$5$. \smallskip
1566
1567
Let's try still another curve, $y^2+y = x^3-7x+6$:
1568
\bprog
1569
e = ellinit([0,0,1,-7,6])
1570
ellglobalred(e)
1571
@eprog\noindent As before, this is a minimal equation; now the conductor is
1572
5077. There are some trivial integral points on this curve, but let's try to
1573
be more systematic. Typing
1574
\bprog
1575
elltors(e)
1576
@eprog\noindent
1577
shows that the torsion subgroup is trivial, so we don't have to worry about
1578
torsion points. Next, the function \kbd{ellratpoints} allows us to find
1579
rational points of small height
1580
\bprog
1581
v = ellratpoints(e,1000)
1582
@eprog\noindent The vector $v$ contains all 130 rational points $(x,y)$ on the
1583
curve whose $x$-coordinate is $n/d$ with $|n|$ and $|d|$ both less than $1000$.
1584
Note that \kbd{ellratpoints(e,10\pow6)} takes less than 1 second, and
1585
produces 344 points. Of course, these are grouped by pairs:
1586
if $(x,y)$ is on the curve, its opposite is $(x,-y-1)$ as
1587
\bprog
1588
ellneg(e, ['x,'y])
1589
@eprog\noindent shows. Note that there is no problem with manipulating points
1590
with formal coordinates. This is large for a curve having such a small
1591
conductor. So we suspect (if we do not know already, since this curve is
1592
quite famous!) that the rank of this curve must be large. Let's try and put
1593
some order into this. First, we eliminate one element in each pair
1594
of opposite points:
1595
\bprog
1596
v = vecsort(v, 1, 8)
1597
@eprog\noindent
1598
The argument $1$ specifies a comparison function: we sort the points by first
1599
coordinate only, in particular two points with the same $x$-coordinate
1600
compare as equal; the $8$ flag eliminates ``duplicates''. The same effect
1601
could be obtained in a more verbose way using an inline anonymous function
1602
\bprog
1603
v = vecsort(v, (P,Q) -> sign(P[1]-Q[1]), 8)
1604
@eprog\noindent We now order the points according to their canonical height:
1605
\bprog
1606
hv = [ ellheight(e,P) | P <- v ];
1607
v = vecextract(v, vecsort(hv,,1)) \\ indirect sort wrt h, then permute
1608
@eprog\noindent
1609
It seems reasonable to take the numbers with smallest height as
1610
possible generators of the Mordell-Weil group. Let's try the first
1611
four: type
1612
\bprog
1613
m = ellheightmatrix(e, v[1..4]); matdet(m)
1614
@eprog\noindent
1615
Since the curve has no torsion, the determinant being close to zero
1616
implies that the first four points are dependent. To find the
1617
dependency, it is enough to find the kernel of the matrix \kbd{m}. So
1618
type \kbd{matker(m)}: we indeed get a nontrivial kernel, and the
1619
coefficients are close to integers. Typing \kbd{elladd(e, v[1],v[3])} does
1620
indeed show that it is equal to \kbd{v[4]}.
1621
1622
Taking any other four points, we seem to always find a dependency.
1623
Let's find all dependencies. Type
1624
\bprog
1625
vp = v[1..3];
1626
m = ellheightmatrix(e,vp);
1627
matdet(m)
1628
@eprog\noindent This is now clearly nonzero so the first 3 points are
1629
linearly independent, showing that the rank of the curve is at least equal to
1630
3. (In fact, \kbd{e} is the curve of smallest conductor having rank 3.)
1631
We would like to see whether the other points are dependent:
1632
if \kbd{Q} is some point which is dependent on \kbd{v[1],v[2]} and \kbd{v[3]}
1633
and
1634
\bprog
1635
c = [ellheight(e, P, Q) | P <- vp]~
1636
@eprog\noindent then \kbd{m\pow(-1) * c} will give the coefficients of the
1637
dependence relation. If these coefficients are not close to integers,
1638
then there is no dependency, otherwise we can round and check rigourously
1639
using a function such as the following:
1640
\bprog
1641
ellcomb(e, P, L) =
1642
{ my (Q = [0]);
1643
for (i = 1, #P, Q = elladd(e, Q, ellmul(e, P[i], L[i])));
1644
return (Q);
1645
}
1646
@eprog\noindent This is safer than using the \kbd{matker} function. Thus, type
1647
\bprog
1648
mi = m^(-1);
1649
w = vector(#v, k, mi * [ellheight(e, P, v[k]) | P <- vp]~)
1650
wr = round(w, &e)
1651
@eprog\noindent
1652
We ``see'' that the coefficients are all very close to integers, and we
1653
quantified it with the last instruction: \kbd{wr} is the vector expressing
1654
all the components of \kbd{v} on its first 3, and $2^{-e}$ gives an upper
1655
bound on the maximum distance to an integer. The rigorous check is positive:
1656
\bprog
1657
for (i=1, #w, if (v[i] != ellcomb(e,vp,wr[i]), error(i)));
1658
@eprog\noindent No error! We must make two technical remarks at this point:
1659
1660
(1) Using the height pairing to find dependence relations as we
1661
have done only finds relations modulo torsion; but in this example, the curve
1662
has trivial torsion, as we checked earlier.
1663
1664
(2) In the above calculation we
1665
were lucky that all the \kbd{v[j]} were $\Z$-linear combinations of
1666
\kbd{v[1]}, \kbd{v[2]} and \kbd{v[3]} and not just $\Q$-linear combinations;
1667
in general the results in $w$ might have given a vector of rationals: if
1668
$k\ge2$ is minimal such that $kQ$ is in the subgroup generated by \kbd{v[1]},
1669
\kbd{v[2]} and \kbd{v[3]}, then the entries of \kbd{matsolve(m, ellbil(e,
1670
vp,Q))} will be rationals with common denominator~$k$. This can be detected
1671
by using \kbd{bestappr} instead of \kbd{round} in the above.
1672
\smallskip
1673
1674
We are thus led to strongly believe that the curve has rank
1675
exactly 3, with generators \kbd{v[1]}, \kbd{v[2]} and \kbd{v[3]}, and this
1676
can be proved to be the case. Indeed, all this (and much more) is automated
1677
in the built-in \kbd{ellrank} function:
1678
\bprog
1679
[r, R, P] = ellrank(e);
1680
Q = ellsaturation(e, P, 100)
1681
@eprog\noindent We find $r = R = 3$ and a vector $P$ containing $3$
1682
rational points. This performs $2$-descent on the curve: the rank belongs
1683
to $[r,R]$ hence is equal to $3$. The points in $P$ are independent
1684
modulo torsion : since $\kbd{\#P} = r = R$, they generate a subgroup
1685
of finite index. The final \kbd{ellsaturation} provides a new vector of
1686
points which is $p$-saturated for all primes $p \leq 100$: the index of the
1687
subgroup they generate is not divisible by any such prime.
1688
1689
In other situations, we could be missing some points and have $\kbd{\#P} <
1690
r$: for instance
1691
\bprog
1692
e = ellinit([-127^2, 0]);
1693
ellrank(e)
1694
@eprog\noindent does not find any point although the rank is $1$; in this
1695
particular case (rank $1$ and ``small'' conductor), \kbd{ellheegner} finds
1696
the missing point, which happens to be a generator.
1697
1698
\smallskip
1699
1700
Let us explore a few more elliptic curve related functions. Keep our
1701
curve \kbd{e} of rank 3, and type
1702
\bprog
1703
v1 = [1,0]; z1 = ellpointtoz(e, v1)
1704
v2 = [2,0]; z2 = ellpointtoz(e, v2)
1705
@eprog\noindent
1706
We thus get the complex parametrization of the curve. To add the points
1707
\kbd{v1} and \kbd{v2}, we should of course type \kbd{elladd(e, v1,v2)},
1708
but we can also type \kbd{ellztopoint(e, z1 + z2)} which has the disadvantage
1709
of giving complex numbers, but illustrates how the group law on \kbd{e} is
1710
obtained from the addition law on $\C$.
1711
1712
Type
1713
\bprog
1714
f = x * Ser(ellan(e, 30))
1715
@eprog\noindent This gives a power series which is the Fourier expansion of a
1716
modular form of weight 2 for $\Gamma_0(5077)$. (This has been proved
1717
directly, before Wiles's general result.) In fact, to find the modular
1718
parametrization of the curve, type
1719
\bprog
1720
modul = elltaniyama(e)
1721
u = modul[1];
1722
v = modul[2];
1723
@eprog\noindent
1724
We can check in various ways that this indeed parametrizes the curve:
1725
\bprog
1726
(v^2 + v) - (u^3 - 7*u + 6)
1727
@eprog\noindent
1728
is close to $0$ for instance, or simply that \kbd{ellisoncurve(e,modul)}
1729
returns~$1$. Now type
1730
\bprog
1731
x * u' / (2*v + 1)
1732
@eprog\noindent and we see that this is equal to the modular form \kbd{f}
1733
found above; the quote \kbd{'} tells \kbd{gp} to take the derivative of the
1734
expression with respect to its main variable. The functions \kbd{u} and
1735
\kbd{v}, considered on the upper half plane with $x=e^{2i\pi\tau}$, are in
1736
fact modular \emph{functions} for $\Gamma_0(5077)$. \smallskip
1737
1738
The function \kbd{ellan(e, 30)} gives the first~$30$ coefficients
1739
$a_n$ of the $L$-series of \kbd{e}. One can also ask for a single
1740
coefficient: the millionth is \kbd{ellak(e, 10\pow 6)}. Note however
1741
that calling \kbd{ellan(e,100000)} is much faster than
1742
the equivalent \kbd{vector(100000,k,ellak(e,k))}. For a
1743
prime~\kbd{p},
1744
\kbd{ellap(e,p)} is equivalent to \kbd{ellak(e,p)}; this is the
1745
integer $a_p$ such that the number of points on \kbd{e} over $\F_p$ is
1746
$1+p-a_p$. (With the standard PARI distribution, \kbd{ellap} is the only way
1747
to obtain the order of an elliptic curve over $\F_p$ in \kbd{gp}. The
1748
external package \kbd{ellsea} provides much more efficient routines.)
1749
1750
Finally, let us come back to the curve \kbd{E} defined above by
1751
\kbd{E = ellinit([0,-1,1,0,0])}, which had an obvious rational $5$-torsion
1752
point. The sign of the functional equation, given by \kbd{ellrootno(E)}, is
1753
$+1$. Assuming the rank parity conjecture, it follows that the Mordell-Weil
1754
group of $E$ has even rank. The value of the L-function of \kbd{E} at 1
1755
\bprog
1756
ls = lfun(E, 1)
1757
@eprog\noindent is definitely nonzero, so \kbd{E} has rank $0$. According to
1758
the Birch and Swinnerton-Dyer conjecture, which is proved for this curve,
1759
\kbd{ls} is given by the following formula (in this case):
1760
%
1761
\def\sha{\hbox{III}}
1762
$$L(E,1)=\dfrac{\Omega\cdot c\cdot|\sha|}{|E_{\text{tors}}|^2}\enspace,$$
1763
%
1764
where $\Omega$ is the real period of $E$, $c$ is the global Tamagawa number,
1765
$|\sha|$ is the order of the Tate-Shafarevich group, and $E_{\text{tors}}$ is the
1766
torsion group of $E$.
1767
1768
Now we know many of these quantities: $\Omega$ is equal to \kbd{E.omega[1]}
1769
The global Tamagawa number $c$ is given by \kbd{elltamagawa(E)} and is $1$
1770
We already know that the torsion subgroup of $E$ contains a point of order 5,
1771
and typing \kbd{elltors(E)} shows that it is of order exactly 5. So type
1772
\bprog
1773
ls * 25/E.omega[1]
1774
@eprog\noindent This shows that $\sha$ must be the trivial group.
1775
A short hand for $\dfrac{\Omega\cdot c}{|E_{\text{tors}}|^2}$ is \kbd{ellbsd(E)},
1776
so the previous line can be written as
1777
\bprog
1778
ls / ellbsd(E)
1779
@eprog
1780
1781
For more detailed information on the local reduction of an elliptic curve at
1782
a specific prime~\kbd{p}, use the function \kbd{elllocalred(E,p)}; the second
1783
component gives the Kodaira symbol in an encoded form. See the manual or
1784
online help for details.
1785
1786
\section{Working in Quadratic Number Fields}
1787
1788
The simplest of all number fields outside $\Q$ are quadratic fields and are
1789
the subject of the present section. We shall deal in the next one with
1790
general number fields (including $\Q$ and quadratic fields!), and one should
1791
be aware that all we will see now has a more powerful, in general easier to
1792
use, equivalent in the general context. But possibly much slower.
1793
1794
Such fields are characterized by their discriminant. Even better, any
1795
nonsquare integer $D$ congruent to 0 or 1 modulo 4 is the discriminant of a
1796
specific order in a quadratic field. We can check whether this order is
1797
maximal with \kbd{isfundamental(D)}. Elements of a quadratic field are of the
1798
form $a+b\omega$, where $\omega$ is chosen as $\sqrt{D}/2$ if $D$ is even and
1799
$(1+\sqrt{D})/2$ if $D$ is odd, and are represented in PARI by quadratic
1800
numbers. To initialize working in a quadratic order, one starts by the
1801
command \kbd{w = quadgen($D$,'w)}.
1802
1803
This sets \kbd{w} equal to $\omega$ as above, and is printed \kbd{w}.
1804
If you need several quadratic orders at the same time, you can
1805
use different variable names:
1806
\bprog
1807
w1 = quadgen(-23,'w1)
1808
w2 = quadgen(-15,'w1)
1809
@eprog\noindent
1810
\smallskip
1811
%
1812
In addition to elements of a quadratic order, we also want to be able to
1813
handle ideals of such orders. In the quadratic case, it is equivalent to
1814
handling binary quadratic forms. Quadratic forms are triples $(a,b,c)$
1815
representing the form $ax^2+bxy+cy^2$. Such a form will be printed as, and
1816
can be created by, \kbd{Qfb($a$,$b$,$c$)}.
1817
1818
Such forms can be multiplied, divided, powered as many PARI objects using
1819
the usual operations, and they can also be reduced using the function
1820
\kbd{qfbred} or \kbd{qfbredsl2} (which also returns the unimodular
1821
transformation matrix). One can also use explicitly \kbd{qfbcomp} /
1822
\kbd{qfbpow} (same as multiplication) and \kbd{qfbcompraw} / \kbd{qfbpowraw}
1823
(composition without reduction) (It is not the purpose of this tutorial to
1824
explain what all these things mean.) In addition, Shanks's NUCOMP algorithm
1825
has been implemented (functions \kbd{qfbnucomp} and \kbd{qfbnupow}), and this
1826
is usually a little faster.
1827
1828
Finally, you have at your disposal the functions \kbd{qfbclassno} which
1829
(\emph{usually}) gives the class number, the function \kbd{qfbhclassno}
1830
which gives the Hurwitz class number, and the much more sophisticated
1831
\kbd{quadclassunit} function which gives the class number and class group
1832
structure.
1833
1834
Let us see examples of all this at work.
1835
1836
Type \kbd{qfbclassno(-10007)}. \kbd{gp} tells us that the result is 77. However,
1837
you may have noticed in the explanation above that the result is only
1838
\emph{usually} correct. This is because the implementers of the algorithm
1839
have been lazy and have not put the complete Shanks algorithm into PARI,
1840
causing it to fail in certain very rare cases. In practice, it is almost
1841
always correct, and the much more powerful \kbd{quadclassunit} program, which
1842
\emph{is} complete (at least for fundamental discriminants) can give
1843
confirmation; but now, under the Generalized Riemann Hypothesis!
1844
1845
So we may be a little suspicious of this class number. Let us check it.
1846
First, we need to find a quadratic form of discriminant $-10007$. Since this
1847
discriminant is congruent to 1 modulo 8, we know that there is an ideal of
1848
norm equal to 2, i.e.~a binary quadratic form $(a,b,c)$ with $a=2$. To
1849
compute it we type \kbd{f = qfbprimeform(-10007, 2)}. OK, now we have a form.
1850
If the class number is correct, the very least is that this form raised to
1851
the power 77 should equal the identity. Type \kbd{f\pow 77}. We get a form
1852
starting with 1, i.e.~the identity. Raising \kbd{f} to the powers 11 and 7
1853
does not give the identity, thus we now know that the order of \kbd{f} is
1854
exactly 77, hence the class number is a multiple of 77. But how can we be
1855
sure that it is exactly 77 and not a proper multiple? Well, type
1856
\bprog
1857
sqrt(10007)/Pi * prodeuler(p=2,500, 1./(1 - kronecker(-10007,p)/p))
1858
@eprog\noindent
1859
This is nothing else than an approximation to the Dirichlet class number
1860
formula. The function \kbd{kronecker} is the Kronecker symbol, in this case
1861
simply the Legendre symbol. Note also that we have written \kbd{1./(1 - \dots)}
1862
with a dot after the first 1. Otherwise, PARI may want to compute the whole
1863
thing as a rational number, which would be terribly long and useless. In fact
1864
PARI does no such thing in this particular case (\kbd{prodeuler} is always
1865
computed as a real number), but you never know. Better safe than sorry!
1866
1867
We find 77.77, pretty close to 77, so things seem in order. Explicit bounds
1868
on the prime limit to be used in the Euler product can be given which make
1869
the above reasoning rigorous.
1870
1871
Let us try the same thing with $D=-3299$. \kbd{qfbclassno} and the Euler
1872
product convince us that the class number must be 27. However, we get stuck
1873
when we try to prove this in the simple-minded way above. Indeed, we type
1874
\kbd{f = qfbprimeform(-3299, 3)} (2 is not the norm of a prime ideal but
1875
3 is), and we see that \kbd{f} raised to the power 9 is equal to the identity.
1876
This is the case for any other quadratic form we choose. So we suspect that the
1877
class group is not cyclic. Indeed, if we list all 9 distinct powers of \kbd{f},
1878
we see that \kbd{qfbprimeform(-3299, 5)} is not on the list, although its cube
1879
is as it must. This implies that the class group is probably equal to a
1880
product of a cyclic group of order 9 by a cyclic group of order 3. The Euler
1881
product plus explicit bounds prove this.
1882
1883
Another way to check it is to use the \kbd{quadclassunit} function by typing
1884
for example
1885
\bprog
1886
quadclassunit(-3299)
1887
@eprog\noindent
1888
Note that this function cheats a little and could still give a wrong answer,
1889
even assuming GRH: the forms given could generate a strict subgroup of the
1890
class group. If we want to use proven bounds under GRH, we have to type
1891
\bprog
1892
quadclassunit(-3299,,[1,6])
1893
@eprog\noindent
1894
The double comma \kbd{,,} is not a typo, it means we omit an optional second
1895
argument. As we want to use the optional \emph{third} argument, we have to
1896
indicate to \kbd{gp} we skipped this one.
1897
1898
Now, if we believe in GRH, the class group is as we thought (see Chapter 3
1899
for a complete description of this function).
1900
1901
Note that using the even more general function \kbd{bnfinit} (which handles
1902
general number fields and gives more complicated results), we could
1903
\emph{certify} this result, i.e~remove the GRH assumption. Let's do it, type
1904
\bprog
1905
bnf = bnfinit(x^2 + 3299); bnfcertify(bnf)
1906
@eprog
1907
1908
A nonzero result (here 1) means that everything is ok. Good, but what did
1909
we certify after all? Let's have a look at this \kbd{bnf} (just type it!).
1910
Enlightening, isn't it? Recall that the \kbd{init} functions (we've already
1911
seen \kbd{ellinit}) store all kind of technical information which you
1912
certainly don't care about, but which will be put to good use by higher level
1913
functions. That's why \kbd{bnfcertify} could not be used on the output of
1914
\kbd{quadclassunit}: it needs much more data.
1915
1916
To extract sensible information from such complicated objects, you must use
1917
one of the many \emph{member functions} (remember: \kbd{?.} to get a complete
1918
list). In this case \kbd{bnf.clgp} which extracts the class group structure.
1919
This is much better. Type \kbd{\%.no} to check that this leading 27 is indeed
1920
what we think it is and not some stupid technical parameter. Note that
1921
\kbd{bnf.clgp.no} would work just as well, or even \kbd{bnf.no}!
1922
1923
As a last check, we can request a relative equation for the Hilbert class
1924
field of $\Q(\sqrt{-3299})$: type \kbd{quadhilbert(-3299)}. It is indeed of
1925
degree 27 so everything fits together.
1926
1927
\medskip
1928
%
1929
Working in real quadratic fields instead of complex ones, i.e.~with $D>0$, is
1930
not very different.
1931
1932
The same \kbd{quadgen} function is used to create elements. Ideals are again
1933
represented by binary quadratic forms $(a,b,c)$, this time indefinite. However,
1934
the Archimedean valuations of the number field start to come into play, hence
1935
in fact quadratic forms with positive discriminant can also
1936
be represented as a pair $[q, d]$ where $q = \kbd{Qfb(a, b, c)}$ is the
1937
indefinite quadratic form $ax^2+bxy+cy^2$, and $d\in \R$ is a ``distance''
1938
component, as defined by Shanks and Lenstra.
1939
1940
The form $q$ can be multiplied, divided, powered, and they can be
1941
reduced using \kbd{qfbred}. But this time, to compose extended forms
1942
$[q,d]$ and $[q,d']$, one must use \kbd{qfbcomp} and \kbd{qfbpow} (since
1943
ordinary multiplication and powerings will not accept pairs)
1944
1945
The \kbd{qfbred} function applies a succession of
1946
elementary reduction steps corresponding essentially to a continued fraction
1947
expansion, and a single one of these steps can be achieved by adding an
1948
(optional) flag to the arguments of \kbd{qfbred}. Again, the function
1949
\kbd{qfbprimeform} gives a prime form, but the form which is given
1950
corresponds to an ideal of prime norm which is usually not reduced. If
1951
desired, it can be reduced using \kbd{qfbred}.
1952
1953
Finally, you still have at your disposal the function \kbd{qfbclassno} which
1954
gives the class number (this time \emph{guaranteed} correct),
1955
\kbd{quadregulator} which gives the regulator, and the much more sophisticated
1956
\kbd{quadclassunit} giving the class group's structure and its generators,
1957
as well as the regulator. The \kbd{qfbclassno} and \kbd{quadregulator}
1958
functions use an algorithm which is $O(\sqrt D)$, hence become very slow for
1959
discriminants of more than 10 digits. \kbd{quadclassunit} can be used on a
1960
much larger range.
1961
1962
Let us see examples of all this at work and learn some little known number
1963
theory at the same time. First of all, type
1964
\bprog
1965
D = 3 * 3299; qfbclassno(D)
1966
@eprog\noindent We see that the class number is 3. (We know
1967
in advance that it must be divisible by 3 from the \kbd{D = -3299} case above
1968
and Scholz's mirror theorem.) Let us create a form by typing
1969
\bprog
1970
f = qfbred(qfbprimeform(D,2))
1971
@eprog\noindent
1972
This gives us a prime ideal of norm equal to 2. Is this ideal principal?
1973
Well, one way to check this, which is not the most efficient but will suffice
1974
for now, is to look at the complete cycle of reduced forms equivalent to
1975
\kbd{f}. Type
1976
\bprog
1977
g = f; for(i=1,20, g = qfbred(g, 1); print(g))
1978
@eprog\noindent
1979
(the flag $1$ in \kbd{qfbred} means to perform a single reduction step). We
1980
see that we come back to the form \kbd{f} without meeting the principal form
1981
(starting with $\pm1$) in the cycle, so the ideal corresponding to \kbd{f} is
1982
not principal.
1983
1984
Since the class number is equal to 3, we know however that \kbd{f\pow 3} will
1985
be a principal ideal $\alpha\Z_K$. How do we find $\alpha$? For this, type
1986
\bprog
1987
f3 = qfbpowraw(f, 3)
1988
@eprog
1989
This computes the cube of \kbd{f}, without
1990
reducing it. Hence it corresponds to an ideal of norm equal to $8=2^3$, so we
1991
already know that the norm of $\alpha$ is equal to $\pm8$. We need more
1992
information, and this is given by supplementing the form by a \emph{distance}
1993
component $d$, a real number that tracks archimedean information that will
1994
eventually allows to recover $\alpha$: we call such a pair $[f,d]$ an
1995
\emph{extended form}.
1996
\bprog
1997
F3 = [f3, 0.0]; /* initialize */
1998
while(abs(component(F3[1], 1)) != 1, F3 = qfbred(F3, 1); print(F3))
1999
d = F3[2];
2000
@eprog
2001
We reduce the form until we reach the unit form (exactly 6 times),
2002
then extract the Archimedean component, say $d = 8.59\dots$
2003
By definition of this distance, we know that
2004
$${\alpha\over{\sigma(\alpha)}}=\pm e^{2d},$$
2005
where $\sigma$ denotes real conjugation in our quadratic field. Thus, if we type
2006
\bprog
2007
Na = 8; /* |Norm(alpha)| */
2008
a = sqrt(Na * exp(2*d))
2009
sa = Na / a
2010
@eprog\noindent
2011
we know that up to sign, \kbd{a} and \kbd{sa} are
2012
numerical approximations of $\alpha$ and $\sigma(\alpha)$. Of course,
2013
$\alpha$ can always be chosen to be positive, and a quick numerical check
2014
shows that the difference of \kbd{a} and \kbd{sa} is close to an integer, and
2015
not the sum, so that in fact the norm of $\alpha$ is equal to $-8$ and the
2016
numerical approximation to $\sigma(\alpha)$ is \kbd{$-$sa}. Thus we type
2017
\bprog
2018
p = x^2 - round(a-sa)*x - 8
2019
@eprog\noindent
2020
and this ($x^2 - 15221x - 8$) is the characteristic polynomial of $\alpha$.
2021
We can check that the discriminant of this polynomial is a square multiple of
2022
\kbd{D} using \kbd{issquare(poldisc(p) / D)}, so $\alpha$ is indeed in our
2023
field. More precisely, solving for $\alpha$ and using the numerical
2024
approximation that we have to resolve the sign ambiguity in the square root,
2025
we get explicitly $\alpha=(15221+153\sqrt D)/2$. Note that this can also be
2026
done automatically using the functions \kbd{polred} and \kbd{modreverse}, as
2027
we will see later in the general number field case. Or by solving a system
2028
of~2 linear equations in 2 variables. (Exercise: now that we have $\alpha$,
2029
check that it is indeed a generator of the ideal corresponding to the form
2030
\kbd{f3}.)
2031
2032
\medskip Let us now play a little with cycles. Type
2033
\bprog
2034
D = 10^7 + 1
2035
quadclassunit(D)
2036
@eprog\noindent
2037
We get as a result a 5-component vector, which tells us that (under GRH) the
2038
class number is equal to 1, and the regulator $R$ is approximately
2039
equal to $2641.5$. You may certify this with
2040
\bprog
2041
bnf = bnfinit(x^2 - D, 1); \\ @com insist on finding fundamental unit
2042
bnfcertify(bnf);
2043
@eprog\noindent
2044
although it's a little inefficient. Indeed \kbd{bnfcertify} needs the
2045
fundamental unit, which is large: it needs about $R/\log(10)\approx 1147$
2046
digits of precision, see \kbd{bnf.fu}!
2047
(\kbd{bnfinit} would have given up had we not inserted the flag $1$.)
2048
On the other hand, you can try \kbd{quadunit(D,'w)}. Impressive, isn't it?
2049
(You can check that its logarithm is indeed equal to the regulator.)
2050
2051
Let's now assume that we want the regulator $R$ to 500 decimals, say.
2052
(Without cheating and computing the fundamental unit exactly first!)
2053
This can be computed with no effort, simply from the crude approximation
2054
$2641.5$ above. This time, we start with the unit form. Type:
2055
\bprog
2056
u = [qfbprimeform(D, 1), 0.0];
2057
R = 2641.5; /* rough approximation */
2058
@eprog\noindent
2059
This initializes the distance to $0$.
2060
Now type \kbd{f = qfbred(u, 1)}. This is the
2061
first form encountered along the principal cycle. For the moment, keep the
2062
precision low, for example the initial default precision. The distance from
2063
the identity of \kbd{f} is around 4.253. Since we want a
2064
distance of $R$, this should be encountered approximately at
2065
$R/f[2]=621$ times the distance of \kbd{f}. Hence, as a first try, we
2066
type \kbd{qfbpow(f,621)} (\kbd{f \pow 621} will not accept extended forms).
2067
Oops, we overshot, since the distance is now $3173.02$.
2068
Now we can refine our initial estimate and believe that we should be close to
2069
the correct distance if we raise \kbd{f} to the power $621*R/3173$ which
2070
is close to $517$. Now if we compute \kbd{qfbpow(f, 517)} we hit the principal
2071
form right on the dot. Note that this is not a lucky accident: we must land
2072
extremely close to the correct target using this method, and usually at most
2073
one reduction correction step is necessary. And the distance component can
2074
tell us where we are along the cycle.
2075
2076
Up to now, we have only worked to low precision. The goal was to obtain this
2077
unknown integer $517$. Note that this number has absolutely no mathematical
2078
significance: indeed the notion of reduction of a form with positive
2079
discriminant is not well defined since there are usually many reduced forms
2080
equivalent to a given form. However, when PARI computes with extended forms,
2081
the specific order and reductions that it performs are dictated entirely by
2082
the coefficients of the quadratic form itself, and not by the distance
2083
component, hence the precision used has no effect.
2084
2085
Hence we now start again by setting the precision to (for example) 500,
2086
we retype the definition of \kbd{u} (why is this necessary?), and then
2087
\kbd{qfbpow(qfbred(u, 1), 517)}. We already know that we land on the
2088
unit form, and the distance component gives us the regulator to 500 decimal
2089
places with no effort at all.
2090
2091
In a similar way, we could obtain the so-called \emph{compact representation}
2092
of the fundamental unit itself, or $p$-adic regulators. I leave this as
2093
exercises for the interested reader.
2094
2095
You can try the \kbd{quadhilbert} function on that field but, since the class
2096
number is $1$, the result won't be that exciting. If you try it on our
2097
preceding example ($3*3299$) it should take about 2 seconds.
2098
\medskip
2099
2100
Time for a coffee break?
2101
2102
\section{Working in General Number Fields}
2103
\subsec{Elements}
2104
2105
The situation here is of course more difficult. First of all, remembering
2106
what we did with elliptic curves, we need to initialize data linked to our
2107
base number field, with something more serious than \kbd{quadgen}. For
2108
example assume that we want to work in the number field $K$ defined by one of
2109
the roots of the equation $x^4+24x^2+585x+1791=0$. This is done by typing
2110
\bprog
2111
T = x^4 + 24*x^2 + 585*x + 1791
2112
nf = nfinit(T)
2113
@eprog\noindent
2114
We get an \kbd{nf} structure but, thanks to member functions, we do not need
2115
to know anything about it. If you type \kbd{nf.pol}, you will get the
2116
polynomial \kbd{T} which you just input. \kbd{nf.sign} yields the signature
2117
$(r_1,r_2)$ of the field, \kbd{nf.disc} the field discriminant, \kbd{nf.zk}
2118
an integral basis, etc\dots.
2119
2120
The integral basis is expressed in terms of a generic root \kbd{x} of \kbd{T}
2121
and we notice it's very far from being a power integral basis, which is a
2122
little strange for such a small field. Hum, let's check that: \kbd{poldisc(T)}?
2123
Ooops, small wonder we had such denominators, the index of the power order
2124
$\Z[x]/(T)$ in the maximal order $\Z_K$ is, well,
2125
\kbd{nf.index}. Note that this is also given by
2126
\bprog
2127
sqrtint(poldisc(nf.pol) / nf.disc)
2128
@eprog\noindent
2129
Anyway, that's $3087$, we don't want to work with such a badly skewed
2130
polynomial! So, we type
2131
\bprog
2132
P = polred(T)
2133
@eprog\noindent
2134
We see from the third component that the
2135
polynomial $x^4-x^3-21x^2+17x+133$ defines the same field with much smaller
2136
coefficients, so type
2137
\bprog
2138
A = P[3]
2139
@eprog\noindent
2140
The \kbd{polred} function usually gives a simpler polynomial, and also
2141
sometimes some information on the existence of subfields. For example in this
2142
case, the second component of \kbd{polred} tells us that the field defined by
2143
$x^2-x+1=0$, i.e.~the field generated by the cube roots of unity, is a subfield
2144
of~$K$. Note this is incidental information and that the list of subfields
2145
found in this way is usually far from complete. To get the complete list, one
2146
uses \kbd{nfsubfields} (we shall do that later on).
2147
2148
Type \kbd{poldisc(A)}, this is much better, but maybe not optimal yet
2149
(the index is still $7$). Type \kbd{polredabs(A)} (the \kbd{abs} stands for
2150
absolute). Since it seems that we won't get anything better, we'll stick with
2151
\kbd{A} (note however that \kbd{polredabs} finds a smallest generating
2152
polynomial with respect to a bizarre norm which ensures that the index will
2153
be small, but not necessarily minimal). In fact, had you typed
2154
\kbd{nfinit(T, 3)}, \kbd{nfinit} would first have tried to find a good
2155
polynomial defining the same field (i.e.~one with small index) before
2156
proceeding.
2157
2158
It's not too late, let's redefine our number field:
2159
\bprog
2160
NF = nfinit(nf, 3)
2161
@eprog\noindent
2162
The output is a two-component vector. The first component is the new
2163
\kbd{nf}: type
2164
\bprog
2165
nf = NF[1];
2166
@eprog\noindent
2167
If you type \kbd{nf.pol}, you notice that \kbd{gp} indeed replaced your bad
2168
polynomial \kbd{T} by a much better one, which happens to be \kbd{A}. (Small
2169
wonder, \kbd{nfinit} internally called \kbd{polredabs}.) The second component
2170
enables you to switch conveniently to our new polynomial.
2171
2172
Namely, call $\theta$ a root of our initial polynomial \kbd{T}, and $\alpha$
2173
a root of the one that \kbd{polred} has found, namely \kbd{A}. These are
2174
algebraic numbers, and as already mentioned are represented as polmods. For
2175
example, in our special case $\theta$ and $\alpha$ are equal to the polmods
2176
\bprog
2177
THETA = Mod(x, x^4 + 24*x^2 + 585*x + 1791)
2178
ALPHA = Mod(x, x^4 - x^3 - 21*x^2 + 17*x + 133)
2179
@eprog\noindent respectively. Here we are considering only the algebraic
2180
aspect, and hence ignore completely \emph{which} root $\theta$ or $\alpha$ is
2181
chosen.
2182
2183
Now you may have a number of elements of your number field which are
2184
expressed as polmods with respect to your old polynomial, i.e.~as polynomials
2185
in $\theta$. Since we are now going to work with $\alpha$ instead, it is
2186
necessary to convert these numbers to a representation using $\alpha$. This
2187
is what the second component of \kbd{NF} is for: type \kbd{C = NF[2]}, you get
2188
\bprog
2189
Mod(-10/7*x^3 + 43/7*x^2 + 73/7*x - 64, x^4 - x^3 - 21*x^2 + 17*x + 133)
2190
@eprog\noindent
2191
meaning that $\theta =
2192
-\dfrac{10}{7}\alpha^3+\dfrac{43}{7}\alpha^2+\dfrac{73}{7}\alpha-64$, and hence the conversion from a
2193
polynomial in $\theta$ to one in $\alpha$ is easy, using \kbd{subst}. (We
2194
could get this polynomial from \kbd{polred} as well, try \kbd{polred(T, 2)}.)
2195
If we want the reverse, i.e.~to go back from a representation in $\alpha$ to
2196
a representation in $\theta$, we use the function \kbd{modreverse} on this
2197
polmod \kbd{C}. Try it. The result has a big denominator (1029) essentially
2198
because our initial polynomial \kbd{T} was so bad. By the way, to get that
2199
1029,
2200
you should type \kbd{denominator(content(C))}. Trying \kbd{denominator} by
2201
itself would not work since the denominator of a polynomial is defined to be
2202
1 (and its numerator is itself). The reason for this is that we think of a
2203
polynomial as a special case of a rational function.\smallskip
2204
2205
From now on, we forget about \kbd{T}, and use only the polynomial
2206
\kbd{A} defining $\alpha$, and the components of the vector \kbd{nf} which
2207
gives information on our number field $K$. Type
2208
\bprog
2209
u = Mod(x^3 - 5*x^2 - 8*x + 56, A) / 7
2210
@eprog\noindent
2211
This is an element in $K$. There are three equivalent
2212
representations for number field elements: polmod, polynomial, and column
2213
vector giving a decomposition in the integral basis \kbd{nf.zk} (\emph{not} on
2214
the power basis $(1,x,x^2,\dots)$). All three are equally valid when the
2215
number field is understood (is given as first argument to the function).
2216
You will be able to use any one of them as long as the function you call
2217
requires an \kbd{nf} argument as well. However, most PARI functions will
2218
return elements as column vectors. It's an important feature of number
2219
theoretic functions that, although they may have a preferred format for
2220
input, they will accept a wealth of other different formats. We already saw
2221
this for \kbd{nfinit} which accepts either a polynomial or an \kbd{nf}. It
2222
will be true for ideals, congruence subgroups, etc.
2223
2224
Let's stick with elements for the time being. How does one go from one
2225
representation to the other? Between polynomials and polmods, it's easy:
2226
\kbd{lift} and \kbd{Mod} will do the job. Next, from polmods/polynomials to
2227
column vectors: type \kbd{v = nfalgtobasis(nf, u)}. So $\kbd{u} = \alpha^3-
2228
\alpha^2 - \alpha + 8$, right? Wrong! The coordinates of \kbd{u} are given
2229
with respect to the \emph{integral basis}, not the power basis
2230
$(1,\alpha,\alpha^2,\alpha^3)$ (and they don't coincide, type \kbd{nf.zk} if
2231
you forgot what the integral basis looked like). As a polynomial in $\alpha$,
2232
we simply have $\kbd{u} = {1\over7}(\alpha^3 - 5\alpha^2-8\alpha+56)$, which
2233
is trivially deduced from the original polmod representation!
2234
2235
Of course \kbd{v = nfalgtobasis(nf, lift(u))} would work equally well. Indeed
2236
we don't need the polmod information since \kbd{nf} already provides the
2237
defining polynomial. To go back to polmod representation, use
2238
\kbd{nfbasistoalg(nf, v)}. Notice that \kbd{u} is an algebraic integer since
2239
\kbd{v} has integer coordinates (try \kbd{denominator(v) == 1}, which is of
2240
course overkill here, but not so in a program).
2241
2242
Let's try this out. We may for instance compute \kbd{u\pow 3}. Try it. Or, we
2243
can type \kbd{1/u}. Better yet, if we want to know the norm from $K$ to $\Q$
2244
of \kbd{u}, we type \kbd{norm(u)} (what else?); \kbd{trace(u)} works as well.
2245
Notice that none of this would work on polynomials or column vectors since
2246
you don't have the opportunity to supply \kbd{nf}! But we could use
2247
\kbd{nfeltpow(nf,u,3)}, \kbd{nfeltdiv(nf,1,u)} (or \kbd{nfeltpow(nf,u,-1)})
2248
which would work whatever representation was chosen. Of course,
2249
there is also an \kbd{nfeltnorm} function (and \kbd{nfelttrace} as well).
2250
You can also consider $(u)$ as a principal ideal, and just type
2251
\bprog
2252
idealnorm(nf,u)
2253
@eprog\noindent
2254
Of course, in this way, we lose the \emph{sign} information. We will talk
2255
about ideals later on.
2256
2257
If we want all the symmetric functions of \kbd{u} and not only the norm, we
2258
type \kbd{charpoly(u)}. Note that this gives the characteristic polynomial of
2259
\kbd{u}, and not in general the minimal polynomial. We have \kbd{minpoly(u)}
2260
for this.
2261
\misctitle{Exercise} Find a simpler expression for \kbd{u}. \smallskip
2262
2263
Now let's work on the field itself. The \kbd{nfinit} command already
2264
gave us some information. The field is totally complex (its signature
2265
\kbd{nf.sign} is $[0,2]$), its discriminant \kbd{nf.disc} is $18981$ and
2266
\kbd{nf.zk} is an integral basis. The Galois group of its Galois closure
2267
can be obtained by typing \kbd{polgalois(A)}. The answer (\kbd{[8,-1,1]}, or
2268
\kbd{[8,-1,1,"D(4)"]} if the \kbd{galdata} package is installed) shows that
2269
it is equal to $D_4$, the dihedral group with 8 elements, i.e.~the group of
2270
symmetries of a square.
2271
2272
This implies that the field is ``partially Galois'', i.e.~that there exists
2273
at least one nontrivial field isomorphism which fixes $K$, exactly one in
2274
this case. Type \kbd{nfgaloisconj(nf)}. The result tells us that, apart from
2275
the trivial automorphism, the map
2276
$$\alpha \mapsto {1\over7}(-\alpha^3+5\alpha^2+\alpha-49)$$
2277
is the only field automorphism.
2278
\bprog
2279
nfgaloisconj(nf);
2280
s = Mod(%[2], A)
2281
charpoly(s)
2282
@eprog\noindent
2283
and we obtain \kbd{A} once again.
2284
2285
Let us check that \kbd{s} is of order 2: \kbd{subst(lift(s), x, s)}. It is. We
2286
may express it as a matrix:
2287
\bprog
2288
w = Vec( matid(4) ) \\@com canonical basis
2289
v = vector(#w, i, nfgaloisapply(nf, s, w[i]))
2290
M = Mat(v)
2291
@eprog\noindent
2292
The vector \kbd{v} contains the images of the integral basis elements (as
2293
column vectors). The last statement concatenates them into a square matrix.
2294
So, \kbd{M} gives the action of \kbd{s} on the integral basis. Let's check
2295
\kbd{M\pow2}. That's the identity all right.
2296
2297
The fixed field of this automorphism is going to be the only nontrivial
2298
subfield of $K$. I seem to recall that \kbd{polred} told us this was the
2299
third cyclotomic field. Let's check this: type \kbd{nfsubfields(nf)}. Indeed,
2300
there's a quadratic subfield, but it's given by \kbd{T = x\pow 2 + 22*x + 133
2301
} and I don't recognize it. But \kbd{nfisisom(T, polcyclo(3))} indeed tells
2302
us that the fields $\Q[x]/(T)$ and $\Q[x]/(x^2+x+1)$ are isomorphic.
2303
(In fact, \kbd{polred(T)} would tell us the same, but does not correspond to
2304
a foolproof test: \kbd{polred} could have returned some other polynomials.)
2305
2306
We may also check that \kbd{k = matker(M-1)} is two-dimensional, then \kbd{z
2307
= nfbasistoalg(nf, k[,2])} generates the quadratic subfield. Notice that 1,
2308
\kbd{z} and \kbd{u} are $\Q$-linearly dependent, and in fact $\Z$-linearly as
2309
well. Exercise: how would you check these two assertions in general? (Answer:
2310
\kbd{concat}, then respectively \kbd{matrank} or \kbd{matkerint} (or
2311
\kbd{qflll})). \kbd{z = charpoly(z)}, \kbd{z = gcd(z,z')} and \kbd{polred(z)}
2312
tell us that we found back the same subfield again (as we ought to!).
2313
2314
Final check: type \kbd{nfrootsof1(nf)}. Again we find that $K$ contains
2315
a cube root of unity, since the torsion subgroup of its unit group
2316
has order 6. The given generator happens to be equal to \kbd{u}.
2317
2318
\misctitle{Additional comment} (you are no longer supposed to skip this,
2319
but do as you wish):
2320
2321
Before working with ideals, let us note one more thing. The main part of the
2322
work of \kbd{polred} or \kbd{nfinit}$(T)$ is to compute an integral basis,
2323
i.e.~a $\Z$-basis of the maximal order $\Z_K$ of $K$. This implies factoring
2324
the discriminant of the polynomial $T$, which is often not feasible. The
2325
situation may be improved in many ways:
2326
2327
1) First, it is often the case that our number field is of quite a special
2328
type. For example, one may know in advance some prime divisors of the
2329
discriminant. Hence we can ``help'' PARI by giving it that information. More
2330
precisely, we can use the function \kbd{addprimes} to inform PARI to keep on
2331
eye for these prime numbers. Do it only for big primes ! (Say, larger than
2332
\kbd{primelimit}.)
2333
2334
2) The second way in which the situation may be improved is that often we do
2335
not need the complete information on the maximal order, but only require that
2336
the order be $p$-maximal for a certain number of primes $p$ --- but then, we
2337
may not be able to use functions which require a genuine \kbd{nf}. The
2338
function \kbd{nfbasis} specifically computes the integral basis and is not
2339
much quicker than \kbd{nfinit} so is not very useful in its standard use. But
2340
we can optionally provide a list of primes: this returns a basis of an order
2341
which is $p$-maximal at the given primes. For example coming back to our
2342
initial polynomial $T$, the discriminant of the polynomial is
2343
$3^7\cdot7^6\cdot19\cdot37$. If we only want a $7$-maximal order, we simply
2344
type
2345
\bprog
2346
nfbasis([T, [7]])
2347
@eprog\noindent Of course, \kbd{nfbasis([T, [2,3,5,7]])} would return an
2348
order which is maximal at $2,3,5,7$. A variant offers a nice generalization:
2349
\bprog
2350
nfbasis([T, 10^5])
2351
@eprog\noindent will return an order which is maximal at all primes less than
2352
$10^5$.
2353
2354
3) Building on the previous points, \emph{if} the field discriminant is
2355
$y$-smooth (never mind the polynomial discriminant), up to a few big primes
2356
known to \kbd{addprimes}, then \kbd{bas = nfbasis(T, y)} returns a basis for
2357
the maximal order! We can then input the resulting basis to \kbd{nfinit}, as
2358
\kbd{nfinit([T, bas])}. Better: the $[T, \var{listP}]$ format can be
2359
directly used with nfinit, where \var{listP} specifies a finite list of
2360
primes in one of the above ways (explicit list or primes up to some bound),
2361
and the result can be unconditionally certified, independently of the
2362
\var{listP} parameter:
2363
\bprog
2364
T = polcompositum(x^7-2, polcyclo(5))[1];
2365
K = nfinit( [T, [2,5,7]] );
2366
nfcertify(K)
2367
@eprog\noindent The output is a list of composite integers whose complete
2368
factorization must be computed in order to certify the result (which may be
2369
very hard, hence is not done on the spot). When the list is empty, as here,
2370
the result is unconditional
2371
2372
\kbd{nfcertify(nf)}
2373
2374
\subsec{Ideals}
2375
2376
We now want to work with ideals and not only
2377
with elements. An ideal can be represented in many different ways. First, an
2378
element of the field (in any of the various guises seen above) will be
2379
considered as a principal ideal. Then the standard representation is a
2380
square matrix giving the Hermite Normal Form (HNF) of a $\Z$-basis of the
2381
ideal expressed on the integral basis \kbd{nf.zk}. Standard means that most
2382
ideal related functions will use this representation for their output.
2383
2384
Prime ideals can be represented in a special form as well (see
2385
\kbd{idealprimedec}) and all ideal-related functions will accept them. On the
2386
other hand, the function \kbd{idealtwoelt} can be used to find a two-element
2387
$\Z_K$-basis of a given ideal (as $a\Z_K + b\Z_K$, where $a$ and $b$ belong
2388
to $K$), but this is \emph{not} a valid representation for an ideal under
2389
\kbd{gp}, and most functions will choke on it (or worse, take it for
2390
something else and output a meaningless result). To be able to use such an
2391
ideal, you will first have to convert it to HNF form.
2392
2393
Whereas it's very easy to go to HNF form (use \kbd{idealhnf(nf,id)} for valid
2394
ideals, or \kbd{idealhnf(nf,a,b)} for a two-element representation as above),
2395
it's a much more complicated problem to check whether an ideal is principal
2396
and find a generator. In fact an \kbd{nf} does not contain enough data for
2397
this particular task. We'll need a Buchmann Number Field, or \kbd{bnf}, for
2398
that. In particular, we need the class group and fundamental units, at least
2399
in some approximate form. More on this later (which will trivialize the end
2400
of the present section).\smallskip
2401
2402
Let us keep our number field $K$ as above and its \kbd{nf} structure. Type
2403
\bprog
2404
P = idealprimedec(nf,7)
2405
@eprog\noindent
2406
This gives the decomposition of the prime number 7 into prime ideals. We have
2407
chosen 7 because it divides \kbd{nf.index} (in fact, is equal to it), hence
2408
is the most difficult case to treat.
2409
2410
The result is a vector with 4 components, showing that 7 is totally split in
2411
the field $K$ into prime ideals of norm 7 (you can check:
2412
\kbd{idealnorm(nf,P[1])}). Let us take one of these ideals, say the first, so
2413
type
2414
\bprog
2415
pr = P[1]
2416
@eprog
2417
We obtain its inertia and residue degree as \kbd{pr.e}
2418
and \kbd{pr.f}, and its two generators as \kbd{pr.gen}. One of them is
2419
$\kbd{pr.p} = 7$, and the other is guaranteed to have valuation $1$ at
2420
\kbd{pr}. What is the Hermite Normal Form of this ideal? No problem:
2421
\bprog
2422
idealhnf(nf,pr)
2423
@eprog\noindent and we have the desired HNF. Let's now perform ideal
2424
operations. For example type
2425
\bprog
2426
idealmul(nf, pr, idealmul(nf, pr,pr))
2427
@eprog\noindent or more simply
2428
\bprog
2429
pr3 = idealpow(nf, pr,3)
2430
@eprog\noindent
2431
to get the cube of the ideal \kbd{pr}. Since the norm of this ideal is equal
2432
to $343=7^3$, to check that it is really the cube of \kbd{pr} and not of
2433
other ideals above 7, we can type
2434
\bprog
2435
for(i=1, #P, print( idealval(nf, pr3, P[i]) ))
2436
@eprog\noindent
2437
and we see that the valuation at \kbd{pr} is equal to 3, while the others are
2438
equal to zero. We could see this as well from \kbd{idealfactor(nf, pr3)}.
2439
2440
Let us now work in the class group ``by hand'' (we shall see simpler ways
2441
later). We shall work with \emph{extended ideals}: an extended ideal is a pair
2442
\kbd{[A, t]}, where $A$ is an ordinary ideal as above, and $t$ a number field
2443
element; this pair represents the ideal $(t) A$.
2444
\bprog
2445
id3 = [pr3, 1]
2446
r0 = idealred(nf, id3)
2447
@eprog\noindent
2448
The input \kbd{id3} is an extended ideal: pr3 together with 1 (trivial
2449
factorization). The new extended ideal \kbd{r0} is equal to the old one,
2450
in the sense that the products $(t)A$ are the same. It contains a ``reduced''
2451
ideal equivalent to \kbd{pr3} (modulo the principal ideals), and a generator
2452
of the principal ideal that was factored out.
2453
2454
Now, just for fun type
2455
\bprog
2456
r = r0; for(i=1,3, r = idealred(nf,r, [1,5]); print(r))
2457
@eprog\noindent
2458
The ideals in the third \kbd{r} and initial \kbd{r0} are equal, say
2459
$(t) A = (t_0) A$: this means we
2460
have found a unit $(t_0/t)$ in our field, and it is easy to extract this unit
2461
given the extended component:
2462
\bprog
2463
t0 = r0[2]; t = r[2];
2464
u = nfeltdiv(nf, t0, t)
2465
u = nfbasistoalg(nf, u)
2466
@eprog\noindent The last line recovers the unit as an algebraic number.
2467
Type
2468
\bprog
2469
ch = charpoly(u)
2470
@eprog\noindent
2471
and we obtain the characteristic polynomial \kbd{ch} of $u$ again. (Whose
2472
constant coefficient is $1$, hence $u$ is indeed a unit.)
2473
2474
There is of course no reason for $u$ to be a fundamental unit. Let us see if
2475
it is a square. Type
2476
\bprog
2477
F = factor(subst(ch, x, x^2))
2478
@eprog\noindent
2479
We see that \kbd{ch(x\pow2)} is a product of 2 polynomials of degree 4, hence
2480
$u$ is a square. (Why?) We now want to find its square root. A simple method
2481
is as follows:
2482
\bprog
2483
NF = subst(nf,x,y);
2484
r = F[1,1] % (x^2 - nfbasistoalg(NF, u))
2485
@eprog\noindent
2486
to find the remainder of the characteristic polynomial of \kbd{u2} divided by
2487
\kbd{x\pow 2 - $u$}. This is a polynomial of degree 1 in \kbd{x}, with polmod
2488
coefficients, and we know that \kbd{u2}, being a root of both polynomials,
2489
is the root of \kbd{r}, hence can be obtained by typing
2490
\bprog
2491
u2 = -polcoef(r,0) / polcoef(r,1)
2492
@eprog\noindent There is an important technicality in the above: why did we
2493
need to substitute \kbd{NF} to \kbd{nf}? The reason is that data related to
2494
\kbd{nf} is given in terms of the variable \kbd{x}, seen modulo \kbd{nf.pol};
2495
but we need \kbd{x} as a free variable for our polynomial divisions. Hence
2496
the substitution of \kbd{x} by \kbd{y} in our \kbd{nf} data.
2497
2498
The most natural method is to try directly
2499
\bprog
2500
nffactor(nf, y^2 - u)
2501
@eprog\noindent
2502
Except that this won't work for the same technical reason as above: the main
2503
variable of the polynomial to be factored must have \emph{higher} priority
2504
than the number field variable. This won't be possible here since \kbd{nf}
2505
was defined using the variable \kbd{x} which has the highest possible
2506
priority. So we need to substitute variables around:
2507
\bprog
2508
nffactor(NF, x^2 - nfbasistoalg(NF, subst(lift(u),x,y)))
2509
@eprog\noindent
2510
(Of course, with better planning, we would just have defined \kbd{nf} in
2511
terms of the \kbd{'y} variable, to avoid all these substitutions.)
2512
\smallskip
2513
2514
A much simpler approach is to consider the above as instances of a
2515
\emph{discrete logarithm} problem, where we want to express some elements an
2516
abelian group (of finite type) in terms of explicitly given generators, and
2517
transfer all computations from abstract groups like $\text{Cl}(K)$ and
2518
$\Z_K^*$ to products of simpler groups like $\Z^n$ or $\Z/d\Z$. We shall do
2519
exactly that in the next section.
2520
2521
Before that, let us mention another famous (but in fact, simpler)
2522
\emph{discrete logarithm} problem, namely the one attached to the
2523
invertible elements modulo an ideal: $(\Z_K / I)^*$. Just use \kbd{idealstar}
2524
(this is an \kbd{init} function) and \kbd{ideallog}.
2525
2526
Many more functions on ideals are available. We mention here the complete
2527
list, referring to Chapter 3 for detailed explanations:
2528
2529
\kbd{idealadd}, \kbd{idealaddtoone}, \kbd{idealappr}, \kbd{idealchinese},
2530
\kbd{idealcoprime}, \kbd{idealdiv}, \kbd{idealfactor}, \kbd{idealhnf},
2531
\kbd{idealintersect}, \kbd{idealinv}, \kbd{ideallist}, \kbd{ideallog},
2532
\kbd{idealmin}, \kbd{idealmul}, \kbd{idealnorm}, \kbd{idealpow},
2533
\kbd{idealprimedec}, \kbd{idealred},
2534
\kbd{idealstar}, \kbd{idealtwoelt}, \kbd{idealval},
2535
\kbd{nfisideal}.
2536
2537
We suggest you play with these to get a feel for the algebraic number theory
2538
package. Remember that when a matrix (usually in HNF) is output, it is always
2539
a $\Z$-basis of the result expressed on the \emph{integral basis} \kbd{nf.zk}
2540
of the number field, which is usually \emph{not} a power basis.
2541
2542
\subsec{Class Groups and Units, \kbd{bnf}}
2543
2544
Apart from the above functions you have at your disposal the powerful
2545
function \kbd{bnfinit}, which initializes a \kbd{bnf} structure, i.e.~a
2546
number field with all its invariants (including class group and units), and
2547
enough technical data to solve discrete logarithm problems in the class and
2548
unit groups.
2549
2550
First type \kbd{setrand(1)}: this resets the random seed (to make sure we
2551
and you get the exact same results). Now type
2552
\bprog
2553
bnf = bnfinit(NF);
2554
@eprog\noindent
2555
where \kbd{NF} is the same number field as before. You do not want to see the
2556
output clutter a number of screens so don't forget the semi-colon. (Well if
2557
you insist, it is about three screenful in this case, but may require several
2558
Megabytes for larger degrees.) Note that \kbd{NF} is now expressed in terms
2559
of the variable \kbd{y}, to avoid later problems with variable priorities.
2560
2561
A word of warning: both the \kbd{bnf} and all results obtained from it are
2562
\emph{conditional} on a Riemann Hypothesis at this point; the \kbd{bnf} must
2563
be certified before the following statements become actual theorems.
2564
\smallskip
2565
2566
Member functions are still available for \kbd{bnf} structures. So, let's try
2567
them: \kbd{bnf.pol} gives \kbd{A}, \kbd{bnf.sign}, \kbd{bnf.disc},
2568
\kbd{bnf.zk}, ok nothing really exciting. In fact, an \kbd{nf} is included
2569
in the \kbd{bnf} structure: \kbd{bnf.nf} should be identical to
2570
\kbd{NF}. Thus, all functions which took an \kbd{nf} as first argument, will
2571
equally accept a \kbd{bnf} (and a \kbd{bnr} as well which contains even more
2572
data).
2573
2574
Anyway, new members are available now: \kbd{bnf.no} tells us the class number
2575
is 4, \kbd{bnf.cyc} that it is cyclic (of order 4 but that we already knew),
2576
\kbd{bnf.gen} that it is generated by the ideal \kbd{g = bnf.gen[1]}. If you
2577
\kbd{idealfactor(bnf, g)}, you recognize \kbd{P[2]}. (You may also play in
2578
the other direction with \kbd{idealhnf}.) The regulator \kbd{bnf.reg} is
2579
equal to $3.794\dots$. \kbd{bnf.tu} tells us that the roots of unity in $K$
2580
are exactly the sixth roots of 1 and gives a primitive root $\zeta =
2581
{1\over7}(\alpha^3 - 5\alpha^2 - 8\alpha + 56)$, which we have seen already.
2582
Finally \kbd{bnf.fu} gives us a fundamental unit $\epsilon =
2583
{1\over7}(\alpha^3 - 5\alpha^2 - \alpha + 28)$, which must be linked to the
2584
units \kbd{u} and \kbd{u2} found above since the unit rank is~1. To find
2585
these relations, type
2586
\bprog
2587
bnfisunit(bnf, u)
2588
bnfisunit(bnf, u2)
2589
@eprog\noindent
2590
Lo and behold, \kbd{u = $\zeta^2\epsilon^2$} and \kbd{u2 =
2591
$\zeta^{4}\epsilon^1$}.
2592
2593
\misctitle{Note} Since the fundamental unit obtained depends on the random
2594
seed, you could have obtained another unit than $\epsilon$, had you not reset
2595
the random seed before the computation. This was the purpose of the initial
2596
\kbd{setrand} instruction, which was otherwise unnecessary.\medskip
2597
2598
We are now ready to perform operations in the class group. First and
2599
foremost, let us certify the result: type \kbd{bnfcertify(bnf)}. The
2600
output is \kbd{1} if all went well; in fact no other output is possible,
2601
whether the input is correct or not, but you can get an error message (or in
2602
exceedingly rare cases an infinite loop) if it is incorrect.
2603
2604
It means that we now know the class group and fundamental units
2605
unconditionally (no more GRH then!). In this case, the certification process
2606
takes a very short time, and you might wonder why it is not built in as a
2607
final check in the \kbd{bnfinit} function. The answer is that as the
2608
regulator gets bigger this process gets increasingly difficult, and becomes
2609
soon impractical, while \kbd{bnfinit} still happily spits out results. So it
2610
makes sense to dissociate the two: you can always check afterwards, if the
2611
result is interesting enough. Looking at the tentative regulator, you know in
2612
advance whether the certification can possibly succeed: if \kbd{bnf.reg} is
2613
large, don't waste your time.
2614
2615
2616
Now that we feel safe about the \kbd{bnf} output, let's do some real work.
2617
For example, let us take again our prime ideal \kbd{pr} above 7. Since we
2618
know that the class group is of order 4, we deduce that \kbd{pr} raised to
2619
the fourth power must be principal. Type
2620
\bprog
2621
pr4 = idealpow(nf, pr, 4)
2622
v = bnfisprincipal(bnf, pr4)
2623
@eprog\noindent
2624
The first component gives the factorization of the ideal in the class group.
2625
Here, \kbd{[0]} means that it is up to equivalence equal to the 0-th power of
2626
the generator \kbd{g} given in \kbd{bnf.gen}, in other words that it is a
2627
principal ideal. The second component gives us the algebraic number $\alpha$
2628
such that $\kbd{pr4}=\alpha\Z_K$, $\alpha$ being as usual expressed on the
2629
integral basis. Type \kbd{alpha = v[2]}. Let us check that the result is
2630
correct: first, type \kbd{idealnorm(bnf, alpha)}. (Note that we can use a
2631
\kbd{bnf} with all the \kbd{nf} functions; but not the other way round, of
2632
course.) It is indeed equal to $7^4 = 2401$, which is the norm of \kbd{pr4}.
2633
This is only a first check. The complete check is obtained by computing the
2634
HNF of the principal ideal generated by \kbd{alpha}. To do this, type
2635
\kbd{idealhnf(bnf, alpha) == pr4}.
2636
2637
Since the equality is true, \kbd{alpha} is correct (not that there was any
2638
doubt!). But \kbd{bnfisprincipal} also gives us information for nonprincipal
2639
ideals. For example, type
2640
\bprog
2641
v = bnfisprincipal(bnf, pr)
2642
@eprog\noindent
2643
The component \kbd{v[1]} is now equal to \kbd{[3]}, and tells us that \kbd{pr}
2644
is ideal-equivalent to the cube of the generator \kbd{g}. Of course we
2645
already knew this since the product of \kbd{P[3]} and \kbd{P[4]} was
2646
principal (generated by \kbd{al}), as well as the product of all the
2647
\kbd{P[$i$]} (generated by 7), and we noticed that \kbd{P[2]} was equal
2648
to \kbd{g}, which has order 4. The second component \kbd{v[2]} gives us
2649
$\alpha$ on the integral basis such that $\kbd{pr}=\alpha \kbd{g}^3$. Note
2650
that if you \emph{don't} want this $\alpha$, which may be large and whose
2651
computation may take some time, you can just add the flag $1$ (see the online
2652
help) to the arguments of \kbd{bnfisprincipal}, so that it only returns the
2653
position of \kbd{pr} in the class group. \smallskip
2654
2655
\subsec{Class Field Theory, \kbd{bnr}}
2656
2657
We now survey quickly some class field theoretic routines. We must first
2658
initialize a Buchmann Number Ray, or \kbd{bnr}, structure, attached to a
2659
\kbd{bnf} base field and a modulus. Let's keep $K$, and try a finite modulus
2660
${\goth f} = 7\Z_K$. (See the manual for how to include infinite places in
2661
the modulus.) Since $K$ will now become a base field over which we want to
2662
build relative extensions, the attached \kbd{bnf} needs to have variables
2663
of lower priority than the polynomials defining the extensions. Fortunately,
2664
we already took care that, but it would have been easy to deal with the
2665
problem now (as easy as \kbd{bnf = subst(bnf, x, y)}). Then type
2666
\bprog
2667
bnr = bnrinit(bnf, 7, 1);
2668
bnr.cyc
2669
@eprog\noindent
2670
tells us the ray class group modulo ${\goth f}$ is isomorphic to
2671
$\Z/24\Z \times \Z/6\Z \times \Z/2\Z $. The attached generators are
2672
\kbd{bnr.gen}. Just as a \kbd{bnf} contained an \kbd{nf}, a \kbd{bnr}
2673
contains a \kbd{bnf} (hence an \kbd{nf}), namely \kbd{bnr.bnf}. Here
2674
\kbd{bnr.clgp} refers to the ray class group, while \kbd{bnr.bnf.clgp} refers
2675
to the class group.
2676
\bprog
2677
rnfkummer(bnr,, 2)
2678
rnfkummer(bnr,, 3)
2679
@eprog\noindent
2680
outputs defining polynomials for the $2$ abelian extensions of $K$ of degree
2681
$2$ (resp.~$3$), whose conductor is exactly equal to ${\goth f}$ (the modulus
2682
used to define \kbd{bnr}). (In the current implementation of \kbd{rnfkummer},
2683
these degrees must be \emph{prime}.) What about other extensions of degree
2684
$2$ for instance?
2685
\bprog
2686
L0= subgrouplist(bnr, [2])
2687
L = subgrouplist(bnr, [2], 1)
2688
@eprog\noindent
2689
\kbd{L0}, resp.~\kbd{L} is the list of those subgroups of the full ray class
2690
group mod $7$, whose index is $2$, and whose conductor is $7$,
2691
resp.~arbitrary. (Subgroups are given by a matrix of generators, in terms of
2692
\kbd{bnr.gen}.) \kbd{L0} has $2$ elements, attached to the $2$ extensions
2693
we already know. \kbd{L} has $7$ elements, the $2$ from \kbd{L0}, and
2694
$5$ new ones:
2695
\bprog
2696
L1 = setminus(Set(L), Set(L0))
2697
@eprog\noindent
2698
The conductors are
2699
\bprog
2700
vector(#L1, i, bnrconductor(bnr, L1[i]))
2701
@eprog\noindent
2702
among which one sees the identity matrix, i.e. the trivial ideal. (It is
2703
\kbd{L1[3]} in my session, maybe not in yours. Take the right one!) Indeed,
2704
the class group was cyclic of order $4$ and there exists a unique unramified
2705
quadratic extension. We could find it directly by recomputing a \kbd{bnr}
2706
with trivial conductor, but we can also use
2707
\bprog
2708
rnfkummer(bnr, L1[3]) \\ @com pick the subgroup with trivial conductor!
2709
@eprog\noindent
2710
directly which outputs the (unique by Takagi's theorem) class field
2711
attached to the subgroup \kbd{L1[3]}. In fact, it is of the form
2712
$K(\sqrt{-\epsilon})$. We can check this directly:
2713
\bprog
2714
rnfconductor(bnf, x^2 + bnf.fu[1])
2715
@eprog\noindent
2716
2717
\subsec{Galois Theory over $\Q$}
2718
2719
PARI includes a nearly complete set of routines to compute with Galois
2720
extensions of $\Q$. We start with a very simple example.
2721
Let $\zeta$ a $8$th-root of unity and $K=\Q(\zeta)$. The minimal
2722
polynomial of $\zeta$ is the 8$th$ cyclotomic polynomial, namely
2723
\kbd{polcyclo(8)} (=$x^4+1$).
2724
2725
We issue the command
2726
\bprog
2727
G = galoisinit(x^4 + 1);
2728
@eprog\noindent
2729
to compute $G=\text{Gal}(K/\Q)$. The command \kbd{galoisisabelian(G)}
2730
returns \kbd{[2,0;0,2]} so $G$ is an abelian group, isomorphic to $(\Z/2\Z)^2$, generated by
2731
$\sigma$=\kbd{G.gen[1]} and $\tau$=\kbd{G.gen[2]}. These automorphisms are
2732
given by their actions on the roots of $x^4+1$ in a suitable $p$-adic
2733
extension. To get the explicit action on $\zeta$, we use
2734
\kbd{galoispermtopol(G,G.gen[i])} for $i=1,2$ and get $\sigma(\zeta)=-\zeta$
2735
and $\tau(\zeta)=\zeta^3$. The last nontrivial automorphism is
2736
$\sigma\tau$=\kbd{G.gen[1]*G.gen[2]} and we have
2737
$\sigma\tau(\zeta)=-\zeta^3$. (At least in my version, yours may return a
2738
different set of generators, rename accordingly.)
2739
2740
We compute the fixed field of $K$ by the subgroup generated by $\tau$ with
2741
\bprog
2742
galoisfixedfield(G, G.gen[2], 1)
2743
@eprog\noindent
2744
and get $x^2 + 2$. Now we want the factorization of $x^4+1$ over that
2745
subfield. Of course, we could use \kbd{nffactor}, but here we have a much
2746
simpler option: \kbd{galoisfixedfield(G, G.gen[1], 2)} outputs
2747
\bprog
2748
[x^2 + 2, Mod(x^3 + x, x^4 + 1), [x^2 - y*x - 1, x^2 + y*x - 1]]
2749
@eprog\noindent
2750
which means that
2751
$x^4+1=(x^2-\alpha\*x-1)(x^2+\alpha\*x-1)$ where $\alpha$ is a root of $x^2+2$,
2752
and more precisely, $\alpha=\zeta^3+\zeta$. So we recover the well-known
2753
factorization:
2754
2755
$$x^4+1=(x^2-\sqrt{-2}\*x-1)(x^2+\sqrt{-2}\*x-1)$$
2756
2757
For our second example, let us take the field $K$ defined by the polynomial
2758
\bprog
2759
P = x^18 - 3*x^15 + 115*x^12 + 104*x^9 + 511*x^6 + 196*x^3 + 343;
2760
G = galoisinit(P);
2761
@eprog\noindent Since \kbd{galoisinit} succeeds,
2762
the extension $K/\Q$ is Galois. This time \kbd{galoisisabelian(G)} returns
2763
$0$, so the extension is not abelian; however we can still put a name on the
2764
underlying abstract group. Use \kbd{galoisidentify(G)}, which returns $[18,
2765
3]$. By looking at the GAP4 classification we find that $[18, 3]$ is
2766
$S_3\times\Z/3\Z$. This time, the subgroups of $G$ are not obvious,
2767
fortunately we can ask PARI : \kbd{galoissubgroups(G)}.
2768
2769
Let us look for a polynomial $Q$ with the property that $K$ is the splitting
2770
field of $Q(x^2)$. For that purpose, let us take $\sigma$=\kbd{G.gen[3]}. We
2771
check that \kbd{G.gen[3]\^{}2} is the identity, so $\sigma$ is of order $2$. We now compute the fixed field $K^\sigma$ and the relative factorization of $P$ over
2772
$K^\sigma$:
2773
\bprog
2774
F = galoisfixedfield(G, G.gen[3], 2);
2775
@eprog\noindent
2776
So $K$ is a quadratic extension of $K^\sigma$ defined by the polynomial
2777
\kbd{R=F[3][1]}. It is well-known that $K$ is also defined by $x^2-D$,
2778
where $D$ is the discriminant of $R$ (over $K^\sigma$).
2779
To compute $D$, we issue:
2780
\bprog
2781
D = poldisc(F[3][1]) * Mod(1,subst(F[1],x,y));
2782
@eprog\noindent
2783
Note that since \kbd{y} in \kbd{F[3][1]} denotes a root of \kbd{F[1]}, we
2784
have to use \kbd{subst(,x,y)}. Now we hope that $D$ generates $K^\sigma$ and
2785
compute \kbd{Q=charpoly(D)}. We check that $Q=x^9+270\*x^6+12393\*x^3+19683$ is
2786
irreducible with \kbd{polisirreducible(Q)}. (Were it not the case, we would
2787
multiply $D$ by a random square.) So $D$ is a generator of $K^\sigma$ and
2788
$\sqrt{D}$ is a generator of $K$. The result is that $K$ is the splitting
2789
field of $Q(x^2)$. We can check that with
2790
\kbd{nfisisom(P,subst(Q,x,x\^{}2))}.
2791
2792
\subsec{Creating and Listing Number Fields}
2793
2794
Suppose you want to work with cyclic quartic fields (i.e., fields with
2795
Galois group $C_4=\Z/4\Z$ over $\Q$): you could look in a database or in
2796
a book for examples, but PARI provides the simple but powerful \kbd{nflist}
2797
command: in this case you could simply write \kbd{V = nflist("C4")},
2798
which would immediately return a list of polynomials (in the present case
2799
$18$, in some random order) defining cyclic quartic fields. Note that these
2800
polynomials are usually not the simplest, you can for instance do
2801
\kbd{V = apply(polredabs, V)} to reduce them.
2802
2803
Using \kbd{vecmax(apply(z->abs(nfdisc(z)),V))}, you can check that the largest
2804
discriminant is $35152$. Thus, if you only want discriminants up to $10000$
2805
you would write \kbd{V = nflist("C4", [1, 10000])}, which would now output only
2806
$10$ number fields. Or if you want only fields with absolute discriminant
2807
exactly equal to $8000$, you would write \kbd{V = nflist("C4", 8000)}, which
2808
would output the two polynomials $x^4\pm10x^2+20$, which define non-isomorphic
2809
number fields (using \kbd{polsturm}, you can check that one is totally real,
2810
the other totally complex). Finally, if you only want $C_4$-fields with a
2811
given number \kbd{s} of complex places, you would write \kbd{nflist("C4",,s)}
2812
(don't forget the two consecutive commas, since the second argument is the
2813
discriminant range), for instance:
2814
2815
\bprog
2816
for(s = 0, 2, print1([s, #nflist("C4", , s)]," "))
2817
@eprog\noindent
2818
would output \kbd{[0, 10] [1, 0], [2, 10]}, so \kbd{nflist} gives you
2819
$10$ totally real and $10$ totally complex cyclic quartic fields, but none
2820
with mixed signature $(2,1)$, which is a good thing since they do not exist!
2821
2822
Of course you can ask for many more: for instance in a few seconds
2823
\bprog apply(length, #nflist("C4", [1, 10^14], -2))@eprog
2824
\noindent will return
2825
\kbd{[607589, 0, 607609]}, which tells you that there are $607589$ totally
2826
real and $607609$ totally complex cyclic quartic fields with absolute
2827
discriminant up to $10^{14}$: this illustrates the special use of the
2828
parameter $s=-2$, which separates the number fields by increasing number of
2829
complex places (the default is $s=-1$ which ignores the signature altogether).
2830
2831
\smallskip
2832
2833
Of course, \kbd{nflist} applies to many other Galois groups than $C_4$
2834
(where ``Galois group'' is understood as Galois group of the Galois closure,
2835
see below), but before leaving cyclic quartic fields, let us see two more
2836
related instructions. Starting again with \kbd{V = nflist("C4")}, write
2837
\kbd{R = apply(nfresolvent, V)}: this outputs a list of $18$ quadratic
2838
polynomials, which define the unique quadratic subfield of each quartic
2839
field. In the present example, the \kbd{nfsubfields} command
2840
(more precisely \kbd{R = apply(z -> polredabs(nfsubfields(z, 2, 1)[1]), V)})
2841
would have given an identical result, but the purpose of \kbd{nfresolvent}
2842
is different. First, for many Galois groups, it really outputs what one usually
2843
calls the resolvent polynomial, for instance a quadratic polynomial for
2844
an $S_3$ field, a cubic for a non-Galois quartic, etc... Second, as here,
2845
the fields are often constructed as extensions of subfields, and
2846
\kbd{nfresolvent} gives the subfield on which the field has been constructed.
2847
Better, typing \kbd{nfresolvent(V[1], 1)} outputs
2848
\kbd{[x\^{}2 - x - 1, [[5, 2; 0, 1], [1, 1]]]}, which not only gives the
2849
subfield, but the relative conductor as a \kbd{module} (a pair ideal,
2850
list of real places).
2851
2852
The second instruction is \kbd{polsubcyclo}, which has existed for a long time
2853
in PARI. The manual states that \kbd{polsubcyclo(n,d)} gives the subfields
2854
of degree $d$ of $\Q(\zeta_n)$. However, if $n$ is very large, previous
2855
versions would take an inordinate amount of time. The present version
2856
allows us to take $n$ very large, but the price to pay is that the degree
2857
$d$ of the desired subfields must be very small, for instance $d\le30$,
2858
and in addition must be a prime number if $d\ge7$. For instance:
2859
2860
\bprog
2861
? p = 10^16 + 649759; /* A prime chosen so that p = 1 mod 11*19*29*41
2862
? polsubcyclo(p, 11);
2863
time = 42 ms. /* Would have been impossible in previous versions */
2864
? polsubcyclo(p, 19);
2865
time = 348 ms.
2866
? polsubcyclo(p, 29);
2867
time = 10,304 ms. /* Still reasonable */
2868
? polsubcyclo(p, 41);
2869
time = 6min, 43,181 ms. /* Slow but feasible. */
2870
@eprog
2871
2872
\medskip
2873
2874
The most common Galois groups corresponding to number fields of small
2875
degree have been implemented: all solvable groups up to degree $7$
2876
(there are $13$ in degree $6$ for instance), the groups $C_{\ell}$ and
2877
$D_{\ell}$ for $\ell$ prime. In addition, the simple group $A_5$ has also
2878
been included, but by cheating since it is obtained by table lookup
2879
(and available only of you have downloaded and installed the
2880
\kbd{nflistdata} package), in particular because of its relation with
2881
modular forms of weight $1$.
2882
2883
\section{Working with Associative Algebras}
2884
2885
Beyond the realm of number fields, we can perform operations with more
2886
general associative algebras, that need not even be commutative! Of course
2887
things become more complicated. We have two different structures: the first
2888
one allows us to manipulate any associative algebra that is
2889
finite-dimensional over a prime field ($\Q$ or $\F_p$ for some prime~$p$),
2890
and the second one is dedicated to central simple algebras over number
2891
fields, which are some nice algebras that behave a lot like number fields.
2892
Like in other parts of~\kbd{gp}, every function that has to do with
2893
associative algebras begins with the same prefix:~\kbd{alg}.
2894
2895
\subsec{Arbitrary Associative Algebras}
2896
2897
In order to create an associative algebra, you need to tell~\kbd{gp} how to
2898
multiply elements. We do this by providing a \emph{multiplication table} for the
2899
algebra, in the form of the matrix of left multiplication by each basis element,
2900
and use the function~\kbd{algtableinit}.
2901
2902
For instance, let us work in~$\F_3[x]/(x^2)$. Of course, we
2903
could use polmods of intmods to represent elements in this algebra, but let's
2904
introduce the general mechanism with this simple example!
2905
This algebra has a basis with two elements:~$1$
2906
and~$\epsilon$, the image of~$x$ in the quotient. By the way,~\kbd{gp} will
2907
only accept your multiplication table if the first basis vector is~$1$. The
2908
multiplication matrix of~$1$ is the~$2\times 2$ identity matrix, and
2909
since~$\epsilon\cdot 1 = \epsilon$ and~$\epsilon\cdot\epsilon = 0$, the left
2910
multiplication table of~$\epsilon$ is~$\pmatrix{0 & 0 \cr 1 & 0}$. So we
2911
use the following multiplication table:
2912
\bprog
2913
mt1 = [matid(2), [0,0;1,0]]
2914
@eprog\noindent
2915
Since
2916
we want our algebra to be over~$\F_3$, we have to specify the characteristic
2917
and create the algebra with
2918
\bprog
2919
al1 = algtableinit(mt1, 3);
2920
@eprog\noindent
2921
Let's create another one: the algebra of upper-triangular~$2\times 2$
2922
matrices over~$\Q$. This algebra has dimension~$3$, with basis~$1$, $a =
2923
\pmatrix{0 & 1 \cr 0 & 0}$ and~$b = \pmatrix{0 & 0 \cr 0 & 1}$, and these
2924
elements satisfy~$a^2=0$, $ab = a$, $ba=0$ and~$b^2=b$. Watch out, even
2925
though~$a$ and~$b$ are~$2\times 2$ matrices, their left multiplication tables
2926
are~$3\times 3$ matrices! The left multiplication tables of~$a$
2927
and~$b$ are respectively
2928
\bprog
2929
ma = [0,0,0; 1,0,1; 0,0,0];
2930
mb = [0,0,0; 0,0,0; 1,0,1];
2931
@eprog\noindent
2932
The multiplication table of our second algebra is therefore
2933
\bprog
2934
mt2 = [matid(3), ma, mb];
2935
@eprog\noindent
2936
and we can create the algebra with
2937
\bprog
2938
al2 = algtableinit(mt2,0);
2939
@eprog\noindent
2940
In fact, we can omit the second argument and type
2941
\bprog
2942
al2 = algtableinit(mt2);
2943
@eprog\noindent
2944
and the
2945
characteristic of the algebra will implicitly be~$0$. Warning: in
2946
characteristic~$0$, \kbd{algtableinit} expects an integral multiplication table.
2947
2948
In fact, \kbd{gp} does not check that the multiplication table you provided
2949
really defines an associative algebra. You can check it a posteriori
2950
with
2951
\bprog
2952
algisassociative(al2)
2953
@eprog\noindent
2954
or before creating the algebra
2955
with
2956
\bprog
2957
algisassociative(mt1,3)
2958
@eprog\noindent
2959
After creating the algebra, you can get back the
2960
multiplication table that you provided with~\kbd{algmultable(al2)}, the
2961
characteristic with~\kbd{algchar(al1)} and the dimension with~\kbd{algdim(al2)}.
2962
2963
\subsubsec{Elements}
2964
2965
In an associative algebra, we represent elements as column vectors expressing them
2966
on the basis of the algebra. For instance, in~\kbd{al1} $=\F_3[\epsilon]$, the
2967
element~$1-\epsilon$ is represented as~\kbd{[1,-1]\til}. Similarly, in~\kbd{al2}
2968
we can define~$a$, $b$ and~$c = \pmatrix{2 & 1\cr 0 & 1}$ by
2969
\bprog
2970
a = [0,1,0]~
2971
b = [0,0,1]~
2972
c = [2,1,-1]~
2973
@eprog\noindent
2974
We can also draw random elements in a box using
2975
\bprog
2976
algrandom(al2, 10)
2977
@eprog\noindent
2978
You can compute any elementary operation: try various combinations
2979
of~\kbd{algadd}, \kbd{algsub}, \kbd{algneg}, \kbd{algmul}, \kbd{alginv},
2980
\kbd{algsqr}, \kbd{algpow}, using the syntax
2981
\bprog
2982
algmul(al2, b, a)
2983
algpow(al2, c, 10)
2984
@eprog\noindent
2985
and the natural variants. In every algebra we have the left regular
2986
representation, which sends every element~$x$ to the matrix of left
2987
multiplication by~$x$. In~\kbd{gp} we access it by calling
2988
\bprog
2989
algtomatrix(al2, c)
2990
@eprog\noindent
2991
For every element~$x$ in an associative algebra, the trace of that matrix is
2992
called the \emph{trace} of~$x$, the determinant is called the \emph{norm}
2993
of~$x$, and the characteristic polynomial is called the \emph{characteristic
2994
polynomial} of~$x$. We can compute them:
2995
\bprog
2996
algtrace(al2, a)
2997
algnorm(al2, c)
2998
algcharpoly(al2, b)
2999
@eprog
3000
3001
\subsubsec{Properties}
3002
3003
Now let's try to compute some interesting properties of our algebras. Maybe the
3004
simplest one we want to test is whether an algebra is commutative;
3005
\kbd{algiscommutative} does that for us: you can use it to check that~\kbd{al1}
3006
is of course commutative, but~\kbd{al2} is not since for instance~$ab=a\neq 0 =
3007
ba$. More precisely, we can compute a basis of the center of an algebra
3008
with~\kbd{algcenter}. Since~\kbd{al1} is commutative, we obtain the identity
3009
matrix, and
3010
\bprog
3011
algcenter(al2)
3012
@eprog\noindent
3013
tells us that the center of~\kbd{al2} is
3014
one-dimensional and generated by the identity.
3015
3016
An important object in the structure of associative algebras is the
3017
\emph{Jacobson radical}: the set of elements that annihilate every simple left
3018
module. It is a nilpotent two-sided ideal. An algebra is \emph{semisimple} if
3019
its Jacobson radical is zero, and for every algebra~$A$ with radical~$J$, the
3020
quotient~$A/J$ is semisimple. You can compute a basis for the Jacobson radical
3021
using~\kbd{algradical}. For instance, the radical of~\kbd{al1} is generated by
3022
the element~$\epsilon$. Indeed, in a commutative algebra the Jacobson
3023
radical is equal to the set of nilpotent elements. The radical of~\kbd{al2} has
3024
basis~$a$: it is the subspace of strictly upper-triangular~$2\times 2$ matrices.
3025
You can also directly test whether an algebra is semisimple
3026
using~\kbd{algissemisimple}. Let's compute the semisimplification of our
3027
second algebra by quotienting out its radical:
3028
\bprog
3029
al3 = algquotient(al2, algradical(al2));
3030
@eprog\noindent
3031
Check that~\kbd{al3} is indeed semisimple now that you know how to do it!
3032
3033
Group algebras provide interesting examples: when~$G$ is a finite group and~$F$
3034
is a field, the group algebra~$F[G]$ is semisimple if and only if the
3035
characteristic of~$F$ does not divide the order of~$G$. Let's try it!
3036
3037
\bprog
3038
K = nfsplitting(x^3-x+1); \\ Galois closure -> S_3
3039
G = galoisinit(K)
3040
al4 = alggroup(G, 5) \\ F_5[S_3]
3041
algissemisimple(al4)
3042
@eprog\noindent
3043
Check what happens when you change the characteristic of the algebra.
3044
3045
The building blocks of semisimple algebras are \emph{simple} algebras:
3046
algebras with no nontrivial two-sided ideals. Since the Jacobson radical is a
3047
two-sided ideal, every simple algebra is semisimple. You can check whether an
3048
algebra is simple using~\kbd{algissimple}. For instance, you can check that
3049
\bprog
3050
algissimple(al1)
3051
@eprog\noindent
3052
returns~\kbd{0}, but this is not very interesting since~\kbd{al1} is not even
3053
semisimple. Instead we can test whether~\kbd{al3} is simple, and since we
3054
already know that it is semisimple we can prevent~\kbd{gp} from checking it
3055
again by using the optional second argument:
3056
\bprog
3057
algissimple(al3, 1)
3058
@eprog\noindent
3059
We see that~\kbd{al3} is not simple, and this implies that we can decompose it
3060
further. Indeed, every semisimple algebra is isomorphic to a product of simple algebras.
3061
We can obtain this decomposition with
3062
\bprog
3063
dec3 = algsimpledec(al3)[2];
3064
apply(algdim, dec3)
3065
@eprog\noindent
3066
We see that~\kbd{al3} is isomorphic to~$\Q\times\Q$. Similarly, we can
3067
decompose~\kbd{al4}.
3068
\bprog
3069
dec4 = algsimpledec(al4)[2];
3070
apply(algdim, dec4)
3071
@eprog\noindent
3072
We see that~\kbd{al4} is isomorphic to~$\F_5\times\F_5\times A$ where~$A$ is a
3073
mysterious 4-dimensional simple algebra. However every simple algebra over a
3074
finite field is isomorphic to a matrix algebra over a possibly larger finite
3075
field. By computing the center
3076
\bprog
3077
algcenter(dec4[3])
3078
@eprog\noindent
3079
we see that this algebra has center~$\F_5$, so that~\kbd{al4} is isomorphic
3080
to~$\F_5\times\F_5\times M_2(\F_5)$.
3081
3082
\subsec{Central Simple Algebras over Number Fields}
3083
3084
As we saw, simple algebras are building blocks for more complicated algebras.
3085
The center of a simple algebra is always a field, and we say that an
3086
algebra over a field~$F$ is \emph{central} if its center is~$F$. The most
3087
natural noncommutative generalization of a number field is a \emph{division
3088
algebra} over~$\Q$: an algebra in which every nonzero element is invertible.
3089
Since the center of a division algebra over~$\Q$ is a number field, we do not
3090
lose any generality by considering central division algebras over number
3091
fields. However, the tensor product of two central division algebras is not
3092
always a division algebra, but division algebras are always simple and central
3093
simple algebras are closed under tensor products, giving a much nicer global
3094
picture. This is why we choose central simple algebras over number fields as our
3095
noncommutative generalization of number fields.
3096
3097
\subsubsec{Creation}
3098
3099
Let's create our first central simple algebras! A well-known construction is
3100
that of \emph{quaternion algebras}, which proceeds as follows.
3101
Let~$F$ be a number field, and let~$a,b\in F^\times$; the quaternion
3102
algebra~$(a,b)_F$ is the $F$-algebra generated by two elements~$i$ and~$j$
3103
satisfying~$i^2=a$, $j^2=b$ and~$ij=-ji$. Hamilton's quaternions
3104
correspond to the choice~$a=b=-1$, but it is not the only possible
3105
one! Here is our first quaternion algebra:
3106
\bprog
3107
Q = nfinit(y);
3108
al1 = alginit(Q,[-2,-1]); \\ (-2,-1)_Q
3109
@eprog\noindent
3110
Note that we represented the rationals~$\Q$ with an~\kbd{nf} structure and used
3111
the variable~$y$ in that structure. The reason for this variable choice will
3112
be clearer after looking at the next construction. You can see from the
3113
definition of a quaternion algebra that it has dimension~$4$ over its center, a
3114
fact that you can check in our example:
3115
\bprog
3116
algdim(al1)
3117
@eprog\noindent
3118
Cyclic algebras generalize the quaternion algebra construction.
3119
Let~$F$ be a number field and~$K/F$ a cyclic extension of degree~$d$
3120
with~$\sigma\in\text{Gal}(K/F)$ an automorphism of order~$d$, and let~$b\in
3121
F^\times$; the \emph{cyclic algebra}~$(K/F,\sigma,b)$ is the
3122
algebra~$\bigoplus_{i=0}^{d-1}u^iK$ with~$u^d=b$ and~$k u = u \sigma(k)$
3123
for all~$k\in K$. It is a central simple algebra of dimension~$d^2$ over~$F$.
3124
Let's construct one. First, start with a cyclic extension of number fields. A
3125
simple way of obtaining such an extension is to take a cyclotomic field
3126
over~$\Q$.
3127
\bprog
3128
T = polcyclo(5)
3129
K = rnfinit(Q,T);
3130
aut = Mod(x^2,T)
3131
@eprog\noindent
3132
Here the variable of~\kbd{T} must have higher priority than that of~\kbd{Q} to
3133
build the~\kbd{rnf} structure. Now choose an element~$b\in\Q^\times$, say~$3$.
3134
\bprog
3135
b = 3
3136
@eprog\noindent
3137
Now we can create the algebra and check that it has the right dimension:~$16$.
3138
\bprog
3139
al2 = alginit(K, [aut,b]);
3140
algdim(al2)
3141
@eprog\noindent
3142
We can recover the field~\kbd{K}, the automorphism~\kbd{aut} and the
3143
element~\kbd{b} respectively as follows.
3144
\bprog
3145
algsplittingfield(al2)
3146
algaut(al2)
3147
algb(al2)
3148
@eprog\noindent
3149
In order to see how we recover quaternion algebras with this construction, let's
3150
look at
3151
\bprog
3152
algsplittingfield(al1).pol
3153
algaut(al1)
3154
algb(al1)
3155
@eprog\noindent
3156
We see that the quaternion algebra~$(-2,-1)_{\Q}$ constructed by~\kbd{gp} is
3157
represented as a cyclic algebra~$(\Q(\sqrt{-2})/\Q, \sigma, -1)$ by
3158
writing~$\Q+\Q i+\Q j+\Q ij = \Q(i) + j\Q(i)$.
3159
3160
A nice feature of central simple algebras over a given number field is that they
3161
are completely classified up to isomorphism, in terms of certain invariants. We
3162
therefore provide functions to create an algebra directly from its invariants.
3163
The first basic invariant is the dimension of the algebra over its center.
3164
In fact, the
3165
dimension of a central simple algebra is always a square, and we call the square
3166
root of the dimension the \emph{degree} of the algebra. For instance, a
3167
quaternion algebra has degree~$2$. We can access the degree with
3168
\bprog
3169
algdegree(al1)
3170
algdegree(al2)
3171
@eprog\noindent
3172
Let~$F$ be a number field and~$A$ a central simple algebra of degree~$d$
3173
over~$F$. To every place~$v$ of~$F$ we can attach a \emph{Hasse invariant}
3174
$h_v(A)\in(\dfrac{1}{d}\Z)/\Z\subset\Q/\Z$, with
3175
the additional restrictions that the invariant is~$0$ at every complex place and
3176
in~$(\dfrac{1}{2}\Z)/\Z$ at every real place. These
3177
invariants are~$0$ at all but finitely many places. For instance we can compute
3178
the invariants for our algebras:
3179
\bprog
3180
alghassei(al1)
3181
alghassef(al1)
3182
alghassei(al2)
3183
alghassef(al2)
3184
@eprog\noindent
3185
The output of~\kbd{alghassei} (infinite places) is a vector of integers of length the number
3186
of real places of~$F$, and the corresponding Hasse invariants are these integers
3187
divided by~$d$. Here we learn that the invariant of~\kbd{al1} at~$\infty$
3188
is~$1/2$ and that of~\kbd{al2} is~$0$. Similarly, the output of~\kbd{alghassef}
3189
(finite places) is a pair of vectors, one containing primes of the base field,
3190
and a vector of integers of the same length representing the Hasse invariants at
3191
finite places. We learn that~\kbd{al1} has invariant~$1/2$ at~$2$ and~$0$ at
3192
every other finite place, and that~\kbd{al2} has invariant~$-1/3$ at~$3$,
3193
invariant~$1/3$ at~$5$, and~$0$ at every other finite place.
3194
These invariants give a complete classification of central simple
3195
algebras over~$F$:
3196
3197
\item two central simple algebras over~$F$ of the same degree are isomorphic if
3198
and only if they have the same invariants;
3199
3200
\item the sum of the Hasse invariants is~$0$ in $\Q/\Z$;
3201
3202
\item for every degree~$d$ and finite collection of Hasse invariants satisfying
3203
the conditions above, there exists a central simple algebra over~$F$ having
3204
those invariants.
3205
3206
Let's use~\kbd{gp} to construct an algebra from its invariants. First let's
3207
construct a number field and a few places.
3208
\bprog
3209
nf = nfinit(y^2-2);
3210
p3 = idealprimedec(nf,3)[1]
3211
p17 = idealprimedec(nf,17)[1]
3212
@eprog\noindent
3213
Now let's construct an algebra of degree~$6$. The following Hasse invariants
3214
satisfy the correct conditions since~$1/3+1/6+1/2=0$ in~$\Q/\Z$:
3215
\bprog
3216
hf = [[p3,p17],[1/3,1/6]]; hi = [1/2,0]; \\ nf has 2 real places
3217
@eprog\noindent
3218
Finally we can create the algebra:
3219
\bprog
3220
al3 = alginit(nf,[6,hf,hi]);
3221
@eprog\noindent
3222
This will require less than half a minute but a lot of memory:
3223
this is an algebra of dimension~$2\times 6^2 = 72$ over~$\Q$ and we
3224
are doing a nontrivial computation in the initialization! You can check that the
3225
dimension over~$\Q$ is what we expect:
3226
\bprog
3227
algdim(al3,1)
3228
@eprog\noindent
3229
During the initialization, \kbd{gp} computes an integral multiplication table
3230
for the algebra. This allows us to recreate a table version of the algebra:
3231
\bprog
3232
mt3 = algmultable(al3);
3233
al4 = algtableinit(mt3);
3234
@eprog\noindent
3235
We can then check that the algebra is simple as expected:
3236
\bprog
3237
algissimple(al4)
3238
@eprog\noindent
3239
Finally, an important test for a central simple algebra is whether it is a
3240
division algebra.
3241
\bprog
3242
algisdivision(al3)
3243
@eprog
3244
3245
\subsubsec{Elements}
3246
3247
In a cyclic algebra~$(K/F,\sigma,b)$ of degree~$d$, we represent elements as
3248
column vectors of length~$d$, expressed on the basis of the~$K$-vector
3249
space~$\bigoplus_{i=0}^{d-1}u^iK$:
3250
\bprog
3251
a = [x^3-1, -x^2, 3, -1]~*Mod(1,T) \\represents an element in al2
3252
@eprog\noindent
3253
To represent elements in the quaternion algebra~\kbd{al1}, we must view it as a
3254
cyclic algebra, and therefore use the representation~\kbd{al1} $ =
3255
\Q(i)+j\Q(i)$. The standard basis elements~$1,i,j,k=ij=-ji$ become
3256
\bprog
3257
one = [1,0]~
3258
i = [x,0]~
3259
j = [0,1]~
3260
k = [0,-x]~
3261
@eprog\noindent
3262
The expected equalities hold:
3263
\bprog
3264
algsqr(al1,i) == -2*one
3265
algsqr(al1,j) == -1*one
3266
algsqr(al1,k) == -2*one
3267
algmul(al1,i,j) == k
3268
algmul(al1,j,i) == -k
3269
@eprog\noindent
3270
3271
Like~\kbd{nfinit} for number fields, the~\kbd{alginit} function computes an
3272
integral basis of
3273
the algebra being initialized. More precisely, an \emph{order} in
3274
a~$\Q$-algebra~$A$ is a subring~${\cal O}\subset A$ that is finitely generated
3275
as a~$\Z$-module and such that~$\Q{\cal O} = A$. In an algebra
3276
structure
3277
computed with~\kbd{alginit}, we store a basis of an order~${\cal O}_0$, which we
3278
will call the integral basis of the algebra. There is no canonical choice for
3279
such a basis, and not every integral element has integral coordinates with
3280
respect to that basis (the set of integral elements in~$A$ does not form a
3281
ring in general). By default, ${\cal O}_0$ is a maximal order and hence behaves
3282
in a way similar to the ring of integers in a number field. You can disable the
3283
(costly) computation of a maximal order with an optional argument:
3284
\bprog
3285
al5 = alginit(nf,[6,hf,hi],,0);
3286
@eprog\noindent
3287
This command should be faster than the initialization of~\kbd{al3}.
3288
As in number fields, you can represent elements of central simple algebras in
3289
\emph{algebraic form}, which means the cyclic algebra representation we
3290
described above, or in \emph{basis form}, which means as a~$\Q$-linear
3291
combination of the integral basis. You can switch between the two
3292
representations:
3293
\bprog
3294
algalgtobasis(al2, a)
3295
algalgtobasis(al1, j)
3296
algbasistoalg(al3, algrandom(al3,1))
3297
@eprog\noindent
3298
As usual you can compute any elementary operation: try various combinations
3299
of~\kbd{algadd}, \kbd{algsub}, \kbd{algneg}, \kbd{algmul}, \kbd{alginv},
3300
\kbd{algsqr}, \kbd{algpow}.
3301
3302
Every central simple algebra~$A$ over a number field~$F$ admits a \emph{splitting
3303
field}, i.e. an extension~$K/F$ such that~$A\otimes_F K\cong M_d(K)$. We always
3304
store such a splitting in an~\kbd{alginit} structure, and you can access it
3305
using
3306
\bprog
3307
algsplittingfield(al1) \\ K as an rnf structure
3308
algtomatrix(al1, k) \\ image of k by the splitting isomorphism
3309
@eprog\noindent
3310
For every~$x\in A$, the trace (resp. determinant, characteristic polynomial)
3311
of that matrix is in~$K$ (resp.~$K$,~$K[X]$) and is called the
3312
\emph{reduced trace} (resp. \emph{reduced norm}, \emph{reduced characteristic
3313
polynomial}) of~$x$. You can compute them using
3314
\bprog
3315
algtrace(al3, vector(72,i,i==3)~)
3316
algnorm(al2, a)
3317
algcharpoly(al1, -1+i+j+2*k)
3318
@eprog
3319
3320
\section{Plotting}
3321
3322
PARI supports high and low-level graphing functions, on a variety of output
3323
devices: a special purpose window under standard graphical environments (the
3324
\kbd{X Windows} system, Mac OS X, Microsoft Windows), or a \kbd{PostScript}
3325
file ready for the printer. These functions use a multitude of flags, which
3326
are mostly power-of-2. To simplify understanding we first give these flags
3327
symbolic names.
3328
\bprog
3329
/* Relative positioning of graphic objects: */
3330
nw = 0; se = 4; relative = 1;
3331
sw = 2; ne = 6;
3332
3333
/* String positioning: */
3334
/* V */ bottom = 0; /* H */ left = 0; /* Fine tuning */ hgap = 16;
3335
vcenter = 4; center = 1; vgap = 32;
3336
top = 8; right = 2;
3337
@eprog\noindent
3338
We also decrease drastically the default precision.
3339
\bprog
3340
\p 9
3341
@eprog\noindent
3342
This is very important, since plotting involves calculation of functions at
3343
a huge number of points, and a relative precision of 38 significant digits
3344
is an obvious overkill: the output device resolution certainly won't reach
3345
$10^{38} \times 10^{38}$ pixels!
3346
3347
Start with a simple plot:
3348
\bprog
3349
ploth(X = -2, 2, sin(X^7))
3350
@eprog\noindent
3351
You can see the limitations of the ``straightforward'' mode of plotting:
3352
while the first several cycles of \kbd{sin} reach $-1$ and $1$, the cycles
3353
which are closer to the left and right border do not. This is understandable,
3354
since PARI is calculating $\sin(X^7)$ at many (evenly spaced) points, but
3355
these points have no direct relationship to the ``interesting'' points on
3356
the graph of this function. No value close enough to the maxima and minima
3357
are calculated, which leads to wrong turning points in the graph. To fix
3358
this, one may use variable steps which are smaller where the function varies
3359
rapidly:
3360
\bprog
3361
ploth(X = -2, 2, sin(X^7), "Recursive")
3362
@eprog\noindent
3363
The precision near the edges of the graph is much better now.
3364
However, the recursive plotting (named so since PARI subdivides intervals
3365
until the graph becomes almost straight) has its own pitfalls. Try
3366
\bprog
3367
ploth(X = -2, 2, sin(X*7), "Recursive")
3368
@eprog\noindent The graph looks correct far away, but it has a straight
3369
interval near the origin, and some sharp corners as well. This happens
3370
because the graph is symmetric with respect to the origin, thus the middle 3
3371
points calculated during the initial subdivision of $[-2,2]$ are exactly on
3372
the same line. To PARI this indicates that no further subdivision is needed,
3373
and it plots the graph on this subinterval as a straight line.
3374
3375
There are many ways to circumvent this. Say, one can make the right limit
3376
2.1. Or one can ask PARI for an initial subdivision into 16 points instead
3377
of default 15:
3378
\bprog
3379
ploth(X = -2, 2, sin(X*7), "Recursive", 16)
3380
@eprog\noindent
3381
All these arrangements break the symmetry of the initial subdivision, thus
3382
make the problem go away. Eventually PARI will be able to better detect such
3383
pathological cases, but currently some manual intervention may be required.
3384
3385
The function \kbd{ploth} has some additional enhancements which allow
3386
graphing in situations when the calculation of the function takes a lot of
3387
time. Let us plot $\zeta({1\over 2} + it)$:
3388
\bprog
3389
ploth(t = 100, 110, real(zeta(0.5+I*t)), /*empty*/, 1000)
3390
@eprog\noindent
3391
This can take quite some time. (1000 is close to the default for many
3392
plotting devices, we want to specify it explicitly so that the result does
3393
not depend on the output device.) Try the recursive plot:
3394
\bprog
3395
ploth(t = 100, 110, real(zeta(0.5+I*t)), "Recursive")
3396
@eprog\noindent
3397
It takes approximately the same time. Now try specifying fewer points,
3398
but make PARI approximate the data by a smooth curve:
3399
\bprog
3400
ploth(t = 100, 110, real(zeta(0.5+I*t)), "Splines", 100)
3401
@eprog\noindent
3402
This takes much less time, and the output is practically the same. How to
3403
compare these two outputs? We will see it shortly. Right now let us plot
3404
both real and complex parts of $\zeta$ on the same graph:
3405
\bprog
3406
f(t) = my(z = zeta(0.5+I*t)); [real(z),imag(z)];
3407
ploth(t = 100, 110, f(t), , 1000)
3408
@eprog\noindent (Note the use of the temporary variable \kbd{z}; \kbd{my}
3409
declares it local to the function's body.)
3410
3411
Note how one half of the roots of the real and imaginary parts coincide.
3412
Why did we define a function \kbd{f(t)}? To avoid calculation of
3413
$\zeta({1\over2} + it)$ twice for the same value of t. Similarly, we can
3414
plot parametric graphs:
3415
\bprog
3416
ploth(t = 100, 110, f(t), "Parametric", 1000)
3417
@eprog\noindent In that case (parametric plot of the real and imaginary parts
3418
of a complex function), we can also use directly
3419
\bprog
3420
ploth(t = 100, 110, zeta(0.5+I*t), "Complex", 1000)
3421
ploth(t = 100, 110, zeta(0.5+I*t), "Complex|Splines", 100)
3422
@eprog
3423
3424
If your plotting device supports it, you may ask PARI to show the points
3425
in which it calculated your function:
3426
\bprog
3427
ploth(t = 100, 110, f(t), "Parametric|Splines|Points_too", 100)
3428
@eprog
3429
3430
As you can see, the points are very dense on the graph. To see some crude
3431
graph, one can even decrease the number of points to 30. However, if you
3432
decrease the number of points to 20, you can see that the approximation to
3433
the graph now misses zero. Using splines, one can create reasonable graphs
3434
for larger values of t, say with
3435
\bprog
3436
ploth(t = 10000, 10004, f(t), "Parametric|Splines|Points_too", 50)
3437
@eprog
3438
3439
How can we compare two graphs of the same function plotted by different
3440
methods? Documentation shows that \kbd{ploth} does not provide any direct
3441
method to do so. However, it is possible, and even not very complicated.
3442
3443
The solution comes from the other direction. PARI has a power mix of high
3444
level plotting function with low level plotting functions, and these functions
3445
can be combined together to obtain many different effects. Return back
3446
to the graph of $\sin(X^7)$. Suppose we want to create an additional
3447
rectangular frame around our graph. No problem!
3448
3449
First, all low-level graphing work takes place in some virtual drawing
3450
boards (numbered from 0 to 15), called ``rectangles'' (or ``rectwindows'').
3451
So we create an empty ``rectangle'' and name it rectangle 2 (any
3452
number between 0 and 15 would do):
3453
\bprog
3454
plotinit(2)
3455
plotscale(2, 0,1, 0,1)
3456
@eprog
3457
This creates a rectwindow whose size exactly fits the size of the output
3458
device, and makes the coordinate system inside it go from 0 to 1 (for both
3459
$x$ and $y$). Create a rectangular frame along the boundary of this rectangle:
3460
\bprog
3461
plotmove(2, 0,0)
3462
plotbox(2, 1,1)
3463
@eprog
3464
Suppose we want to draw the graph inside a subrectangle of this with upper
3465
and left margins of $0.10$ (so 10\% of the full rectwindow width), and
3466
lower and top margins of $0.02$, just to make it more interesting. That
3467
makes it an $0.88 \times 0.88$ subrectangle; so we create another rectangle
3468
(call it 3) of linear size 0.88 of the size of the initial rectangle and
3469
graph the function in there:
3470
\bprog
3471
plotinit(3, 0.88, 0.88, relative)
3472
plotrecth(3, X = -2, 2, sin(X^7), "Recursive")
3473
@eprog
3474
(nothing is output yet, these commands only fills the virtual drawing
3475
boards with PARI graphic objects). Finally, output rectangles 2 and 3 on
3476
the same plot, with the required offsets (counted from upper-left corner):
3477
\bprog
3478
plotdraw([2, 0,0, 3, 0.1,0.02], relative)
3479
@eprog
3480
\noindent The output misses something comparing to the output of
3481
\kbd{ploth}: there are no coordinates of the corners of the internal
3482
rectangle. If your output device supports mouse operations (only
3483
\kbd{gnuplot} does), you can find coordinates of particular points of the
3484
graph, but it is nice to have something printed on a hard copy too.
3485
3486
However, it is easy to put $x$- and $y$-limits on the graph. In the
3487
coordinate system of the rectangle 2 the corners are $(0.1,0.1)$,
3488
$(0.1,0.98)$, $(0.98,0.1)$, $(0.98,0.98)$. We can mark lower $x$-limit by
3489
doing
3490
\bprog
3491
plotmove(2, 0.1,0.1)
3492
plotstring(2, "-2.000", left+top+vgap)
3493
@eprog\noindent
3494
Computing the minimal and maximal $y$-coordinates might be trickier, since
3495
in principle we do not know the range in advance (though for $\sin(X^7)$ it
3496
is easy to guess!). Fortunately, \kbd{plotrecth} returns the $x$- and
3497
$y$-limits.
3498
3499
Here is the complete program:
3500
\bprog
3501
plotinit(3, 0.88, 0.88, relative)
3502
lims = plotrecth(3, X = -2, 2, sin(X^7), "Recursive")
3503
\p 3 \\ @com $3$ significant digits for the bounding box are enough
3504
plotinit(2); plotscale(2, 0,1, 0,1)
3505
plotmove(2, 0,0); plotbox(2, 1,1)
3506
plotmove(2, 0.1,0.1);
3507
plotstring(2, lims[1], left+top+vgap)
3508
plotstring(2, lims[3], bottom+vgap+right+hgap)
3509
plotmove(2, 0.98,0.1); plotstring(2, lims[2], right+top+vgap)
3510
plotmove(2, 0.1,0.98); plotstring(2, lims[4], right+hgap+top)
3511
plotdraw([2, 0,0, 3, 0.1,0.02], relative)
3512
@eprog
3513
3514
We started with a trivial requirement: have an additional frame around
3515
the graph, and it took some effort to do so. But at least it was possible,
3516
and PARI did the hardest part: creating the actual graph.
3517
Now do a different thing: plot together the ``exact'' graph of
3518
$\zeta({1/2}+it)$ together with one obtained from splines approximation.
3519
We can emit these graphs into two rectangles, say 0 and 1, then put these
3520
two rectangles together on one plot. Or we can emit these graphs into one
3521
rectangle 0.
3522
3523
However, a problem arises: note how we
3524
introduced a coordinate system in rectangle 2 of the above example, but we
3525
did not introduce a coordinate system in rectangle 3. Plotting a
3526
graph into rectangle 3 automatically created a coordinate system
3527
inside this rectangle (you could see this coordinate system in action
3528
if your output device supports mouse operations). If we use two different
3529
methods of graphing, the bounding boxes of the graphs will not be exactly
3530
the same, thus outputting the rectangles may be tricky. Thus during
3531
the second plotting we ask \kbd{plotrecth} to use the coordinate system of
3532
the first plotting. Let us add another plotting with fewer
3533
points too:
3534
\bprog
3535
plotinit(0, 0.9,0.9, relative)
3536
plotrecth(0, t=100,110, f(t), "Parametric",300)
3537
plotrecth(0, t=100,110, f(t), "Parametric|Splines|Points_too|no_Rescale",30);
3538
plotrecth(0, t=100,110, f(t), "Parametric|Splines|Points_too|no_Rescale",20);
3539
plotdraw([0, 0.05,0.05], relative)
3540
@eprog
3541
3542
This achieves what we wanted: we may compare different ways to plot a graph,
3543
but the picture is confusing: which graph is what, and why there are multiple
3544
boxes around the graph? At least with some output devices one can control
3545
how the output curves look like, so we can use this to distinguish different
3546
graphs. And the mystery of multiple boxes is also not that hard to solve:
3547
they are bounding boxes for calculated points on each graph. We can disable
3548
output of bounding boxes with appropriate options for \kbd{plotrect}.
3549
With these frills the script becomes:
3550
\bprog
3551
plotinit(0, 0.9,0.9, relative)
3552
plotrecth(0, t=100,110, f(t), "Parametric|no_Lines", 300)
3553
opts="Parametric|Splines|Points_too|no_Rescale|no_Frame|no_X_axis|no_Y_axis";
3554
plotrecth(0, t=100,110,f(t), opts, 30);
3555
plotdraw([0, 0.05,0.05], relative)
3556
@eprog
3557
3558
\noindent Plotting axes on the second graph would not hurt, but
3559
is not needed either, so we omit them. One can see that the discrepancies
3560
between the exact graph and one based on 30 points exist, but are pretty
3561
small. On the other hand, decreasing the number of points to 20 would make
3562
quite a noticeable difference.
3563
3564
Additionally, one can ask PARI to convert a plot to PS (PostScript)
3565
or SVG (Scalable Vector Graphics) format: just use the command
3566
\kbd{plotexport} instead of \kbd{plotdraw} in the above examples (or
3567
\kbd{plothexport} instead of \kbd{ploth}). This returns a character string
3568
which you can then write to a file using \kbd{write}.
3569
3570
Now suppose we want to join many different small graphs into one picture.
3571
We cannot use one rectangle for all the output as we did in the example
3572
with $\zeta({1/2}+it)$, since the graphs should go into different places.
3573
Rectangles are a scarce commodity in PARI, since only 16 of them are
3574
user-accessible. Does it mean that we cannot have more than 16 graphs on
3575
one picture? Thanks to an additional operation of PARI plotting engine,
3576
there is no such restrictions. This operation is \kbd{plotcopy}.
3577
3578
The following script puts 4 different graphs on one plot using 2 rectangles
3579
only, \kbd{A} and \kbd{T}:
3580
\bprog
3581
A = 2; \\@com accumulator
3582
T = 3; \\@com temporary target
3583
plotinit(A); plotscale(A, 0, 1, 0, 1)
3584
3585
plotinit(T, 0.42, 0.42, relative);
3586
plotrecth(T, x= -5, 5, sin(x), "Recursive")
3587
plotcopy(T, 2, 0.05, 0.05, relative + nw)
3588
3589
plotmove(A, 0.05 + 0.42/2, 1 - 0.05/2)
3590
plotstring(A,"Graph", center + vcenter)
3591
3592
plotinit(T, 0.42, 0.42, relative);
3593
plotrecth(T, x= -5, 5, [sin(x),cos(2*x)], 0)
3594
plotcopy(T, 2, 0.05, 0.05, relative + ne)
3595
3596
plotmove(A, 1 - 0.05 - 0.42/2, 1 - 0.05/2)
3597
plotstring(A,"Multigraph", center + vcenter)
3598
3599
plotinit(T, 0.42, 0.42, relative);
3600
plotrecth(T, x= -5, 5, [sin(3*x), cos(2*x)], "Parametric")
3601
plotcopy(T, 2, 0.05, 0.05, relative + sw)
3602
3603
plotmove(A, 0.05 + 0.42/2, 0.5)
3604
plotstring(A,"Parametric", center + vcenter)
3605
3606
plotinit(T, 0.42, 0.42, relative);
3607
plotrecth(T, x= -5, 5, [sin(x), cos(x), sin(3*x),cos(2*x)], "Parametric")
3608
plotcopy(T, 2, 0.05, 0.05, relative + se)
3609
3610
plotmove(A, 1 - 0.05 - 0.42/2, 0.5)
3611
plotstring(A,"Multiparametric", center + vcenter)
3612
3613
plotmove(A, 0, 0)
3614
plotbox(A, 1, 1)
3615
3616
plotdraw(A)
3617
\\ s = plotexport(A, relative); write("foo.ps", s) \\ @com if hard copy needed
3618
@eprog
3619
3620
The rectangle \kbd{A} plays the role of accumulator, rectangle \kbd{T} is
3621
used as a target to \kbd{plotrecth} only. Immediately after plotting into
3622
rectangle \kbd{T} the contents is copied to accumulator. Let us explain
3623
numbers which appear in this example: we want to create 4 internal rectangles
3624
with a gap 0.06 between them, and the outside gap 0.05 (of the size of the
3625
plot). This leads to the size 0.42 for each rectangle. We also
3626
put captions above each graph, centered in the middle of each gap. There
3627
is no need to have a special rectangle for captions: they go into the
3628
accumulator too.
3629
3630
To simplify positioning of the rectangles, the above example uses relative
3631
``geographic'' notation: the last argument of \kbd{plotcopy} specifies the
3632
corner of the graph (say, northwest) one counts offset from. (Positive
3633
offsets go into the rectangle.)
3634
3635
To demonstrate yet another useful plotting function, design a program to
3636
plot Taylor polynomials for a $\sin x$ about 0. For simplicity, make the
3637
program good for any function, but assume that a function is odd, so only
3638
odd-numbered Taylor series about 0 should be plotted. Start with defining
3639
some useful shortcuts
3640
\bprog
3641
xlim = 13; ordlim = 25; f(x) = sin(x);
3642
default(seriesprecision,ordlim)
3643
farray(t) = vector((ordlim+1)/2, k, truncate( f(1.*t + O(t^(2*k+1)) )));
3644
FARRAY = farray('t); \\@com\kbd{'t} to make sure \kbd{t} is a free variable
3645
@eprog\noindent
3646
\kbd{farray(x)} returns a vector of Taylor polynomials for $f(x)$, which we
3647
store in \kbd{FARRAY}. We want to plot $f(x)$ into a rectangle, then make
3648
the rectangle which is 1.2 times higher, and plot Taylor polynomials into the
3649
larger rectangle. Assume that the larger rectangle takes 0.9 of the final
3650
plot.
3651
3652
First of all, we need to measure the height of the smaller rectangle:
3653
\bprog
3654
plotinit(3, 0.9, 0.9/1.2, 1);
3655
opts = "Recursive | no_X_axis|no_Y_axis|no_Frame";
3656
lims = plotrecth(3, x= -xlim, xlim, f(x), opts,16);
3657
h = lims[4] - lims[3];
3658
@eprog\noindent
3659
Next step is to create a larger rectangle, and plot the Taylor polynomials
3660
into the larger rectangle:
3661
\bprog
3662
plotinit(4, 0.9,0.9, relative);
3663
plotscale(4, lims[1], lims[2], lims[3] - h/10, lims[4] + h/10)
3664
plotrecth(4, x = -xlim, xlim, subst(FARRAY,t,x), "no_Rescale");
3665
@eprog
3666
3667
Here comes the central command of this example:
3668
\bprog
3669
plotclip(4)
3670
@eprog\noindent
3671
What does it do? The command \kbd{plotrecth(\dots, "no\_Rescale")} scales the
3672
graphs according to coordinate system in the rectangle, but it does not pay
3673
any other attention to the size of the rectangle. Since \kbd{xlim} is 13,
3674
the Taylor polynomials take very large values in the interval
3675
\kbd{-xlim...xlim}. In particular, significant part of the graphs is going
3676
to be \emph{outside} of the rectangle. \kbd{plotclip} removes the parts of
3677
the plottings which fall off the rectangle boundary
3678
\bprog
3679
plotinit(2)
3680
plotscale(2, 0.0, 1.0, 0.0, 1.0)
3681
plotmove(2,0.5,0.975)
3682
plotstring(2,"Multiple Taylor Approximations",center+vcenter)
3683
plotdraw([2, 0, 0, 3, 0.05, 0.05 + 0.9/12, 4, 0.05, 0.05], relative)
3684
@eprog\noindent
3685
These commands draw a caption, and combine 3 rectangles (one with the
3686
caption, one with the graph of the function, and one with graph of Taylor
3687
polynomials) together. The plots are not very beautiful with the default
3688
colors. See \kbd{examples/taylor.gp} for a user function encapsulating the
3689
above example, and a colormap generator.
3690
3691
This finishes our survey of PARI plotting functions, but let us add
3692
some remarks. First of all, for a typical output device the picture is
3693
composed of small colored squares (pixels), as a very large checkerboard.
3694
Each output rectangle is a disjoint union of such squares. Each drop
3695
of paint in the rectangle will color a whole square in it. Since the
3696
rectangle has a coordinate system, it is important to know how this
3697
coordinate system is positioned with respect to the boundaries of these
3698
squares.
3699
3700
The command \kbd{plotscale} describes a range of $x$ and $y$ in the
3701
rectangle. The limit values of $x$ and $y$ in the coordinate system are
3702
coordinates \emph{of the centers} of corner squares. In particular,
3703
if ranges of $x$ and $y$ are $[0,1]$, then the segment which connects (0,0)
3704
with (0,1) goes along the \emph{middle} of the left column of the rectangle.
3705
In particular, if we made tiny errors in calculation of endpoints of this
3706
segment, this will not change which squares the segment intersects, thus
3707
the resulting picture will be the same. (It is important to know such details
3708
since many calculations are approximate.)
3709
3710
Another consideration is that all examples we did in this section were
3711
using relative sizes and positions for the rectangles. This is nice, since
3712
different output devices will have very similar pictures, while we
3713
did not need to care about particular resolution of the output device.
3714
On the other hand,
3715
using relative positions does not guarantee that the pictures will be
3716
similar. Why? Even if two output devices have the same resolution,
3717
the picture may be different. The devices may use fonts of different
3718
size, or may have a different ``unit of length''.
3719
3720
The information about the device in PARI is encoded in 6 numbers: resolution,
3721
size of a character cell of the font, and unit of length, all separately
3722
for horizontal and vertical direction. These sizes are expressed as
3723
numbers of pixels. To inspect these numbers one may use the function
3724
\kbd{plothsizes}. The ``units of length'' are currently used to calculate
3725
right and top gaps near graph rectangle of \kbd{ploth}, and gaps for
3726
\kbd{plotstring}. Left and bottom gaps near graph rectangle are calculate
3727
using both units of length, and sizes of character boxes (so that there
3728
is enough place to print limits of the graphs).
3729
3730
What does it show? Using relative sizes during plotting produces
3731
\var{approximately} the same plotting on different devices, but does not
3732
ensure that the plottings ``look the same''. Moreover, ``looking the
3733
same'' is not a desirable target, ``looking tuned for the environment''
3734
will be much better. If you want to produce such fine-tuned plottings,
3735
you need to abandon a relative-size model, and do your plottings in
3736
pixel units. To do this one removes flag \kbd{relative} from the above
3737
examples, which will make size and offset arguments interpreted this way.
3738
After querying sizes with \kbd{plothsizes} one can fine-tune sizes and
3739
locations of subrectangles to the details of an arbitrary plotting
3740
device.
3741
3742
The last two elements of the array returned by \kbd{plothsizes} are the
3743
dimensions of the display, if applicable. If there is no real display, like
3744
in svg or postscript plots, the width and height of display are set to $0$.
3745
3746
To check how good your fine-tuning is, you may test your graphs with a
3747
medium-resolution plotting (as many display output devices are), and
3748
with a low-resolution plotting (say, with \kbd{plotterm("dumb")} of gnuplot).
3749
3750
\section{GP Programming}
3751
3752
Do we really need such a section after all we have learnt so far? We now
3753
know how to write scripts and feed them to \kbd{gp}, in particular how to
3754
define functions. It's possible to define \emph{member} function as well, but
3755
we trust you to find them in the manual. We have seen most control
3756
statements: the missing ones (\kbd{while}, \kbd{break}, \kbd{next},
3757
\kbd{return} and various \kbd{for} loops) should be straightforward. (You
3758
won't forget to look them up in the manual, will you?)
3759
3760
Output is done via variants of the familiar \kbd{print} (to screen),
3761
\kbd{write} (to a file). Input via \kbd{read} (from file), \kbd{input}
3762
(querying user), or \kbd{extern} (from an external auxiliary program).
3763
3764
To customize \kbd{gp}, e.g.~increase the default stack space or load your
3765
private script libraries on startup, look up \kbd{The preferences file}
3766
section in the User's manual. We strongly advise to set \kbd{parisizemax} to
3767
a large nonzero value, about what you believe your machine can stand: this
3768
both limits the amount of memory PARI will use for its computation (thereby
3769
keeping your machine usable), and let PARI increases its stack size (up to
3770
this limit) to accommodate large computations. If you regularly see \kbd{PARI
3771
stack overflows} messages, think about this one!
3772
3773
For clarity, it is advisable to declare local variables in user functions
3774
(and in fact, with the smallest possible scope), as we have done so far with
3775
the keyword \kbd{my}. As usual, one is usually better off avoiding global
3776
variables altogether.
3777
3778
\emph{Break loops} are more powerful than we saw: look up \kbd{dbg\_down} /
3779
\kbd{dbg\_up} (to get a chance to inspect local variables in various scopes)
3780
and \kbd{dbg\_err} (to access all components of an error context).
3781
3782
To reach grandwizard status, you may need to understand the all powerful
3783
\kbd{install} function, which imports into \kbd{gp} an (almost) arbitrary
3784
function from the PARI library (and elsewhere too!), or how to use the
3785
\kbd{gp2c} compiler and its extended types. But both are beyond the scope of
3786
the present document.
3787
3788
Have fun!
3789
\bye
3790
3791