Testing latest pari + WASM + node.js... and it works?! Wow.
License: GPL3
ubuntu2004
% Copyright (c) 2000 The PARI Group1%2% This file is part of the PARI/\kbd{gp} documentation3%4% Permission is granted to copy, distribute and/or modify this document5% under the terms of the GNU General Public License67% This should be compiled with plain TeX8\def\TITLE{A Tutorial for Pari/GP}9\input parimacro.tex1011\chapno=012\begintitle13\vskip2.5truecm14\centerline{\mine A Tutorial}15\vskip1.truecm16\centerline{\mine for}17\vskip1.truecm18\centerline{\mine PARI / GP}19\vskip1.truecm20\centerline{\sectiontitlebf (version \vers)}21\vskip1.truecm22\authors23\endtitle2425\copyrightpage26\tableofcontents2728\noindent This booklet is a guided tour and a tutorial to the \kbd{gp}29calculator. Many examples will be given, but each time a new function is30used, the reader should look at the appropriate section in the \emph{User's31Manual to PARI/GP} for detailed explanations. This chapter can be read32independently, for example to get acquainted with the possibilities of33\kbd{gp} without having to read the whole manual. At this point.3435\section{Greetings!}3637So you are sitting in front of your workstation (or terminal, or PC\dots),38and you type \kbd{gp} to get the program started (or click on the relevant39icon, or select some menu item). It says hello in its particular manner, and40then waits for you after its \kbd{prompt}, initially \kbd{?} (or something41like {\bf gp}~\kbd{>}). Type42\bprog432 + 244@eprog\noindent What happens? Maybe not what you expect. First of all, of45course, you should tell \kbd{gp} that your input is finished, and this is46done by hitting the \kbd{Return} (or \kbd{Newline}, or \kbd{Enter}) key. If47you do exactly this, you will get the expected answer. However some of you48may be used to other systems like Gap, Macsyma, Magma or Maple. In this case,49you will have subconsciously ended the line with a semicolon ``\kbd{;}''50before hitting \kbd{Return}, since this is how it is done on those systems.51In that case, you will simply see \kbd{gp} answering you with a smug52expression, i.e.~a new prompt and no answer! This is because a semicolon at53the end of a line tells \kbd{gp} not to print the result (it is still stored54in the result history). You will certainly want to use this feature if the55output is several pages long. Try56\bprog5727 * 3758@eprog\noindent Wow! even multiplication works. Actually, maybe those59spaces are not necessary after all. Let's try \kbd{27*37}. Seems to be ok. We60will still insert them in this document since it makes things easier to read,61but as \kbd{gp} does not care about them, you don't have to type them all.6263Now this session is getting lengthy, so the second thing one needs to learn64is to quit. Each system has its quit signal. In \kbd{gp}, you can use65\kbd{quit} or \b{q} (backslash q), the \kbd{q} being of course for quit.66Try it.6768Now you've done it! You're out of \kbd{gp}, so how do you want to continue69studying this tutorial? Get back in please.7071Let's get to more serious stuff. I seem to remember that the decimal72expansion of $1/7$ has some interesting properties. Let's see what \kbd{gp}73has to say about this. Type74\bprog751 / 776@eprog\noindent77What? This computer is making fun of me, it just spits back to me my own78input, that's not what I want!7980Now stop complaining, and think a little. Mathematically, $1/7$ is an element81of the field $\Q$ of rational numbers, so how else but $1/7$ can the computer82give the answer to you? Well maybe $2/14$ or $7^{-1}$, but why complicate83matters? Seriously, the basic point here is that PARI, hence \kbd{gp}, will84almost always try to give you a result which is as precise as possible (we85will see why ``almost'' later). Hence since here the result can be86represented exactly, that's what it gives you.8788But I still want the decimal expansion of $1/7$. No problem. Type one of89the following:90\bprog911./ 7921 / 7.931./ 7.941 / 7 + 0.95@eprog\noindent96Immediately a number of decimals of this fraction appear, 38 on most systems,9728 on the others, and the repeating pattern is $142857$. The reason is that98you have included in the operations numbers like \kbd{0.}, \kbd{1.} or \kbd{7.}99which are \emph{imprecise} real numbers, hence \kbd{gp} cannot give you an100exact result.101102Why 28 / 38 decimals by the way? Well, it is the default initial precision.103This has been chosen so that the computations are very fast, and gives104already 12 decimals more accuracy than conventional double precision floating105point operations. The precise value depends on a technical reason: if your106machine supports 64-bit integers (the standard C library can handle integers107up to $2^{64}$), the default precision is 38 decimals, and 28 otherwise.108For definiteness, we will assume the former henceforth. Of course, you can109extend the precision (almost) as much as you like as we will see in a moment.110111I'm getting bored, why don't we get on with some more exciting stuff? Well,112try \kbd{exp(1)}. Presto, comes out the value of $e$ to 38 digits. Try113\kbd{log(exp(1))}. Well, we get a floating point number and not an exact $1$,114but pretty close! That's what you lose by working numerically.115116What could we try now? Hum, \kbd{pi}? The answer is not that117enlightening. \kbd{Pi}? Ah. This works better. But let's remember that118\kbd{gp} distinguishes between uppercase and lowercase letters. \kbd{pi} was119as meaningless to it as \kbd{stupid garbage} would have been: in both cases120\kbd{gp} will just create a variable with that funny unknown name you just121used. Try it! Note that it is actually equivalent to type122\kbd{stupidgarbage}: all spaces are suppressed from the input. In the123\kbd{27~*~37} example it was not so conspicuous as we had an operator to124separate the two operands. This has important consequences for the writing of125\kbd{gp} scripts. More about this later.126127By the way, you can ask \kbd{gp} about any identifier you think it might know128about: just type it, prepending a question mark ``\kbd{?}''. Try \kbd{?Pi}129and \kbd{?pi} for instance. On most systems, an extended online help should130be available: try doubling the question mark to check whether it's the case131on yours: \kbd{??Pi}. In fact the \kbd{gp} header already gave you that132information if it was the case, just before the copyright message. As well,133if it says something like ``\kbd{readline enabled}'' then you should have a134look at the \kbd{readline} introduction in the User's Manual before you go135on: it will be much easier to type in examples and correct typos after you've136done that.137138Now try \kbd{exp(Pi * sqrt(163))}. Hmmm, we suspect that the last digit may139be wrong, can this really be an integer? This is the time to change140precision. Type \kbd{\b{p} 50}, then try \kbd{exp(Pi * sqrt(163))} again. We141were right to suspect that the last decimal was incorrect, since we get quite142a few nines in its place, but it is now convincingly clear that this is not143an integer. Maybe it's a bug in PARI, and the result is really an integer?144Type145\bprog146(log(%) / Pi)^2147@eprog\noindent148immediately after the preceding computation; \kbd{\%} means the result of the149last computed expression. More generally, the results are numbered \kbd{\%1,150\%2, \dots} \emph{including} the results151that you do not want to see printed by putting a semicolon at the end of the152line, and you can evidently use all these quantities in any further153computations. The result seems to be indistinguishable from $163$, hence it154does not seem to be a bug.155156In fact, it is known that $\exp(\pi*\sqrt{n})$ not only is not an integer or157a rational number, but is even a transcendental number when $n$ is a nonzero158rational number.159160So \kbd{gp} is just a fancy calculator, able to give me more decimals than I161will ever need? Not so, \kbd{gp} is incredibly more powerful than an ordinary162calculator, independently of its arbitrary precision possibilities.163164\misctitle{Additional comments} (you are supposed to skip this at first,165and come back later)1661671) If you are a PARI old timer, say the last version of PARI you used was168released around 1996, you have certainly noticed already that many many169things changed between the older 1.39.xx versions and this one.170Conspicuously, most function names have been changed. To know how a specific171function was changed, type \kbd{whatnow({\rm function})}.1721732) It seems that the text implicitly says that as soon as an imprecise number174is entered, the result will be imprecise. Is this always true? There is a175unique exception: when you multiply an imprecise number by the exact number1760, you will get the exact 0. Compare \kbd{0 * 1.4} and \kbd{0.~*~1.4}.177\smallskip178%1793) Not only can the number of decimal places of real numbers be large, but180the number of digits of integers also. Try \kbd{1000!}. It is never necessary181to tell \kbd{gp} in advance the size of the integers that it will encounter.182The same is true for real numbers, although most computations with floating183point assume a default precision and truncate their results to this accuracy;184initially 38 decimal digits, but we may change that with \b{p} of course.185\smallskip186%1874) Come back to 38 digits of precision (\kbd{\b{p} 38}), and type188\kbd{exp(100)}. As you can see the result is printed in exponential format.189This is because \kbd{gp} never wants you to believe that a result is correct190when it is not. We are working with 38 digits of precision, but the integer191part of $\exp(100)$ has 44 decimal digits. Hence if \kbd{gp} had dutifully192printed out 44 digits, the last few digits would have been wrong. Hence193\kbd{gp} wants to print only 38 significant digits, but to do so it has to194print in exponential format. \smallskip195%1965) There are two ways to avoid this. One is of course to increase the197precision. Let's try it. To give it a wide margin, we set the precision to 50198decimals. Then we recall our last result (\kbd{\%}199or \kbd{\%n} where \kbd{n} is the number of the result). What? We still have200an exponential format! Do you understand why?201202Again let's try to see what's happening. The number you recalled had been203computed only to 38 decimals, and even if you set the precision to 1000204decimals, \kbd{gp} knows that your number has only 38 digits of accuracy but205an integral part with 44 digits. So you haven't improved things by increasing206the precision. Or have you? What if we retype \kbd{exp(100)} now that we207have 50 digits? Try it. Now we no longer have an exponential format.208\medskip209%2106) What if I forget what the current precision is and I don't feel like211counting all the decimals? Well, you can type \b{p} by itself. You may also212learn about \kbd{gp} internal variables (and change them!) using213\kbd{default}. Type \kbd{default(realprecision)}, then214\kbd{default(realprecision, 38)}. Huh? In fact this last command is strictly215equivalent to \kbd{\b{p} 38}! (Admittedly more cumbersome to type.) There are216more ``defaults'' than just \kbd{format} and \kbd{realprecision}: type217\kbd{default} by itself now, they are all there. \smallskip218%2197) Note that the \kbd{default} command reacts differently according to the220number of input arguments. This is not an uncommon behavior for \kbd{gp}221functions. You can see this from the online help, or the complete description222in Chapter~3: any argument surrounded by braces \kbd{\obr\cbr} in the223function prototype is optional, which really means that a \emph{default}224argument will be supplied by \kbd{gp}. You can then check out from the text225what effect a given value will have, and in particular the default one.226\smallskip227%2288) Try the following: starting in precision 38, type first229\kbd{default(format, "e0.100")}, then \kbd{exp(1)}. Where are my 100230significant digits? Well, \kbd{default(format,)} only changes the output231format, but \emph{not} the default precision. On the other hand, the \b{p}232command changes both the precision and the output format.233234\section{Warming up}235236Another thing you better get used to pretty fast is error messages. Try237typing \kbd{1/0}. Could not be clearer. But why has the prompt238become funny, turning from \kbd{?} to \kbd{break>} ? When an error occurs, we239enter a so-called \emph{break loop}, where you get a chance, e.g to inspect240(and save!) values of variables before the prompt returns and all241computations so far are lost. In fact you can run an arbitrary command at242this point, and this mechanism is a tremendous help in debugging. To get out243of the break loop, type \kbd{break}, as instructed in the error message244last line.245246\misctitle{Comment} You can enter the break loop at any time using247\kbd{Control-C}: this freezes the current computation and gets you a new248prompt so that you may e.g., increase debugging level, inspect or modify249variables (again, run arbitrary commands), before letting the program go250on.251\medskip252253Now, back to our favorite example, in precision 38, type254\bprog255floor(exp(100))256@eprog\noindent257\kbd{floor} is the mathematician's integer part, not to be confused with258\kbd{truncate}, which is the computer scientist's: \kbd{floor(-3.4)} is equal259to $-4$ whereas \kbd{truncate(-3.4)} is equal to $-3$. You get a more260cryptic error message, which you would immediately understand if you had read261the additional comments of the preceding section. Since you were told not to262read them, here's the explanation: \kbd{gp} is unable to compute the263integer part of \kbd{exp(100)} given only 38 decimals of accuracy, since264it has 44 digits.265266Some error messages are more cryptic and sometimes not so easy to understand.267For instance, try \kbd{log(x)}. It simply tells you that \kbd{gp} does not268understand what \kbd{log(x)} is, although it does know the \kbd{log}269function, as \kbd{?log} will readily tell us.270271Now let's try \kbd{sqrt(-1)} to see what error message we get now. Haha!272\kbd{gp} even knows about complex numbers, so impossible to trick it that273way. Similarly, try typing \kbd{log(-2)}, \kbd{exp(I*Pi)}, \kbd{I\pow274I}\dots\ So we have a lot of real and complex analysis at our disposal.275There always is a specific branch of multivalued complex transcendental276functions which is taken, specified in the manual. Again, beware that277\kbd{I} and \kbd{i} are not the same thing. Compare \kbd{I\pow2} with278\kbd{i\pow2} for instance.279280Just for fun, let's try \kbd{6*zeta(2) / Pi\pow2}. Pretty close, no?281282\medskip283Now \kbd{gp} didn't seem to know what \kbd{log(x)} was, although it did know284how to compute numerical values of \kbd{log}. This is annoying. Maybe it285knows the exponential function? Let's give it a try. Type \kbd{exp(x)}.286What's this? If you had any experience with other computer algebra systems,287the answer should have simply been \kbd{exp(x)} again. But here the answer is288the Taylor expansion of the function around $\kbd{x}=0$, to 17 terms. Note289the \kbd{O(x\pow17)} which ends the series, and which is trademark of power290series in \kbd{gp}. It is the familiar ``big--oh'' notation of analysis.291Why 17 terms? This is governed by the \kbd{seriesprecision}, which292can be changed by typing \kbd{\b{ps} $n$} or \kbd{default(seriesprecision,293$n$)} where $n$ is the number of terms that you want in your power series294and is $16$ by default. Converting a polynomial or rational function to a295power series will yield 16 significant terms: so $x$ gets converted to $x +296O(x^{17})$; this is completely analogous to \kbd{realprecision} when an eact297integer or rational number is converted to a floating point real number.298Then we take the exponential of this new object and, since it has positive299valuation, we can actually deduce $17$ significant terms from the given $16$.300This is in keeping with PARI's philosophy of always returning a result which301is as precise as possible from a given input.302303You thus automatically get the Taylor expansion of any function that can be304expanded around $0$, and incidentally this explains why we weren't able to do305anything with \kbd{log(x)} which is not defined at $0$. (In fact \kbd{gp}306knows about Laurent series, but \kbd{log(x)} is not meromorphic either at307$0$.) If we try \kbd{log(1+x)}, then it works, but this time we \emph{lose}308one significant term: the result is $x - 1/2*x^2 + \dots + 1/15*x^15 +309O(x^16))$. (Do you understand why ?)310311But what if we wanted the expansion around a point different from 0? Well,312you're able to change $x$ into $x+a$, aren't you? So for instance you can313type \kbd{log(x+2)} to have the expansion of \kbd{log} around $\kbd{x}=2$. As314exercises you can try315\bprog316cos(x)317cos(x)^2 + sin(x)^2318exp(cos(x))319gamma(1 + x)320exp(exp(x) - 1)3211 / tan(x)322@eprog\noindent323for different values of \kbd{serieslength} (change it using \b{ps}324\var{newvalue}).325326Let's try something else: type \kbd{(1 + x)\pow 3}. No \kbd{O(x)} here, since327the result is a polynomial. Haha, but I have learnt that if you do not take328exponents which are integers greater or equal to 0, you obtain a power series329with an infinite number of nonzero terms. Let's try. Type330\kbd{(1 + x)\pow (-3)} (the parentheses around \kbd{-3} are not necessary but331make things easier to read). Surprise! Contrary to what we expected, we don't332get a power series but a rational function. Again this is for the same reason333that \kbd{1 / 7} just gave you $1/7$: the result being exact, PARI doesn't see334any reason to make it inexact.335336But I still want that power series. To obtain it, you can do as in the $1/7$337example and force a conversion using the $O(x^n)$ notation:338\bprog339(1 + x)^(-3) + O(x^16)340(1 + x)^(-3) * (1 + O(x^16))341(1 + x + O(x^16))^(-3)342@eprog\noindent343(Not on this example, but there is a difference between the first $2$344methods. Do you spot it?) Better yet, use the series constructor which345transforms any object into a power series, using the current346\kbd{seriesprecision}, and simply type347\bprog348Ser( (1 + x)^(-3) )349@eprog350351Now try \kbd{(1 + x)\pow (1/2)}: we obtain a power series, since the352result is an object which PARI does not know how to represent exactly. (We353could teach PARI about algebraic functions, but then take \kbd{(1 + x)\pow Pi}354as another example.) This gives us still another solution to our preceding355exercise: we can type \kbd{(1 + x)\pow (-3.)}. Since \kbd{-3.} is not an exact356quantity, PARI has no means to know that we are dealing with a rational357function, and will instead give you the power series, this time with real358instead of integer coefficients.359\smallskip360361To summarize, in this section we have seen that in addition to integers, real362numbers and rational numbers, PARI can handle complex numbers, polynomials,363rational functions and power series. A large number of functions exist which364handle these types, but in this tutorial we will only look at a few.365366\misctitle{Additional comments} (as before, you are supposed to skip this367at first reading)3683691) In almost all cases, there is no loss of information in PARI output: what370you see is all that PARI knows about the object, and you can happily371copy-paste it into another session. There are exceptions, though. Type372\kbd{n = 3 + 0*x}, then \kbd{n} is not the integer 3 but a constant polynomial373equal to $3 x^0$. Check it with \kbd{type(n)}.374375However, it \emph{looks} like an integer without being one, and this may376cause some confusion in programs which actually expect integers. Hence if you377try to \kbd{factor(n)}, you obtain an empty factorization ! (Because, once378considered as a polynomial, \kbd{n} is a unit in $\Q[x]$.)379380If you try to apply more general arithmetic functions, say the Euler totient381function (known as \kbd{eulerphi} to \kbd{gp}), you get an error message382worrying about integer arguments. You would have guessed yourself, but the383message is difficult to understand since 3 looks like a genuine integer!384Please make sure you understand the above, it is a common source of385incomprehension.3863872) If you want the final expression to be in the simplest form possible (for388example before applying an arithmetic function, or simply because things will389go faster afterwards), apply the function \kbd{simplify} to the result.390This is done automatically at the end of a \kbd{gp} command, but391\emph{not} in intermediate expressions. Hence \kbd{n} above is not an392integer, but the final result stored in the output history is! So393if you type \kbd{type(\%)} instead of \kbd{type(n)} the answer is394\typ{INT}, adding to the confusion.3953963) As already stated, power series expansions are always implicitly around397$\kbd{x} = 0$. When we wante them around $\kbd{x} = \kbd{a}$, we replace398\kbd{x} by \kbd{z + a} in the function we want to expand. For complicated399functions, it may be simpler to use the substitution function \kbd{subst}.400For example, if \kbd{p~= 1 / (x\pow 4 + 3*x\pow 3 + 5*x\pow 2 - 6*x + 7)},401you may not want to retype this, replacing \kbd{x} by \kbd{z~+ a}, so you can402write \kbd{subst(p, x, z+a)} (look up the exact description of the403\kbd{subst} function).4044054) The valuation at $\kbd{x} = 0$ for a power series \kbd{p} is obtained406as \kbd{valuation(p, x)}.407408\section{The Remaining PARI Types}409Let's talk some more about the basic PARI types.410411Type \kbd{p = x * exp(-x)}. As expected, you get the power series expansion412to 17 terms (if you have not changed the default). Now type413\kbd{pr = serreverse(p)}. You are asking here for the \emph{reversion} of the414power series \kbd{p}, in other words the expansion of the inverse function.415This is possible only for power series whose first nonzero coefficient is416that of $x^1$. To check the correctness of the result, you can type417\kbd{subst(p, x, pr)} or \kbd{ subst(pr, x, p)} and you should get back418\kbd{x + O(x\pow 18)}.419420Now the coefficients of \kbd{pr} obey a very simple formula. First, we would421like to multiply the coefficient of \kbd{x\pow n} by \kbd{n!} (in the case of422the exponential function, this would simplify things considerably!). The PARI423function \kbd{serlaplace} does just that. So type \kbd{ps = serlaplace(pr)}.424The coefficients now become integers, which can be immediately recognized by425inspection. The coefficient of $x^n$ is now equal to426$n^{n-1}$. In other words, we have427%428$$\kbd{pr} = \sum_{n\ge1}\dfrac{n^{n-1}}{n!} X^{n}.$$429%430Do you know how to prove this? (The proof is difficult.)431\smallskip432%433Of course PARI knows about vectors (rows and columns are distinguished, even434though mathematically there is no difference) and matrices. Type for example435\kbd{[1,2,3,4]}. This gives the row vector whose coordinates are 1, 2, 3 and4364. If you want a column vector, type \kbd{[1,2,3,4]\til}, the tilde meaning437of course transpose. You don't see much difference in the output, except for438the tilde at the end. However, now type \b{B}: lo and behold, the column439vector appears as a proper vertical thingy now. The \b{B} command is used440mainly for this purpose. The length of a vector is given by, well441\kbd{length} of course. The shorthand ``cardinality'' notation \kbd{\#v} for442\kbd{length(v)} is also available, for instance \kbd{v[\#v]} is the last443element of \kbd{v}.444445Type \kbd{m = [a,b,c; d,e,f]}. You have just entered a matrix with 2 rows and4463 columns. Note that the matrix is entered by \emph{rows} and the rows are447separated by semicolons ``\kbd{;}''. The matrix is printed naturally in a448rectangle shape. If you want it printed horizontally just as you typed it,449type \b{a}, or if you want this type of printing to be the permanent default450type \kbd{default(output, 0)}. Type \kbd{default(output, 1)} if you want to451come back to the original output mode.452453Now type \kbd{m[1,2]}, \kbd{m[1,]}, \kbd{m[,2]}. Are explanations necessary?454(In an expression such as \kbd{m[j,k]}, the \kbd{j} always refers to the455row number, and the \kbd{k} to the column number, and the first index is456always 1, never 0. This default cannot be changed.)457458Even better, type \kbd{m[1,2] = 5; m}. The semicolon also allows us to put459several instructions on the same line; the final result is the output of460the last statement on the line. Now type \kbd{m[1,] = [15,-17,8]}. No461problem. Finally type \kbd{m[,2] = [j,k]}. You have an error message since you462have typed a row vector, while \kbd{m[,2]} is a column vector. If you type463instead \kbd{m[,2] = [j,k]\til} it works. \smallskip464%465\label{se:types}466Type now \kbd{h = mathilbert(20)}. You get the so-called ``Hilbert matrix''467whose coefficient of row $i$ and column $j$ is equal to $(i+j-1)^{-1}$.468Incidentally, the matrix \kbd{h} takes too much room. If you don't want to469see it, simply type a semi-colon ``\kbd{;}'' at the end of the line470(\kbd{h = mathilbert(20);}). This is an example of a ``precomputed'' matrix,471built into PARI. We will see a more general construction later.472473What is interesting about Hilbert matrices is that first their inverses and474determinants can be computed explicitly (and the inverse has integer475coefficients), and second they are numerically very unstable, which make them476a severe test for linear algebra packages in numerical analysis. Of course477with PARI, no such problem can occur: since the coefficients are given as478rational numbers, the computation will be done exactly, so there cannot be479any numerical error. Try it. Type \kbd{d~=~matdet(h)}. The result is a480rational number (of course) of numerator equal to 1 and denominator having481226 digits. How do I know, by the way? Well, type \kbd{sizedigit(1/d)}. Or482\kbd{\#Str(1/d)}. (The length of the character string representing the483result.)484485Now type \kbd{hr = 1.* h;} (do not forget the semicolon, we don't want to see486the result!), then \kbd{dr = matdet(hr)}. You notice two things. First the487computation, is much faster than in the rational case. (If your computer is488too fast for you to notice, try again with \kbd{h = mathilbert(40)}, or489even some larger value.) The reason for this is that PARI is handling real490numbers with 38 digits of accuracy, while in the rational case it is491handling integers having up to 226 decimal digits.492493The second, more important, fact is that the result is terribly wrong. If you494compare with \kbd{1.$*$d} computed earlier, which is the correct answer, you495will see that few decimals agree! (None agree if you replaced 20 by 40 as496suggested above.) This catastrophic instability is as already mentioned one497of the characteristics of Hilbert matrices. In fact, the situation is498worse than that. Type \kbd{norml2(1/h - 1/hr)} (the function \kbd{norml2}499gives the square of the $L^2$ norm, i.e.~the sum of the squares of the500coefficients). The result is larger than $10^{32}$, showing that some501coefficients of \kbd{1/hr} are wrong by as much as $10^{16}$. To obtain the502correct result after rounding for the inverse, we have to use a default503precision of 57 digits (try it).504505Although vectors and matrices can be entered manually, by typing explicitly506their elements, very often the elements satisfy a simple law and one uses a507different syntax. For example, assume that you want a vector whose $i$-th508coordinate is equal to $i^2$. No problem, type for example509\kbd{vector(10,i, i\pow 2)} if you want a vector of length 10. Similarly, if510you type511\bprog512matrix(5,5, i,j, 1 / (i+j-1))513@eprog\noindent514you will get the Hilbert matrix of order 5, hence the \kbd{mathilbert}515function is in fact redundant. The \kbd{i} and \kbd{j} represent dummy516variables which are used to number the rows and columns respectively (in517the case of a vector only one is present of course). You must not forget,518in addition to the dimensions of the vector or matrix, to indicate519explicitly the names of these variables. You may omit the variables and520the final expression to get zero entries, as in \kbd{matrix(10,20)}.521522\misctitle{Warning} The letter \kbd{I} is reserved for the complex number523equal to the square root of $-1$. Hence it is forbidden to use it as a524variable. Try typing \kbd{vector(10,I, I\pow 2)}, the error message that you525get clearly indicates that \kbd{gp} does not consider \kbd{I} as a variable.526There are other reserved variable names: \kbd{Pi}, \kbd{Euler},527\kbd{Catalan} and \kbd{oo}. All function names are forbidden as well. On the528other hand there is nothing special about \kbd{i}, \kbd{pi}, \kbd{euler} or529\kbd{catalan}.530531When creating vectors or matrices, it is often useful to use Boolean532operators and the \kbd{if()} statement. Indeed, an \kbd{if} expression has a533value, which is of course equal to the evaluated part of the \kbd{if}. So for534example you can type535\bprog536matrix(8,8, i,j, if ((i-j)%2, 1, 0))537@eprog\noindent538to get a checkerboard matrix of \kbd{1} and \kbd{0}. Note however539that a vector or matrix must be \emph{created} first before being used. For540example, it is possible to write541\bprog542v = vector(5);543for (i = 1, 5, v[i] = 1/i)544@eprog\noindent545but this would fail if the vector \kbd{v} had not been created beforehand.546Of course, the above example is better written as547\bprog548v = vector(5, i, 1/i);549@eprog550551Another useful way to create vectors and matrices is to extract them from552larger ones. For instance, if \kbd{h} is the $20\times 20$ Hilbert matrix as above,553\bprog554h = mathilbert(20);555h[11..20, 11..20]556@eprog\noindent is its lower right quadrant.557558\medskip The last PARI types which we have not yet played with are closely559linked to number theory. People not interested in number theory can skip560ahead.561562The first is the type ``integer--modulo''. Let us see an example. Type563\bprog564n = 10^15 + 3565@eprog566We want to know whether this number is prime or not. Of course we could make567use of the built-in facilities of PARI, but let us do otherwise. We first568trial divide by the built-in table of primes. We slightly cheat here and use569a variant of the function \kbd{factor} which does exactly this. So type570\kbd{factor(n, 200000)}. The last argument tells \kbd{factor} to trial divide571up to the given bound and stop at this point. Set it to 0 to trial divide by572the full set of built-in primes, which goes up to $500000$ by default.573574As for all factoring functions, the result is a 2 column matrix: the first575column gives the primes and the second their exponents. Here we get a single576row, telling us that if primes stopped at $200000$ as we made \kbd{factor}577believe, \kbd{n} would be prime. (Or is that a contradiction?) More578seriously, \kbd{n} is not divisible by any prime up to $200000$.579580We could now trial divide further, or cheat and call the PARI function581\kbd{factor} without the optional second argument, but before we do this let582us see how to get an answer ourselves.583584By Fermat's little theorem, if $n$ is prime we must have $a^{n-1}\equiv 1585\pmod{n}$ for all $a$ not divisible by $n$. Hence we could try this with $a=2$586for example. But $2^{n-1}$ is a number with approximately $3\cdot10^{14}$587digits, hence impossible to write down, let alone to compute. But instead type588\kbd{a = Mod(2,n)}. This creates the number $2$ considered now as an element589of the ring $R = \Z/\kbd{n}\Z$. The elements of $R$, called intmods, can590always be represented by numbers smaller than \kbd{n}, hence small. Fermat's591theorem can be rewritten592%593$\kbd{a}^{n-1} = \kbd{Mod(1,n)}$594%595in the ring $R$, and this can be computed very efficiently. Elements of $R$596may be lifted back to $\Z$ with either \kbd{lift} or \kbd{centerlift}. Type597\kbd{a\pow (n-1)}. The result is definitely \emph{not} equal to598\kbd{Mod(1,n)}, thus \emph{proving} that \kbd{n} is not a prime. If we had599obtained \kbd{Mod(1,n)} on the other hand, it would have given us a hint that600\kbd{n} is maybe prime, but not a proof.601602To find the factors is another story. In this case, the integer $n$ is small603enough to let trial division run to completion. Type \kbd{\#} to turn on the604\kbd{gp} timer, then605\bprog606for (i = 2, ceil(sqrt(n)), if (n%i==0, print(i); break))607@eprog\noindent608This should take less than 5 seconds. In general, one must use less naive609techniques than trial division, or be very patient. Type \kbd{fa = factor(n)}610to let the factoring engine find all prime factors. You may stop the timer by611typing \kbd{\#} again.612613Note that, as is the case with most ``prime''-producing functions, the614``prime'' factors given by \kbd{factor} are only strong pseudoprimes, and not615\emph{proven} primes. Use \kbd{isprime( fa[,1] )} to rigorously prove616primality of the factors. The latter command applies \kbd{isprime} to all617entries in the first column of \kbd{fa}, i.e to all pseudoprimes, and returns618the column vector of results: all equal to 1, so our pseudoprimes were619true primes. All arithmetic functions can be applied in this way to the entries620of a vector or matrix. In fact, it has been checked that the strong621pseudoprimes output by \kbd{factor} (Baillie-Pomerance-Selfridge-Wagstaff622pseudoprimes, without small divisors) are true primes at least up to623$2^{64}$, and no explicit counter-example is known.\smallskip624625The second specifically number-theoretic type is the $p$-adic numbers. I have626no room for definitions, so please skip ahead if you have no use for such627beasts. A $p$-adic number is entered as a rational or integer valued628expression to which is added \kbd{O(p\pow n)}, or simply \kbd{O(p)} if629$\kbd{n}=1$, where \kbd{p} is the prime and \kbd{n} the $p$-adic precision.630Note that you have to explicitly type in \kbd{3\pow 2} for instance, \kbd{9}631will not do. Unless you want to cheat \kbd{gp} into believing that \kbd{9}632is prime, but you had better know what you are doing in this case: most633computations will yield a wrong result.634635Apart from the usual arithmetic operations, you can apply a number of636transcendental functions. For example, type \kbd{n = 569 + O(7\pow 8)}, then637\kbd{s~=~sqrt(n)}, you obtain one of the square roots of \kbd{n}; to check638this, type \kbd{s\pow 2 - n}). Type now \kbd{s = log(n)}, then \kbd{e =639exp(s)}. If you know about $p$-adic logarithms, you will not be surprised640that \kbd{e} is not equal to \kbd{n}. Type \kbd{(n/e)\pow 6}: \kbd{e} is in641fact equal to \kbd{n} times the $(p-1)$-st root of unity \kbd{teichmuller(n)}.642643Incidentally, if you want to get back the integer 569 from the $p$-adic644number \kbd{n}, type \kbd{lift(n)} or \kbd{truncate(n)}.645\smallskip646647The third number-theoretic type is the type ``quadratic number''. This type648is specially tailored so that we can easily work in a quadratic extension of649a base field, usually $\Q$. It is a generalization of the type650``complex''. To start, we must specify which quadratic field we want to work651in. For this, we use the function \kbd{quadgen} applied to the652\emph{discriminant} \kbd{d} (as opposed to the radicand) of the quadratic653field. This returns a number equal to654$(\kbd{d}+a) / 2$ where $a$ is equal to 0 or 1 according to whether \kbd{d} is655even or odd. The function \kbd{quadgen} takes an extra parameter which is how656the number will be printed. To avoid confusion, this number should be657set to a variable of the same name, i.e. do \kbd{w = quadgen(d, 'w)}.658659So type \kbd{w = quadgen(-163,'w)}, then \kbd{charpoly(w)} which asks for the660characteristic polynomial of \kbd{w}. The result shows what \kbd{w} will661represent. You may ask for \kbd{1.*w} to see which root of the quadratic has662been taken, but this is rarely necessary. We can now play in the field663$\Q(\sqrt{-163})$. Type for example \kbd{w\pow 10}, \kbd{norm(3 + 4*w)},664\kbd{1 / (4+w)}. More interesting, type \kbd{a = Mod(1,23) * w} then \kbd{b =665a\pow 264}. This is a generalization of Fermat's theorem to quadratic fields.666If you do not want to see the modulus 23 all the time, type \kbd{lift(b)}.667668Another example: type \kbd{p = x\pow 2 + w*x + 5*w + 7}, then \kbd{norm(p)}. We669thus obtain the quartic equation over $\Q$ corresponding to the relative670quadratic extension over $\Q(\kbd{w})$ defined by \kbd{p}.671672On the other hand, if you type \kbd{wr = sqrt(w\pow 2)}, do not expect to get673back \kbd{w}. Instead, you get the numerical value, the function \kbd{sqrt}674being considered as a ``transcendental'' function, even though it is675algebraic. Type \kbd{algdep(wr,2)}: this looks for algebraic relations676involving the powers of \kbd{w} up to degree 2. This is one way to get677\kbd{w} back. Similarly, type \kbd{algdep(sqrt(3*w + 5), 4)}. See the user's678manual for the function \kbd{algdep}.\smallskip679680The fourth number-theoretic type is the type ``polynomial--modulo'', i.e.681polynomial modulo another polynomial. This type is used to work in general682algebraic extensions, for example elements of number fields (if the base683field is $\Q$), or elements of finite fields (if the base field is684$\Z/p\Z$ for a prime $p$). In a sense it is a generalization of the type685quadratic number. The syntax used is the same as for intmods. For example,686instead of typing \kbd{w = quadgen(-163,'w)}, you can type687\bprog688w = Mod(x, quadpoly(-163))689@eprog\noindent690Then, exactly as in the quadratic case, you can type \kbd{w\pow 10},691\kbd{norm(3 + 4*w)}, \kbd{1 / (4+w)}, \kbd{a = Mod(1,23)*w}, \kbd{b = a\pow692264}, obtaining of course the same results. (Type \kbd{lift(\dots)} if you693don't want to see the polynomial \kbd{x\pow 2 - x + 41} repeated all the694time.) Of course, you can work in any degree, not only quadratic. For the695latter, the corresponding elementary operations will be slower than696with quadratic numbers. Start the timer, then compare697\bprog698w = quadgen(-163,'w); W = Mod(x, quadpoly(-163));699a = 2 + w; A = 2 + W;700b = 3 + w; B = 3 + W;701for (i=1,10^5, a+b)702for (i=1,10^5, A+B)703for (i=1,10^5, a*b)704for (i=1,10^5, A*B)705for (i=1,10^5, a/b)706for (i=1,10^5, A/B)707@eprog\noindent708Don't retype everything, use the arrow keys!709710There is however a slight difference in behavior. Keeping our polmod \kbd{w},711type \kbd{1.*w}. As you can see, the result is not the same. Type712\kbd{sqrt(w)}. Here, we obtain a vector with 2 components, the two components713being the principal branch of the square root of all the possible embeddings714of \kbd{w} in $\C$. More generally, if715\kbd{w} was of degree $n$, we would get an $n$-component vector, and similarly716for all transcendental functions.717718We have at our disposal the usual arithmetic functions, plus a few others.719Type \kbd{a = Mod(x, x\pow 3 - x - 1)} defining a cubic extension. We can for720example ask for \kbd{b = a\pow 5}. Now assume we want to express \kbd{a}721as a polynomial in \kbd{b}. This is possible since \kbd{b} is also a722generator of the same field. No problem, type \kbd{modreverse(b)}. This gives723a new defining polynomial for the same field, i.e.~the characteristic724polynomial of \kbd{b}, and expresses \kbd{a} in terms of this new polmod,725i.e.~in terms of \kbd{a}. We will see this in more detail in the number726field section.727728An important special case of the above construction allows to work in finite729fields, by choosing an irreducible polynomial $T$ of degree $f$ over $\F_p$730and considering $\F_p[t]/(T)$. As in731\bprog732T = ffinit(5, 6, 't); \\ @com degree 6, irreducible over $\F_5$733g = Mod(t, T)734@eprog\noindent Try a few elementary operations involving $g$, such as735$g^{100}$. This special case of \typ{POLMOD}s is in fact so important that we736now introduce a final dedicated number theoretical type \typ{FFELT}, for737``finite field element'', to simplify work with finite fields: \kbd{g =738ffgen(5\pow6, 't)} computes a suitable polynomial $T$ as above and returns739the generator $t \mod T(t)$. This has major advantages over the generic740\typ{POLMOD} solution: elements are printed in a simplified way (in lifted741form), and functions can assume that $T$ is indeed irreducible. A few dedicated742functions \kbd{ffprimroot} (analog of \kbd{znprimroot}), \kbd{fforder}743(analog of \kbd{znorder}), \kbd{fflog} (analog of \kbd{znlog}) are available.744Rational expressions in the variable $t$ can be mapped to such a finite745field by substituting $t$ by $g$, for instance746\bprog747? g = ffgen(5^6, 't);748? g.mod \\ @com irreducible over $\F_5$, defines $\F_{5^6}$749%2 = t^6 + t^5 + t^4 + t^3 + t^2 + t + 1750? Q = x^2 + t*x + 1751? factor(subst(Q,t,g))752%3 =753[ x + (t^5 + 3*t^4 + t^3 + 4*t + 1) 1]754755[x + (4*t^5 + 2*t^4 + 4*t^3 + 2*t + 4) 1]756@eprog\noindent factors the polynomial $Q \in \F_{5^6}[x]$, where757$\F_{5^6} = \F_5[t]/(\kbd{g.mod})$.758759\section{Elementary Arithmetic Functions}760761Since PARI is aimed at number theorists, it is not surprising that there762exists a large number of arithmetic functions; see the list by typing763\kbd{?5}. We have already seen several, such as \kbd{factor}. Note that764\kbd{factor} handles not only integers, but also univariate polynomials.765Type for example \kbd{factor(x\pow 200 - 1)}. You can also ask to factor a766polynomial modulo a finite field or a number field !767768Evidently, you have functions for computing GCD's (\kbd{gcd}), extended GCD's769(\kbd{bezout}), solving the Chinese remainder theorem (\kbd{chinese}) and so770on.771772In addition to the factoring facilities, you have a few functions related to773primality testing such as \kbd{isprime}, \kbd{ispseudoprime},774\kbd{precprime}, and \kbd{nextprime}. As previously mentioned, only strong775pseudoprimes are produced by the latter two (they pass the776\kbd{ispseudoprime} test); the more sophisticated primality tests in777\kbd{isprime}, being so much slower, are not applied by default.778779We also have the usual multiplicative arithmetic functions: the M\"obius $\mu$780function (\kbd{moebius}), the Euler $\phi$ function (\kbd{eulerphi}), the781$\omega$ and $\Omega$ functions (\kbd{omega} and \kbd{bigomega}), the782$\sigma_k$ functions (\kbd{sigma}), which compute sums of $k$-th powers of the783positive divisors of a given integer, etc\dots784785You can compute continued fractions. For example, type \kbd{\b{p} 1000}, then786\kbd{contfrac(exp(1))}: you obtain the continued fraction of the base of787natural logarithms, which as you can see obeys a very simple pattern. Can788you prove it?789790In many cases, one wants to perform some task only when an arithmetic791condition is satisfied. \kbd{gp} gives you the following functions: \kbd{isprime}792as mentioned above, \kbd{issquare}, \kbd{isfundamental} to test whether an793integer is a fundamental discriminant (i.e.~$1$ or the discriminant of a794quadratic field), and the \kbd{forprime}, \kbd{fordiv} and \kbd{sumdiv}795loops. Assume for example that we want to compute the product of all the796divisors of a positive integer \kbd{n}. The easiest way is to write797\bprog798p = 1; fordiv(n,d, p *= d); p799@eprog\noindent800(There is a simple formula for this product in terms of $n$ and the number of801its divisors: find and prove it!) The notation \kbd{p *= d} is just a802shorthand for \kbd{p = p * d}.803804If we want to know the list of primes $p$ less than 1000 such that 2 is a805primitive root modulo $p$, one way would be to write:806\bprog807forprime(p=3,1000, if (znprimroot(p) == 2, print(p)))808@eprog\noindent809%810Note that this assumes that \kbd{znprimroot} returns the smallest primitive811root, and this is indeed the case. Had we not known about this, we could812have written813\bprog814forprime(p=3,1000, if (znorder(Mod(2,p)) == p-1, print(p)))815@eprog\noindent816%817(which is actually faster since we only compute the order of $2$ in $\Z/p\Z$,818instead of looking for a generator by trying successive elements whose orders819have to be computed as well.) Once we know a primitive root $g$, we can write820any nonzero element of $\Z/p\Z$ as $g^x$ for some unique $x$ in $\Z/(p-1)\Z$.821Computing such a discrete logarithm is a hard problem in general, performed822by the function \kbd{znlog}.823824Arithmetic functions related to quadratic fields, binary quadratic forms and825general number fields will be seen in the next sections.826827\section{Performing Linear Algebra}828The standard linear algebra routines are available: \kbd{matdet},829\kbd{mateigen} (eigenvectors), \kbd{matker}, \kbd{matimage}, \kbd{matrank},830\kbd{matsolve} (to solve a linear system), \kbd{charpoly} (characteristic831polynomial), to name a few. Bilinear algebra over $\R$ is also there:832\kbd{qfgaussred} (Gauss reduction), \kbd{qfsign} (signature). You may also833type \kbd{?7}. Can you guess what each of these do?834835Let us see how this works. First, a vector space (or module) is given by a836generating set of vectors (often a basis) which are represented as837\emph{column} vectors. This set of vectors is in turn represented by the838columns of a matrix. Quadratic forms are represented by their Gram matrix.839The base field (or ring) can be any ring type PARI supports. However, certain840operations are specifically written for a real or complex base field, while841others are written for $\Z$ as the base ring.842843We had some fun with Hilbert matrices and numerical instability a while back,844but most of the linear algebra routines are generic. If as before \kbd{h =845mathilbert(20)}, we may compute846\bprog847matdet(h * Mod(1,101))848matdet(h * (1 + O(101^100)))849@eprog\noindent850in $\Z/101\Z$ and the $p$-adic ring $\Z_{101}$ (to $100$ words of accuracy)851respectively. Let \kbd{H = 1/h} the inverse of \kbd{h}:852\bprog853H = 1/h; \\ @com integral854L = primes([10^5, 10^5 + 1000]); \\ @com pick a few primes855v = vector(#L, i, matdet(H * Mod(1,L[i])));856centerlift( chinese(v) )857@eprog\noindent858returns the determinant of \kbd{H}. (Assuming it is an integer859less than half the product of elements of \kbd{L} in absolute value, which860it is.)861In fact, we computed an homomorphic image of the determinant in a few small862finite fields, which admits a single integer representative given the size863constraints. We could also have made a single determinant computation modulo864a big prime (or pseudoprime) number, e.g \kbd{nextprime(2 * B)} if we know865that the determinant is less than \kbd{B} in absolute value.866(Why is that $2$ necessary?)867868By the way, this is how you insert comments in a script: everything869following a double backslash, up to the first newline character, is ignored.870If you want comments which span many lines, you can brace them between871\kbd{/* ... */} pairs. Everything in between will be ignored as well. For872instance as a header for the script above you could insert the873following:874\bprog875/* Homomorphic imaging scheme to compute the determinant of a classical876* integral matrix.877* TODO: Look up the explicit formula878*/879@eprog\noindent880(I hope you did not waste your time copying this nonsense, did you?)881\medskip882883In addition, linear algebra over $\Z$, i.e.~work on lattices, can also be884performed. Let us now consider the lattice $\Lambda$ generated by the columns885of \kbd{H} in $\Z^{20}\subset\R^{20}$. Since the determinant is nonzero, we886have in fact a basis. What is the structure of the finite abelian group887$\Z^{20}/\Lambda$? Type \kbd{matsnf(H)}. Wow, 20 cyclic factors.888889890There is a triangular basis for $\Lambda$ (triangular when expressed in891the canonical basis), perhaps it looks better than our initial one? Type892\kbd{mathnf(H)}. Hum, what if I also want the unimodular transformation893matrix? Simple : \kbd{z = mathnf(H, 1);} \kbd{z[1]} is the triangular HNF894basis, and \kbd{z[2]} is the base change matrix from the canonical basis to895the new one, with determinant $\pm 1$. Try \kbd{matdet(z[2])},896then \kbd{H * z[2] == z[1]}. Fine, it works. And \kbd{z[1]} indeed looks897better than \kbd{H}.898899Can we do better? Perhaps, but then we'd better drop the requirement that900the basis be triangular, since the latter is essentially canonical. Type901\bprog902M = H * qflll(H)903@eprog904Its columns give an LLL-reduced basis for $\Lambda$ (\kbd{qflll(H)} itself905gives the base change matrix). The LLL algorithm outputs a nice basis for a906lattice given by an arbitrary basis, where nice means the basis vectors are907almost orthogonal and short, with precise guarantees on their relations to908the shortest vectors. Not really spectacular on this example, though.909910Let us try something else, there should be an integer relation between911$\log 3$, $\log 5$ and $\log 15$. How to detect it?912\bprog913u = [log(15), log(5), log(3)];914m = matid(3); m[3,] = round(u * 10^25);915v = qflll(m)[,1] \\@com first vector of the LLL-reduced basis916u * v917@eprog\noindent918Pretty close. In fact, \kbd{lindep} automates this kind of search for integer919relations; try \kbd{lindep(u)}.920921Let us come back to $\Lambda$ above, and our LLL basis in \kbd{M}. Type922\bprog923G = M~*M \\@com Gram matrix924m = qfminim(G, norml2(M[,1]), 100, 2);925@eprog\noindent926This enumerates the vectors in $\Lambda$ which are shorter than the first LLL927basis vector, at most 100 of them. The final argument $2$ instructs the928function to use a safe (slower) algorithm, since the matrix entries are929rather large; trying to remove it should produce an error, in this case.930There are $\kbd{m[1]} = 6$ such vectors, and \kbd{m[3]} gives half of them931(\kbd{-m[3]} would complete the lot): they are the first 3 basis vectors! So932these are optimally short, at least with respect to the Euclidean length. Let933us try934\bprog935m = qfminim(G, norml2(M[,4]), 100, 2);936@eprog\noindent937(The flag $2$ instructs \kbd{qfminim} to use a different enumeration938strategy, which is much faster when we expect more short vectors than we want939to store. Without the flag, this example requires several hours. This is an940exponential time algorithm, after all!) This time, we find a slew of short941vectors; \kbd{matrank(m[3])} says the 100 we have are all included in a9422-dimensional space. Let us try943\bprog944m = qfminim(G, norml2(M[,4]) - 1, 100000, 2);945@eprog\noindent946This time we find 50886 vectors of the requested length, spanning a947$4$-dimensional space, which is actually generated by \kbd{M[,1]},948\kbd{M[,2]} \kbd{M[,3]} and \kbd{M[,5]}.949950\section{Using Transcendental Functions}951952All the elementary transcendental functions and several higher transcendental953functions are provided: $\Gamma$ function, incomplete $\Gamma$ function, error954function, exponential integral, Bessel functions ($H^1$, $H^2$, $I$, $J$,955$K$, $N$), confluent hypergeometric functions, Riemann $\zeta$ function,956polylogarithms, Weber functions, theta functions. More will be written if the957need arises.958959In this type of functions, the default precision plays an essential role.960In almost all cases transcendental functions work in the following way.961If the argument is exact, the result is computed using the current962default precision. If the argument is not exact, the precision of the963argument is used for the computation. A note of warning however: even in this964case the \emph{printed} value is the current real format, usually the965same as the default precision. In the present chapter we assume that your966machine works with 64-bit long integers. If it is not the case, we leave it967to you as a good exercise to make the necessary modifications.968969Let's assume that we have 38 decimals of default precision (this is what we970get automatically at the start of a \kbd{gp} session on 64-bit machines). Type971\kbd{e = exp(1)}. We get the number $e=2.718\dots$ to 38 decimals. Let us check972how many correct decimals we really have. Change the precision to a973substantially higher value, for example by typing \kbd{\b{p} 100}. Then type974\kbd{e}, then \kbd{exp(1)} once again. This last value is the correct value975of the mathematical constant $e$ to 100 decimals, while the variable \kbd{e}976shows the value that was computed to 38 decimals. Clearly they coincide to977exactly 38 significant digits.978979So 38 digits are printed, but how many significant digits are actually980contained in the variable \kbd{e}? Type \kbd{\#e} which indicates we have981exactly $2$ mantissa words. Since $2\ln(2^{64}) / \ln(10)\approx38.5$ we see982that we have 38 or 39 significant digits (on 64-bit machines).983984\smallskip985Come back to 38 decimals (\kbd{\b{p} 38}). If we type \kbd{exp(1.)}986you can check that we also obtain 38 decimals. However, type987\kbd{f = exp(1 + 1E-40)}. Although the default precision is still 38,988you can check using the method above that we have in fact 96 significant989digits! The reason is that \kbd{1 + 1E-40} is computed according to the PARI990philosophy, i.e.~to the best possible precision. Since \kbd{1E-40} has 39991significant digits and 1 has ``infinite'' precision, the number \kbd{1 +9921E-40} will have at least $79=39+40$ significant digits, hence \kbd{f} also.993994Now type \kbd{cos(1E-19)}. The result is printed as $1.0000\dots$, but995is of course not exactly equal to 1. Using \kbd{\#\%}, we see that the996result has 4 mantissa words, giving us the possibility of having 77997correct significant digits. PARI gives you as much as it can, and since 3998mantissa words would have given you only 57 digits, it uses 4. But why does999it give so precise a result? Well, it is the same reason as before. When $x$1000is close to 1, $\cos(x)$ is close to $1-x^2/2$, hence the precision is going1001to be approximately the same as when computing this quantity, here1002$1-0.5*10^{-38}$ where $0.5*10^{-38}$ is considered with 38 significant digit1003accuracy. Hence the result will have approximately $38+38=76$ significant1004digits.10051006This philosophy cannot go too far. For example, when you type \kbd{cos(0)},1007\kbd{gp} should give you exactly 1. Since it is reasonable for a program to1008assume that a transcendental function never gives you an exact result,1009\kbd{gp} gives you $1.000\dots$ with as many mantissa word as the current1010precision.1011\medskip1012Let's see some more transcendental functions at work. Type1013\kbd{gamma(10)}. No problem (type \kbd{9!} to check). Type \kbd{gamma(100)}.1014The number is now written in exponential format because the default accuracy1015is too small to give the correct result. To get all digits, the most natural1016solution is to increase the precision; since \kbd{gamma(100)} has 156 decimal1017digits, type \kbd{\b{p} 170} to be on the safe side, then \kbd{gamma(100)}1018once again. Another one is to compute \kbd{99!} directly.10191020Try \kbd{gamma(1/2 + 10*I)}. No problem, we have the complex $\Gamma$ function.1021Now type1022\bprog1023t = 1000;1024z = gamma(1 + I*t) * t^(-1/2) * exp(Pi/2*t) / sqrt(2*Pi)1025norm(z)1026@eprog\noindent The latter is very close to 1, in accordance with the complex1027Stirling formula.1028\smallskip10291030Let's play now with the Riemann zeta function. First turn on the timer (type1031\kbd{\#}). Type \kbd{zeta(2)}, then \kbd{Pi\pow 2/6}. This seems correct. Type1032\kbd{zeta(3)}. All this takes essentially no time at all. However, type1033\kbd{zeta(3.1)}. You will notice that the time is substantially larger; if1034your machine is too fast to see the difference, increase the precision to1035\kbd{\b{p}1000}. This is because PARI uses special formulas to compute1036\kbd{zeta(n)} when \kbd{n} is an integer.10371038Type \kbd{zeta(1 + I)}. This also works. Now for fun, let us compute in a1039naive way the first complex zero of \kbd{zeta}. We know that it is1040of the form $1/2 + i*t$ with $t$ between 14 and 15. Thus, we can use the1041following series of instructions. But instead of typing them directly, write1042them into a file, say \kbd{zeta.gp}, then type \kbd{\b{r} zeta.gp} under1043\kbd{gp} to read it in:1044\bprog1045{1046t1 = 1/2 + 14*I;1047t2 = 1/2 + 15*I; eps = 1E-50;1048z1 = zeta(t1);1049until (norm(z2) < eps,1050z2 = zeta(t2);1051if (norm(z2) < norm(z1),1052t3 = t1; t1 = t2; t2 = t3; z1 = z21053);1054t2 = (t1+t2) / 2.;1055print(t1 ": " z1)1056)1057}1058@eprog\noindent1059Don't forget the braces: they tell \kbd{gp} that a sequence of instructions1060is going to span many lines. We thus obtain the first zero to 25 significant1061digits.10621063By the way, you don't need to type in the suffix~\kbd{.gp} in the \b{r}1064command: it is supplied by \kbd{gp} if you forget it. The suffix is not1065mandatory either, but it is convenient to have all GP scripts labeled in the1066same distinctive way. Also, some text editors, e.g. Emacs or Vim, will1067recognize GP scripts as such by their suffix and load special colourful1068modes. \medskip1069%1070As mentioned at the beginning of this tutorial, some transcendental functions1071can also be applied to $p$-adic numbers. This is as good a time as any to1072familiarize yourself with them. Type1073\bprog1074a = exp(7 + O(7^10))1075log(a)1076@eprog\noindent All seems in order.1077\bprog1078b = log(5 + O(7^10))1079exp(b)1080@eprog\noindent Is something wrong? We don't recover the number we started1081with? This is normal: type1082\bprog1083exp(b) * teichmuller(5 + O(7^10))1084@eprog\noindent1085and we indeed recover our initial number. The Teichm\"uller1086character \kbd{teichmuller(x)} on $\Z_p^*$ is the unique \hbox{$(p-1)$-st}1087root of unity which is congruent to \kbd{x} modulo $p$, assuming that \kbd{x}1088is a $p$-adic unit.\smallskip1089%1090Let us come back to real numbers for the moment. Type \kbd{agm(1,sqrt(2))}.1091This gives the arithmetic-geometric mean of 1 and $\sqrt2$, and is the basic1092method for computing complete elliptic integrals. In fact, type10931094\kbd{Pi/2 / intnum(t=0,Pi/2, 1 / sqrt(1 + sin(t)\pow 2))},10951096\noindent and the result is the same. The elementary transformation1097\kbd{x = sin(t)} gives the mathematical equality1098$$\int_0^1 \dfrac{dx}{\sqrt{1-x^4}} = \dfrac{\pi}{2\text{AGM}(1,\sqrt2)}1099\enspace,$$1100which was one of Gauss's remarkable discoveries in his youth.11011102Now type \kbd{2 * agm(1,I) / (1+I)}. As you see, the complex AGM also works,1103although one must be careful with its definition. The result found is1104almost identical to the previous one. Do you see why?11051106Finally, type \kbd{agm(1, 1 + 7 + O(7\pow 10))}. So we also have $p$-adic1107AGM. Note however that since the square root of a $p$-adic number is not1108in general an element of the same $p$-adic field,1109only certain $p$-adic AGMs can be computed. In addition,1110when $p=2$, the congruence restriction is that \kbd{agm(a,b)} can be computed1111only when \kbd{a/b} is congruent to 1 modulo $16$, and not 8 as could be1112expected.\smallskip1113%1114Now type \kbd{?8}. This gives you the list of all transcendental functions.1115Instead of continuing with more examples, we suggest that you experiment1116yourself with this list. Try integer, real, complex and $p$-adic arguments.1117You will notice that some have not been implemented (or do not have a1118reasonable definition).11191120\section{Using Numerical Tools}11211122Although not written to be a numerical analysis package, PARI can1123nonetheless perform some numerical computations. Since linear algebra and1124polynomial computations are treated somewhere else, this section focuses on1125solving equations and various methods of summation.11261127You of course know the formula $\pi = 4(1-\dfrac13+\dfrac15-\dfrac17+\cdots)$1128which is deduced from the power series expansion of \kbd{atan(x)}. You also1129know that $\pi$ cannot be computed from this formula, since the convergence1130is so slow. Right? Wrong! Type1131\bprog1132\p 10011334 * sumalt(k=0, (-1)^k/(2*k + 1))1134@eprog\noindent In a split second, we get $\pi$ to 100 significant digits1135(type \kbd{Pi} to check).11361137Similarly, try1138\bprog1139sumpos(k=1, k^-2)1140@eprog\noindent Although once again the convergence is slow, the summation is1141rather fast; compare with the exact result \kbd{Pi\pow 2/6}. This is less1142impressive because a bit slower than for alternating sums, but still useful.11431144Even better, \kbd{sumalt} can be used to sum divergent series! Type1145\bprog1146zet(s) = sumalt(k=1, (-1)^(k-1) / k^s) / (1 - 2^(1-s))1147@eprog\noindent1148Then for positive values of \kbd{s} different from 1, \kbd{zet(s)} is equal1149to \kbd{zeta(s)} and the series converges, albeit slowly; \kbd{sumalt}1150doesn't care however. For negative \kbd{s}, the series diverges, but1151\kbd{zet(s)} still gives the correct result! (Namely, the value of a suitable1152analytic continuation.) Try \kbd{zet(-1)}, \kbd{zet(-2)}, \kbd{zet(-1.5)},1153and compare with the corresponding values of \kbd{zeta}. You should not push1154the game too far: \kbd{zet(-100)}, for example, gives a completely wrong1155answer.11561157Try \kbd{zet(I)}, and compare with \kbd{zeta(I)}. Even (some) complex values1158work, although the sum is not alternating any more! Similarly, try1159\bprog1160sumalt(n=1, (-1)^n / (n+I))1161@eprog1162\medskip1163More traditional functions are the numerical integration functions. Try1164\kbd{intnum(t=1,2, 1/t)} and presto! you get 100 decimals of $\log(2)$. Look1165at Chapter 3 to see the available integration functions.11661167With PARI, however, you can go further since complex types are allowed.1168For example, assume that we want to know the location of the zeros of the1169function $h(z)=e^z-z$. We use Cauchy's theorem, which tells us that the1170number of zeros in a disk of radius $r$ centered around the origin is1171equal to1172$$\dfrac{1}{2i\pi}\int_{C_r}\dfrac{h'(z)}{h(z)}\,dz\enspace,$$1173where $C_r$ is the circle of radius $r$ centered at the origin.1174The function we want to integrate is1175\bprog1176fun(z) = my(u = exp(z)); (u-1) / (u-z)1177@eprog\noindent1178(Here \kbd{u} is a local variable to the function \kbd{f}: whenever1179a function is called, \kbd{gp} fills its argument list with the actual arguments1180given, and initializes the other declared parameters and local variables to11810. It will then restore their former values upon exit. If we had not declared1182\kbd{u} in the function prototype, it would be considered as a global1183variable, whose value would be permanently changed. It is not mandatory to1184declare in this way all parameters, but beware of side effects!)11851186Type now:1187\bprog1188zero(r) = r/(2*Pi) * intnum(t=0, 2*Pi, real( fun(r*exp(I*t)) * exp(I*t) ))1189@eprog1190The function \kbd{zero(r)} will count the number of zeros of \kbd{fun}1191whose modulus is less than \kbd{r}: we simply made the change of variable1192$z = r*\exp(i*t)$, and took the real part to avoid integrating the1193imaginary part. Actually, there is a built-in function \kbd{intcirc}1194to integrate over a circle, yielding the much simpler:1195\bprog1196zero2(r) = intcirc(z=0, r, fun(z))1197@eprog1198(This is a little faster than the previous implementation, and no less1199accurate.)12001201We may type \kbd{\b{p} 9} since we know that the result is a small integer1202(but the computations should be instantaneous even at \b{p} 100 or so),1203then \kbd{zero(1)}, \kbd{zero(1.5)}. The result tells us that there are1204no zeros inside the unit disk, but that there are two (necessarily1205complex conjugate) in the annulus $1<|z|<1.5$. For the sake of1206completeness, let us compute them. Let $z = x+iy$ be such a zero, with1207$x$ and $y$ real. Then the equation $e^z-z=0$ implies, after elementary1208transformations, that $e^{2x}=x^2+y^2$ and that $e^x\cos(y)=x$. Hence1209$y=\pm\sqrt{e^{2x}-x^2}$ and hence $e^x\cos(\sqrt{e^{2x}-x^2})=x$.1210Therefore, type1211\bprog1212fun(x) = my(u = exp(x)); u * cos(sqrt(u^2 - x^2)) - x1213@eprog\noindent1214Then \kbd{fun(0)} is positive while \kbd{fun(1)} is negative. Come1215back to precision 38 and type1216\bprog1217x0 = solve(x=0,1, fun(x))1218z = x0 + I*sqrt(exp(2*x0) - x0^2)1219@eprog\noindent1220which is the required zero. As a check, type \kbd{exp(z) - z}.12211222Of course you can integrate over contours which are more complicated than1223circles, but you must perform yourself the variable changes, as we have done1224above to reduce the integral to a number of integrals on line segments.1225\smallskip1226%1227The example above also shows the use of the \kbd{solve} function. To use1228\kbd{solve} on functions of a complex variable, it is necessary to reduce the1229problem to a real one. For example, to find the first complex zero of the1230Riemann zeta function as above, we could try typing12311232\kbd{solve(t=14,15, real( zeta(1/2 + I*t) ))},12331234\noindent but this does not work because the real part is positive for1235$\kbd{t}=14$ and $15$. As it happens, the imaginary part works. Type12361237\kbd{solve(t=14,15, imag( zeta(1/2 + I*t) ))},12381239\noindent and this now works. We could also narrow the search interval and1240type for instance12411242\kbd{solve(t=14,14.2, real( zeta(1/2 + I*t) ))}12431244\noindent which would also work.12451246\section{Polynomials}12471248First a word of warning: it is essential to understand the difference between1249exact and inexact objects. Try1250\bprog1251gcd(x - Pi, x^2 - 6*zeta(2))1252@eprog\noindent1253We return a trivial GCD because the notion of GCD for inexact polynomials1254doesn't make much sense. A better quantitative approach is to use1255\bprog1256polresultant(x - Pi, x^2 - 6*zeta(2))1257@eprog\noindent1258A result close to zero shows that the GCD is nontrivial for small1259deformations of the inputs. Without telling us what it is, of course. This1260being said, we will mostly use polynomials (and power series) with exact1261coefficients in our examples.\smallskip12621263The simplest way to input a polynomial, is to simply write it down,1264or use an explicit formula for the coefficients and the function \kbd{sum}:1265\bprog1266T = 1 + x^2 + 27*x^10;1267T = sum(i = 1, 100, (i+1) * x^i);1268@eprog\noindent but it is in much more efficient to create a vector of1269coefficients then convert it to a polynomial using \kbd{Pol} or \kbd{Polrev}1270(\kbd{Pol([1,2])} is $x+2$, \kbd{Polrev([1,2]) is $2x + 1$}) :1271\bprog1272T = Polrev( vector(100, i, i) );12731274for (i=1, 10^4, Polrev( vector(100, i, i) ) ) \\@com time: 60ms1275for (i=1, 10^4, sum(i = 1, 100, (i+1) * x^i) ) \\@com time: 1,74ms1276@eprog\noindent The reason for the discrepancy is that the explicit summation1277(of densely encoded polynomials) is quadratic in the degree, whereas creating1278a vector of coefficients then converting it to a polynomial type is linear.12791280We also have a few built-in classical polynomial families. Consider the1281$15$-th cyclotomic polynomial,1282\bprog1283pol = polcyclo(15)1284@eprog\noindent1285which is of degree $\varphi(15)=8$. Now, type1286\bprog1287r = polroots(pol)1288@eprog\noindent We obtain the 8 complex roots of \kbd{pol}, given to 381289significant digits. To see them better, type \b{B}: they are given as pairs1290of complex conjugate roots, in some order. In fact, the1291function \kbd{polroots} returns the real roots first, in increasing order,1292then the other roots by increasing absolute value of their imaginary parts1293(so that pairs of complex conjugate roots appear together).12941295The roots of \kbd{pol} are by definition the primitive $15$-th roots of unity.1296To check this, simply type \kbd{rc = r\pow 15}. Why, we get an error message!1297Fair enough, vectors cannot be multiplied, even less raised to a power.1298However, type1299\bprog1300rc = r^15.01301@eprog\noindent without forgetting the `\kbd{.}' at the end. Now it works,1302because powering to a nonintegral exponent is a transcendental function and1303hence is applied termwise. Note that the fact that $15.0$ is a real number1304which is representable exactly as an integer has nothing to do with the1305problem.13061307We see that the components of the result are very close to 1. It is however1308tedious to look at all these real and imaginary parts. It would be impossible1309if we had many more. Let's do it automatically. Type1310\bprog1311rr = round(rc)1312exponent(rc - rr)1313@eprog\noindent We see that \kbd{rr} is indeed all 1's, and that the1314sup-norm of \kbd{rc - rr} is around $2^{-125}$, reasonable enough when we1315work with 128 bits of accuracy! In fact, \kbd{round} itself already provides1316a built-in rough approximation of the error:1317\bprog1318rr = round(rc, &e)1319@eprog\noindent Again, \kbd{e} contains the number of error bits when rounding1320\kbd{rc} to \kbd{rr}; in other words the sup norm of $\kbd{rc} - \kbd{rr}$1321is bounded by $2^{-\kbd{e}}$.1322%1323\smallskip1324Now type1325\bprog1326pol = x^5 + x^4 + 2*x^3 - 2*x^2 - 4*x - 31327factor(pol)1328factor( poldisc(pol) )1329fun(p) = factor(pol, O(p^10));1330@eprog\noindent The polynomial \kbd{pol} factors over $\Q$ (or $\Z$) as a1331product of two factors, and the primes dividing its discriminant are1332$11$, $23$ and $37$. We also created a function \kbd{fun(p)} which factors1333\kbd{pol} over $\Q_p$ to $p$-adic precision 10. Type1334\bprog1335fun(5)1336fun(11)1337fun(23)1338fun(37)1339@eprog\noindent to see different splittings. You can use \kbd{lift} to1340convert $p$-adic numbers to neighbouring rational numbers.13411342Similarly, type1343\bprog1344lf(p) = lift( factor(pol, p) );1345lf(2)1346lf(11)1347lf(23)1348lf(37)1349@eprog\noindent which show the different factorizations, this time over1350$\F_p$. In fact, even better: type successively1351\bprog1352T = ffgen(3^3, 't) \\@com we want \kbd{t} to be a free variable1353factor(pol, t)1354@eprog\noindent1355The element $T$ is printed as \kbd{t} but is actually defined modulo the1356irreducible polynomial \kbd{t\pow 3 + 2t + 2} over $\F_{3}$ (see1357\kbd{t.mod}): it defines the finite field $\F_{27}$. Note that we introduced1358a new variable $t$ to express elements in this nonprime field.1359More generally, the generic \kbd{factor} function allows a second argument1360which describes the domain over which we want to factor, here $\F_{27}$1361(and, above, $\Q_p$ to $10$ digits of accuracy and $\F_p$).1362Typing \kbd{factor(pol)} directly would factor it over $\Q$, not what we1363wanted.13641365Similarly, type1366\bprog1367pol2 = x^4 - 4*x^2 + 161368fn = lift( factor(pol2, t^2 + 1) )1369@eprog\noindent and we get the factorization of the polynomial \kbd{pol2}1370over the number field $\Q[t]/(t^2+1)$, i.e.~over $\Q(i)$. Without the1371\kbd{lift}, the result would involve number field elements as \typ{POLMOD}s1372of the form \kbd{Mod(1+t, t\pow2+1)}, which are more explicit but less1373readable.1374\smallskip13751376To summarize, in addition to being able to factor integers, you can factor1377polynomials over $\C$ using \kbd{polroots}, over $\R$ using1378\kbd{factor(,1.0)}, over finite fields using1379\kbd{factor(, p)}, over $\Q_p$ using \kbd{factor(, O(p\pow $n$))},1380over $\Q$ using \kbd{factor}, and over the number field $\Q[t]/(T)$ using1381\kbd{factor(, T)}.1382Note however that \kbd{factor} itself will guess intelligently over1383which ring you want to factor: try1384\bprog1385pol = x^2 + 1;1386factor(pol)1387factor(pol *1.)1388factor(pol * (1 + 0*I))1389factor(pol * (1 + 0.*I))1390factor(pol * Mod(1,2))1391factor(pol * Mod(1, Mod(1,3)*(t^2+1)))1392pol2 = x^2 + y^2;1393factor(pol2)1394factor(pol2 * Mod(1,5))1395@eprog\noindent1396In the present version \vers{}, it is not possible to factor over other1397base rings than the ones mentioned above, but multivariate polynomials over1398those rings are allowed as shown in the last examples. Other functions1399related to factoring are \kbd{padicappr}, \kbd{polrootsmod},1400\kbd{polrootspadic}, \kbd{polsturm}. Play with them a little.14011402Finally, type1403\bprog1404polsym(pol2, 20)1405@eprog\noindent where \kbd{pol2} was defined above. This gives the sum of the1406$k$-th powers of the roots of \kbd{pol2} up to $k=20$, of course computed1407using Newton's formula and not using \kbd{polroots}. You notice that every1408odd sum is zero (expected, since the polynomial is even), but also that1409the signs follow a regular pattern and that the (nonzero) absolute values1410are powers of 2. This is true: prove it, and more precisely find an explicit1411formula for the $k$-th symmetric power not involving (nonrational) algebraic1412numbers.14131414\section{Power Series}14151416Now let's play with power series as we have done at the beginning. Type1417\bprog1418N = 39;14198*x + prod(n=1,N, if(n%4, 1 - x^n, 1), 1 + O(x^(N+1)))^81420@eprog\noindent1421Apparently, only even powers of \kbd{x} appear. This is surprising, but can1422be proved using the theory of modular forms. Note that we initialize1423the product to \kbd{1 + O(x\pow (N+1))}, otherwise the whole computation would1424be done with polynomials; this would first have been slightly slower and also1425totally useless since the coefficients of \kbd{x\pow (N+1)} and above are1426irrelevant anyhow if we stop the product at $\kbd{n} = \kbd{N}$.14271428While we are on the subject of modular forms (which, together with Taylor1429series expansions are another great source of power series), type1430\bprog1431\ps 122 \\@com shortcut for \kbd{default(seriesprecision, 122)}1432d = x * eta(x)^241433@eprog\noindent This gives the first 122 terms of the Fourier series1434expansion of the modular discriminant function $\Delta$ of Ramanujan. Its1435coefficients give by definition the Ramanujan $\tau$ function, which has a1436number of marvelous properties (look at any book on modular forms for1437explanations). We would like to see its properties modulo 2. Type \kbd{d\%2}.1438Hmm, apparently PARI doesn't like to reduce coefficients of power series, or1439polynomials for that matter, directly. Can we do it without writing a little1440program? No problem. Type instead1441\bprog1442lift(Mod(1,2) * d)1443centerlift(Mod(1,3) * d)1444@eprog\noindent and now this works like a charm. The pattern in the first1445result is clear; the pattern is less clear in the second result, but1446nonetheless there is one. Of course, it now remains to prove it (see Antwerp1447III or your resident modular forms guru).14481449\section{Working with Elliptic Curves}14501451Now we are getting to more complicated objects. Just as with number fields1452which we will meet later on, the first thing to do is to initialize them.1453That's because a lot of data will be needed repeatedly, and it's much more1454convenient to have it ready once and for all. Here, this is done with the1455function \kbd{ellinit}.14561457So type1458\bprog1459e0 = ellinit([6,-3,9,-16,-14])1460@eprog1461This computes a number of things1462about the elliptic curve defined by the affine equation1463%1464$$ y^2+6xy+9y = x^3-3x^2-16x-14\enspace. $$1465%1466It is not that clear what all these funny numbers mean, except that we1467recognize the first few of them as the coefficients we just input. To1468retrieve meaningful information from such complicated objects (and number1469fields will be much worse), one uses so-called \emph{member1470functions}. Type \kbd{?.} to get a complete list. Whenever \kbd{ell} appears1471in the right hand side, we can apply the corresponding function to an object1472output by \kbd{ellinit}. (I'm sure you know how the other \kbd{init} functions1473will be called now, don't you? Oh, by the way, neither \kbd{clgpinit} nor1474\kbd{pridinit} exist.)14751476Let's try it. The discriminant \kbd{e0.disc} is equal to 37, hence1477the conductor of the curve is 37. Of course in general it is not so1478trivial. In fact, although the equation of the curve is clearly1479minimal (since the discriminant is $12$th-power-free), it is not in1480standard reduced form, so type1481\bprog1482e = ellminimalmodel(e0)1483@eprog\noindent which1484gives the \kbd{ell} structure attached to the standard model,1485exactly as if we had used \kbd{ellinit} on a reduced equation. For1486some related data, type1487\bprog1488gr = ellglobalred(e0)1489@eprog\noindent The first1490component \kbd{gr[1]} tells us that the conductor is 37 as we already1491knew. The second component is a 4-component vector which allows us to1492get the minimal equation: in fact \kbd{e} is \kbd{ellchangecurve(e0, gr[2])}.1493Type1494\bprog1495q0 = [-2,2]1496ellisoncurve(e0, q0)1497q = ellchangepoint(q0,gr[2])1498ellisoncurve(e, q)1499@eprog\noindent1500The point \kbd{q0} is on the curve, as checked by \kbd{ellisoncurve}, and we1501transferred it onto the minimal model \kbd{e}, using \kbd{ellchangepoint} and1502the change of variable computed above. Note that \kbd{ellchangepoint()} is1503unusual among the elliptic curve functions in that it does not take an1504\kbd{ell} structure as its first argument: in \kbd{gp}, points do not1505``know'' which curve they are on, but to move a point from one model to1506another we only need to know the coordinates of the point and the1507transformation data here stored in \kbd{gr[2]}. Also, the point at infinity1508is represented as \kbd{[0]} on all elliptic curves; this is the identity for1509the group law.15101511Here, \kbd{q=[0,0]} obviously lies on \kbd{e}, which has equation1512$y^2+y = x^3-x$. Let us now play a little with points on \kbd{e}.1513The group law on an elliptic curve is implemented with the functions1514\kbd{elladd} for addition, \kbd{ellsub} for subtraction and1515\kbd{ellmul} for multiplication by an integer. For1516example, the negative of \kbd{q} is \kbd{ellsub(e,[0],q)}, and the1517double is obtained either as \kbd{ellmul(e,q,2)} or as1518\kbd{elladd(e,q,q)}.15191520Now \kbd{q} may be a torsion point. Type \kbd{ellheight(e, q)}, which1521computes the canonical Neron-Tate height of \kbd{q}. Note that1522\kbd{ellheight} does not assume that \kbd{e} is \emph{minimal}! (Although1523it is, making things a little faster.)1524This is nonzero, hence \kbd{q} is not torsion. To see this even better,1525type1526\bprog1527for(k = 1, 20, print(ellmul(e, q, k)))1528@eprog\noindent and we see the characteristic parabolic explosion of the size1529of the points. (And another proof that \kbd{q} is not torsion, assuming1530Mazur's bound on the size of the rational torsion.) We could can also type1531\kbd{ellorder(e, q)} which returns 0, telling us yet again that \kbd{q} is1532nontorsion. As a consistency check, type1533\bprog1534ellheight(e, ellmul(e, q,20)) / ellheight(e, q)1535@eprog\noindent1536We indeed find $400=20^2$ as it should be.15371538Notice how (almost) all those \kbd{ell}--prefixed functions take our1539elliptic curve as a first argument? This will be true with number1540fields as well: whatever object was initialized by an $ob$--\kbd{init}1541function will have to be used as a first argument of all the1542$ob$--prefixed functions. Conversely, you won't be able to use any1543such high-level function before you correctly initialize the relevant1544object. \smallskip15451546Ok, let's try another curve. Type1547\bprog1548E = ellinit([0,-1,1,0,0])1549q = [0,0]; ellheight(E, q)1550@eprog\noindent This corresponds to the equation $y^2+y = x^3-x^2$ and an1551obvious rational point on it. Again from the discriminant we see that the1552conductor is equal to 11, and if you type \kbd{ellminimalmodel(E)} you will1553see that the equation for \kbd{E} is minimal. This time the height is1554exactly zero, hence \kbd{q} must be a torsion point. Indeed, typing1555\bprog1556for(k=1, 5, print(ellmul(E, q,k)))1557ellorder(E, q) \\@com simpler1558@eprog\noindent1559we see in two different ways that \kbd{q} is a point of order 5. Moreover,1560typing1561\bprog1562elltors(E)1563@eprog\noindent shows that \kbd{q} generates all the torsion of \kbd{E},1564which is cyclic of order~$5$. \smallskip15651566Let's try still another curve, $y^2+y = x^3-7x+6$:1567\bprog1568e = ellinit([0,0,1,-7,6])1569ellglobalred(e)1570@eprog\noindent As before, this is a minimal equation; now the conductor is15715077. There are some trivial integral points on this curve, but let's try to1572be more systematic. Typing1573\bprog1574elltors(e)1575@eprog\noindent1576shows that the torsion subgroup is trivial, so we don't have to worry about1577torsion points. Next, the function \kbd{ellratpoints} allows us to find1578rational points of small height1579\bprog1580v = ellratpoints(e,1000)1581@eprog\noindent The vector $v$ contains all 130 rational points $(x,y)$ on the1582curve whose $x$-coordinate is $n/d$ with $|n|$ and $|d|$ both less than $1000$.1583Note that \kbd{ellratpoints(e,10\pow6)} takes less than 1 second, and1584produces 344 points. Of course, these are grouped by pairs:1585if $(x,y)$ is on the curve, its opposite is $(x,-y-1)$ as1586\bprog1587ellneg(e, ['x,'y])1588@eprog\noindent shows. Note that there is no problem with manipulating points1589with formal coordinates. This is large for a curve having such a small1590conductor. So we suspect (if we do not know already, since this curve is1591quite famous!) that the rank of this curve must be large. Let's try and put1592some order into this. First, we eliminate one element in each pair1593of opposite points:1594\bprog1595v = vecsort(v, 1, 8)1596@eprog\noindent1597The argument $1$ specifies a comparison function: we sort the points by first1598coordinate only, in particular two points with the same $x$-coordinate1599compare as equal; the $8$ flag eliminates ``duplicates''. The same effect1600could be obtained in a more verbose way using an inline anonymous function1601\bprog1602v = vecsort(v, (P,Q) -> sign(P[1]-Q[1]), 8)1603@eprog\noindent We now order the points according to their canonical height:1604\bprog1605hv = [ ellheight(e,P) | P <- v ];1606v = vecextract(v, vecsort(hv,,1)) \\ indirect sort wrt h, then permute1607@eprog\noindent1608It seems reasonable to take the numbers with smallest height as1609possible generators of the Mordell-Weil group. Let's try the first1610four: type1611\bprog1612m = ellheightmatrix(e, v[1..4]); matdet(m)1613@eprog\noindent1614Since the curve has no torsion, the determinant being close to zero1615implies that the first four points are dependent. To find the1616dependency, it is enough to find the kernel of the matrix \kbd{m}. So1617type \kbd{matker(m)}: we indeed get a nontrivial kernel, and the1618coefficients are close to integers. Typing \kbd{elladd(e, v[1],v[3])} does1619indeed show that it is equal to \kbd{v[4]}.16201621Taking any other four points, we seem to always find a dependency.1622Let's find all dependencies. Type1623\bprog1624vp = v[1..3];1625m = ellheightmatrix(e,vp);1626matdet(m)1627@eprog\noindent This is now clearly nonzero so the first 3 points are1628linearly independent, showing that the rank of the curve is at least equal to16293. (In fact, \kbd{e} is the curve of smallest conductor having rank 3.)1630We would like to see whether the other points are dependent:1631if \kbd{Q} is some point which is dependent on \kbd{v[1],v[2]} and \kbd{v[3]}1632and1633\bprog1634c = [ellheight(e, P, Q) | P <- vp]~1635@eprog\noindent then \kbd{m\pow(-1) * c} will give the coefficients of the1636dependence relation. If these coefficients are not close to integers,1637then there is no dependency, otherwise we can round and check rigourously1638using a function such as the following:1639\bprog1640ellcomb(e, P, L) =1641{ my (Q = [0]);1642for (i = 1, #P, Q = elladd(e, Q, ellmul(e, P[i], L[i])));1643return (Q);1644}1645@eprog\noindent This is safer than using the \kbd{matker} function. Thus, type1646\bprog1647mi = m^(-1);1648w = vector(#v, k, mi * [ellheight(e, P, v[k]) | P <- vp]~)1649wr = round(w, &e)1650@eprog\noindent1651We ``see'' that the coefficients are all very close to integers, and we1652quantified it with the last instruction: \kbd{wr} is the vector expressing1653all the components of \kbd{v} on its first 3, and $2^{-e}$ gives an upper1654bound on the maximum distance to an integer. The rigorous check is positive:1655\bprog1656for (i=1, #w, if (v[i] != ellcomb(e,vp,wr[i]), error(i)));1657@eprog\noindent No error! We must make two technical remarks at this point:16581659(1) Using the height pairing to find dependence relations as we1660have done only finds relations modulo torsion; but in this example, the curve1661has trivial torsion, as we checked earlier.16621663(2) In the above calculation we1664were lucky that all the \kbd{v[j]} were $\Z$-linear combinations of1665\kbd{v[1]}, \kbd{v[2]} and \kbd{v[3]} and not just $\Q$-linear combinations;1666in general the results in $w$ might have given a vector of rationals: if1667$k\ge2$ is minimal such that $kQ$ is in the subgroup generated by \kbd{v[1]},1668\kbd{v[2]} and \kbd{v[3]}, then the entries of \kbd{matsolve(m, ellbil(e,1669vp,Q))} will be rationals with common denominator~$k$. This can be detected1670by using \kbd{bestappr} instead of \kbd{round} in the above.1671\smallskip16721673We are thus led to strongly believe that the curve has rank1674exactly 3, with generators \kbd{v[1]}, \kbd{v[2]} and \kbd{v[3]}, and this1675can be proved to be the case. Indeed, all this (and much more) is automated1676in the built-in \kbd{ellrank} function:1677\bprog1678[r, R, P] = ellrank(e);1679Q = ellsaturation(e, P, 100)1680@eprog\noindent We find $r = R = 3$ and a vector $P$ containing $3$1681rational points. This performs $2$-descent on the curve: the rank belongs1682to $[r,R]$ hence is equal to $3$. The points in $P$ are independent1683modulo torsion : since $\kbd{\#P} = r = R$, they generate a subgroup1684of finite index. The final \kbd{ellsaturation} provides a new vector of1685points which is $p$-saturated for all primes $p \leq 100$: the index of the1686subgroup they generate is not divisible by any such prime.16871688In other situations, we could be missing some points and have $\kbd{\#P} <1689r$: for instance1690\bprog1691e = ellinit([-127^2, 0]);1692ellrank(e)1693@eprog\noindent does not find any point although the rank is $1$; in this1694particular case (rank $1$ and ``small'' conductor), \kbd{ellheegner} finds1695the missing point, which happens to be a generator.16961697\smallskip16981699Let us explore a few more elliptic curve related functions. Keep our1700curve \kbd{e} of rank 3, and type1701\bprog1702v1 = [1,0]; z1 = ellpointtoz(e, v1)1703v2 = [2,0]; z2 = ellpointtoz(e, v2)1704@eprog\noindent1705We thus get the complex parametrization of the curve. To add the points1706\kbd{v1} and \kbd{v2}, we should of course type \kbd{elladd(e, v1,v2)},1707but we can also type \kbd{ellztopoint(e, z1 + z2)} which has the disadvantage1708of giving complex numbers, but illustrates how the group law on \kbd{e} is1709obtained from the addition law on $\C$.17101711Type1712\bprog1713f = x * Ser(ellan(e, 30))1714@eprog\noindent This gives a power series which is the Fourier expansion of a1715modular form of weight 2 for $\Gamma_0(5077)$. (This has been proved1716directly, before Wiles's general result.) In fact, to find the modular1717parametrization of the curve, type1718\bprog1719modul = elltaniyama(e)1720u = modul[1];1721v = modul[2];1722@eprog\noindent1723We can check in various ways that this indeed parametrizes the curve:1724\bprog1725(v^2 + v) - (u^3 - 7*u + 6)1726@eprog\noindent1727is close to $0$ for instance, or simply that \kbd{ellisoncurve(e,modul)}1728returns~$1$. Now type1729\bprog1730x * u' / (2*v + 1)1731@eprog\noindent and we see that this is equal to the modular form \kbd{f}1732found above; the quote \kbd{'} tells \kbd{gp} to take the derivative of the1733expression with respect to its main variable. The functions \kbd{u} and1734\kbd{v}, considered on the upper half plane with $x=e^{2i\pi\tau}$, are in1735fact modular \emph{functions} for $\Gamma_0(5077)$. \smallskip17361737The function \kbd{ellan(e, 30)} gives the first~$30$ coefficients1738$a_n$ of the $L$-series of \kbd{e}. One can also ask for a single1739coefficient: the millionth is \kbd{ellak(e, 10\pow 6)}. Note however1740that calling \kbd{ellan(e,100000)} is much faster than1741the equivalent \kbd{vector(100000,k,ellak(e,k))}. For a1742prime~\kbd{p},1743\kbd{ellap(e,p)} is equivalent to \kbd{ellak(e,p)}; this is the1744integer $a_p$ such that the number of points on \kbd{e} over $\F_p$ is1745$1+p-a_p$. (With the standard PARI distribution, \kbd{ellap} is the only way1746to obtain the order of an elliptic curve over $\F_p$ in \kbd{gp}. The1747external package \kbd{ellsea} provides much more efficient routines.)17481749Finally, let us come back to the curve \kbd{E} defined above by1750\kbd{E = ellinit([0,-1,1,0,0])}, which had an obvious rational $5$-torsion1751point. The sign of the functional equation, given by \kbd{ellrootno(E)}, is1752$+1$. Assuming the rank parity conjecture, it follows that the Mordell-Weil1753group of $E$ has even rank. The value of the L-function of \kbd{E} at 11754\bprog1755ls = lfun(E, 1)1756@eprog\noindent is definitely nonzero, so \kbd{E} has rank $0$. According to1757the Birch and Swinnerton-Dyer conjecture, which is proved for this curve,1758\kbd{ls} is given by the following formula (in this case):1759%1760\def\sha{\hbox{III}}1761$$L(E,1)=\dfrac{\Omega\cdot c\cdot|\sha|}{|E_{\text{tors}}|^2}\enspace,$$1762%1763where $\Omega$ is the real period of $E$, $c$ is the global Tamagawa number,1764$|\sha|$ is the order of the Tate-Shafarevich group, and $E_{\text{tors}}$ is the1765torsion group of $E$.17661767Now we know many of these quantities: $\Omega$ is equal to \kbd{E.omega[1]}1768The global Tamagawa number $c$ is given by \kbd{elltamagawa(E)} and is $1$1769We already know that the torsion subgroup of $E$ contains a point of order 5,1770and typing \kbd{elltors(E)} shows that it is of order exactly 5. So type1771\bprog1772ls * 25/E.omega[1]1773@eprog\noindent This shows that $\sha$ must be the trivial group.1774A short hand for $\dfrac{\Omega\cdot c}{|E_{\text{tors}}|^2}$ is \kbd{ellbsd(E)},1775so the previous line can be written as1776\bprog1777ls / ellbsd(E)1778@eprog17791780For more detailed information on the local reduction of an elliptic curve at1781a specific prime~\kbd{p}, use the function \kbd{elllocalred(E,p)}; the second1782component gives the Kodaira symbol in an encoded form. See the manual or1783online help for details.17841785\section{Working in Quadratic Number Fields}17861787The simplest of all number fields outside $\Q$ are quadratic fields and are1788the subject of the present section. We shall deal in the next one with1789general number fields (including $\Q$ and quadratic fields!), and one should1790be aware that all we will see now has a more powerful, in general easier to1791use, equivalent in the general context. But possibly much slower.17921793Such fields are characterized by their discriminant. Even better, any1794nonsquare integer $D$ congruent to 0 or 1 modulo 4 is the discriminant of a1795specific order in a quadratic field. We can check whether this order is1796maximal with \kbd{isfundamental(D)}. Elements of a quadratic field are of the1797form $a+b\omega$, where $\omega$ is chosen as $\sqrt{D}/2$ if $D$ is even and1798$(1+\sqrt{D})/2$ if $D$ is odd, and are represented in PARI by quadratic1799numbers. To initialize working in a quadratic order, one starts by the1800command \kbd{w = quadgen($D$,'w)}.18011802This sets \kbd{w} equal to $\omega$ as above, and is printed \kbd{w}.1803If you need several quadratic orders at the same time, you can1804use different variable names:1805\bprog1806w1 = quadgen(-23,'w1)1807w2 = quadgen(-15,'w1)1808@eprog\noindent1809\smallskip1810%1811In addition to elements of a quadratic order, we also want to be able to1812handle ideals of such orders. In the quadratic case, it is equivalent to1813handling binary quadratic forms. Quadratic forms are triples $(a,b,c)$1814representing the form $ax^2+bxy+cy^2$. Such a form will be printed as, and1815can be created by, \kbd{Qfb($a$,$b$,$c$)}.18161817Such forms can be multiplied, divided, powered as many PARI objects using1818the usual operations, and they can also be reduced using the function1819\kbd{qfbred} or \kbd{qfbredsl2} (which also returns the unimodular1820transformation matrix). One can also use explicitly \kbd{qfbcomp} /1821\kbd{qfbpow} (same as multiplication) and \kbd{qfbcompraw} / \kbd{qfbpowraw}1822(composition without reduction) (It is not the purpose of this tutorial to1823explain what all these things mean.) In addition, Shanks's NUCOMP algorithm1824has been implemented (functions \kbd{qfbnucomp} and \kbd{qfbnupow}), and this1825is usually a little faster.18261827Finally, you have at your disposal the functions \kbd{qfbclassno} which1828(\emph{usually}) gives the class number, the function \kbd{qfbhclassno}1829which gives the Hurwitz class number, and the much more sophisticated1830\kbd{quadclassunit} function which gives the class number and class group1831structure.18321833Let us see examples of all this at work.18341835Type \kbd{qfbclassno(-10007)}. \kbd{gp} tells us that the result is 77. However,1836you may have noticed in the explanation above that the result is only1837\emph{usually} correct. This is because the implementers of the algorithm1838have been lazy and have not put the complete Shanks algorithm into PARI,1839causing it to fail in certain very rare cases. In practice, it is almost1840always correct, and the much more powerful \kbd{quadclassunit} program, which1841\emph{is} complete (at least for fundamental discriminants) can give1842confirmation; but now, under the Generalized Riemann Hypothesis!18431844So we may be a little suspicious of this class number. Let us check it.1845First, we need to find a quadratic form of discriminant $-10007$. Since this1846discriminant is congruent to 1 modulo 8, we know that there is an ideal of1847norm equal to 2, i.e.~a binary quadratic form $(a,b,c)$ with $a=2$. To1848compute it we type \kbd{f = qfbprimeform(-10007, 2)}. OK, now we have a form.1849If the class number is correct, the very least is that this form raised to1850the power 77 should equal the identity. Type \kbd{f\pow 77}. We get a form1851starting with 1, i.e.~the identity. Raising \kbd{f} to the powers 11 and 71852does not give the identity, thus we now know that the order of \kbd{f} is1853exactly 77, hence the class number is a multiple of 77. But how can we be1854sure that it is exactly 77 and not a proper multiple? Well, type1855\bprog1856sqrt(10007)/Pi * prodeuler(p=2,500, 1./(1 - kronecker(-10007,p)/p))1857@eprog\noindent1858This is nothing else than an approximation to the Dirichlet class number1859formula. The function \kbd{kronecker} is the Kronecker symbol, in this case1860simply the Legendre symbol. Note also that we have written \kbd{1./(1 - \dots)}1861with a dot after the first 1. Otherwise, PARI may want to compute the whole1862thing as a rational number, which would be terribly long and useless. In fact1863PARI does no such thing in this particular case (\kbd{prodeuler} is always1864computed as a real number), but you never know. Better safe than sorry!18651866We find 77.77, pretty close to 77, so things seem in order. Explicit bounds1867on the prime limit to be used in the Euler product can be given which make1868the above reasoning rigorous.18691870Let us try the same thing with $D=-3299$. \kbd{qfbclassno} and the Euler1871product convince us that the class number must be 27. However, we get stuck1872when we try to prove this in the simple-minded way above. Indeed, we type1873\kbd{f = qfbprimeform(-3299, 3)} (2 is not the norm of a prime ideal but18743 is), and we see that \kbd{f} raised to the power 9 is equal to the identity.1875This is the case for any other quadratic form we choose. So we suspect that the1876class group is not cyclic. Indeed, if we list all 9 distinct powers of \kbd{f},1877we see that \kbd{qfbprimeform(-3299, 5)} is not on the list, although its cube1878is as it must. This implies that the class group is probably equal to a1879product of a cyclic group of order 9 by a cyclic group of order 3. The Euler1880product plus explicit bounds prove this.18811882Another way to check it is to use the \kbd{quadclassunit} function by typing1883for example1884\bprog1885quadclassunit(-3299)1886@eprog\noindent1887Note that this function cheats a little and could still give a wrong answer,1888even assuming GRH: the forms given could generate a strict subgroup of the1889class group. If we want to use proven bounds under GRH, we have to type1890\bprog1891quadclassunit(-3299,,[1,6])1892@eprog\noindent1893The double comma \kbd{,,} is not a typo, it means we omit an optional second1894argument. As we want to use the optional \emph{third} argument, we have to1895indicate to \kbd{gp} we skipped this one.18961897Now, if we believe in GRH, the class group is as we thought (see Chapter 31898for a complete description of this function).18991900Note that using the even more general function \kbd{bnfinit} (which handles1901general number fields and gives more complicated results), we could1902\emph{certify} this result, i.e~remove the GRH assumption. Let's do it, type1903\bprog1904bnf = bnfinit(x^2 + 3299); bnfcertify(bnf)1905@eprog19061907A nonzero result (here 1) means that everything is ok. Good, but what did1908we certify after all? Let's have a look at this \kbd{bnf} (just type it!).1909Enlightening, isn't it? Recall that the \kbd{init} functions (we've already1910seen \kbd{ellinit}) store all kind of technical information which you1911certainly don't care about, but which will be put to good use by higher level1912functions. That's why \kbd{bnfcertify} could not be used on the output of1913\kbd{quadclassunit}: it needs much more data.19141915To extract sensible information from such complicated objects, you must use1916one of the many \emph{member functions} (remember: \kbd{?.} to get a complete1917list). In this case \kbd{bnf.clgp} which extracts the class group structure.1918This is much better. Type \kbd{\%.no} to check that this leading 27 is indeed1919what we think it is and not some stupid technical parameter. Note that1920\kbd{bnf.clgp.no} would work just as well, or even \kbd{bnf.no}!19211922As a last check, we can request a relative equation for the Hilbert class1923field of $\Q(\sqrt{-3299})$: type \kbd{quadhilbert(-3299)}. It is indeed of1924degree 27 so everything fits together.19251926\medskip1927%1928Working in real quadratic fields instead of complex ones, i.e.~with $D>0$, is1929not very different.19301931The same \kbd{quadgen} function is used to create elements. Ideals are again1932represented by binary quadratic forms $(a,b,c)$, this time indefinite. However,1933the Archimedean valuations of the number field start to come into play, hence1934in fact quadratic forms with positive discriminant can also1935be represented as a pair $[q, d]$ where $q = \kbd{Qfb(a, b, c)}$ is the1936indefinite quadratic form $ax^2+bxy+cy^2$, and $d\in \R$ is a ``distance''1937component, as defined by Shanks and Lenstra.19381939The form $q$ can be multiplied, divided, powered, and they can be1940reduced using \kbd{qfbred}. But this time, to compose extended forms1941$[q,d]$ and $[q,d']$, one must use \kbd{qfbcomp} and \kbd{qfbpow} (since1942ordinary multiplication and powerings will not accept pairs)19431944The \kbd{qfbred} function applies a succession of1945elementary reduction steps corresponding essentially to a continued fraction1946expansion, and a single one of these steps can be achieved by adding an1947(optional) flag to the arguments of \kbd{qfbred}. Again, the function1948\kbd{qfbprimeform} gives a prime form, but the form which is given1949corresponds to an ideal of prime norm which is usually not reduced. If1950desired, it can be reduced using \kbd{qfbred}.19511952Finally, you still have at your disposal the function \kbd{qfbclassno} which1953gives the class number (this time \emph{guaranteed} correct),1954\kbd{quadregulator} which gives the regulator, and the much more sophisticated1955\kbd{quadclassunit} giving the class group's structure and its generators,1956as well as the regulator. The \kbd{qfbclassno} and \kbd{quadregulator}1957functions use an algorithm which is $O(\sqrt D)$, hence become very slow for1958discriminants of more than 10 digits. \kbd{quadclassunit} can be used on a1959much larger range.19601961Let us see examples of all this at work and learn some little known number1962theory at the same time. First of all, type1963\bprog1964D = 3 * 3299; qfbclassno(D)1965@eprog\noindent We see that the class number is 3. (We know1966in advance that it must be divisible by 3 from the \kbd{D = -3299} case above1967and Scholz's mirror theorem.) Let us create a form by typing1968\bprog1969f = qfbred(qfbprimeform(D,2))1970@eprog\noindent1971This gives us a prime ideal of norm equal to 2. Is this ideal principal?1972Well, one way to check this, which is not the most efficient but will suffice1973for now, is to look at the complete cycle of reduced forms equivalent to1974\kbd{f}. Type1975\bprog1976g = f; for(i=1,20, g = qfbred(g, 1); print(g))1977@eprog\noindent1978(the flag $1$ in \kbd{qfbred} means to perform a single reduction step). We1979see that we come back to the form \kbd{f} without meeting the principal form1980(starting with $\pm1$) in the cycle, so the ideal corresponding to \kbd{f} is1981not principal.19821983Since the class number is equal to 3, we know however that \kbd{f\pow 3} will1984be a principal ideal $\alpha\Z_K$. How do we find $\alpha$? For this, type1985\bprog1986f3 = qfbpowraw(f, 3)1987@eprog1988This computes the cube of \kbd{f}, without1989reducing it. Hence it corresponds to an ideal of norm equal to $8=2^3$, so we1990already know that the norm of $\alpha$ is equal to $\pm8$. We need more1991information, and this is given by supplementing the form by a \emph{distance}1992component $d$, a real number that tracks archimedean information that will1993eventually allows to recover $\alpha$: we call such a pair $[f,d]$ an1994\emph{extended form}.1995\bprog1996F3 = [f3, 0.0]; /* initialize */1997while(abs(component(F3[1], 1)) != 1, F3 = qfbred(F3, 1); print(F3))1998d = F3[2];1999@eprog2000We reduce the form until we reach the unit form (exactly 6 times),2001then extract the Archimedean component, say $d = 8.59\dots$2002By definition of this distance, we know that2003$${\alpha\over{\sigma(\alpha)}}=\pm e^{2d},$$2004where $\sigma$ denotes real conjugation in our quadratic field. Thus, if we type2005\bprog2006Na = 8; /* |Norm(alpha)| */2007a = sqrt(Na * exp(2*d))2008sa = Na / a2009@eprog\noindent2010we know that up to sign, \kbd{a} and \kbd{sa} are2011numerical approximations of $\alpha$ and $\sigma(\alpha)$. Of course,2012$\alpha$ can always be chosen to be positive, and a quick numerical check2013shows that the difference of \kbd{a} and \kbd{sa} is close to an integer, and2014not the sum, so that in fact the norm of $\alpha$ is equal to $-8$ and the2015numerical approximation to $\sigma(\alpha)$ is \kbd{$-$sa}. Thus we type2016\bprog2017p = x^2 - round(a-sa)*x - 82018@eprog\noindent2019and this ($x^2 - 15221x - 8$) is the characteristic polynomial of $\alpha$.2020We can check that the discriminant of this polynomial is a square multiple of2021\kbd{D} using \kbd{issquare(poldisc(p) / D)}, so $\alpha$ is indeed in our2022field. More precisely, solving for $\alpha$ and using the numerical2023approximation that we have to resolve the sign ambiguity in the square root,2024we get explicitly $\alpha=(15221+153\sqrt D)/2$. Note that this can also be2025done automatically using the functions \kbd{polred} and \kbd{modreverse}, as2026we will see later in the general number field case. Or by solving a system2027of~2 linear equations in 2 variables. (Exercise: now that we have $\alpha$,2028check that it is indeed a generator of the ideal corresponding to the form2029\kbd{f3}.)20302031\medskip Let us now play a little with cycles. Type2032\bprog2033D = 10^7 + 12034quadclassunit(D)2035@eprog\noindent2036We get as a result a 5-component vector, which tells us that (under GRH) the2037class number is equal to 1, and the regulator $R$ is approximately2038equal to $2641.5$. You may certify this with2039\bprog2040bnf = bnfinit(x^2 - D, 1); \\ @com insist on finding fundamental unit2041bnfcertify(bnf);2042@eprog\noindent2043although it's a little inefficient. Indeed \kbd{bnfcertify} needs the2044fundamental unit, which is large: it needs about $R/\log(10)\approx 1147$2045digits of precision, see \kbd{bnf.fu}!2046(\kbd{bnfinit} would have given up had we not inserted the flag $1$.)2047On the other hand, you can try \kbd{quadunit(D,'w)}. Impressive, isn't it?2048(You can check that its logarithm is indeed equal to the regulator.)20492050Let's now assume that we want the regulator $R$ to 500 decimals, say.2051(Without cheating and computing the fundamental unit exactly first!)2052This can be computed with no effort, simply from the crude approximation2053$2641.5$ above. This time, we start with the unit form. Type:2054\bprog2055u = [qfbprimeform(D, 1), 0.0];2056R = 2641.5; /* rough approximation */2057@eprog\noindent2058This initializes the distance to $0$.2059Now type \kbd{f = qfbred(u, 1)}. This is the2060first form encountered along the principal cycle. For the moment, keep the2061precision low, for example the initial default precision. The distance from2062the identity of \kbd{f} is around 4.253. Since we want a2063distance of $R$, this should be encountered approximately at2064$R/f[2]=621$ times the distance of \kbd{f}. Hence, as a first try, we2065type \kbd{qfbpow(f,621)} (\kbd{f \pow 621} will not accept extended forms).2066Oops, we overshot, since the distance is now $3173.02$.2067Now we can refine our initial estimate and believe that we should be close to2068the correct distance if we raise \kbd{f} to the power $621*R/3173$ which2069is close to $517$. Now if we compute \kbd{qfbpow(f, 517)} we hit the principal2070form right on the dot. Note that this is not a lucky accident: we must land2071extremely close to the correct target using this method, and usually at most2072one reduction correction step is necessary. And the distance component can2073tell us where we are along the cycle.20742075Up to now, we have only worked to low precision. The goal was to obtain this2076unknown integer $517$. Note that this number has absolutely no mathematical2077significance: indeed the notion of reduction of a form with positive2078discriminant is not well defined since there are usually many reduced forms2079equivalent to a given form. However, when PARI computes with extended forms,2080the specific order and reductions that it performs are dictated entirely by2081the coefficients of the quadratic form itself, and not by the distance2082component, hence the precision used has no effect.20832084Hence we now start again by setting the precision to (for example) 500,2085we retype the definition of \kbd{u} (why is this necessary?), and then2086\kbd{qfbpow(qfbred(u, 1), 517)}. We already know that we land on the2087unit form, and the distance component gives us the regulator to 500 decimal2088places with no effort at all.20892090In a similar way, we could obtain the so-called \emph{compact representation}2091of the fundamental unit itself, or $p$-adic regulators. I leave this as2092exercises for the interested reader.20932094You can try the \kbd{quadhilbert} function on that field but, since the class2095number is $1$, the result won't be that exciting. If you try it on our2096preceding example ($3*3299$) it should take about 2 seconds.2097\medskip20982099Time for a coffee break?21002101\section{Working in General Number Fields}2102\subsec{Elements}21032104The situation here is of course more difficult. First of all, remembering2105what we did with elliptic curves, we need to initialize data linked to our2106base number field, with something more serious than \kbd{quadgen}. For2107example assume that we want to work in the number field $K$ defined by one of2108the roots of the equation $x^4+24x^2+585x+1791=0$. This is done by typing2109\bprog2110T = x^4 + 24*x^2 + 585*x + 17912111nf = nfinit(T)2112@eprog\noindent2113We get an \kbd{nf} structure but, thanks to member functions, we do not need2114to know anything about it. If you type \kbd{nf.pol}, you will get the2115polynomial \kbd{T} which you just input. \kbd{nf.sign} yields the signature2116$(r_1,r_2)$ of the field, \kbd{nf.disc} the field discriminant, \kbd{nf.zk}2117an integral basis, etc\dots.21182119The integral basis is expressed in terms of a generic root \kbd{x} of \kbd{T}2120and we notice it's very far from being a power integral basis, which is a2121little strange for such a small field. Hum, let's check that: \kbd{poldisc(T)}?2122Ooops, small wonder we had such denominators, the index of the power order2123$\Z[x]/(T)$ in the maximal order $\Z_K$ is, well,2124\kbd{nf.index}. Note that this is also given by2125\bprog2126sqrtint(poldisc(nf.pol) / nf.disc)2127@eprog\noindent2128Anyway, that's $3087$, we don't want to work with such a badly skewed2129polynomial! So, we type2130\bprog2131P = polred(T)2132@eprog\noindent2133We see from the third component that the2134polynomial $x^4-x^3-21x^2+17x+133$ defines the same field with much smaller2135coefficients, so type2136\bprog2137A = P[3]2138@eprog\noindent2139The \kbd{polred} function usually gives a simpler polynomial, and also2140sometimes some information on the existence of subfields. For example in this2141case, the second component of \kbd{polred} tells us that the field defined by2142$x^2-x+1=0$, i.e.~the field generated by the cube roots of unity, is a subfield2143of~$K$. Note this is incidental information and that the list of subfields2144found in this way is usually far from complete. To get the complete list, one2145uses \kbd{nfsubfields} (we shall do that later on).21462147Type \kbd{poldisc(A)}, this is much better, but maybe not optimal yet2148(the index is still $7$). Type \kbd{polredabs(A)} (the \kbd{abs} stands for2149absolute). Since it seems that we won't get anything better, we'll stick with2150\kbd{A} (note however that \kbd{polredabs} finds a smallest generating2151polynomial with respect to a bizarre norm which ensures that the index will2152be small, but not necessarily minimal). In fact, had you typed2153\kbd{nfinit(T, 3)}, \kbd{nfinit} would first have tried to find a good2154polynomial defining the same field (i.e.~one with small index) before2155proceeding.21562157It's not too late, let's redefine our number field:2158\bprog2159NF = nfinit(nf, 3)2160@eprog\noindent2161The output is a two-component vector. The first component is the new2162\kbd{nf}: type2163\bprog2164nf = NF[1];2165@eprog\noindent2166If you type \kbd{nf.pol}, you notice that \kbd{gp} indeed replaced your bad2167polynomial \kbd{T} by a much better one, which happens to be \kbd{A}. (Small2168wonder, \kbd{nfinit} internally called \kbd{polredabs}.) The second component2169enables you to switch conveniently to our new polynomial.21702171Namely, call $\theta$ a root of our initial polynomial \kbd{T}, and $\alpha$2172a root of the one that \kbd{polred} has found, namely \kbd{A}. These are2173algebraic numbers, and as already mentioned are represented as polmods. For2174example, in our special case $\theta$ and $\alpha$ are equal to the polmods2175\bprog2176THETA = Mod(x, x^4 + 24*x^2 + 585*x + 1791)2177ALPHA = Mod(x, x^4 - x^3 - 21*x^2 + 17*x + 133)2178@eprog\noindent respectively. Here we are considering only the algebraic2179aspect, and hence ignore completely \emph{which} root $\theta$ or $\alpha$ is2180chosen.21812182Now you may have a number of elements of your number field which are2183expressed as polmods with respect to your old polynomial, i.e.~as polynomials2184in $\theta$. Since we are now going to work with $\alpha$ instead, it is2185necessary to convert these numbers to a representation using $\alpha$. This2186is what the second component of \kbd{NF} is for: type \kbd{C = NF[2]}, you get2187\bprog2188Mod(-10/7*x^3 + 43/7*x^2 + 73/7*x - 64, x^4 - x^3 - 21*x^2 + 17*x + 133)2189@eprog\noindent2190meaning that $\theta =2191-\dfrac{10}{7}\alpha^3+\dfrac{43}{7}\alpha^2+\dfrac{73}{7}\alpha-64$, and hence the conversion from a2192polynomial in $\theta$ to one in $\alpha$ is easy, using \kbd{subst}. (We2193could get this polynomial from \kbd{polred} as well, try \kbd{polred(T, 2)}.)2194If we want the reverse, i.e.~to go back from a representation in $\alpha$ to2195a representation in $\theta$, we use the function \kbd{modreverse} on this2196polmod \kbd{C}. Try it. The result has a big denominator (1029) essentially2197because our initial polynomial \kbd{T} was so bad. By the way, to get that21981029,2199you should type \kbd{denominator(content(C))}. Trying \kbd{denominator} by2200itself would not work since the denominator of a polynomial is defined to be22011 (and its numerator is itself). The reason for this is that we think of a2202polynomial as a special case of a rational function.\smallskip22032204From now on, we forget about \kbd{T}, and use only the polynomial2205\kbd{A} defining $\alpha$, and the components of the vector \kbd{nf} which2206gives information on our number field $K$. Type2207\bprog2208u = Mod(x^3 - 5*x^2 - 8*x + 56, A) / 72209@eprog\noindent2210This is an element in $K$. There are three equivalent2211representations for number field elements: polmod, polynomial, and column2212vector giving a decomposition in the integral basis \kbd{nf.zk} (\emph{not} on2213the power basis $(1,x,x^2,\dots)$). All three are equally valid when the2214number field is understood (is given as first argument to the function).2215You will be able to use any one of them as long as the function you call2216requires an \kbd{nf} argument as well. However, most PARI functions will2217return elements as column vectors. It's an important feature of number2218theoretic functions that, although they may have a preferred format for2219input, they will accept a wealth of other different formats. We already saw2220this for \kbd{nfinit} which accepts either a polynomial or an \kbd{nf}. It2221will be true for ideals, congruence subgroups, etc.22222223Let's stick with elements for the time being. How does one go from one2224representation to the other? Between polynomials and polmods, it's easy:2225\kbd{lift} and \kbd{Mod} will do the job. Next, from polmods/polynomials to2226column vectors: type \kbd{v = nfalgtobasis(nf, u)}. So $\kbd{u} = \alpha^3-2227\alpha^2 - \alpha + 8$, right? Wrong! The coordinates of \kbd{u} are given2228with respect to the \emph{integral basis}, not the power basis2229$(1,\alpha,\alpha^2,\alpha^3)$ (and they don't coincide, type \kbd{nf.zk} if2230you forgot what the integral basis looked like). As a polynomial in $\alpha$,2231we simply have $\kbd{u} = {1\over7}(\alpha^3 - 5\alpha^2-8\alpha+56)$, which2232is trivially deduced from the original polmod representation!22332234Of course \kbd{v = nfalgtobasis(nf, lift(u))} would work equally well. Indeed2235we don't need the polmod information since \kbd{nf} already provides the2236defining polynomial. To go back to polmod representation, use2237\kbd{nfbasistoalg(nf, v)}. Notice that \kbd{u} is an algebraic integer since2238\kbd{v} has integer coordinates (try \kbd{denominator(v) == 1}, which is of2239course overkill here, but not so in a program).22402241Let's try this out. We may for instance compute \kbd{u\pow 3}. Try it. Or, we2242can type \kbd{1/u}. Better yet, if we want to know the norm from $K$ to $\Q$2243of \kbd{u}, we type \kbd{norm(u)} (what else?); \kbd{trace(u)} works as well.2244Notice that none of this would work on polynomials or column vectors since2245you don't have the opportunity to supply \kbd{nf}! But we could use2246\kbd{nfeltpow(nf,u,3)}, \kbd{nfeltdiv(nf,1,u)} (or \kbd{nfeltpow(nf,u,-1)})2247which would work whatever representation was chosen. Of course,2248there is also an \kbd{nfeltnorm} function (and \kbd{nfelttrace} as well).2249You can also consider $(u)$ as a principal ideal, and just type2250\bprog2251idealnorm(nf,u)2252@eprog\noindent2253Of course, in this way, we lose the \emph{sign} information. We will talk2254about ideals later on.22552256If we want all the symmetric functions of \kbd{u} and not only the norm, we2257type \kbd{charpoly(u)}. Note that this gives the characteristic polynomial of2258\kbd{u}, and not in general the minimal polynomial. We have \kbd{minpoly(u)}2259for this.2260\misctitle{Exercise} Find a simpler expression for \kbd{u}. \smallskip22612262Now let's work on the field itself. The \kbd{nfinit} command already2263gave us some information. The field is totally complex (its signature2264\kbd{nf.sign} is $[0,2]$), its discriminant \kbd{nf.disc} is $18981$ and2265\kbd{nf.zk} is an integral basis. The Galois group of its Galois closure2266can be obtained by typing \kbd{polgalois(A)}. The answer (\kbd{[8,-1,1]}, or2267\kbd{[8,-1,1,"D(4)"]} if the \kbd{galdata} package is installed) shows that2268it is equal to $D_4$, the dihedral group with 8 elements, i.e.~the group of2269symmetries of a square.22702271This implies that the field is ``partially Galois'', i.e.~that there exists2272at least one nontrivial field isomorphism which fixes $K$, exactly one in2273this case. Type \kbd{nfgaloisconj(nf)}. The result tells us that, apart from2274the trivial automorphism, the map2275$$\alpha \mapsto {1\over7}(-\alpha^3+5\alpha^2+\alpha-49)$$2276is the only field automorphism.2277\bprog2278nfgaloisconj(nf);2279s = Mod(%[2], A)2280charpoly(s)2281@eprog\noindent2282and we obtain \kbd{A} once again.22832284Let us check that \kbd{s} is of order 2: \kbd{subst(lift(s), x, s)}. It is. We2285may express it as a matrix:2286\bprog2287w = Vec( matid(4) ) \\@com canonical basis2288v = vector(#w, i, nfgaloisapply(nf, s, w[i]))2289M = Mat(v)2290@eprog\noindent2291The vector \kbd{v} contains the images of the integral basis elements (as2292column vectors). The last statement concatenates them into a square matrix.2293So, \kbd{M} gives the action of \kbd{s} on the integral basis. Let's check2294\kbd{M\pow2}. That's the identity all right.22952296The fixed field of this automorphism is going to be the only nontrivial2297subfield of $K$. I seem to recall that \kbd{polred} told us this was the2298third cyclotomic field. Let's check this: type \kbd{nfsubfields(nf)}. Indeed,2299there's a quadratic subfield, but it's given by \kbd{T = x\pow 2 + 22*x + 1332300} and I don't recognize it. But \kbd{nfisisom(T, polcyclo(3))} indeed tells2301us that the fields $\Q[x]/(T)$ and $\Q[x]/(x^2+x+1)$ are isomorphic.2302(In fact, \kbd{polred(T)} would tell us the same, but does not correspond to2303a foolproof test: \kbd{polred} could have returned some other polynomials.)23042305We may also check that \kbd{k = matker(M-1)} is two-dimensional, then \kbd{z2306= nfbasistoalg(nf, k[,2])} generates the quadratic subfield. Notice that 1,2307\kbd{z} and \kbd{u} are $\Q$-linearly dependent, and in fact $\Z$-linearly as2308well. Exercise: how would you check these two assertions in general? (Answer:2309\kbd{concat}, then respectively \kbd{matrank} or \kbd{matkerint} (or2310\kbd{qflll})). \kbd{z = charpoly(z)}, \kbd{z = gcd(z,z')} and \kbd{polred(z)}2311tell us that we found back the same subfield again (as we ought to!).23122313Final check: type \kbd{nfrootsof1(nf)}. Again we find that $K$ contains2314a cube root of unity, since the torsion subgroup of its unit group2315has order 6. The given generator happens to be equal to \kbd{u}.23162317\misctitle{Additional comment} (you are no longer supposed to skip this,2318but do as you wish):23192320Before working with ideals, let us note one more thing. The main part of the2321work of \kbd{polred} or \kbd{nfinit}$(T)$ is to compute an integral basis,2322i.e.~a $\Z$-basis of the maximal order $\Z_K$ of $K$. This implies factoring2323the discriminant of the polynomial $T$, which is often not feasible. The2324situation may be improved in many ways:232523261) First, it is often the case that our number field is of quite a special2327type. For example, one may know in advance some prime divisors of the2328discriminant. Hence we can ``help'' PARI by giving it that information. More2329precisely, we can use the function \kbd{addprimes} to inform PARI to keep on2330eye for these prime numbers. Do it only for big primes ! (Say, larger than2331\kbd{primelimit}.)233223332) The second way in which the situation may be improved is that often we do2334not need the complete information on the maximal order, but only require that2335the order be $p$-maximal for a certain number of primes $p$ --- but then, we2336may not be able to use functions which require a genuine \kbd{nf}. The2337function \kbd{nfbasis} specifically computes the integral basis and is not2338much quicker than \kbd{nfinit} so is not very useful in its standard use. But2339we can optionally provide a list of primes: this returns a basis of an order2340which is $p$-maximal at the given primes. For example coming back to our2341initial polynomial $T$, the discriminant of the polynomial is2342$3^7\cdot7^6\cdot19\cdot37$. If we only want a $7$-maximal order, we simply2343type2344\bprog2345nfbasis([T, [7]])2346@eprog\noindent Of course, \kbd{nfbasis([T, [2,3,5,7]])} would return an2347order which is maximal at $2,3,5,7$. A variant offers a nice generalization:2348\bprog2349nfbasis([T, 10^5])2350@eprog\noindent will return an order which is maximal at all primes less than2351$10^5$.235223533) Building on the previous points, \emph{if} the field discriminant is2354$y$-smooth (never mind the polynomial discriminant), up to a few big primes2355known to \kbd{addprimes}, then \kbd{bas = nfbasis(T, y)} returns a basis for2356the maximal order! We can then input the resulting basis to \kbd{nfinit}, as2357\kbd{nfinit([T, bas])}. Better: the $[T, \var{listP}]$ format can be2358directly used with nfinit, where \var{listP} specifies a finite list of2359primes in one of the above ways (explicit list or primes up to some bound),2360and the result can be unconditionally certified, independently of the2361\var{listP} parameter:2362\bprog2363T = polcompositum(x^7-2, polcyclo(5))[1];2364K = nfinit( [T, [2,5,7]] );2365nfcertify(K)2366@eprog\noindent The output is a list of composite integers whose complete2367factorization must be computed in order to certify the result (which may be2368very hard, hence is not done on the spot). When the list is empty, as here,2369the result is unconditional23702371\kbd{nfcertify(nf)}23722373\subsec{Ideals}23742375We now want to work with ideals and not only2376with elements. An ideal can be represented in many different ways. First, an2377element of the field (in any of the various guises seen above) will be2378considered as a principal ideal. Then the standard representation is a2379square matrix giving the Hermite Normal Form (HNF) of a $\Z$-basis of the2380ideal expressed on the integral basis \kbd{nf.zk}. Standard means that most2381ideal related functions will use this representation for their output.23822383Prime ideals can be represented in a special form as well (see2384\kbd{idealprimedec}) and all ideal-related functions will accept them. On the2385other hand, the function \kbd{idealtwoelt} can be used to find a two-element2386$\Z_K$-basis of a given ideal (as $a\Z_K + b\Z_K$, where $a$ and $b$ belong2387to $K$), but this is \emph{not} a valid representation for an ideal under2388\kbd{gp}, and most functions will choke on it (or worse, take it for2389something else and output a meaningless result). To be able to use such an2390ideal, you will first have to convert it to HNF form.23912392Whereas it's very easy to go to HNF form (use \kbd{idealhnf(nf,id)} for valid2393ideals, or \kbd{idealhnf(nf,a,b)} for a two-element representation as above),2394it's a much more complicated problem to check whether an ideal is principal2395and find a generator. In fact an \kbd{nf} does not contain enough data for2396this particular task. We'll need a Buchmann Number Field, or \kbd{bnf}, for2397that. In particular, we need the class group and fundamental units, at least2398in some approximate form. More on this later (which will trivialize the end2399of the present section).\smallskip24002401Let us keep our number field $K$ as above and its \kbd{nf} structure. Type2402\bprog2403P = idealprimedec(nf,7)2404@eprog\noindent2405This gives the decomposition of the prime number 7 into prime ideals. We have2406chosen 7 because it divides \kbd{nf.index} (in fact, is equal to it), hence2407is the most difficult case to treat.24082409The result is a vector with 4 components, showing that 7 is totally split in2410the field $K$ into prime ideals of norm 7 (you can check:2411\kbd{idealnorm(nf,P[1])}). Let us take one of these ideals, say the first, so2412type2413\bprog2414pr = P[1]2415@eprog2416We obtain its inertia and residue degree as \kbd{pr.e}2417and \kbd{pr.f}, and its two generators as \kbd{pr.gen}. One of them is2418$\kbd{pr.p} = 7$, and the other is guaranteed to have valuation $1$ at2419\kbd{pr}. What is the Hermite Normal Form of this ideal? No problem:2420\bprog2421idealhnf(nf,pr)2422@eprog\noindent and we have the desired HNF. Let's now perform ideal2423operations. For example type2424\bprog2425idealmul(nf, pr, idealmul(nf, pr,pr))2426@eprog\noindent or more simply2427\bprog2428pr3 = idealpow(nf, pr,3)2429@eprog\noindent2430to get the cube of the ideal \kbd{pr}. Since the norm of this ideal is equal2431to $343=7^3$, to check that it is really the cube of \kbd{pr} and not of2432other ideals above 7, we can type2433\bprog2434for(i=1, #P, print( idealval(nf, pr3, P[i]) ))2435@eprog\noindent2436and we see that the valuation at \kbd{pr} is equal to 3, while the others are2437equal to zero. We could see this as well from \kbd{idealfactor(nf, pr3)}.24382439Let us now work in the class group ``by hand'' (we shall see simpler ways2440later). We shall work with \emph{extended ideals}: an extended ideal is a pair2441\kbd{[A, t]}, where $A$ is an ordinary ideal as above, and $t$ a number field2442element; this pair represents the ideal $(t) A$.2443\bprog2444id3 = [pr3, 1]2445r0 = idealred(nf, id3)2446@eprog\noindent2447The input \kbd{id3} is an extended ideal: pr3 together with 1 (trivial2448factorization). The new extended ideal \kbd{r0} is equal to the old one,2449in the sense that the products $(t)A$ are the same. It contains a ``reduced''2450ideal equivalent to \kbd{pr3} (modulo the principal ideals), and a generator2451of the principal ideal that was factored out.24522453Now, just for fun type2454\bprog2455r = r0; for(i=1,3, r = idealred(nf,r, [1,5]); print(r))2456@eprog\noindent2457The ideals in the third \kbd{r} and initial \kbd{r0} are equal, say2458$(t) A = (t_0) A$: this means we2459have found a unit $(t_0/t)$ in our field, and it is easy to extract this unit2460given the extended component:2461\bprog2462t0 = r0[2]; t = r[2];2463u = nfeltdiv(nf, t0, t)2464u = nfbasistoalg(nf, u)2465@eprog\noindent The last line recovers the unit as an algebraic number.2466Type2467\bprog2468ch = charpoly(u)2469@eprog\noindent2470and we obtain the characteristic polynomial \kbd{ch} of $u$ again. (Whose2471constant coefficient is $1$, hence $u$ is indeed a unit.)24722473There is of course no reason for $u$ to be a fundamental unit. Let us see if2474it is a square. Type2475\bprog2476F = factor(subst(ch, x, x^2))2477@eprog\noindent2478We see that \kbd{ch(x\pow2)} is a product of 2 polynomials of degree 4, hence2479$u$ is a square. (Why?) We now want to find its square root. A simple method2480is as follows:2481\bprog2482NF = subst(nf,x,y);2483r = F[1,1] % (x^2 - nfbasistoalg(NF, u))2484@eprog\noindent2485to find the remainder of the characteristic polynomial of \kbd{u2} divided by2486\kbd{x\pow 2 - $u$}. This is a polynomial of degree 1 in \kbd{x}, with polmod2487coefficients, and we know that \kbd{u2}, being a root of both polynomials,2488is the root of \kbd{r}, hence can be obtained by typing2489\bprog2490u2 = -polcoef(r,0) / polcoef(r,1)2491@eprog\noindent There is an important technicality in the above: why did we2492need to substitute \kbd{NF} to \kbd{nf}? The reason is that data related to2493\kbd{nf} is given in terms of the variable \kbd{x}, seen modulo \kbd{nf.pol};2494but we need \kbd{x} as a free variable for our polynomial divisions. Hence2495the substitution of \kbd{x} by \kbd{y} in our \kbd{nf} data.24962497The most natural method is to try directly2498\bprog2499nffactor(nf, y^2 - u)2500@eprog\noindent2501Except that this won't work for the same technical reason as above: the main2502variable of the polynomial to be factored must have \emph{higher} priority2503than the number field variable. This won't be possible here since \kbd{nf}2504was defined using the variable \kbd{x} which has the highest possible2505priority. So we need to substitute variables around:2506\bprog2507nffactor(NF, x^2 - nfbasistoalg(NF, subst(lift(u),x,y)))2508@eprog\noindent2509(Of course, with better planning, we would just have defined \kbd{nf} in2510terms of the \kbd{'y} variable, to avoid all these substitutions.)2511\smallskip25122513A much simpler approach is to consider the above as instances of a2514\emph{discrete logarithm} problem, where we want to express some elements an2515abelian group (of finite type) in terms of explicitly given generators, and2516transfer all computations from abstract groups like $\text{Cl}(K)$ and2517$\Z_K^*$ to products of simpler groups like $\Z^n$ or $\Z/d\Z$. We shall do2518exactly that in the next section.25192520Before that, let us mention another famous (but in fact, simpler)2521\emph{discrete logarithm} problem, namely the one attached to the2522invertible elements modulo an ideal: $(\Z_K / I)^*$. Just use \kbd{idealstar}2523(this is an \kbd{init} function) and \kbd{ideallog}.25242525Many more functions on ideals are available. We mention here the complete2526list, referring to Chapter 3 for detailed explanations:25272528\kbd{idealadd}, \kbd{idealaddtoone}, \kbd{idealappr}, \kbd{idealchinese},2529\kbd{idealcoprime}, \kbd{idealdiv}, \kbd{idealfactor}, \kbd{idealhnf},2530\kbd{idealintersect}, \kbd{idealinv}, \kbd{ideallist}, \kbd{ideallog},2531\kbd{idealmin}, \kbd{idealmul}, \kbd{idealnorm}, \kbd{idealpow},2532\kbd{idealprimedec}, \kbd{idealred},2533\kbd{idealstar}, \kbd{idealtwoelt}, \kbd{idealval},2534\kbd{nfisideal}.25352536We suggest you play with these to get a feel for the algebraic number theory2537package. Remember that when a matrix (usually in HNF) is output, it is always2538a $\Z$-basis of the result expressed on the \emph{integral basis} \kbd{nf.zk}2539of the number field, which is usually \emph{not} a power basis.25402541\subsec{Class Groups and Units, \kbd{bnf}}25422543Apart from the above functions you have at your disposal the powerful2544function \kbd{bnfinit}, which initializes a \kbd{bnf} structure, i.e.~a2545number field with all its invariants (including class group and units), and2546enough technical data to solve discrete logarithm problems in the class and2547unit groups.25482549First type \kbd{setrand(1)}: this resets the random seed (to make sure we2550and you get the exact same results). Now type2551\bprog2552bnf = bnfinit(NF);2553@eprog\noindent2554where \kbd{NF} is the same number field as before. You do not want to see the2555output clutter a number of screens so don't forget the semi-colon. (Well if2556you insist, it is about three screenful in this case, but may require several2557Megabytes for larger degrees.) Note that \kbd{NF} is now expressed in terms2558of the variable \kbd{y}, to avoid later problems with variable priorities.25592560A word of warning: both the \kbd{bnf} and all results obtained from it are2561\emph{conditional} on a Riemann Hypothesis at this point; the \kbd{bnf} must2562be certified before the following statements become actual theorems.2563\smallskip25642565Member functions are still available for \kbd{bnf} structures. So, let's try2566them: \kbd{bnf.pol} gives \kbd{A}, \kbd{bnf.sign}, \kbd{bnf.disc},2567\kbd{bnf.zk}, ok nothing really exciting. In fact, an \kbd{nf} is included2568in the \kbd{bnf} structure: \kbd{bnf.nf} should be identical to2569\kbd{NF}. Thus, all functions which took an \kbd{nf} as first argument, will2570equally accept a \kbd{bnf} (and a \kbd{bnr} as well which contains even more2571data).25722573Anyway, new members are available now: \kbd{bnf.no} tells us the class number2574is 4, \kbd{bnf.cyc} that it is cyclic (of order 4 but that we already knew),2575\kbd{bnf.gen} that it is generated by the ideal \kbd{g = bnf.gen[1]}. If you2576\kbd{idealfactor(bnf, g)}, you recognize \kbd{P[2]}. (You may also play in2577the other direction with \kbd{idealhnf}.) The regulator \kbd{bnf.reg} is2578equal to $3.794\dots$. \kbd{bnf.tu} tells us that the roots of unity in $K$2579are exactly the sixth roots of 1 and gives a primitive root $\zeta =2580{1\over7}(\alpha^3 - 5\alpha^2 - 8\alpha + 56)$, which we have seen already.2581Finally \kbd{bnf.fu} gives us a fundamental unit $\epsilon =2582{1\over7}(\alpha^3 - 5\alpha^2 - \alpha + 28)$, which must be linked to the2583units \kbd{u} and \kbd{u2} found above since the unit rank is~1. To find2584these relations, type2585\bprog2586bnfisunit(bnf, u)2587bnfisunit(bnf, u2)2588@eprog\noindent2589Lo and behold, \kbd{u = $\zeta^2\epsilon^2$} and \kbd{u2 =2590$\zeta^{4}\epsilon^1$}.25912592\misctitle{Note} Since the fundamental unit obtained depends on the random2593seed, you could have obtained another unit than $\epsilon$, had you not reset2594the random seed before the computation. This was the purpose of the initial2595\kbd{setrand} instruction, which was otherwise unnecessary.\medskip25962597We are now ready to perform operations in the class group. First and2598foremost, let us certify the result: type \kbd{bnfcertify(bnf)}. The2599output is \kbd{1} if all went well; in fact no other output is possible,2600whether the input is correct or not, but you can get an error message (or in2601exceedingly rare cases an infinite loop) if it is incorrect.26022603It means that we now know the class group and fundamental units2604unconditionally (no more GRH then!). In this case, the certification process2605takes a very short time, and you might wonder why it is not built in as a2606final check in the \kbd{bnfinit} function. The answer is that as the2607regulator gets bigger this process gets increasingly difficult, and becomes2608soon impractical, while \kbd{bnfinit} still happily spits out results. So it2609makes sense to dissociate the two: you can always check afterwards, if the2610result is interesting enough. Looking at the tentative regulator, you know in2611advance whether the certification can possibly succeed: if \kbd{bnf.reg} is2612large, don't waste your time.261326142615Now that we feel safe about the \kbd{bnf} output, let's do some real work.2616For example, let us take again our prime ideal \kbd{pr} above 7. Since we2617know that the class group is of order 4, we deduce that \kbd{pr} raised to2618the fourth power must be principal. Type2619\bprog2620pr4 = idealpow(nf, pr, 4)2621v = bnfisprincipal(bnf, pr4)2622@eprog\noindent2623The first component gives the factorization of the ideal in the class group.2624Here, \kbd{[0]} means that it is up to equivalence equal to the 0-th power of2625the generator \kbd{g} given in \kbd{bnf.gen}, in other words that it is a2626principal ideal. The second component gives us the algebraic number $\alpha$2627such that $\kbd{pr4}=\alpha\Z_K$, $\alpha$ being as usual expressed on the2628integral basis. Type \kbd{alpha = v[2]}. Let us check that the result is2629correct: first, type \kbd{idealnorm(bnf, alpha)}. (Note that we can use a2630\kbd{bnf} with all the \kbd{nf} functions; but not the other way round, of2631course.) It is indeed equal to $7^4 = 2401$, which is the norm of \kbd{pr4}.2632This is only a first check. The complete check is obtained by computing the2633HNF of the principal ideal generated by \kbd{alpha}. To do this, type2634\kbd{idealhnf(bnf, alpha) == pr4}.26352636Since the equality is true, \kbd{alpha} is correct (not that there was any2637doubt!). But \kbd{bnfisprincipal} also gives us information for nonprincipal2638ideals. For example, type2639\bprog2640v = bnfisprincipal(bnf, pr)2641@eprog\noindent2642The component \kbd{v[1]} is now equal to \kbd{[3]}, and tells us that \kbd{pr}2643is ideal-equivalent to the cube of the generator \kbd{g}. Of course we2644already knew this since the product of \kbd{P[3]} and \kbd{P[4]} was2645principal (generated by \kbd{al}), as well as the product of all the2646\kbd{P[$i$]} (generated by 7), and we noticed that \kbd{P[2]} was equal2647to \kbd{g}, which has order 4. The second component \kbd{v[2]} gives us2648$\alpha$ on the integral basis such that $\kbd{pr}=\alpha \kbd{g}^3$. Note2649that if you \emph{don't} want this $\alpha$, which may be large and whose2650computation may take some time, you can just add the flag $1$ (see the online2651help) to the arguments of \kbd{bnfisprincipal}, so that it only returns the2652position of \kbd{pr} in the class group. \smallskip26532654\subsec{Class Field Theory, \kbd{bnr}}26552656We now survey quickly some class field theoretic routines. We must first2657initialize a Buchmann Number Ray, or \kbd{bnr}, structure, attached to a2658\kbd{bnf} base field and a modulus. Let's keep $K$, and try a finite modulus2659${\goth f} = 7\Z_K$. (See the manual for how to include infinite places in2660the modulus.) Since $K$ will now become a base field over which we want to2661build relative extensions, the attached \kbd{bnf} needs to have variables2662of lower priority than the polynomials defining the extensions. Fortunately,2663we already took care that, but it would have been easy to deal with the2664problem now (as easy as \kbd{bnf = subst(bnf, x, y)}). Then type2665\bprog2666bnr = bnrinit(bnf, 7, 1);2667bnr.cyc2668@eprog\noindent2669tells us the ray class group modulo ${\goth f}$ is isomorphic to2670$\Z/24\Z \times \Z/6\Z \times \Z/2\Z $. The attached generators are2671\kbd{bnr.gen}. Just as a \kbd{bnf} contained an \kbd{nf}, a \kbd{bnr}2672contains a \kbd{bnf} (hence an \kbd{nf}), namely \kbd{bnr.bnf}. Here2673\kbd{bnr.clgp} refers to the ray class group, while \kbd{bnr.bnf.clgp} refers2674to the class group.2675\bprog2676rnfkummer(bnr,, 2)2677rnfkummer(bnr,, 3)2678@eprog\noindent2679outputs defining polynomials for the $2$ abelian extensions of $K$ of degree2680$2$ (resp.~$3$), whose conductor is exactly equal to ${\goth f}$ (the modulus2681used to define \kbd{bnr}). (In the current implementation of \kbd{rnfkummer},2682these degrees must be \emph{prime}.) What about other extensions of degree2683$2$ for instance?2684\bprog2685L0= subgrouplist(bnr, [2])2686L = subgrouplist(bnr, [2], 1)2687@eprog\noindent2688\kbd{L0}, resp.~\kbd{L} is the list of those subgroups of the full ray class2689group mod $7$, whose index is $2$, and whose conductor is $7$,2690resp.~arbitrary. (Subgroups are given by a matrix of generators, in terms of2691\kbd{bnr.gen}.) \kbd{L0} has $2$ elements, attached to the $2$ extensions2692we already know. \kbd{L} has $7$ elements, the $2$ from \kbd{L0}, and2693$5$ new ones:2694\bprog2695L1 = setminus(Set(L), Set(L0))2696@eprog\noindent2697The conductors are2698\bprog2699vector(#L1, i, bnrconductor(bnr, L1[i]))2700@eprog\noindent2701among which one sees the identity matrix, i.e. the trivial ideal. (It is2702\kbd{L1[3]} in my session, maybe not in yours. Take the right one!) Indeed,2703the class group was cyclic of order $4$ and there exists a unique unramified2704quadratic extension. We could find it directly by recomputing a \kbd{bnr}2705with trivial conductor, but we can also use2706\bprog2707rnfkummer(bnr, L1[3]) \\ @com pick the subgroup with trivial conductor!2708@eprog\noindent2709directly which outputs the (unique by Takagi's theorem) class field2710attached to the subgroup \kbd{L1[3]}. In fact, it is of the form2711$K(\sqrt{-\epsilon})$. We can check this directly:2712\bprog2713rnfconductor(bnf, x^2 + bnf.fu[1])2714@eprog\noindent27152716\subsec{Galois Theory over $\Q$}27172718PARI includes a nearly complete set of routines to compute with Galois2719extensions of $\Q$. We start with a very simple example.2720Let $\zeta$ a $8$th-root of unity and $K=\Q(\zeta)$. The minimal2721polynomial of $\zeta$ is the 8$th$ cyclotomic polynomial, namely2722\kbd{polcyclo(8)} (=$x^4+1$).27232724We issue the command2725\bprog2726G = galoisinit(x^4 + 1);2727@eprog\noindent2728to compute $G=\text{Gal}(K/\Q)$. The command \kbd{galoisisabelian(G)}2729returns \kbd{[2,0;0,2]} so $G$ is an abelian group, isomorphic to $(\Z/2\Z)^2$, generated by2730$\sigma$=\kbd{G.gen[1]} and $\tau$=\kbd{G.gen[2]}. These automorphisms are2731given by their actions on the roots of $x^4+1$ in a suitable $p$-adic2732extension. To get the explicit action on $\zeta$, we use2733\kbd{galoispermtopol(G,G.gen[i])} for $i=1,2$ and get $\sigma(\zeta)=-\zeta$2734and $\tau(\zeta)=\zeta^3$. The last nontrivial automorphism is2735$\sigma\tau$=\kbd{G.gen[1]*G.gen[2]} and we have2736$\sigma\tau(\zeta)=-\zeta^3$. (At least in my version, yours may return a2737different set of generators, rename accordingly.)27382739We compute the fixed field of $K$ by the subgroup generated by $\tau$ with2740\bprog2741galoisfixedfield(G, G.gen[2], 1)2742@eprog\noindent2743and get $x^2 + 2$. Now we want the factorization of $x^4+1$ over that2744subfield. Of course, we could use \kbd{nffactor}, but here we have a much2745simpler option: \kbd{galoisfixedfield(G, G.gen[1], 2)} outputs2746\bprog2747[x^2 + 2, Mod(x^3 + x, x^4 + 1), [x^2 - y*x - 1, x^2 + y*x - 1]]2748@eprog\noindent2749which means that2750$x^4+1=(x^2-\alpha\*x-1)(x^2+\alpha\*x-1)$ where $\alpha$ is a root of $x^2+2$,2751and more precisely, $\alpha=\zeta^3+\zeta$. So we recover the well-known2752factorization:27532754$$x^4+1=(x^2-\sqrt{-2}\*x-1)(x^2+\sqrt{-2}\*x-1)$$27552756For our second example, let us take the field $K$ defined by the polynomial2757\bprog2758P = x^18 - 3*x^15 + 115*x^12 + 104*x^9 + 511*x^6 + 196*x^3 + 343;2759G = galoisinit(P);2760@eprog\noindent Since \kbd{galoisinit} succeeds,2761the extension $K/\Q$ is Galois. This time \kbd{galoisisabelian(G)} returns2762$0$, so the extension is not abelian; however we can still put a name on the2763underlying abstract group. Use \kbd{galoisidentify(G)}, which returns $[18,27643]$. By looking at the GAP4 classification we find that $[18, 3]$ is2765$S_3\times\Z/3\Z$. This time, the subgroups of $G$ are not obvious,2766fortunately we can ask PARI : \kbd{galoissubgroups(G)}.27672768Let us look for a polynomial $Q$ with the property that $K$ is the splitting2769field of $Q(x^2)$. For that purpose, let us take $\sigma$=\kbd{G.gen[3]}. We2770check 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$ over2771$K^\sigma$:2772\bprog2773F = galoisfixedfield(G, G.gen[3], 2);2774@eprog\noindent2775So $K$ is a quadratic extension of $K^\sigma$ defined by the polynomial2776\kbd{R=F[3][1]}. It is well-known that $K$ is also defined by $x^2-D$,2777where $D$ is the discriminant of $R$ (over $K^\sigma$).2778To compute $D$, we issue:2779\bprog2780D = poldisc(F[3][1]) * Mod(1,subst(F[1],x,y));2781@eprog\noindent2782Note that since \kbd{y} in \kbd{F[3][1]} denotes a root of \kbd{F[1]}, we2783have to use \kbd{subst(,x,y)}. Now we hope that $D$ generates $K^\sigma$ and2784compute \kbd{Q=charpoly(D)}. We check that $Q=x^9+270\*x^6+12393\*x^3+19683$ is2785irreducible with \kbd{polisirreducible(Q)}. (Were it not the case, we would2786multiply $D$ by a random square.) So $D$ is a generator of $K^\sigma$ and2787$\sqrt{D}$ is a generator of $K$. The result is that $K$ is the splitting2788field of $Q(x^2)$. We can check that with2789\kbd{nfisisom(P,subst(Q,x,x\^{}2))}.27902791\subsec{Creating and Listing Number Fields}27922793Suppose you want to work with cyclic quartic fields (i.e., fields with2794Galois group $C_4=\Z/4\Z$ over $\Q$): you could look in a database or in2795a book for examples, but PARI provides the simple but powerful \kbd{nflist}2796command: in this case you could simply write \kbd{V = nflist("C4")},2797which would immediately return a list of polynomials (in the present case2798$18$, in some random order) defining cyclic quartic fields. Note that these2799polynomials are usually not the simplest, you can for instance do2800\kbd{V = apply(polredabs, V)} to reduce them.28012802Using \kbd{vecmax(apply(z->abs(nfdisc(z)),V))}, you can check that the largest2803discriminant is $35152$. Thus, if you only want discriminants up to $10000$2804you would write \kbd{V = nflist("C4", [1, 10000])}, which would now output only2805$10$ number fields. Or if you want only fields with absolute discriminant2806exactly equal to $8000$, you would write \kbd{V = nflist("C4", 8000)}, which2807would output the two polynomials $x^4\pm10x^2+20$, which define non-isomorphic2808number fields (using \kbd{polsturm}, you can check that one is totally real,2809the other totally complex). Finally, if you only want $C_4$-fields with a2810given number \kbd{s} of complex places, you would write \kbd{nflist("C4",,s)}2811(don't forget the two consecutive commas, since the second argument is the2812discriminant range), for instance:28132814\bprog2815for(s = 0, 2, print1([s, #nflist("C4", , s)]," "))2816@eprog\noindent2817would output \kbd{[0, 10] [1, 0], [2, 10]}, so \kbd{nflist} gives you2818$10$ totally real and $10$ totally complex cyclic quartic fields, but none2819with mixed signature $(2,1)$, which is a good thing since they do not exist!28202821Of course you can ask for many more: for instance in a few seconds2822\bprog apply(length, #nflist("C4", [1, 10^14], -2))@eprog2823\noindent will return2824\kbd{[607589, 0, 607609]}, which tells you that there are $607589$ totally2825real and $607609$ totally complex cyclic quartic fields with absolute2826discriminant up to $10^{14}$: this illustrates the special use of the2827parameter $s=-2$, which separates the number fields by increasing number of2828complex places (the default is $s=-1$ which ignores the signature altogether).28292830\smallskip28312832Of course, \kbd{nflist} applies to many other Galois groups than $C_4$2833(where ``Galois group'' is understood as Galois group of the Galois closure,2834see below), but before leaving cyclic quartic fields, let us see two more2835related instructions. Starting again with \kbd{V = nflist("C4")}, write2836\kbd{R = apply(nfresolvent, V)}: this outputs a list of $18$ quadratic2837polynomials, which define the unique quadratic subfield of each quartic2838field. In the present example, the \kbd{nfsubfields} command2839(more precisely \kbd{R = apply(z -> polredabs(nfsubfields(z, 2, 1)[1]), V)})2840would have given an identical result, but the purpose of \kbd{nfresolvent}2841is different. First, for many Galois groups, it really outputs what one usually2842calls the resolvent polynomial, for instance a quadratic polynomial for2843an $S_3$ field, a cubic for a non-Galois quartic, etc... Second, as here,2844the fields are often constructed as extensions of subfields, and2845\kbd{nfresolvent} gives the subfield on which the field has been constructed.2846Better, typing \kbd{nfresolvent(V[1], 1)} outputs2847\kbd{[x\^{}2 - x - 1, [[5, 2; 0, 1], [1, 1]]]}, which not only gives the2848subfield, but the relative conductor as a \kbd{module} (a pair ideal,2849list of real places).28502851The second instruction is \kbd{polsubcyclo}, which has existed for a long time2852in PARI. The manual states that \kbd{polsubcyclo(n,d)} gives the subfields2853of degree $d$ of $\Q(\zeta_n)$. However, if $n$ is very large, previous2854versions would take an inordinate amount of time. The present version2855allows us to take $n$ very large, but the price to pay is that the degree2856$d$ of the desired subfields must be very small, for instance $d\le30$,2857and in addition must be a prime number if $d\ge7$. For instance:28582859\bprog2860? p = 10^16 + 649759; /* A prime chosen so that p = 1 mod 11*19*29*412861? polsubcyclo(p, 11);2862time = 42 ms. /* Would have been impossible in previous versions */2863? polsubcyclo(p, 19);2864time = 348 ms.2865? polsubcyclo(p, 29);2866time = 10,304 ms. /* Still reasonable */2867? polsubcyclo(p, 41);2868time = 6min, 43,181 ms. /* Slow but feasible. */2869@eprog28702871\medskip28722873The most common Galois groups corresponding to number fields of small2874degree have been implemented: all solvable groups up to degree $7$2875(there are $13$ in degree $6$ for instance), the groups $C_{\ell}$ and2876$D_{\ell}$ for $\ell$ prime. In addition, the simple group $A_5$ has also2877been included, but by cheating since it is obtained by table lookup2878(and available only of you have downloaded and installed the2879\kbd{nflistdata} package), in particular because of its relation with2880modular forms of weight $1$.28812882\section{Working with Associative Algebras}28832884Beyond the realm of number fields, we can perform operations with more2885general associative algebras, that need not even be commutative! Of course2886things become more complicated. We have two different structures: the first2887one allows us to manipulate any associative algebra that is2888finite-dimensional over a prime field ($\Q$ or $\F_p$ for some prime~$p$),2889and the second one is dedicated to central simple algebras over number2890fields, which are some nice algebras that behave a lot like number fields.2891Like in other parts of~\kbd{gp}, every function that has to do with2892associative algebras begins with the same prefix:~\kbd{alg}.28932894\subsec{Arbitrary Associative Algebras}28952896In order to create an associative algebra, you need to tell~\kbd{gp} how to2897multiply elements. We do this by providing a \emph{multiplication table} for the2898algebra, in the form of the matrix of left multiplication by each basis element,2899and use the function~\kbd{algtableinit}.29002901For instance, let us work in~$\F_3[x]/(x^2)$. Of course, we2902could use polmods of intmods to represent elements in this algebra, but let's2903introduce the general mechanism with this simple example!2904This algebra has a basis with two elements:~$1$2905and~$\epsilon$, the image of~$x$ in the quotient. By the way,~\kbd{gp} will2906only accept your multiplication table if the first basis vector is~$1$. The2907multiplication matrix of~$1$ is the~$2\times 2$ identity matrix, and2908since~$\epsilon\cdot 1 = \epsilon$ and~$\epsilon\cdot\epsilon = 0$, the left2909multiplication table of~$\epsilon$ is~$\pmatrix{0 & 0 \cr 1 & 0}$. So we2910use the following multiplication table:2911\bprog2912mt1 = [matid(2), [0,0;1,0]]2913@eprog\noindent2914Since2915we want our algebra to be over~$\F_3$, we have to specify the characteristic2916and create the algebra with2917\bprog2918al1 = algtableinit(mt1, 3);2919@eprog\noindent2920Let's create another one: the algebra of upper-triangular~$2\times 2$2921matrices over~$\Q$. This algebra has dimension~$3$, with basis~$1$, $a =2922\pmatrix{0 & 1 \cr 0 & 0}$ and~$b = \pmatrix{0 & 0 \cr 0 & 1}$, and these2923elements satisfy~$a^2=0$, $ab = a$, $ba=0$ and~$b^2=b$. Watch out, even2924though~$a$ and~$b$ are~$2\times 2$ matrices, their left multiplication tables2925are~$3\times 3$ matrices! The left multiplication tables of~$a$2926and~$b$ are respectively2927\bprog2928ma = [0,0,0; 1,0,1; 0,0,0];2929mb = [0,0,0; 0,0,0; 1,0,1];2930@eprog\noindent2931The multiplication table of our second algebra is therefore2932\bprog2933mt2 = [matid(3), ma, mb];2934@eprog\noindent2935and we can create the algebra with2936\bprog2937al2 = algtableinit(mt2,0);2938@eprog\noindent2939In fact, we can omit the second argument and type2940\bprog2941al2 = algtableinit(mt2);2942@eprog\noindent2943and the2944characteristic of the algebra will implicitly be~$0$. Warning: in2945characteristic~$0$, \kbd{algtableinit} expects an integral multiplication table.29462947In fact, \kbd{gp} does not check that the multiplication table you provided2948really defines an associative algebra. You can check it a posteriori2949with2950\bprog2951algisassociative(al2)2952@eprog\noindent2953or before creating the algebra2954with2955\bprog2956algisassociative(mt1,3)2957@eprog\noindent2958After creating the algebra, you can get back the2959multiplication table that you provided with~\kbd{algmultable(al2)}, the2960characteristic with~\kbd{algchar(al1)} and the dimension with~\kbd{algdim(al2)}.29612962\subsubsec{Elements}29632964In an associative algebra, we represent elements as column vectors expressing them2965on the basis of the algebra. For instance, in~\kbd{al1} $=\F_3[\epsilon]$, the2966element~$1-\epsilon$ is represented as~\kbd{[1,-1]\til}. Similarly, in~\kbd{al2}2967we can define~$a$, $b$ and~$c = \pmatrix{2 & 1\cr 0 & 1}$ by2968\bprog2969a = [0,1,0]~2970b = [0,0,1]~2971c = [2,1,-1]~2972@eprog\noindent2973We can also draw random elements in a box using2974\bprog2975algrandom(al2, 10)2976@eprog\noindent2977You can compute any elementary operation: try various combinations2978of~\kbd{algadd}, \kbd{algsub}, \kbd{algneg}, \kbd{algmul}, \kbd{alginv},2979\kbd{algsqr}, \kbd{algpow}, using the syntax2980\bprog2981algmul(al2, b, a)2982algpow(al2, c, 10)2983@eprog\noindent2984and the natural variants. In every algebra we have the left regular2985representation, which sends every element~$x$ to the matrix of left2986multiplication by~$x$. In~\kbd{gp} we access it by calling2987\bprog2988algtomatrix(al2, c)2989@eprog\noindent2990For every element~$x$ in an associative algebra, the trace of that matrix is2991called the \emph{trace} of~$x$, the determinant is called the \emph{norm}2992of~$x$, and the characteristic polynomial is called the \emph{characteristic2993polynomial} of~$x$. We can compute them:2994\bprog2995algtrace(al2, a)2996algnorm(al2, c)2997algcharpoly(al2, b)2998@eprog29993000\subsubsec{Properties}30013002Now let's try to compute some interesting properties of our algebras. Maybe the3003simplest one we want to test is whether an algebra is commutative;3004\kbd{algiscommutative} does that for us: you can use it to check that~\kbd{al1}3005is of course commutative, but~\kbd{al2} is not since for instance~$ab=a\neq 0 =3006ba$. More precisely, we can compute a basis of the center of an algebra3007with~\kbd{algcenter}. Since~\kbd{al1} is commutative, we obtain the identity3008matrix, and3009\bprog3010algcenter(al2)3011@eprog\noindent3012tells us that the center of~\kbd{al2} is3013one-dimensional and generated by the identity.30143015An important object in the structure of associative algebras is the3016\emph{Jacobson radical}: the set of elements that annihilate every simple left3017module. It is a nilpotent two-sided ideal. An algebra is \emph{semisimple} if3018its Jacobson radical is zero, and for every algebra~$A$ with radical~$J$, the3019quotient~$A/J$ is semisimple. You can compute a basis for the Jacobson radical3020using~\kbd{algradical}. For instance, the radical of~\kbd{al1} is generated by3021the element~$\epsilon$. Indeed, in a commutative algebra the Jacobson3022radical is equal to the set of nilpotent elements. The radical of~\kbd{al2} has3023basis~$a$: it is the subspace of strictly upper-triangular~$2\times 2$ matrices.3024You can also directly test whether an algebra is semisimple3025using~\kbd{algissemisimple}. Let's compute the semisimplification of our3026second algebra by quotienting out its radical:3027\bprog3028al3 = algquotient(al2, algradical(al2));3029@eprog\noindent3030Check that~\kbd{al3} is indeed semisimple now that you know how to do it!30313032Group algebras provide interesting examples: when~$G$ is a finite group and~$F$3033is a field, the group algebra~$F[G]$ is semisimple if and only if the3034characteristic of~$F$ does not divide the order of~$G$. Let's try it!30353036\bprog3037K = nfsplitting(x^3-x+1); \\ Galois closure -> S_33038G = galoisinit(K)3039al4 = alggroup(G, 5) \\ F_5[S_3]3040algissemisimple(al4)3041@eprog\noindent3042Check what happens when you change the characteristic of the algebra.30433044The building blocks of semisimple algebras are \emph{simple} algebras:3045algebras with no nontrivial two-sided ideals. Since the Jacobson radical is a3046two-sided ideal, every simple algebra is semisimple. You can check whether an3047algebra is simple using~\kbd{algissimple}. For instance, you can check that3048\bprog3049algissimple(al1)3050@eprog\noindent3051returns~\kbd{0}, but this is not very interesting since~\kbd{al1} is not even3052semisimple. Instead we can test whether~\kbd{al3} is simple, and since we3053already know that it is semisimple we can prevent~\kbd{gp} from checking it3054again by using the optional second argument:3055\bprog3056algissimple(al3, 1)3057@eprog\noindent3058We see that~\kbd{al3} is not simple, and this implies that we can decompose it3059further. Indeed, every semisimple algebra is isomorphic to a product of simple algebras.3060We can obtain this decomposition with3061\bprog3062dec3 = algsimpledec(al3)[2];3063apply(algdim, dec3)3064@eprog\noindent3065We see that~\kbd{al3} is isomorphic to~$\Q\times\Q$. Similarly, we can3066decompose~\kbd{al4}.3067\bprog3068dec4 = algsimpledec(al4)[2];3069apply(algdim, dec4)3070@eprog\noindent3071We see that~\kbd{al4} is isomorphic to~$\F_5\times\F_5\times A$ where~$A$ is a3072mysterious 4-dimensional simple algebra. However every simple algebra over a3073finite field is isomorphic to a matrix algebra over a possibly larger finite3074field. By computing the center3075\bprog3076algcenter(dec4[3])3077@eprog\noindent3078we see that this algebra has center~$\F_5$, so that~\kbd{al4} is isomorphic3079to~$\F_5\times\F_5\times M_2(\F_5)$.30803081\subsec{Central Simple Algebras over Number Fields}30823083As we saw, simple algebras are building blocks for more complicated algebras.3084The center of a simple algebra is always a field, and we say that an3085algebra over a field~$F$ is \emph{central} if its center is~$F$. The most3086natural noncommutative generalization of a number field is a \emph{division3087algebra} over~$\Q$: an algebra in which every nonzero element is invertible.3088Since the center of a division algebra over~$\Q$ is a number field, we do not3089lose any generality by considering central division algebras over number3090fields. However, the tensor product of two central division algebras is not3091always a division algebra, but division algebras are always simple and central3092simple algebras are closed under tensor products, giving a much nicer global3093picture. This is why we choose central simple algebras over number fields as our3094noncommutative generalization of number fields.30953096\subsubsec{Creation}30973098Let's create our first central simple algebras! A well-known construction is3099that of \emph{quaternion algebras}, which proceeds as follows.3100Let~$F$ be a number field, and let~$a,b\in F^\times$; the quaternion3101algebra~$(a,b)_F$ is the $F$-algebra generated by two elements~$i$ and~$j$3102satisfying~$i^2=a$, $j^2=b$ and~$ij=-ji$. Hamilton's quaternions3103correspond to the choice~$a=b=-1$, but it is not the only possible3104one! Here is our first quaternion algebra:3105\bprog3106Q = nfinit(y);3107al1 = alginit(Q,[-2,-1]); \\ (-2,-1)_Q3108@eprog\noindent3109Note that we represented the rationals~$\Q$ with an~\kbd{nf} structure and used3110the variable~$y$ in that structure. The reason for this variable choice will3111be clearer after looking at the next construction. You can see from the3112definition of a quaternion algebra that it has dimension~$4$ over its center, a3113fact that you can check in our example:3114\bprog3115algdim(al1)3116@eprog\noindent3117Cyclic algebras generalize the quaternion algebra construction.3118Let~$F$ be a number field and~$K/F$ a cyclic extension of degree~$d$3119with~$\sigma\in\text{Gal}(K/F)$ an automorphism of order~$d$, and let~$b\in3120F^\times$; the \emph{cyclic algebra}~$(K/F,\sigma,b)$ is the3121algebra~$\bigoplus_{i=0}^{d-1}u^iK$ with~$u^d=b$ and~$k u = u \sigma(k)$3122for all~$k\in K$. It is a central simple algebra of dimension~$d^2$ over~$F$.3123Let's construct one. First, start with a cyclic extension of number fields. A3124simple way of obtaining such an extension is to take a cyclotomic field3125over~$\Q$.3126\bprog3127T = polcyclo(5)3128K = rnfinit(Q,T);3129aut = Mod(x^2,T)3130@eprog\noindent3131Here the variable of~\kbd{T} must have higher priority than that of~\kbd{Q} to3132build the~\kbd{rnf} structure. Now choose an element~$b\in\Q^\times$, say~$3$.3133\bprog3134b = 33135@eprog\noindent3136Now we can create the algebra and check that it has the right dimension:~$16$.3137\bprog3138al2 = alginit(K, [aut,b]);3139algdim(al2)3140@eprog\noindent3141We can recover the field~\kbd{K}, the automorphism~\kbd{aut} and the3142element~\kbd{b} respectively as follows.3143\bprog3144algsplittingfield(al2)3145algaut(al2)3146algb(al2)3147@eprog\noindent3148In order to see how we recover quaternion algebras with this construction, let's3149look at3150\bprog3151algsplittingfield(al1).pol3152algaut(al1)3153algb(al1)3154@eprog\noindent3155We see that the quaternion algebra~$(-2,-1)_{\Q}$ constructed by~\kbd{gp} is3156represented as a cyclic algebra~$(\Q(\sqrt{-2})/\Q, \sigma, -1)$ by3157writing~$\Q+\Q i+\Q j+\Q ij = \Q(i) + j\Q(i)$.31583159A nice feature of central simple algebras over a given number field is that they3160are completely classified up to isomorphism, in terms of certain invariants. We3161therefore provide functions to create an algebra directly from its invariants.3162The first basic invariant is the dimension of the algebra over its center.3163In fact, the3164dimension of a central simple algebra is always a square, and we call the square3165root of the dimension the \emph{degree} of the algebra. For instance, a3166quaternion algebra has degree~$2$. We can access the degree with3167\bprog3168algdegree(al1)3169algdegree(al2)3170@eprog\noindent3171Let~$F$ be a number field and~$A$ a central simple algebra of degree~$d$3172over~$F$. To every place~$v$ of~$F$ we can attach a \emph{Hasse invariant}3173$h_v(A)\in(\dfrac{1}{d}\Z)/\Z\subset\Q/\Z$, with3174the additional restrictions that the invariant is~$0$ at every complex place and3175in~$(\dfrac{1}{2}\Z)/\Z$ at every real place. These3176invariants are~$0$ at all but finitely many places. For instance we can compute3177the invariants for our algebras:3178\bprog3179alghassei(al1)3180alghassef(al1)3181alghassei(al2)3182alghassef(al2)3183@eprog\noindent3184The output of~\kbd{alghassei} (infinite places) is a vector of integers of length the number3185of real places of~$F$, and the corresponding Hasse invariants are these integers3186divided by~$d$. Here we learn that the invariant of~\kbd{al1} at~$\infty$3187is~$1/2$ and that of~\kbd{al2} is~$0$. Similarly, the output of~\kbd{alghassef}3188(finite places) is a pair of vectors, one containing primes of the base field,3189and a vector of integers of the same length representing the Hasse invariants at3190finite places. We learn that~\kbd{al1} has invariant~$1/2$ at~$2$ and~$0$ at3191every other finite place, and that~\kbd{al2} has invariant~$-1/3$ at~$3$,3192invariant~$1/3$ at~$5$, and~$0$ at every other finite place.3193These invariants give a complete classification of central simple3194algebras over~$F$:31953196\item two central simple algebras over~$F$ of the same degree are isomorphic if3197and only if they have the same invariants;31983199\item the sum of the Hasse invariants is~$0$ in $\Q/\Z$;32003201\item for every degree~$d$ and finite collection of Hasse invariants satisfying3202the conditions above, there exists a central simple algebra over~$F$ having3203those invariants.32043205Let's use~\kbd{gp} to construct an algebra from its invariants. First let's3206construct a number field and a few places.3207\bprog3208nf = nfinit(y^2-2);3209p3 = idealprimedec(nf,3)[1]3210p17 = idealprimedec(nf,17)[1]3211@eprog\noindent3212Now let's construct an algebra of degree~$6$. The following Hasse invariants3213satisfy the correct conditions since~$1/3+1/6+1/2=0$ in~$\Q/\Z$:3214\bprog3215hf = [[p3,p17],[1/3,1/6]]; hi = [1/2,0]; \\ nf has 2 real places3216@eprog\noindent3217Finally we can create the algebra:3218\bprog3219al3 = alginit(nf,[6,hf,hi]);3220@eprog\noindent3221This will require less than half a minute but a lot of memory:3222this is an algebra of dimension~$2\times 6^2 = 72$ over~$\Q$ and we3223are doing a nontrivial computation in the initialization! You can check that the3224dimension over~$\Q$ is what we expect:3225\bprog3226algdim(al3,1)3227@eprog\noindent3228During the initialization, \kbd{gp} computes an integral multiplication table3229for the algebra. This allows us to recreate a table version of the algebra:3230\bprog3231mt3 = algmultable(al3);3232al4 = algtableinit(mt3);3233@eprog\noindent3234We can then check that the algebra is simple as expected:3235\bprog3236algissimple(al4)3237@eprog\noindent3238Finally, an important test for a central simple algebra is whether it is a3239division algebra.3240\bprog3241algisdivision(al3)3242@eprog32433244\subsubsec{Elements}32453246In a cyclic algebra~$(K/F,\sigma,b)$ of degree~$d$, we represent elements as3247column vectors of length~$d$, expressed on the basis of the~$K$-vector3248space~$\bigoplus_{i=0}^{d-1}u^iK$:3249\bprog3250a = [x^3-1, -x^2, 3, -1]~*Mod(1,T) \\represents an element in al23251@eprog\noindent3252To represent elements in the quaternion algebra~\kbd{al1}, we must view it as a3253cyclic algebra, and therefore use the representation~\kbd{al1} $ =3254\Q(i)+j\Q(i)$. The standard basis elements~$1,i,j,k=ij=-ji$ become3255\bprog3256one = [1,0]~3257i = [x,0]~3258j = [0,1]~3259k = [0,-x]~3260@eprog\noindent3261The expected equalities hold:3262\bprog3263algsqr(al1,i) == -2*one3264algsqr(al1,j) == -1*one3265algsqr(al1,k) == -2*one3266algmul(al1,i,j) == k3267algmul(al1,j,i) == -k3268@eprog\noindent32693270Like~\kbd{nfinit} for number fields, the~\kbd{alginit} function computes an3271integral basis of3272the algebra being initialized. More precisely, an \emph{order} in3273a~$\Q$-algebra~$A$ is a subring~${\cal O}\subset A$ that is finitely generated3274as a~$\Z$-module and such that~$\Q{\cal O} = A$. In an algebra3275structure3276computed with~\kbd{alginit}, we store a basis of an order~${\cal O}_0$, which we3277will call the integral basis of the algebra. There is no canonical choice for3278such a basis, and not every integral element has integral coordinates with3279respect to that basis (the set of integral elements in~$A$ does not form a3280ring in general). By default, ${\cal O}_0$ is a maximal order and hence behaves3281in a way similar to the ring of integers in a number field. You can disable the3282(costly) computation of a maximal order with an optional argument:3283\bprog3284al5 = alginit(nf,[6,hf,hi],,0);3285@eprog\noindent3286This command should be faster than the initialization of~\kbd{al3}.3287As in number fields, you can represent elements of central simple algebras in3288\emph{algebraic form}, which means the cyclic algebra representation we3289described above, or in \emph{basis form}, which means as a~$\Q$-linear3290combination of the integral basis. You can switch between the two3291representations:3292\bprog3293algalgtobasis(al2, a)3294algalgtobasis(al1, j)3295algbasistoalg(al3, algrandom(al3,1))3296@eprog\noindent3297As usual you can compute any elementary operation: try various combinations3298of~\kbd{algadd}, \kbd{algsub}, \kbd{algneg}, \kbd{algmul}, \kbd{alginv},3299\kbd{algsqr}, \kbd{algpow}.33003301Every central simple algebra~$A$ over a number field~$F$ admits a \emph{splitting3302field}, i.e. an extension~$K/F$ such that~$A\otimes_F K\cong M_d(K)$. We always3303store such a splitting in an~\kbd{alginit} structure, and you can access it3304using3305\bprog3306algsplittingfield(al1) \\ K as an rnf structure3307algtomatrix(al1, k) \\ image of k by the splitting isomorphism3308@eprog\noindent3309For every~$x\in A$, the trace (resp. determinant, characteristic polynomial)3310of that matrix is in~$K$ (resp.~$K$,~$K[X]$) and is called the3311\emph{reduced trace} (resp. \emph{reduced norm}, \emph{reduced characteristic3312polynomial}) of~$x$. You can compute them using3313\bprog3314algtrace(al3, vector(72,i,i==3)~)3315algnorm(al2, a)3316algcharpoly(al1, -1+i+j+2*k)3317@eprog33183319\section{Plotting}33203321PARI supports high and low-level graphing functions, on a variety of output3322devices: a special purpose window under standard graphical environments (the3323\kbd{X Windows} system, Mac OS X, Microsoft Windows), or a \kbd{PostScript}3324file ready for the printer. These functions use a multitude of flags, which3325are mostly power-of-2. To simplify understanding we first give these flags3326symbolic names.3327\bprog3328/* Relative positioning of graphic objects: */3329nw = 0; se = 4; relative = 1;3330sw = 2; ne = 6;33313332/* String positioning: */3333/* V */ bottom = 0; /* H */ left = 0; /* Fine tuning */ hgap = 16;3334vcenter = 4; center = 1; vgap = 32;3335top = 8; right = 2;3336@eprog\noindent3337We also decrease drastically the default precision.3338\bprog3339\p 93340@eprog\noindent3341This is very important, since plotting involves calculation of functions at3342a huge number of points, and a relative precision of 38 significant digits3343is an obvious overkill: the output device resolution certainly won't reach3344$10^{38} \times 10^{38}$ pixels!33453346Start with a simple plot:3347\bprog3348ploth(X = -2, 2, sin(X^7))3349@eprog\noindent3350You can see the limitations of the ``straightforward'' mode of plotting:3351while the first several cycles of \kbd{sin} reach $-1$ and $1$, the cycles3352which are closer to the left and right border do not. This is understandable,3353since PARI is calculating $\sin(X^7)$ at many (evenly spaced) points, but3354these points have no direct relationship to the ``interesting'' points on3355the graph of this function. No value close enough to the maxima and minima3356are calculated, which leads to wrong turning points in the graph. To fix3357this, one may use variable steps which are smaller where the function varies3358rapidly:3359\bprog3360ploth(X = -2, 2, sin(X^7), "Recursive")3361@eprog\noindent3362The precision near the edges of the graph is much better now.3363However, the recursive plotting (named so since PARI subdivides intervals3364until the graph becomes almost straight) has its own pitfalls. Try3365\bprog3366ploth(X = -2, 2, sin(X*7), "Recursive")3367@eprog\noindent The graph looks correct far away, but it has a straight3368interval near the origin, and some sharp corners as well. This happens3369because the graph is symmetric with respect to the origin, thus the middle 33370points calculated during the initial subdivision of $[-2,2]$ are exactly on3371the same line. To PARI this indicates that no further subdivision is needed,3372and it plots the graph on this subinterval as a straight line.33733374There are many ways to circumvent this. Say, one can make the right limit33752.1. Or one can ask PARI for an initial subdivision into 16 points instead3376of default 15:3377\bprog3378ploth(X = -2, 2, sin(X*7), "Recursive", 16)3379@eprog\noindent3380All these arrangements break the symmetry of the initial subdivision, thus3381make the problem go away. Eventually PARI will be able to better detect such3382pathological cases, but currently some manual intervention may be required.33833384The function \kbd{ploth} has some additional enhancements which allow3385graphing in situations when the calculation of the function takes a lot of3386time. Let us plot $\zeta({1\over 2} + it)$:3387\bprog3388ploth(t = 100, 110, real(zeta(0.5+I*t)), /*empty*/, 1000)3389@eprog\noindent3390This can take quite some time. (1000 is close to the default for many3391plotting devices, we want to specify it explicitly so that the result does3392not depend on the output device.) Try the recursive plot:3393\bprog3394ploth(t = 100, 110, real(zeta(0.5+I*t)), "Recursive")3395@eprog\noindent3396It takes approximately the same time. Now try specifying fewer points,3397but make PARI approximate the data by a smooth curve:3398\bprog3399ploth(t = 100, 110, real(zeta(0.5+I*t)), "Splines", 100)3400@eprog\noindent3401This takes much less time, and the output is practically the same. How to3402compare these two outputs? We will see it shortly. Right now let us plot3403both real and complex parts of $\zeta$ on the same graph:3404\bprog3405f(t) = my(z = zeta(0.5+I*t)); [real(z),imag(z)];3406ploth(t = 100, 110, f(t), , 1000)3407@eprog\noindent (Note the use of the temporary variable \kbd{z}; \kbd{my}3408declares it local to the function's body.)34093410Note how one half of the roots of the real and imaginary parts coincide.3411Why did we define a function \kbd{f(t)}? To avoid calculation of3412$\zeta({1\over2} + it)$ twice for the same value of t. Similarly, we can3413plot parametric graphs:3414\bprog3415ploth(t = 100, 110, f(t), "Parametric", 1000)3416@eprog\noindent In that case (parametric plot of the real and imaginary parts3417of a complex function), we can also use directly3418\bprog3419ploth(t = 100, 110, zeta(0.5+I*t), "Complex", 1000)3420ploth(t = 100, 110, zeta(0.5+I*t), "Complex|Splines", 100)3421@eprog34223423If your plotting device supports it, you may ask PARI to show the points3424in which it calculated your function:3425\bprog3426ploth(t = 100, 110, f(t), "Parametric|Splines|Points_too", 100)3427@eprog34283429As you can see, the points are very dense on the graph. To see some crude3430graph, one can even decrease the number of points to 30. However, if you3431decrease the number of points to 20, you can see that the approximation to3432the graph now misses zero. Using splines, one can create reasonable graphs3433for larger values of t, say with3434\bprog3435ploth(t = 10000, 10004, f(t), "Parametric|Splines|Points_too", 50)3436@eprog34373438How can we compare two graphs of the same function plotted by different3439methods? Documentation shows that \kbd{ploth} does not provide any direct3440method to do so. However, it is possible, and even not very complicated.34413442The solution comes from the other direction. PARI has a power mix of high3443level plotting function with low level plotting functions, and these functions3444can be combined together to obtain many different effects. Return back3445to the graph of $\sin(X^7)$. Suppose we want to create an additional3446rectangular frame around our graph. No problem!34473448First, all low-level graphing work takes place in some virtual drawing3449boards (numbered from 0 to 15), called ``rectangles'' (or ``rectwindows'').3450So we create an empty ``rectangle'' and name it rectangle 2 (any3451number between 0 and 15 would do):3452\bprog3453plotinit(2)3454plotscale(2, 0,1, 0,1)3455@eprog3456This creates a rectwindow whose size exactly fits the size of the output3457device, and makes the coordinate system inside it go from 0 to 1 (for both3458$x$ and $y$). Create a rectangular frame along the boundary of this rectangle:3459\bprog3460plotmove(2, 0,0)3461plotbox(2, 1,1)3462@eprog3463Suppose we want to draw the graph inside a subrectangle of this with upper3464and left margins of $0.10$ (so 10\% of the full rectwindow width), and3465lower and top margins of $0.02$, just to make it more interesting. That3466makes it an $0.88 \times 0.88$ subrectangle; so we create another rectangle3467(call it 3) of linear size 0.88 of the size of the initial rectangle and3468graph the function in there:3469\bprog3470plotinit(3, 0.88, 0.88, relative)3471plotrecth(3, X = -2, 2, sin(X^7), "Recursive")3472@eprog3473(nothing is output yet, these commands only fills the virtual drawing3474boards with PARI graphic objects). Finally, output rectangles 2 and 3 on3475the same plot, with the required offsets (counted from upper-left corner):3476\bprog3477plotdraw([2, 0,0, 3, 0.1,0.02], relative)3478@eprog3479\noindent The output misses something comparing to the output of3480\kbd{ploth}: there are no coordinates of the corners of the internal3481rectangle. If your output device supports mouse operations (only3482\kbd{gnuplot} does), you can find coordinates of particular points of the3483graph, but it is nice to have something printed on a hard copy too.34843485However, it is easy to put $x$- and $y$-limits on the graph. In the3486coordinate system of the rectangle 2 the corners are $(0.1,0.1)$,3487$(0.1,0.98)$, $(0.98,0.1)$, $(0.98,0.98)$. We can mark lower $x$-limit by3488doing3489\bprog3490plotmove(2, 0.1,0.1)3491plotstring(2, "-2.000", left+top+vgap)3492@eprog\noindent3493Computing the minimal and maximal $y$-coordinates might be trickier, since3494in principle we do not know the range in advance (though for $\sin(X^7)$ it3495is easy to guess!). Fortunately, \kbd{plotrecth} returns the $x$- and3496$y$-limits.34973498Here is the complete program:3499\bprog3500plotinit(3, 0.88, 0.88, relative)3501lims = plotrecth(3, X = -2, 2, sin(X^7), "Recursive")3502\p 3 \\ @com $3$ significant digits for the bounding box are enough3503plotinit(2); plotscale(2, 0,1, 0,1)3504plotmove(2, 0,0); plotbox(2, 1,1)3505plotmove(2, 0.1,0.1);3506plotstring(2, lims[1], left+top+vgap)3507plotstring(2, lims[3], bottom+vgap+right+hgap)3508plotmove(2, 0.98,0.1); plotstring(2, lims[2], right+top+vgap)3509plotmove(2, 0.1,0.98); plotstring(2, lims[4], right+hgap+top)3510plotdraw([2, 0,0, 3, 0.1,0.02], relative)3511@eprog35123513We started with a trivial requirement: have an additional frame around3514the graph, and it took some effort to do so. But at least it was possible,3515and PARI did the hardest part: creating the actual graph.3516Now do a different thing: plot together the ``exact'' graph of3517$\zeta({1/2}+it)$ together with one obtained from splines approximation.3518We can emit these graphs into two rectangles, say 0 and 1, then put these3519two rectangles together on one plot. Or we can emit these graphs into one3520rectangle 0.35213522However, a problem arises: note how we3523introduced a coordinate system in rectangle 2 of the above example, but we3524did not introduce a coordinate system in rectangle 3. Plotting a3525graph into rectangle 3 automatically created a coordinate system3526inside this rectangle (you could see this coordinate system in action3527if your output device supports mouse operations). If we use two different3528methods of graphing, the bounding boxes of the graphs will not be exactly3529the same, thus outputting the rectangles may be tricky. Thus during3530the second plotting we ask \kbd{plotrecth} to use the coordinate system of3531the first plotting. Let us add another plotting with fewer3532points too:3533\bprog3534plotinit(0, 0.9,0.9, relative)3535plotrecth(0, t=100,110, f(t), "Parametric",300)3536plotrecth(0, t=100,110, f(t), "Parametric|Splines|Points_too|no_Rescale",30);3537plotrecth(0, t=100,110, f(t), "Parametric|Splines|Points_too|no_Rescale",20);3538plotdraw([0, 0.05,0.05], relative)3539@eprog35403541This achieves what we wanted: we may compare different ways to plot a graph,3542but the picture is confusing: which graph is what, and why there are multiple3543boxes around the graph? At least with some output devices one can control3544how the output curves look like, so we can use this to distinguish different3545graphs. And the mystery of multiple boxes is also not that hard to solve:3546they are bounding boxes for calculated points on each graph. We can disable3547output of bounding boxes with appropriate options for \kbd{plotrect}.3548With these frills the script becomes:3549\bprog3550plotinit(0, 0.9,0.9, relative)3551plotrecth(0, t=100,110, f(t), "Parametric|no_Lines", 300)3552opts="Parametric|Splines|Points_too|no_Rescale|no_Frame|no_X_axis|no_Y_axis";3553plotrecth(0, t=100,110,f(t), opts, 30);3554plotdraw([0, 0.05,0.05], relative)3555@eprog35563557\noindent Plotting axes on the second graph would not hurt, but3558is not needed either, so we omit them. One can see that the discrepancies3559between the exact graph and one based on 30 points exist, but are pretty3560small. On the other hand, decreasing the number of points to 20 would make3561quite a noticeable difference.35623563Additionally, one can ask PARI to convert a plot to PS (PostScript)3564or SVG (Scalable Vector Graphics) format: just use the command3565\kbd{plotexport} instead of \kbd{plotdraw} in the above examples (or3566\kbd{plothexport} instead of \kbd{ploth}). This returns a character string3567which you can then write to a file using \kbd{write}.35683569Now suppose we want to join many different small graphs into one picture.3570We cannot use one rectangle for all the output as we did in the example3571with $\zeta({1/2}+it)$, since the graphs should go into different places.3572Rectangles are a scarce commodity in PARI, since only 16 of them are3573user-accessible. Does it mean that we cannot have more than 16 graphs on3574one picture? Thanks to an additional operation of PARI plotting engine,3575there is no such restrictions. This operation is \kbd{plotcopy}.35763577The following script puts 4 different graphs on one plot using 2 rectangles3578only, \kbd{A} and \kbd{T}:3579\bprog3580A = 2; \\@com accumulator3581T = 3; \\@com temporary target3582plotinit(A); plotscale(A, 0, 1, 0, 1)35833584plotinit(T, 0.42, 0.42, relative);3585plotrecth(T, x= -5, 5, sin(x), "Recursive")3586plotcopy(T, 2, 0.05, 0.05, relative + nw)35873588plotmove(A, 0.05 + 0.42/2, 1 - 0.05/2)3589plotstring(A,"Graph", center + vcenter)35903591plotinit(T, 0.42, 0.42, relative);3592plotrecth(T, x= -5, 5, [sin(x),cos(2*x)], 0)3593plotcopy(T, 2, 0.05, 0.05, relative + ne)35943595plotmove(A, 1 - 0.05 - 0.42/2, 1 - 0.05/2)3596plotstring(A,"Multigraph", center + vcenter)35973598plotinit(T, 0.42, 0.42, relative);3599plotrecth(T, x= -5, 5, [sin(3*x), cos(2*x)], "Parametric")3600plotcopy(T, 2, 0.05, 0.05, relative + sw)36013602plotmove(A, 0.05 + 0.42/2, 0.5)3603plotstring(A,"Parametric", center + vcenter)36043605plotinit(T, 0.42, 0.42, relative);3606plotrecth(T, x= -5, 5, [sin(x), cos(x), sin(3*x),cos(2*x)], "Parametric")3607plotcopy(T, 2, 0.05, 0.05, relative + se)36083609plotmove(A, 1 - 0.05 - 0.42/2, 0.5)3610plotstring(A,"Multiparametric", center + vcenter)36113612plotmove(A, 0, 0)3613plotbox(A, 1, 1)36143615plotdraw(A)3616\\ s = plotexport(A, relative); write("foo.ps", s) \\ @com if hard copy needed3617@eprog36183619The rectangle \kbd{A} plays the role of accumulator, rectangle \kbd{T} is3620used as a target to \kbd{plotrecth} only. Immediately after plotting into3621rectangle \kbd{T} the contents is copied to accumulator. Let us explain3622numbers which appear in this example: we want to create 4 internal rectangles3623with a gap 0.06 between them, and the outside gap 0.05 (of the size of the3624plot). This leads to the size 0.42 for each rectangle. We also3625put captions above each graph, centered in the middle of each gap. There3626is no need to have a special rectangle for captions: they go into the3627accumulator too.36283629To simplify positioning of the rectangles, the above example uses relative3630``geographic'' notation: the last argument of \kbd{plotcopy} specifies the3631corner of the graph (say, northwest) one counts offset from. (Positive3632offsets go into the rectangle.)36333634To demonstrate yet another useful plotting function, design a program to3635plot Taylor polynomials for a $\sin x$ about 0. For simplicity, make the3636program good for any function, but assume that a function is odd, so only3637odd-numbered Taylor series about 0 should be plotted. Start with defining3638some useful shortcuts3639\bprog3640xlim = 13; ordlim = 25; f(x) = sin(x);3641default(seriesprecision,ordlim)3642farray(t) = vector((ordlim+1)/2, k, truncate( f(1.*t + O(t^(2*k+1)) )));3643FARRAY = farray('t); \\@com\kbd{'t} to make sure \kbd{t} is a free variable3644@eprog\noindent3645\kbd{farray(x)} returns a vector of Taylor polynomials for $f(x)$, which we3646store in \kbd{FARRAY}. We want to plot $f(x)$ into a rectangle, then make3647the rectangle which is 1.2 times higher, and plot Taylor polynomials into the3648larger rectangle. Assume that the larger rectangle takes 0.9 of the final3649plot.36503651First of all, we need to measure the height of the smaller rectangle:3652\bprog3653plotinit(3, 0.9, 0.9/1.2, 1);3654opts = "Recursive | no_X_axis|no_Y_axis|no_Frame";3655lims = plotrecth(3, x= -xlim, xlim, f(x), opts,16);3656h = lims[4] - lims[3];3657@eprog\noindent3658Next step is to create a larger rectangle, and plot the Taylor polynomials3659into the larger rectangle:3660\bprog3661plotinit(4, 0.9,0.9, relative);3662plotscale(4, lims[1], lims[2], lims[3] - h/10, lims[4] + h/10)3663plotrecth(4, x = -xlim, xlim, subst(FARRAY,t,x), "no_Rescale");3664@eprog36653666Here comes the central command of this example:3667\bprog3668plotclip(4)3669@eprog\noindent3670What does it do? The command \kbd{plotrecth(\dots, "no\_Rescale")} scales the3671graphs according to coordinate system in the rectangle, but it does not pay3672any other attention to the size of the rectangle. Since \kbd{xlim} is 13,3673the Taylor polynomials take very large values in the interval3674\kbd{-xlim...xlim}. In particular, significant part of the graphs is going3675to be \emph{outside} of the rectangle. \kbd{plotclip} removes the parts of3676the plottings which fall off the rectangle boundary3677\bprog3678plotinit(2)3679plotscale(2, 0.0, 1.0, 0.0, 1.0)3680plotmove(2,0.5,0.975)3681plotstring(2,"Multiple Taylor Approximations",center+vcenter)3682plotdraw([2, 0, 0, 3, 0.05, 0.05 + 0.9/12, 4, 0.05, 0.05], relative)3683@eprog\noindent3684These commands draw a caption, and combine 3 rectangles (one with the3685caption, one with the graph of the function, and one with graph of Taylor3686polynomials) together. The plots are not very beautiful with the default3687colors. See \kbd{examples/taylor.gp} for a user function encapsulating the3688above example, and a colormap generator.36893690This finishes our survey of PARI plotting functions, but let us add3691some remarks. First of all, for a typical output device the picture is3692composed of small colored squares (pixels), as a very large checkerboard.3693Each output rectangle is a disjoint union of such squares. Each drop3694of paint in the rectangle will color a whole square in it. Since the3695rectangle has a coordinate system, it is important to know how this3696coordinate system is positioned with respect to the boundaries of these3697squares.36983699The command \kbd{plotscale} describes a range of $x$ and $y$ in the3700rectangle. The limit values of $x$ and $y$ in the coordinate system are3701coordinates \emph{of the centers} of corner squares. In particular,3702if ranges of $x$ and $y$ are $[0,1]$, then the segment which connects (0,0)3703with (0,1) goes along the \emph{middle} of the left column of the rectangle.3704In particular, if we made tiny errors in calculation of endpoints of this3705segment, this will not change which squares the segment intersects, thus3706the resulting picture will be the same. (It is important to know such details3707since many calculations are approximate.)37083709Another consideration is that all examples we did in this section were3710using relative sizes and positions for the rectangles. This is nice, since3711different output devices will have very similar pictures, while we3712did not need to care about particular resolution of the output device.3713On the other hand,3714using relative positions does not guarantee that the pictures will be3715similar. Why? Even if two output devices have the same resolution,3716the picture may be different. The devices may use fonts of different3717size, or may have a different ``unit of length''.37183719The information about the device in PARI is encoded in 6 numbers: resolution,3720size of a character cell of the font, and unit of length, all separately3721for horizontal and vertical direction. These sizes are expressed as3722numbers of pixels. To inspect these numbers one may use the function3723\kbd{plothsizes}. The ``units of length'' are currently used to calculate3724right and top gaps near graph rectangle of \kbd{ploth}, and gaps for3725\kbd{plotstring}. Left and bottom gaps near graph rectangle are calculate3726using both units of length, and sizes of character boxes (so that there3727is enough place to print limits of the graphs).37283729What does it show? Using relative sizes during plotting produces3730\var{approximately} the same plotting on different devices, but does not3731ensure that the plottings ``look the same''. Moreover, ``looking the3732same'' is not a desirable target, ``looking tuned for the environment''3733will be much better. If you want to produce such fine-tuned plottings,3734you need to abandon a relative-size model, and do your plottings in3735pixel units. To do this one removes flag \kbd{relative} from the above3736examples, which will make size and offset arguments interpreted this way.3737After querying sizes with \kbd{plothsizes} one can fine-tune sizes and3738locations of subrectangles to the details of an arbitrary plotting3739device.37403741The last two elements of the array returned by \kbd{plothsizes} are the3742dimensions of the display, if applicable. If there is no real display, like3743in svg or postscript plots, the width and height of display are set to $0$.37443745To check how good your fine-tuning is, you may test your graphs with a3746medium-resolution plotting (as many display output devices are), and3747with a low-resolution plotting (say, with \kbd{plotterm("dumb")} of gnuplot).37483749\section{GP Programming}37503751Do we really need such a section after all we have learnt so far? We now3752know how to write scripts and feed them to \kbd{gp}, in particular how to3753define functions. It's possible to define \emph{member} function as well, but3754we trust you to find them in the manual. We have seen most control3755statements: the missing ones (\kbd{while}, \kbd{break}, \kbd{next},3756\kbd{return} and various \kbd{for} loops) should be straightforward. (You3757won't forget to look them up in the manual, will you?)37583759Output is done via variants of the familiar \kbd{print} (to screen),3760\kbd{write} (to a file). Input via \kbd{read} (from file), \kbd{input}3761(querying user), or \kbd{extern} (from an external auxiliary program).37623763To customize \kbd{gp}, e.g.~increase the default stack space or load your3764private script libraries on startup, look up \kbd{The preferences file}3765section in the User's manual. We strongly advise to set \kbd{parisizemax} to3766a large nonzero value, about what you believe your machine can stand: this3767both limits the amount of memory PARI will use for its computation (thereby3768keeping your machine usable), and let PARI increases its stack size (up to3769this limit) to accommodate large computations. If you regularly see \kbd{PARI3770stack overflows} messages, think about this one!37713772For clarity, it is advisable to declare local variables in user functions3773(and in fact, with the smallest possible scope), as we have done so far with3774the keyword \kbd{my}. As usual, one is usually better off avoiding global3775variables altogether.37763777\emph{Break loops} are more powerful than we saw: look up \kbd{dbg\_down} /3778\kbd{dbg\_up} (to get a chance to inspect local variables in various scopes)3779and \kbd{dbg\_err} (to access all components of an error context).37803781To reach grandwizard status, you may need to understand the all powerful3782\kbd{install} function, which imports into \kbd{gp} an (almost) arbitrary3783function from the PARI library (and elsewhere too!), or how to use the3784\kbd{gp2c} compiler and its extended types. But both are beyond the scope of3785the present document.37863787Have fun!3788\bye378937903791