Annotation of OpenXM_contrib/pari-2.2/doc/usersch2.tex, Revision 1.2
1.2 ! noro 1: % $Id: usersch2.tex,v 1.49 2002/08/04 11:51:57 karim Exp $
1.1 noro 2: % Copyright (c) 2000 The PARI Group
3: %
4: % This file is part of the PARI/GP documentation
5: %
6: % Permission is granted to copy, distribute and/or modify this document
7: % under the terms of the GNU Free Documentation License
8: \chapter{Specific Use of the GP Calculator}
9:
10: Originally, \idx{GP} was designed as a debugging tool for the PARI system
11: library, and hence not much thought had been given to making it
12: user-friendly. The situation has now changed somewhat, and GP is very
13: useful as a stand-alone tool. The operations and functions available in
14: PARI and GP will be described in the next chapter. In the present one, we
15: describe the specific use of the GP programmable calculator.
16:
1.2 ! noro 17: For starting the calculator, the general command line syntax is:
1.1 noro 18:
19: \kbd{gp [-s stacksize] [-p primelimit]}
20:
21: \noindent
22: where items within brackets are optional\footnote{*}{On the Macintosh, even
23: after clicking on the gp icon, once in the MPW Shell, you still need to type
24: explicitly a command of the above form.}. These correspond to some internal
25: parameters of GP, or \var{defaults}. See \secref{se:defaults} below for a
26: list and explanation of all defaults, there are many more than just those
27: two. These defaults can be changed by adding parameters to the input line
28: as above, or interactively during a GP session or in a preferences file (also
1.2 ! noro 29: known as \tet{gprc}).
1.1 noro 30:
31: \unix Some new features were developed on UNIX platforms, and depend heavily
32: on the operating system in use. It is \var{possible} that some of these
33: will be ported to other operating systems (BeOS, MacOS, DOS, OS/2, Windows,
34: etc.) in future versions (most of them should be easy tasks for anybody
35: acquainted with those). As for now, most of them were not. So, whenever a
36: specific feature of the UNIX version is discussed in a paragraph, a UNIX sign
37: sticks out in the left margin, like here. Just skip these if you're stranded
38: on a different operating system: the core GP functions (i.e.~at least
39: everything which is even faintly mathematical in nature) will still be
40: available to you. It may also be possible (and then definitely advisable) to
41: install \idx{Linux} or \idx{FreeBSD} on your machine.
42:
43: \misctitle{Note (added in version 2.0.12):} Most UNIX goodies are now
44: available for DOS, OS/2 and Windows, thanks to the \tet{EMX}/\tet{RSX}
45: runtime package (\kbd{install} excluded under DOS, since DLLs are not
46: supported by the OS). For Windows 95 and higher, you can also use the
47: \tet{Cygwin} compatibility library to run GP almost as if running a genuine
48: Unix system. Note that a native \key{Linux} binary will be faster than one
49: using any of these compatibility packages (see the \tet{MACHINES} benchmark
50: file, included in the distribution).
51:
52: \emacs If you have GNU Emacs, you can work in a special Emacs shell (see
53: \secref{se:emacs}), which is started by typing \kbd{M-x gp} (where as
54: usual \kbd{M} is the \kbd{Meta} key) if you accept the default stack, prime
55: and buffer sizes, or \kbd{C-u M-x gp} which will ask you for the name of the
56: gp executable, the stack size, the prime limit and the buffer size. Specific
57: features of this Emacs shell will be indicated by an EMACS sign.\smallskip
58:
59: If a \idx{preferences file} (or \kbd{gprc}, to be discussed in
60: \secref{se:gprc}) can be found, GP will then read it and execute the commands
61: it contains. This provides an easy way to customize GP without having to
62: delve into the code to hardwire it to your likings.
63:
64: A copyright message then appears which includes the version number. Please
65: note this number, so as to be sure to have the most recent version if you
66: wish to have updates of PARI. The present manual is written for version
67: \vers, and has undergone major changes since the 1.39.xx versions.
68:
69: After the copyright, the computer works for a few seconds (it is in fact
70: computing and storing a table of primes), writes the top-level help
71: information, some initial defaults, and then waits after printing its prompt
72: (initially: \kbd{?}).
73:
74: Note that at any point the user can type \kbd{Ctrl-C} (that is press
75: simultaneously the \kbd{Control} and \kbd{C} keys): the current
76: computation will be interrupted and control given back to the user at the GP
77: prompt.
78:
79: The top-level help information tells you that (as in many systems) to get
80: help, you should type a \kbd{?}. When you do this and hit return, a menu
81: appears, describing the eleven main categories of available functions and
82: what to do to get more detailed help. If you now type \kbd{?$n$} with $1\le
83: n\le11$, you will get the list of commands corresponding to category $n$
84: and simultaneously to Section $3.n$ of this manual.
85:
86: If you type \kbd{?}\var{functionname} where \var{functionname} is the
87: name of a PARI function, you will get a short explanation of this
88: function.
89:
90: \unix If extended help (see \secref{se:exthelp}) is available on your
91: system, you can double or triple the \kbd{?} sign to get much more:
92: respectively the complete description of the function (e.g.~\kbd{??~sqrt}),
93: or a list of GP functions relevant to your query (e.g.~ \kbd{???~"elliptic
94: curve"} or \kbd{???~"quadratic field"}).
95:
96: If GP was compiled with the right options (see Appendix A), a line
97: editor will be available to correct the command line, get automatic
98: completions, and so on. See \secref{se:readline} for a short summary of
99: available commands. This might not be available for all architectures.
100:
101: Whether extended on-line help and line editing are available or not is
102: indicated in the GP banner, between the version number and the copyright
103: message.
104:
105: If you type \kbd{?\bs} you will get a short description of the metacommands
106: (keyboard shortcuts).
107:
108: Finally, typing \kbd{?.} will return the list of available (pre-defined)
109: member functions. These are functions attached to specific kind of objects,
110: used to retrieve easily some information from complicated structures (you
111: can define your own but they won't be shown here). We will soon describe
112: these commands in more detail.
113:
114: As a general rule, under GP, commands starting with \b\ or with some
115: other symbols like \kbd{?} or \kbd{\#}, are not computing commands, but are
116: metacommands which allow the user to exchange information with GP. The
117: available metacommands can be divided into default setting commands
118: (explained below) and simple commands (or keyboard shortcuts, to be dealt
119: with in \secref{se:meta}).
120:
121: \section{Defaults and output formats}\sidx{defaults}\sidx{output formats}
122: \label{se:defaults}
123:
124: \noindent
125: There are many internal variables in GP, defining how the system will behave
126: in certain situations, unless a specific override has been given. Most
127: of them are a matter of basic customization (colors, prompt) and will be set
128: once and for all in your \idx{preferences file} (see \secref{se:gprc}), but
129: some of them are useful interactively (set timer on, increase precision,
130: etc.).
131:
132: The function used to manipulate these values is called \kbd{default}, which
133: is described in \secref{se:default}. The basic syntax is
134:
135: \kbd{default(\var{def}, \var{value})},
136:
137: \noindent
138: which sets the default \var{def} to \var{value}. In interactive use, most
139: of these can be abbreviated using historic GP metacommands (mostly,
140: starting with \b), which we shall describe in the next section.
141:
142: Here we will only describe the available defaults and how they are used. Just
143: be aware that typing \kbd{default} by itself will list all of them, as well
144: as their current values (see \b{d}). Just after the default name, we give
145: between parentheses the initial value when GP starts (assuming you did not
146: tamper with it using command-line switches or a~\tet{gprc}).
147:
148: \misctitle{Note:} the suffixes \kbd{k} or \kbd{M} can be appended to a
149: \var{value} which is a numeric argument, with the effect of multiplying it
150: by $10^3$ or $10^6$ respectively. Case is not taken into account there, so
151: for instance \kbd{30k} and \kbd{30K} both stand for $30000$. This is mostly
152: useful to modify or set the defaults \kbd{primelimit} or \kbd{stacksize}
153: which typically involve a lot of trailing zeroes.
154:
155: \misctitle{(somewhat technical) Note:} As we will see in
156: \secref{se:strings}, the second argument to \kbd{default} will be subject
157: to string context expansion, which means you can use run-time values. In
158: other words, something like \kbd{a = 3; default(logfile, "\var{some
159: filename}" a ".log")} will work (and log the output in
160: \var{some filename}3.log).
161:
162: Some defaults will be expanded further when the values are used (after the
163: above expansion has been performed):
164:
165: $\bullet$ \teb{time expansion}: the string is sent through the library
166: function \tet{strftime}. This means that \kbd{\%}\var{char} combinations have
167: a special meaning, usually related to the time and date. For instance,
168: \kbd{\%H} = hour (24-hour clock) and \kbd{\%M} = minute [00,59] (on a Unix
169: system, you can try \kbd{man strftime} at your shell prompt to get a complete
170: list). This is applied to \kbd{prompt}, \kbd{psfile}, and \kbd{logfile}. For
171: instance,
172:
173: \kbd{default(prompt,"(\%R) ? ")}
174:
175: \noindent
176: will prepend the time of day, in the form \kbd{(\var{hh}:\var{mm})}
177: to GP's usual prompt.
178:
179: \unix \indent $\bullet$ \teb{environment expansion}: When the string contains a
180: sequence of the form \kbd{\$\var{SOMEVAR}} (e.g.~\kbd{\$HOME}) the
181: environment is searched and if \var{SOMEVAR} is defined, the sequence is
182: replaced by the corresponding value. Also the \kbd{\til} symbol has the
183: same meaning as in the C and bash shells~--- \kbd{\til} by itself stands
184: for your home directory, and \kbd{\til{}user} is expanded to \kbd{user}'s
185: home directory. This is applied to all filenames\sidx{filename}.
186:
187: \subsecidx{buffersize} (default \kbd{30k}): GP input is buffered, which means
188: only so many bytes of data can be read at a time before a command is
189: executed. This used to be a very important variable, to allow for very
190: large input files to be read into GP, for example large matrices, without it
191: complaining about ``unused characters''. Currently, \kbd{buffersize} is
192: automatically adjusted to the size of the data that are to be read. It will
193: never go down by itself though. Thus this option may come in handy to decrease
194: the buffer size after some unusually large \kbd{read}, when you don't need to
195: keep gigantic buffers around anymore.
196:
197: \subsecidxunix{colors} (default \kbd{""}): this default is only usable if GP
198: \label{se:colors}
199: is running within certain color-capable terminals. For instance \kbd{rxvt},
200: \kbd{color\_xterm} and modern versions of \kbd{xterm} under X Windows, or
201: standard Linux/DOS text consoles. It causes GP to use a small palette of
202: colors for its output. With xterms, the colormap used corresponds to the
203: resources \kbd{Xterm*color$n$} where $n$ ranges from $0$ to $15$ (see the
204: file \kbd{misc/color.dft} for an example). Legal values for this default are
205: strings \kbd{"$a_1$,\dots,$a_k$"} where $k\le7$ and each $a_i$ is either
206:
207: \noindent $\bullet$ the keyword \kbd{no} (use the default color, usually
208: black on transparent background)
209:
210: \noindent $\bullet$ an integer between 0 and 15 corresponding to the
211: aforementioned colormap
212:
213: \noindent $\bullet$ a triple $[c_0,c_1,c_2]$ where $c_0$ stands for foreground
214: color, $c_1$ for background color, and $c_2$ for attributes (0 is default, 1
215: is bold, 4 is underline).
216:
217: The output objects thus affected are respectively error messages,
218: history numbers, prompt, input line, output, help messages, timer (that's
219: seven of them). If $k < 7$, the remaining $a_i$ are assumed to be $no$. For
220: instance
221: %
222: \bprog
223: default(colors, "9, 5, no, no, 4")
224: @eprog
225: \noindent
226: typesets error messages in color $9$, history numbers in color $5$, output in
227: color $4$, and does not affect the rest.
228:
229: A set of default colors for dark (reverse video or PC console) and light
230: backgrounds respectively is activated when \kbd{colors} is set to
231: \kbd{darkbg}, resp.~\kbd{lightbg} (or any proper prefix: \kbd{d} is
232: recognized as an abbreviation for \kbd{darkbg}). A bold variant of
233: \kbd{darkbg}, called \kbd{boldfg}, is provided if you find the former too
234: pale.
235:
236: \emacs{In the present version, this default is incompatible with Emacs.
237: Changing it will just fail silently (the alternative would be to display
238: escape sequences as is, since Emacs will refuse to interpret them). On the
239: other hand, you can customize highlighting in your \kbd{.emacs} so as to mimic
240: exactly this behaviour. See \kbd{emacs/pariemacs.txt}.}
241:
242: If you use an old \kbd{readline} library (version number less than 2.0),
243: you should do as in the example above and leave $a_3$ and $a_4$ (prompt
244: and input line) strictly alone. Since old versions of \kbd{readline} did
245: not handle escape characters correctly (or more accurately, treated them
246: in the only sensible way since they did not care to check all your terminal
247: capabilities: it just ignored them), changing them would result in many
248: annoying display bugs.
249:
250: The hacker's way to check if this is the case would be to look in the
251: \kbd{readline.h} include file (wherever your readline include files are) for
252: the string \kbd{RL\_PROMPT\_START\_IGNORE}. If it's there, you are safe.
253:
254: A more sensible way is to make some experiments, and get a more recent
1.2 ! noro 255: \kbd{readline} if yours doesn't work the way you would like it to. See the
! 256: file \kbd{misc/gprc.dft} for some examples.
1.1 noro 257:
258: \subsecidx{compatible} (default \kbd{0}): The GP function names and syntax
259: have changed tremendously between versions 1.xx and 2.00. To help you cope
260: with this we provide some kind of backward compatibility, depending on the
261: value of this default:
262:
263: \quad \kbd{compatible} = 0: no backward compatibility. In this mode, a very
264: handy function, to be described in \secref{se:whatnow}, is \kbd{whatnow},
265: which tells you what has become of your favourite functions, which GP
266: suddenly can't seem to remember.
267:
268: \quad \kbd{compatible} = 1: warn when using obsolete functions, but
269: otherwise accept them. The output uses the new conventions though, and
270: there may be subtle incompatibilities between the behaviour of former and
271: current functions, even when they share the same name (the current function
272: is used in such cases, of course!). We thought of this one as a transitory
273: help for GP old-timers. Thus, to encourage switching to \kbd{compatible}=0,
274: it is not possible to disable the warning.
275:
276: \quad \kbd{compatible} = 2: use only the old function naming scheme (as
277: used up to version 1.39.15), but {\it taking case into account}. Thus
278: \kbd{I} (${}=\sqrt{-1}$) is not the same as \kbd{i} (user variable, unbound
279: by default), and you won't get an error message using \kbd{i} as a loop
280: index as used to be the case.
281:
282: \quad \kbd{compatible} = 3: try to mimic exactly the former behaviour. This
283: is not always possible when functions have changed in a fundamental way.
284: But these differences are usually for the better (they were meant to,
285: anyway), and will probably not be discovered by the casual user.
286:
287: One adverse side effect is that any user functions and aliases that have
288: been defined \var{before} changing \kbd{compatible} will get erased if this
289: change modifies the function list, i.e.~if you move between groups
290: $\{0,1\}$ and $\{2,3\}$ (variables are unaffected). We of course strongly
291: encourage you to try and get used to the setting \kbd{compatible}=0.
292:
1.2 ! noro 293: Note that the default \tet{new_galois_format} is another compatibility setting,
! 294: which is completely independent of \kbd{compatible}.
! 295:
1.1 noro 296: \subsecidx{debug} (default \kbd{0}): debugging level. If it is non-zero,
297: some extra messages may be printed (some of it in French), according to
298: what is going on (see~\b{g}).
299:
300: \subsecidx{debugfiles} (default \kbd{0}): file usage debugging level. If it
301: is non-zero, GP will print information on file descriptors in use, from
302: PARI's point of view (see~\b{gf}).
303:
304: \subsecidx{debugmem} (default \kbd{0}): memory debugging level. If it is
305: non-zero, GP will regularly print information on memory usage. If it's
306: greater than 2, it will indicate any important garbage collecting and the
307: function it is taking place in (see~\b{gm}).
308:
309: \noindent {\bf Important Note:} As it noticeably slows down the performance
310: (and triggers bugs in some versions of a popular compiler), the first
311: functionality (memory usage) is disabled if you're not running a version
312: compiled for debugging (see Appendix~A).
313:
314: \subsecidx{echo} (default \kbd{0}): this is a toggle, which can be either 1
315: (on) or 0 (off). When \kbd{echo} mode is on, each command is reprinted before
316: being executed. This can be useful when reading a file with the \b{r} or
317: \kbd{read} commands. For example, it is turned on at the beginning of the test
318: files used to check whether GP has been built correctly (see \b{e}).
319:
320: \subsecidx{format} (default \kbd{"g0.28"} and \kbd{"g0.38"} on 32-bit and
321: 64-bit machines, respectively): of the form x$m.n$, where x is a letter in
322: $\{\kbd{e},\kbd{f},\kbd{g}\}$, and $n$, $m$ are integers. If x is \kbd{f},
323: real numbers will be printed in \idx{fixed floating point format} with no
324: explicit exponent (e.g.~\kbd{0.000033}), unless their integer part is not
325: defined (not enough significant digits); if the letter is \kbd{e}, they
326: will be printed in \idx{scientific format}, always with an explicit
327: exponent (e.g.~\kbd{3.3e-5}). If the letter is \kbd{g}, real numbers will
328: be printed in \kbd{f} format, except when their absolute value is less than
329: $2^{-32}$ or they are real zeroes (of arbitrary exponent), in which case
330: they are printed in \kbd{e} format.\label{se:format}
331:
332: The number $n$ is the number of significant digits printed for real
333: numbers, except if $n<0$ where all the significant digits will be printed
334: (initial default 28, or 38 for 64-bit machines), and the number $m$ is the
335: number of characters to be used for printing integers, but is ignored if
336: equal to 0 (which is the default). This is a feeble attempt at formatting.
337:
338: \subsecidxunix{help} (default: the location of the \kbd{gphelp} script): the
339: name of the external help program which will be used from within GP when
340: extended help is invoked, usually through a \kbd{??} or \kbd{???} request
341: (see \secref{se:exthelp}), or \kbd{M-H} under readline (see
342: \secref{se:readline}).
343:
344: \subsecidx{histsize} (default \kbd{5000}): GP keeps a history of the last
345: \kbd{histsize} results computed so far, which you can recover using the
346: \kbd{\%} notation (see \secref{se:history}). When this number is exceeded,
347: the oldest values are erased. Tampering with this default is the only way to
348: get rid of the ones you don't need anymore.
349:
350: \subsecidx{lines} (default \kbd{0}): if set to a positive value, GP prints at
351: most that many lines from each result, terminating the last line shown with
352: \kbd{[+++]} if further material has been suppressed. The various \kbd{print}
353: commands (see \secref{se:gp_program}) are unaffected, so you can always type
354: \kbd{print(\%)}, \b{a}, or \b{b} to view the full result. If the actual
355: screen width cannot be determined, a ``line'' is assumed to be 80 characters
356: long.
357:
358: \subsecidx{log} (default \kbd{0}): this is a toggle, which can be either 1
359: (on) or 0 (off). When logging mode is turned on, GP opens a log file, whose
360: exact name is determined by the \kbd{logfile} default. Subsequently, all the
361: commands and results will be written to that file (see \b{l}). In case a file
362: with this precise name already existed, it will not be erased: your data will
363: be \var{appended} at the end.
364:
365: \subsecidx{logfile} (default \kbd{"pari.log"}): name of the log file to be
366: used when the \kbd{log} toggle is on. Tilde and time expansion are performed.
367:
1.2 ! noro 368: \subsecidx{new_galois_format} (default \kbd{0}): if this is set, the
! 369: \tet{polgalois} command will use a different, more consistent, naming scheme
! 370: for Galois groups. This default is provided to ensure that scripts
! 371: can control this behaviour and do not break unexpectedly. Note that the
! 372: default value of $0$ (unset) will change to $1$ (set) in the next major
! 373: version.
! 374:
1.1 noro 375: \subsecidx{output} (default \kbd{1}): there are four possible values: 0
376: (=~\var{raw}), 1 (=~\var{prettymatrix}), 2 (=~\var{prettyprint}), or 3
377: (=~\var{external prettyprint}). This
378: means that, independently of the default \kbd{format} for reals which we
379: explained above, you can print results in four ways: either in \tev{raw
380: format}, i.e.~a format which is equivalent to what you input, including
381: explicit multiplication signs, and everything typed on a line instead of
382: two dimensional boxes. This can have several advantages, for instance it
383: allows you to pick the result with a mouse or an editor, and to paste it
384: somewhere else.\label{se:output}
385:
386: The second format is the \tev{prettymatrix format}. The only difference to
387: raw format is that matrices are printed as boxes instead of horizontally.
388: This is prettier, but takes more space and cannot be used for input. Column
389: vectors are still printed horizontally.
390:
391: The third format is the \tev{prettyprint format}, or beautified format. In
392: the present version \vers, this is not beautiful at all.
393:
394: \unix{\indent The fourth format is \tev{external prettyprint}, which pipes
395: all GP output in TeX format to an external prettyprinter, according to the
396: value of \tet{prettyprinter}. The default script (\tet{tex2mail}) converts
397: its input to readable two-dimensional text.}
398:
399: Independently of the setting of this default, an object can be printed
400: in any of the three formats at any time using the commands \b{a}, \b{m}
401: and~\b{b} respectively (see below).
402:
403: \subsecidx{parisize} (default, 1M bytes on the Mac, 4M otherwise): GP, and
404: in fact any program using the PARI library, needs a stack in which to do
405: its computations. \kbd{parisize} is the stack size, in bytes. It is
406: strongly recommended you increase this default (using the \kbd{-s}
1.2 ! noro 407: command-line switch, or a \tet{gprc}) if you can afford it. Don't increase
1.1 noro 408: it beyond the actual amount of RAM installed on your computer or GP will
409: spend most of its time paging.
410:
411: In case of emergency, you can use the \tet{allocatemem} function to
412: increase \kbd{parisize}, once the session is started. GP will try to
413: \var{double} the stack size by itself when memory runs low during a
414: computation, but this very computation will then be lost, and you will have
415: to type the command again.
416:
417: \subsecidx{path} (default \kbd{".:\til:\til/gp"} on UNIX systems,
418: \kbd{".;C:\bs;C:\bs GP} on DOS, OS/2 and Windows, and \kbd{"."} otherwise):
419: This is a list of directories, separated by colons ':' (semicolons ';' in the
420: DOS world, since colons are pre-empted for drive names). When asked to read a
421: file whose name does not contain \kbd{/} (i.e.~no explicit path was given),
422: GP will look for it in these directories, in the order they were written in
423: \kbd{path}. Here, as usual, '.' means the current directory, and '$.\,.$' its
424: immediate parent. Tilde expansion is performed.
425:
426: \subsecidxunix{prettyprinter} (default \kbd{"tex2mail -TeX -noindent
427: -ragged -by\_par"}) the name of an external prettyprinter to use when
428: \kbd{output} is~3 (\var{alternate prettyprinter}). {\bf This is
429: experimental} but the default \tet{tex2mail} looks already much nicer than
430: the built-in ``beautified format'' ($\kbd{output} = 2$). If the
431: corresponding program doesn't exist on your system,
432:
433: \subsecidx{primelimit} (default \kbd{200k} on the Mac, and \kbd{500k}
434: otherwise): GP precomputes a list of all primes less than \kbd{primelimit}
435: at initialization time. These are used by many arithmetical functions. If
436: you don't plan to invoke any of them, you can just set this to 1.
437:
438: \subsecidx{prompt} (default \kbd{"? "}): a string that will be printed as
439: prompt. Note that most usual escape sequences are available there: \b{e} for
440: Esc, \b{n} for Newline, \dots, \kbd{\bs\bs} for \kbd{\bs}. Time expansion is
441: performed.
442:
443: This string is sent through the library function \tet{strftime} (on a
444: Unix system, you can try \kbd{man strftime} at your shell prompt). This means
445: that \kbd{\%} constructs have a special meaning, usually related to the time
446: and date. For instance, \kbd{\%H} = hour (24-hour clock) and \kbd{\%M} =
447: minute [00,59] (use \kbd{\%\%} to get a real \kbd{\%}).
448:
449: If you use \kbd{readline}, escape sequences in your prompt will result in
450: display bugs. If you have a relatively recent \kbd{readline} (see the comment
451: at the end of \secref{se:colors}), you can brace them with special sequences
452: (\kbd{\bs[} and \kbd{\bs]}), and you will be safe. If these just result in
453: extra spaces in your prompt, then you'll have to get a more recent
454: \kbd{readline}. See the file \kbd{misc/gprc.dft} for an example.
455:
456: \emacs {\bf Caution}: Emacs needs to know about the prompt pattern to
457: separate your input from previous GP results, without ambiguity. It's not a
458: trivial problem to adapt automatically this regular expression to an
459: arbitrary prompt (which can be self-modifying!). Thus, in this version \vers,
460: Emacs relies on the prompt being the default one. So, do not tamper with the
461: \kbd{prompt} variable \var{unless} you modify it simultaneously in your
462: \kbd{.emacs} file (see \kbd{emacs/pariemacs.txt} and \kbd{misc/gprc.dft} for
463: examples).
464:
1.2 ! noro 465: \subsecidx{prompt_cont} (default \kbd{""}): a string that will be printed
! 466: to prompt for continuation lines (e.g. in between braces, or after a
! 467: line-terminating backslash). Everything that applies to \kbd{prompt}
! 468: applies to \kbd{prompt\_cont} as well.
! 469:
1.1 noro 470: \subsecidx{psfile} (default \kbd{"pari.ps"}): name of the default file where
471: GP is to dump its PostScript drawings (these will always be appended, so that
472: no previous data are lost). Tilde and time expansion are performed.
473:
474: \subsecidx{readline} (default \kbd{1}): switches readline line-editing
475: facilities on and off. This may be useful if you are running GP in a Sun
476: \tet{cmdtool}, which interacts badly with readline. Of course, until readline
477: is switched on again, advanced editing features like automatic completion
478: and editing history are not available.
479:
480: % leave the long line for gphelp (expects ':' on the first line)
481: \subsecidx{realprecision} (default \kbd{28} and \kbd{38} on 32-bit and 64-bit machines respectively): the number of significant digits and, at the same
482: time, the number of printed digits of real numbers (see~\b{p}). Note that
483: PARI internal precision works on a word basis (32 or 64 bits), hence may not
484: coincide with the number of decimal digits you input. For instance to get 2
485: decimal digits you need one word of precision which, on a 32-bit machine,
486: actually gives you 9 digits ($9 < \log_{10}(2^{32}) < 10$):
487:
488: \bprog
489: ? default(realprecision, 2)
490: realprecision = 9 significant digits (2 digits displayed)
491: @eprog
492:
493: \subsecidx{secure} (default \kbd{0}): this is a toggle which can be either 1
494: (on) or 0 (off). If on, the \tet{system} and \tet{extern} command are
495: disabled. These two commands are potentially dangerous when you execute
496: foreign scripts since they let GP execute arbitrary UNIX commands. GP will
497: ask for confirmation before letting you (or a script) unset this toggle.
498:
499: \subsecidx{seriesprecision} (default \kbd{16}): precision of power series
500: (see~\b{ps}).
501:
502: \subsecidx{simplify} (default \kbd{1}): this is a toggle which can be either
503: 1 (on) or 0 (off). When the PARI library computes something, the type of the
504: result is not always the simplest possible. The only type conversions which
505: the PARI library does automatically are rational numbers to integers (when
506: they are of type \typ{FRAC} and equal to integers), and similarly rational
507: functions to polynomials (when they are of type \typ{RFRAC} and equal to
508: polynomials). This feature is useful in many cases, and saves time, but can
509: be annoying at times. Hence you can disable this and, whenever you feel like
510: it, use the function \kbd{simplify} (see Chapter 3) which allows you to
511: simplify objects to the simplest possible types recursively (see~\b{y}).
512: \sidx{automatic simplification}
513:
514: \subsecidx{strictmatch} (default \kbd{1}): this is a toggle which can be
515: either 1 (on) or 0 (off). If on, unused characters after a sequence has been
516: processed will produce an error. Otherwise just a warning is printed. This
517: can be useful when you're not sure how many parentheses you have to close after
518: complicated nested loops.
519:
520: \subsecidx{timer} (default \kbd{0}): this is a toggle which can be either 1
521: (on) or 0 (off). If on, every instruction sequence (anything ended by a
522: newline in your input) is timed, to some accuracy depending on the hardware
523: and operating system. The time measured is the user \idx{CPU time},
524: \var{not} including the time for printing the results (see \kbd{\#} and
525: \kbd{\#\#}).
526:
527: \subsec{Note on output formats.}
528:
529: \noindent
530: A zero real number is printed in \kbd{e} format as $0.Exx$ where $xx$ is
531: the (usually negative) \var{decimal} exponent of the number (cf.\ %
532: \secref{se:whatzero}). This allows the user to check the accuracy of the zero
533: in question (this could also be done using \b{x}, but that would be more
534: technical).
535:
536: When the integer part of a real number $x$ is not known exactly because the
537: exponent of $x$ is greater than the internal precision, the real number is
538: printed in \kbd{e} format (note that in versions before 1.38.93, this was
539: instead printed with a $*$ at the end).
540:
541: Note also that in beautified format, a number of type integer or real is
542: written without enclosing parentheses, while most other types have them.
543: Hence, if you see the expression $( 3.14 )$, it is not of type real, but
544: probably of type complex with zero imaginary part (if you want to be sure, type
545: \b{x} or use the function \kbd{type}).
546:
547: \section{Simple metacommands}\label{se:meta}
548:
549: \noindent
550: Simple metacommands are meant as shortcuts and should not be used in GP
551: scripts (see \secref{se:programming}). Beware that these, as all of GP input,
552: are now \var{case sensitive}. For example, \b{Q} is no longer identical to
553: \b{q}. In the following list, braces are used to denote optional arguments,
554: with their default values when applicable, e.g.~$\{n=0\}$ means that if $n$
555: is not there, it is assumed to be~$0$. Whitespace (or spaces) between the
556: metacommand and its arguments and within arguments is optional. (This can
557: cause problems only with \b{w}, when you insist on having a filename whose
558: first character is a digit, and with \b{r} or \b{w}, if the filename itself
559: contains a space. In such cases, just use the underlying \tet{read} or
560: \tet{write} function; see~\secref{se:write}).
561:
562: \subseckbd{?} $\{\var{command}\}$: GP on-line help interface.
563: As already mentioned, if you type \kbd{?$n$} where $n$ is a number from 1
564: to 11, you will get the list of functions in Section $3.n$ of the manual
565: (the list of sections being obtained by simply typing \kbd{?}).
566: \label{se:exthelp}
567:
568: These names are in general not informative enough. More details can be
569: obtained by typing \kbd{?\var{function}}, which gives a short explanation of
570: the function's calling convention and effects. Of course, to have complete
571: information, read Chapter 3 of this manual (the source code is at your
572: disposal as well, though a trifle less readable!). Much better help can be
573: obtained through the extended help system (see below).
574:
575: \unix If the line before the copyright message indicates that extended help
576: is available (this means \kbd{perl} is installed on your system, GP was
577: told about it at compile time, and the whole PARI distribution was
578: correctly installed), you can add more \kbd{?} signs for extended
579: functionalities:
580:
581: \kbd{??~\var{keyword}} yields the functions description as it stands in this
582: manual, usually in Chapter~2 or~3. If you're not satisfied with the default
583: chapter chosen, you can impose a given chapter by ending the keyword with
584: \kbd{@} followed by the chapter number, e.g.~\kbd{??~Hello@2} will look in
585: Chapter~2 for section heading \kbd{Hello} (which doesn't exist, by the way).
586:
587: All operators (e.g.~\kbd{+}, \kbd{\&\&}, etc.) are accepted by this
588: extended help, as well as a few other keywords describing key GP concepts,
589: e.g.~\kbd{readline} (the line editor), \kbd{integer}, \kbd{nf} (``number
590: field'' as used in most algebraic number theory computations), \kbd{ell}
591: (elliptic curves), etc.
592:
593: In case of conflicts between function and default names (e.g \tet{log},
594: \tet{simplify}), the function has higher priority. Use \kbd{?? default
595: /}\var{defaultname} to get the default help.
596:
597: \kbd{???~\var{pattern}} produces a list of sections in Chapter~3 of the
598: manual related to your query. As before, if \var{pattern} ends by \kbd{@}
599: followed by a chapter number, that chapter is searched instead; you also
600: have the option to append a simple \kbd{@} (without a chapter number) to
601: browse through the whole manual.
602:
603: If your query contains dangerous characters (e.g \kbd{?} or blanks) it is
604: advisable to enclose it within double quotes, as for GP strings (e.g
605: \kbd{???~"elliptic curve"}).
606:
607: Note that extended help is much more powerful than the short help, since
608: it knows about operators as well: you can type \kbd{??~*} or
609: \kbd{??~\&\&}, whereas a single \kbd{?} would just yield a not too helpful
610:
611: \kbd{*** unknown identifier.}
612:
613: \noindent message. Also, you can ask for extended help on section
614: number~$n$ in Chapter~3, just by typing \kbd{??~$n$} (where \kbd{?$n$} would
615: yield merely a list of functions). Finally, a few key concepts in GP are
616: documented in this way: metacommands (e.g \kbd{??~"??"}), defaults (e.g
617: \kbd{??~psfile}) and type names (e.g \typ{INT} or \kbd{integer}), as well as
618: various miscellaneous keywords such as \kbd{edit} (short summary of line
619: editor commands), \kbd{operator}, \kbd{member}, \kbd{"user defined"},
620: \kbd{nf}, \kbd{ell}, \dots
621:
622: Last but not least~: \kbd{??} without argument will open a \kbd{dvi}
623: previewer (\kbd{xdvi} by default, \kbd{\$GPXDVI} if it is defined in your
624: environment) containing the full user's manual. \kbd{??tutorial} and
625: \kbd{??refcard} do the same with the \idx{tutorial} and \idx{reference card}
626: respectively.
627:
628: \misctitle{Technical note:} these functionalities are provided by an
629: external \kbd{perl} script that you are free to use outside any GP session
630: (and modify to your liking, if you are perl-knowledgeable). It is called
631: \tet{gphelp}, lies in the \kbd{doc} subdirectory of your distribution
632: (just make sure you run \kbd{Configure} first, see Appendix~A) and is
633: really two programs in one. The one which is used from within GP is
634: \kbd{gphelp} which runs \TeX\ on a selected part of this manual, then opens
635: a previewer. \kbd{gphelp -detex} is a text mode equivalent, which looks
636: often nicer especially on a colour-capable terminal (see
637: \kbd{misc/gprc.dft} for examples). The default \kbd{help} selects which
638: help program will be used from within GP. You are welcome to improve this
639: help script, or write new ones (and we really would like to know about it
640: so that we may include them in future distributions). By the way, outside
641: of GP you can give more than one keyword as argument to \kbd{gphelp}.
642:
643: \subseckbd{/*...*/}: comment. Everything between the stars is ignored by
644: GP. These comments can span any number of lines.
645:
646: \subseckbd{\bs\bs}: one-line comment. The rest of the line
647: is ignored by GP.
648:
649: \subsec{\b{a}} $\{n\}$: prints the object number $n$ ($\%n$)
650: in raw format. If the number $n$ is omitted, print the latest computed object
651: ($\%$). \label{se:history}
652:
653: \subsec{\b{b}} $\{n\}$: Same as \b{a}, in prettyprint (i.e.~beautified)
654: format.
655:
656: \subsec{\b{c}}:\sidx{available commands} prints the list of all available
657: hardcoded functions under GP, not including operators written as special
658: symbols (see \secref{se:operators}). More information can be obtained using
659: the \kbd{?} metacommand (see above). For user-defined functions / member
660: functions, see \b{u} and \b{um}.
661:
662: \subsec{\b{d}}: prints the \idx{defaults} as described in the
663: previous section (shortcut for \kbd{default()}, see \secref{se:default}).
664:
665: \subsec{\b{e}} $\{n\}$: switches the \tet{echo} mode on (1) or off (0). If
666: $n$ is explicitly given, set echo to $n$.
667:
668: \subsec{\b{g}} $\{n\}$: sets the debugging level \tet{debug} to the
669: non-negative integer $n$.
670:
671: \subsec{\b{gf}} $\{n\}$: sets the file usage debugging level \tet{debugfiles}
672: to the non-negative integer $n$.
673:
674: \subsec{\b{gm}} $\{n\}$: sets the memory debugging level \tet{debugmem}
675: to the non-negative integer $n$.
676:
677: \subsec{\b{h}} $\{m$\kbd{-}$n\}$: outputs some debugging info about the
678: hashtable. If the argument is a number $n$, outputs the contents of cell
679: $n$. Ranges can be given in the form $m$\kbd{-}$n$ (from cell $m$ to cell
680: $n$, \$ = last cell). If a function name is given instead of a number or
681: range, outputs info on the internal structure of the hash cell this
682: function occupies (a \kbd{struct entree} in C). If the range is reduced to
683: a dash ('\kbd{-}'), outputs statistics about hash cell usage.
684:
685: \subsec{\b{l}} $\{$\var{logfile}$\}$: switches \tet{log} mode on and off.
686: If a \var{logfile} argument is given, change the default logfile name to
687: \var{logfile} and switch log mode on.
688:
689: \subsec{\b{m}}: as \b{a}, but using prettymatrix format.
690:
691: \subsec{\b{o}} $\{n\}$: sets \tet{output} mode to $n$ ($0$: raw, $1$:
692: prettymatrix, $2$: prettyprint, $3$: external prettyprint).
693:
694: \subsec{\b{p}} $\{n\}$: sets \tet{realprecision} to $n$ decimal
695: digits. Prints its current value if $n$ is omitted.
696:
697: \subsec{\b{ps}} $\{n\}$: sets \tet{seriesprecision} to $n$ significant terms.
698: Prints its current value if $n$ is omitted.
699:
700: \subsec{\b{q}}: quits the GP session and returns to the system.
701: Shortcut for the function \tet{quit} (see \secref{se:quit}).
702:
703: \subsec{\b{r}} $\{$\var{filename}$\}$: \idx{read}s into GP all the commands
704: contained in the named file as if they had been typed from the keyboard, one
705: line after the other. Can be used in combination with the \b{w} command (see
706: below). Related but not equivalent to the function \kbd{read} (see
707: \secref{se:read}); in particular, if the file contains more than one line of
708: input, there will be one history entry for each of them, whereas \kbd{read}
709: would only record the last one. If \var{filename} is omitted, re-read the
710: previously used input file (fails if no file has ever been successfully read
711: in the current session). If a GP \tet{binary file} (see \secref{se:writebin})
712: is read using this command, it is silently loaded, without cluttering the
713: history.
714:
715: \unix This command accepts compressed files in \idx{compress}ed (\kbd{.Z})
716: or \idx{gzip}ped (\kbd{.gz} or \kbd{.z}) format. They will be uncompressed on
717: the fly as GP reads them, without changing the files themselves.
718:
719: \subsec{\b{s}}: prints the state of the PARI \idx{stack} and \idx{heap}.
720: This is used primarily as a debugging device for PARI, and is not intended
721: for the casual user.
722:
723: \subsec{\b{t}}: prints the \idx{internal longword format} of all the PARI
724: types. The detailed bit or byte format of the initial codeword(s) is
725: explained in Chapter~4, but its knowledge is not necessary for a GP user.
726:
727: \subsec{\b{u}}: prints the definitions of all user-defined functions.
728:
729: \subsec{\b{um}}: prints the definitions of all user-defined member functions.
730:
731: \subsec{\b{v}}: prints the \idx{version number} and implementation architecture
732: (680x0, Sparc, Alpha, other) of the GP executable you are using. In library
733: mode, you can use instead the two character strings \kbd{PARIVERSION} and
734: \kbd{PARIINFO}, which correspond to the first two lines printed by GP just
735: before the Copyright message.
736:
737: \subsec{\b{w}} $\{n\}$ $\{$\var{filename}$\}$: writes the object number
738: $n$ ( $\%n$ ) into the named file, in raw format. If the number $n$ is
739: omitted, writes the latest computed object ( $\%$ ). If \var{filename} is
740: omitted, appends to \kbd{logfile} (the GP function \tet{write} is a trifle more
741: powerful, as you can have arbitrary filenames).
742:
743: \subsec{\b{x}}: prints the complete tree with addresses and contents (in
744: hexadecimal) of the \idx{internal representation} of the latest computed
745: object in GP. As for \b{s}, this is used primarily as a debugging device for
746: PARI, and the format should be self-explanatory (a $*$ before an object --
747: typically a modulus -- means the corresponding component is out of stack).
748: However, used on a PARI integer, it can be used as a
749: decimal$\rightarrow$hexadecimal converter.
750:
751: \subsec{\b{y}} $\{n\}$: switches \kbd{simplify} on (1) or off (0). If $n$
752: is explicitly given, set simplify to $n$.
753:
754: \subseckbd{\#}: switches the \kbd{timer} on or off.
755:
756: \subseckbd{\#\#}: prints the time taken by the latest computation.
757: Useful when you forgot to turn on the \kbd{timer}.
758:
759: \section{Input formats for the PARI types}
760:
761: \noindent
762: Before describing more sophisticated functions in the next section, let us
763: see here how to input values of the different data types known to PARI.
764: Recall that blanks are ignored in any expression which is not a string (see
765: below).
766:
767: \subsec{Integers} \sidx{integer}
768: (type \tet{t_INT}): type the integer (with an initial
769: \kbd{+} or \kbd{-}, if desired) with no decimal point.
770:
771: \subsec{Real numbers} \sidx{real number}
772: (type \tet{t_REAL}): type the number with a decimal
773: point. The internal precision of the real number will be the supremum of the
774: input precision and the default precision. For example, if the default
775: precision is 28 digits, typing \kbd{2.} will give a number with internal
776: precision 28, but typing a 45 significant digit real number will give a
777: number with internal precision at least 45 (although less may be printed).
778:
779: You can also use scientific notation with the letter \kbd{E} or
780: \kbd{e}, in which case the (non leading) decimal point may be omitted (like
781: \kbd{6.02 E 23} or \kbd{1e-5}, but \var{not} \kbd{e10}). By definition,
782: \kbd{0.E $N$} (or \kbd{0 E $N$}) returns a real $0$ of (decimal) exponent
783: $N$, whereas \kbd{0.} returns a real 0 ``of default precision'' (of exponent
784: $-\kbd{defaultprecision}$), see \secref{se:whatzero}.
785:
786: \subsec{Integermods}\sidx{integermod}
787: (type \tet{t_INTMOD}): to enter $n \mod m$, type
788: \kbd{Mod(n,m)}, \var{not} \kbd{n\%m} (see \secref{se:Mod}).
789:
790: \subsec{Rational numbers}\sidx{rational number}
791: (types \tet{t_FRAC} and \tet{t_FRACN}): under GP, all fractions are
792: automatically reduced to lowest terms, so it is in principle impossible to
793: work with reducible fractions (of type \typ{FRACN}), although of course in
794: library mode this is easy. To enter $n/m$ just type it as written. As
795: explained in \secref{se:gdiv}, division will \var{not} be performed, only
796: reduction to lowest terms.\label{se:FRAC}
797:
798: If you really want a reducible fraction under GP, you must use the \kbd{type}
799: function (see \secref{se:gptype}), by typing \kbd{type(x,FRACN)}. Be warned
800: however that this function must be used with extreme care.
801:
802: \subsec{Complex numbers}\sidx{complex number}
803: (type \tet{t_COMPLEX}): to enter $x+iy$, type \kbd{x + I*y} (\var{not}
804: \kbd{x+i*y}). The letter \tet{I} stands for $\sqrt{-1}$. Recall from
805: Chapter 1 that $x$ and $y$ can be of type \typ{INT}, \typ{REAL},
806: \typ{INTMOD}, \typ{FRAC}/\typ{FRACN}, or \typ{PADIC}.
807:
808: \subsec{$p$-adic numbers}\sidx{p-adic number}\label{se:padic}
809: (type \tet{t_PADIC}): to enter a $p$-adic number, simply write a
810: rational or integer expression and add to it \kbd{O($p$\pow $k$)}, where $p$
811: and $k$ are integers. This last expression indicates three things to GP:
812: first that it is dealing with a \typ{PADIC} type (the fact that $p$ is an
813: integer, and not a polynomial, which would be used to enter a series, see
814: \secref{se:series}), secondly the ``prime'' $p$ (note that it is not
815: checked whether $p$ is indeed prime; you can work on 10-adics if you want, but
816: beware of disasters as soon as you do something non-trivial like taking a
817: square root), and finally the number of significant $p$-adic digits $k$.
818: Note that \kbd{O(25)} is not the same as \kbd{O(5\pow 2)}; you probably
819: want the latter!
820:
821: For example, you can type in the $7$-adic number
822:
823: \kbd{2*7\pow(-1) + 3 + 4*7 + 2*7\pow 2 + O(7\pow3)}
824:
825: \noindent
826: exactly as shown, or equivalently as
827: \kbd{905/7 + O(7\pow3)}.
828:
829: \subsec{Quadratic numbers}\sidx{quadratic number}
830: (type \tet{t_QUAD}): first, you must define the default quadratic order or
831: field in which you want to work. This is done using the \tet{quadgen}
832: function, in the following way. Write something like
833: \bprog
834: w = quadgen(d)
835: @eprog\noindent
836: where \kbd{d} is the \var{discriminant} of the quadratic order in
837: which you want to work (hence $d$ is congruent to $0$ or $1$ modulo $4$). The
838: name \kbd{w} is of course just a suggestion, but corresponds to traditional
839: usage. You can of course use any variable name that you like. However,
840: quadratic numbers are always printed with a \kbd{w}, regardless of the
841: discriminant. So beware, two numbers can be printed in the same way and not
842: be equal. However GP will refuse to add or multiply them for example.
843:
844: Now $(1,w)$ will be the ``canonical'' integral basis of the quadratic order
845: (i.e.~$w=\sqrt{d}/2$ if $d\equiv 0 \mod 4$, and $w=(1+\sqrt{d})/2$ if
846: $d\equiv 1 \mod 4$, where $d$ is the discriminant), and to enter $x+yw$ you
847: just type \kbd{x + y*w}.
848:
849: \subsec{Polmods}\sidx{polmod} (type \tet{t_POLMOD}): exactly as
850: for integermods, to enter $x \mod y$ (where $x$ and $y$ are polynomials),
851: type \kbd{Mod(x,y)}, not \kbd{x\%y} (see \secref{se:Mod}). Note that when $y$
852: is an irreducible polynomial in one variable, polmods whose modulus is $y$
853: are simply algebraic numbers in the finite extension defined by the
854: polynomial $y$. This allows us to work easily in \idx{number field}s, finite
855: extensions of the $p$-adic field $\Q_p$, or \idx{finite field}s.
856:
857: \label{se:rempolmod}
1.2 ! noro 858: \misctitle{Important remark.}\sidx{variable (priority)} Since the
! 859: variables\sidx{variable} occurring in a polmod are not free variables, it is
! 860: essential in order to avoid inconsistencies that polmods use the same
! 861: variable in internal operations (i.e.~between polmods) and variables of lower
! 862: priority (which have been introduced later in the GP session) for external
! 863: operations (typically between a polynomial and a polmod). For example, PARI
! 864: will not recognize that \kbd{Mod(y, y\pow2 + 1)} is the same as \kbd{Mod(x,
! 865: x\pow2 + 1)}. Hopefully, this problem will pass away when type ``element of a
! 866: number field'' is eventually introduced. See \secref{se:priority} for a
! 867: definition of ``priority'' and a discussion of (PARI's idea of) multivariate
! 868: polynomial arithmetic.
1.1 noro 869:
870: On the other hand, \kbd{Mod(x, x\pow2 + 1) + Mod(x, x\pow2 + 1)}
871: (which gives \kbd{Mod(2*x, x\pow2 + 1)}) and \kbd{x + Mod(y, y\pow2 + 1)}
872: (which gives a result mathematically equivalent to $\kbd{x} + i$ with
873: $i^2=-1$) are completely correct, while \kbd{y + Mod(x, x\pow2 + 1)}
874: gives \kbd{Mod(x + y, x\pow2 + 1)}, which may not be what you want (\kbd{y}
875: is treated here as a numerical parameter, not as a polynomial variable).
876:
877: \misctitle{Note (added in version 2.0.16)} As long as the main variables
878: are the same, it is allowed to mix \typ{POL} and \typ{POLMOD}s. The result
879: will be the expected \typ{POLMOD}. For instance \kbd{x + Mod(x, x\pow2 +
880: 1)} is equal to \kbd{Mod(2*x, x\pow2 + 1)}. This wasn't the case prior to
881: version 2.0.16: it returned a polynomial in \kbd{x} equivalent to $\kbd{x}
882: + i$, which was in fact an invalid object (you couldn't \kbd{lift} it).
883:
884: \subsec{Polynomials}\sidx{polynomial}\label{se:pol}
885: (type \tet{t_POL}): type the polynomial in a natural way, not
886: forgetting to put a ``$*$'' between a coefficient and a formal variable
887: (this $*$ does not appear in beautified output). Any \idx{variable} name
888: can be used except for the reserved names \kbd{I} (used exclusively for the
889: square root of $-1$), \kbd{Pi} ($3.14\dots$), \kbd{Euler} (Euler's
890: constant), and all the function names: predefined functions, as described
891: in Chapter~3 (use \b{c} to get the complete list of them) and user-defined
892: functions, which you ought to know about (use \b{u} if you are subject to
893: memory lapses). The total number of different variable names is limited to
894: $16384$ and $65536$ on 32-bit and 64-bit machines respectively, which
895: should be enough. If you ever need hundreds of variables, you should
1.2 ! noro 896: probably be using vectors instead. See \secref{se:priority} for a discussion
! 897: of multivariate polynomial rings.
1.1 noro 898:
899: \subsec{Power series}\sidx{power series}\label{se:series}
900: (type \tet{t_SER}): type a rational function or
901: polynomial expression and add to it \hbox{\kbd{O(\var{expr} \pow $k$)}},
902: where \var{expr} is an expression which has non-zero valuation (it can be a
903: polynomial, power series, or a rational function; the most common case being
904: simply a variable name).
905: This indicates to GP that it is dealing with a power series, and the desired
906: precision is $k$ times the valuation of \var{expr} with respect to the
907: main variable of \var{expr} (to check the ordering of the variables, or
908: to modify it, use the function \kbd{reorder}; see~\secref{se:reorder}).
909:
910: \subsec{Rational functions}\sidx{rational function}
911: (types \tet{t_RFRAC} and \tet{t_RFRACN}): as for fractions, all rational
912: functions are automatically reduced to lowest terms under GP. All that was
913: said about fractions in \secref{se:FRAC} remains valid here.
914:
915: \subsec{Binary quadratic forms of positive or negative discriminant}%
916: \sidx{binary quadratic form}
917: (type \tet{t_QFR} and \tet{t_QFI}):
918: these are input using the function \kbd{Qfb} (see Chapter~3). For example
919: \kbd{Qfb(1,2,3)} will create the binary form $x^2+2xy+3y^2$. It will be
920: imaginary (of internal type \typ{QFI}) since $2^2 - 4*3 = -8$ is negative.
921:
922: In the case of forms with positive discriminant (type \typ{QFR}), you
923: may add an optional fourth component (related to the regulator, more
924: precisely to Shanks and Lenstra's ``distance''), which must be a real number.
925: See also the function \kbd{qfbprimeform} which directly creates a prime form
926: of given discriminant (see Chapter~3).
927:
928: \subsec{Row and column vectors}\sidx{row vector}\sidx{column vector} (types
929: \tet{t_VEC} and \tet{t_COL}): to enter a row vector, type the components
930: separated by commas ``\kbd{,}'', and enclosed between brackets
931: ``\kbd{[}$\,$'' and ``$\,$\kbd{]}'', e.g.~\kbd{[1,2,3]}. To enter a column
932: vector, type the vector horizontally, and add a tilde ``\til'' to
933: transpose. \kbd{[ ]} yields the empty (row) vector. The function \tet{Vec}
934: can be used to transform any object into a vector (see Chapter~3).
935:
936: \subsec{Matrices} (type \tet{t_MAT}):\sidx{matrix} to enter a matrix, type
937: the components line by line, the components being separated by commas
938: ``\kbd{,}'', the lines by semicolons ``\kbd{;}'', and everything enclosed
939: in brackets ``\kbd{[}$\,$'' and ``$\,$\kbd{]}'', e.g. \kbd{[x,y; z,t;
940: u,v]}. \kbd{[ ; ]} yields the empty (0x0) matrix. The function \tet{Mat}
941: can be used to transform any object into a matrix (see Chapter 3).
942:
943: Note that although the internal representation is essentially the same (only
944: the type number is different), a row vector of column vectors is \var{not}
945: a matrix; for example, multiplication will not work in the same way.
946:
947: Note also that it is possible to create matrices (by conversion of empty
948: column vectors and concatenation, or using the \kbd{matrix} function) with a
949: given positive number of columns, each of which has zero rows. It is not
950: possible to create or represent matrices with zero columns and a nonzero
951: number of rows.
952:
953: \subsec{Lists} (type \tet{t_LIST}):\sidx{list} lists cannot be input
954: directly; you have to use the function \kbd{listcreate} first, then
955: \kbd{listput} each time you want to append a new element (but you can
956: access the elements directly as with the vector types described above). The
957: function \kbd{List} can be used to transform (row or column) vectors into
958: lists (see Chapter~3).
959:
960: \subsec{Strings} (type \tet{t_STR}):\sidx{string}\sidx{character string}
961: to enter a string, just enclose it between double quotes \kbd{"}, like
962: this: \kbd{"this is a string"}. The function \kbd{Str} can be used to
963: transform any object into a string (see Chapter~3).
964:
965: \subsec{Small vectors} (type \tet{t_VECSMALL}): this is an internal type,
966: used to code in an efficient way vectors containing only small integers (such
967: as permutations). Most GP functions will refuse to operate on these objects.
968:
969: \section{GP operators}\label{se:operators}
970:
971: \noindent
972: Loosely speaking, an \idx{operator} is a function (usually associated to
973: basic arithmetic operations) whose name contains only non-alphanumeric
974: characters. In practice, most of these are simple functions, which take
975: arguments, and return a value; assignment operators also have side effects.
976: Each of these has some fixed and unchangeable priority, which means that,
977: in a given expression, the operations with the highest priority will be
978: performed first. Operations at the same priority level will always be
979: performed in the order they were written, i.e.~from left to right. Anything
980: enclosed between parenthesis is considered a complete subexpression, and
981: will be resolved independently of the surrounding context. For instance,
982: assuming that \var{op}$_1$, \var{op}$_2$, \var{op}$_3$ are standard binary
983: operators with increasing priorities (think of \kbd{+}, \kbd{*}, \kbd{\pow}
984: for instance),
985: $$ x~\var{op}_1~y~\var{op}_2~z~\var{op}_2~x~\var{op}_3~y $$
986: is equivalent to
987: $$ x~\var{op}_1~((y~\var{op}_2~z)~\var{op}_2~ (x~\var{op}_3~y)).$$
988:
989: GP knows quite a lot of different operators, some of them unary (having
1.2 ! noro 990: only one argument), some binary, plus special selection operators. Unary
! 991: operators are defined for either
1.1 noro 992: prefix (preceding their single argument: \var{op}~$x$) or postfix (following
993: the argument: $x$~\var{op}) position, never both
994: (some are syntactically correct in both positions, but with different
995: meanings). Binary operators all use the syntax $x$~\var{op}~$y$. Most of
996: them are well known, some are borrowed from C~syntax, and a few are specific
997: to GP. Beware that some GP operators may differ slightly from their C
998: counterparts. For instance, GP's postfix \kbd{++} returns the \var{new}
999: value, like the prefix \kbd{++} of~C, and the binary shifts \kbd{<<},
1000: \kbd{>>} have a priority which is different from (higher than) that of
1001: their C counterparts.
1002: When in doubt, just surround everything by parentheses (besides, your code
1003: will probably be more legible).
1004:
1005: \noindent Here is the complete list (in order of decreasing \idx{priority},
1006: binary unless mentioned otherwise):
1007:
1008: \def\point#1{\noindent $\bullet$ #1\hfill\break\indent\strut}
1.2 ! noro 1009: \point{Priority 10}
1.1 noro 1010: %
1011: \kbd{++} and \kbd{--} (unary, postfix): \kbd{$x$++} assigns the value $x+1$ to
1012: $x$, then returns the new value of $x$. This corresponds to the C
1013: statement \kbd{++$x$} (there is no prefix \kbd{++} operator in GP).
1014: \kbd{$x$--} does the same with $x-1$.
1015:
1.2 ! noro 1016: \point{Priority 9}
1.1 noro 1017: %
1018: \kbd{\var{op}=}, where \var{op} is any simple binary operator
1019: (i.e.~a binary operator with no side effects, i.e.~one of those defined below)
1020: which is not a boolean operator (comparison or logical).
1021: \kbd{x~\var{op}=~$y$} assigns $(\kbd{x}~\var{op}~y)$ to~\kbd{x},
1022: and returns the new value of~\kbd{x}, \var{not} a reference to the
1.2 ! noro 1023: \idx{variable}~\kbd{x}. (Thus an assignment cannot occur on the left hand
1.1 noro 1024: side of another assignment.)
1025:
1.2 ! noro 1026: \point{Priority 8}
1.1 noro 1027: %
1028: \kbd{=} is the assignment operator. The result of \kbd{x~=~$y$} is the value
1029: of the expression~$y$, which is also assigned to the variable~\kbd{x}. This
1030: is \var{not} the equality test operator. Beware that a statement like
1031: \kbd{x~=~1} is always true (i.e.~non-zero), and sets \kbd{x} to~1.
1.2 ! noro 1032: The right hand side of the assignment operator is evaluated before the left
! 1033: hand side. If the left hand side cannot be modified, raise an error.
! 1034:
! 1035: \point{Priority 7}
! 1036: \kbd{[ ]} is the selection operator. \kbd{$x$[$i$]} returns the $i$-th
! 1037: component of vector $x$; \kbd{$x[$i$,$j$]$}, \kbd{$x[,$j$]$} and
! 1038: \kbd{$x$[$i$,]} respectively return the entry of coordinates $(i,j)$, the
! 1039: $j$-th column, and the $i$-th row of matrix $x$. If the assignment operator
! 1040: (\kbd{=}) immediately follows a sequence of selections, it assigns its
! 1041: right hand side to the selected component. E.g \kbd{x[1][1] = 0} is valid;
! 1042: but beware that \kbd{(x[1])[1] = 0} is not (because the parentheses force
! 1043: the complete evaluation of \kbd{x[1]}, and the result is not modifiable).
1.1 noro 1044:
1045: \point{Priority 6}
1046: %
1.2 ! noro 1047: \kbd{'} (unary, prefix): quote its argument (a variable name) without
! 1048: evaluating it.
1.1 noro 1049: \bprog
1050: ? a = x + 1; x = 1;
1051: ? subst(a,x,1)
1052: *** variable name expected: subst(a,x,1)
1053: ^---
1054: ? subst(a,'x,1)
1055: %1 = 2
1056: @eprog
1057: %
1058: \kbd{\pow}: powering.
1059:
1060: \kbd{'} (unary, postfix): derivative with respect to the main variable. If
1061: $f$ is a (GP or user) function, $f'(x)$ is allowed. If $x$ is a scalar, the
1062: operator performs \idx{numerical derivation}, defined as $(f(x+\varepsilon) -
1063: f(x-\varepsilon)) / 2\varepsilon$ for a suitably small epsilon depending on
1064: current precision. It behaves as $(f(x))'$ otherwise.
1065:
1066: \strut\kbd{\til} (unary, postfix): vector/matrix transpose.
1067:
1068: \kbd{!} (unary, postfix): factorial. $x\kbd{!}=x(x-1)\cdots 1$.
1069:
1.2 ! noro 1070: \kbd{.}\var{member} (unary, postfix): \kbd{$x$.\var{member}} extracts
! 1071: \var{member} from structure $x$ (see~\secref{se:member}).
! 1072:
! 1073: \point{Priority 5}
! 1074: %
! 1075: \kbd{!} (unary, prefix): logical \var{not}. \kbd{!$x$} return $1$ if $x$ is
! 1076: equal to $0$ (specifically, if \kbd{gcmp0($x$)==1}), and $0$ otherwise.
! 1077:
! 1078: \kbd{\#} (unary, prefix): cardinality; \kbd{\#$x$} returns \kbd{length($x$)}.
1.1 noro 1079:
1080: \point{Priority 4}
1081: %
1082: \kbd{+}, \kbd{-} (unary, prefix): \kbd{-} toggles the sign of its argument,
1083: \kbd{+} has no effect whatsoever.
1084:
1085: \point{Priority 3}
1086: %
1087: \kbd{*}: multiplication.
1088:
1089: \kbd{/}: exact division (\kbd{3/2}=$3/2$, not $1.5$).
1090:
1.2 ! noro 1091: \kbd{\bs}, \kbd{\%}: Euclidean quotient and remainder, i.e.~if $x =
1.1 noro 1092: qy + r$, with $0\le r < y$ (if $x$ and $y$ are polynomials, assume instead
1093: that $\deg r< \deg y$ and that the leading terms of $r$ and $x$ have the
1094: same sign), then $\kbd{x \b{ } y} = q$, $\kbd{x\%y} = r$.
1095:
1.2 ! noro 1096: \kbd{\bs/}: rounded Euclidean quotient for integers (rounded towards
1.1 noro 1097: $+\infty$ when the exact quotient would be a half-integer).
1098:
1099: \kbd{<<}, \kbd{>>}: left and right binary shift: \kbd{x<<n}$~=~x * 2^n$
1.2 ! noro 1100: if $n>0$, and $x \b{/} 2^{-n}$ otherwise. Right shift is defined by
1.1 noro 1101: \kbd{x>>n}$~=~$\kbd{x<<(-n)}.
1102:
1103: \point{Priority 2}
1104: %
1105: \kbd{+}, \kbd{-}: addition/subtraction.
1106:
1107: \point{Priority 1}
1108: %
1109: \kbd{<}, \kbd{>}, \kbd{<=}, \kbd{>=}: the usual comparison operators,
1110: returning 1 for \kbd{true} and 0 for \kbd{false}. For instance,
1111: \kbd{x<=1} returns $1$ if $x\le 1$ and $0$ otherwise.
1112:
1113: \kbd{<>}, \kbd{!=}: test for (exact) inequality.
1114:
1115: \kbd{==}: test for (exact) equality.
1116:
1117: \point{Priority 0}
1118: %
1119: \kbd{\&}, \kbd{\&\&}: logical \var{and}.
1120:
1121: \kbd{|}, \kbd{||}: logical (inclusive) \var{or}. Any sequence of logical
1122: \var{or} and \var{and} operations is evaluated from left to right,
1123: and aborted as soon as the final truth value is known. Thus, for instance,
1124: \kbd{(x \&\& 1/x)} or \kbd{(type(p) == "t\_INT" \&\& isprime(p))} will never
1125: produce an error since the second argument need not (and will not) be processed
1126: when the first is already zero (false).
1127:
1.2 ! noro 1128: \misctitle{Remark:} For optimal efficiency, you should use the
1.1 noro 1129: \kbd{++}, \kbd{--} and \var{op}\kbd{=} operators whenever possible:
1130: \bprog
1131: ? a = 200000;
1132: ? i = 0; while(i<a, i=i+1)
1133: time = 4,919 ms.
1134: ? i = 0; while(i<a, i+=1)
1135: time = 4,478 ms.
1136: ? i = 0; while(i<a, i++)
1137: time = 3,639 ms.
1138: @eprog
1139: \noindent For the same reason, the shift operators should be preferred to
1140: multiplication:
1141: \bprog
1142: ? a = 1<<20000;
1143: ? i = 1; while(i<a, i=i*2);
1144: time = 5,255 ms.
1145: ? i = 1; while(i<a, i<<=1);
1146: time = 988 ms.
1147: @eprog
1148:
1149: \section{The general GP input line}
1150: \subsec{Generalities}. User interaction with a GP session proceeds as
1151: follows: a sequence of characters is typed by the user at the GP prompt. This
1152: can be either a \b~command, a function definition, an expression, or a
1153: sequence of expressions (i.e.~a program). In the latter two cases, after the
1154: last expression has been computed its result is put into an internal
1155: (``history'') array, and printed. The successive elements of this array are
1156: called \kbd{\%1}, \kbd{\%2}, \dots As a shortcut, the latest computed
1157: expression can also be called \kbd{\%}, the previous one \kbd{\%`}, the one
1158: before that \kbd{\%``} and so on.
1159:
1160: If you want to suppress the printing of the result, for example because it
1161: is a long unimportant intermediate result, end the expression with a
1162: \kbd{;} sign. This same sign is used as an instruction separator when several
1163: instructions are written on the same line (note that for the pleasure of BASIC
1164: addicts, the \kbd{:} sign can also be used, but we will try to stick to
1165: C-style conventions in this manual). The final expression computed, even
1166: if not printed, will still be assigned to the history array, so you may have
1167: to pay close attention when you intend to refer back to it by number since
1168: this number does not appear explicitly. Of course, if you just want to use
1169: it on the next line, use \kbd{\%} as usual.
1170:
1171: Any legal expression can be typed in, and is evaluated using the
1172: conventions about operator priorities and left to right associativity (see
1173: the previous section), using the available operator symbols, function names
1174: (including user-defined functions and member functions see
1175: \secref{se:user_defined}), and special variables. Please note that, from
1176: version $1.900$ on, there\sidx{case distinction} \var{is} a distinction
1177: between lowercase and uppercase. Also, note that, outside of constant
1178: strings, blanks are completely ignored in the input to GP.
1179:
1.2 ! noro 1180: The special variable names known to GP are \tet{Euler} (Euler's constant
! 1181: $\gamma=0.577\dots$), \tet{I} (the square root of $-1$), \tet{Pi}
! 1182: (3.14\dots)~--- which could be thought of as functions with no arguments, and
! 1183: which may therefore be invoked without parentheses~---, and \tet{O} which
! 1184: obeys the following syntax:
1.1 noro 1185:
1186: \kbd{O(\var{expr}\pow k)}
1187:
1188: \noindent
1189: When \var{expr} is an integer or a rational number, this creates an
1190: \var{expr}-adic number (zero in fact) of precision \kbd{k}. When \var{expr}
1191: is a polynomial, a power series or a rational function whose main variable is
1192: $X$, say, this creates a power series (also zero) of precision $v*\kbd{k}$
1193: where $v$ is the $X$-adic valuation of \var{expr} (see \ref{se:padic}
1194: and~\ref{se:pol}).
1195:
1196: \subsec{Special editing characters}.\sidx{editing characters} A GP program
1197: can of course have more than one line. Since GP executes your commands as
1198: soon as you have finished typing them, there must be a way to tell it to
1199: wait for the next line or lines of input before doing anything. There are
1200: three ways of doing this.
1201:
1202: The first one is simply to use the \idx{backslash character} \kbd{\bs} at the
1203: end of the line that you are typing, just before hitting \kbd{<Return>}. This
1204: tells GP that what you will write on the next line is the physical
1205: continuation of what you have just written. In other words, it makes GP
1206: forget your newline character. For example if you use this while defining a
1207: function, and if you ask for the definition of the function using
1208: \kbd{?name}, you will see that your backslash has disappeared and that
1209: everything is on the same line. You can type a \kbd{\bs} anywhere. It will be
1210: interpreted as above only if (apart from ignored whitespace characters) it is
1211: immediately followed by a newline. For example, you can type
1212: \bprog
1213: ? 3 + \
1214: 4
1215: @eprog
1216: \noindent instead of typing \kbd{3 + 4}.
1217:
1218: The second one is a slight variation on the first, and is mostly useful when
1219: defining a user function (see \secref{se:user_defined}): since an equal sign
1220: can never end a valid expression, GP will disregard a newline immediately
1221: following an \kbd{=}.
1222: \bprog
1223: ? a =
1224: 123
1225: %1 = 123
1226: @eprog
1227:
1228: The third one cannot be used everywhere, but is in general much more useful.
1229: It is the use of braces \kbd{\obr} and \kbd{\cbr}.\sidx{brace characters}
1230: When GP sees an opening brace (\kbd{\obr}) {\it at the beginning of a line}
1231: (modulo spaces as usual), it understands that you are typing a multi-line
1232: command, and newlines will be ignored until you type a closing brace
1233: \kbd{\cbr}. However, there is an important (but easily obeyed) restriction:
1234: inside an open brace-close brace pair, all your input lines will be
1235: concatenated, suppressing any newlines. Thus, all newlines should occur after
1236: a semicolon (\kbd{;}), a comma (\kbd{,}) or an operator (for clarity's sake,
1237: we don't recommend splitting an identifier over two lines in this way). For
1238: instance, the following program
1239: \bprog
1240: {
1241: a = b
1242: b = c
1243: }
1244: @eprog
1245:
1246: \noindent would silently produce garbage, since what GP will really see is
1247: \kbd{a=bb=c} which will assign the value of \kbd{c} to both \kbd{bb} and
1248: \kbd{a} (if this really is what you intended, you're a hopeless case).
1249:
1250: \section{The GP/PARI programming language}
1251:
1252: The GP calculator uses a purely interpreted language. The structure of this
1253: language is reminiscent of LISP with a functional notation, \kbd{f(x,y)}
1254: rather than \kbd{(f x y)}: all \idx{programming} constructs, such as
1255: \kbd{if}, \kbd{while,} etc... are functions \footnote{*}{Not exactly, since
1256: not all their arguments need be evaluated. For instance it would be stupid
1257: to evaluate both branches of an \kbd{if} statement: since only one will
1258: apply, GP only expands this one.} (see \secref{se:programming} for a
1259: complete list), and the main loop does not really execute, but rather
1260: evaluates (sequences of) expressions. Of course, it is by no means a true
1261: LISP.
1262:
1263: \subsec{Variables and symbolic expressions}.\sidx{variable}
1264:
1265: In GP you can use up to 16383 variable names (up to 65535 on 64-bit
1266: machines). These names can be any standard identifier names, i.e.~they must
1267: start with a letter and contain only valid keyword characters: \kbd{\_} or
1268: alphanumeric characters ([\kbd{\_A-Za-z0-9}]). To avoid confusion with other
1269: symbols, you must not use other non-alphanumeric symbols like \kbd{\$}, or
1270: '\kbd{.}'. In addition to the function names which you must not use (see the
1271: list with \b{c}), there are exactly three special variable names which you
1272: are not allowed to use: \kbd{Pi} and \tet{Euler}, which represent well known
1273: constants, and $\kbd{I}=\sqrt{-1}$.
1274:
1275: Note that GP names are case sensitive since version 1.900. This means for
1276: instance that the symbol \kbd{i} is perfectly safe to use, and will not be
1277: mistaken for $\sqrt{-1}$, and that \kbd{o} is not synonymous anymore to
1278: \kbd{O}. If you grew addicted to the previous behaviour, you can have it back
1279: by setting the default \kbd{compatible} to $3$.
1280:
1281: Now the main thing to understand is that PARI/GP is \var{not} a symbolic
1282: manipulation package, although it shares some of the functionalities. One of
1283: the main consequences of this fact is that all expressions are evaluated as
1284: soon as they are written, they never stay in a purely abstract form%
1285: \footnote{**}{An obvious but important exception are character strings which
1.2 ! noro 1286: are evaluated essentially to themselves (type \typ{STR}). Not exactly
1.1 noro 1287: so though, since we do some work to treat the quoted characters correctly
1288: (those preceded by a \b{)}.}.
1289: %
1290: As an important example, consider what happens when you use a variable name
1291: \var{before} assigning a value into it. This is perfectly acceptable to GP,
1292: which considers this variable in fact as a polynomial of degree 1, with
1293: coefficients 1 in degree 1, 0 in degree 0, whose variable is the variable
1294: name you used.
1295:
1296: If later you assign a value to that variable, the objects which you have
1297: created before will still be considered as polynomials. If you want to obtain
1298: their value, use the function \kbd{eval} (see \secref{se:eval}).
1299:
1300: Finally, note that if the variable $x$ contains a vector or list, you can
1301: assign a result to $x[m]$ (i.e.~write something like $x[k]=\var{expr}$). If
1302: $x$ is a matrix, you can assign a result to $x[m,n]$, but \var{not} to
1303: $x[m]$. If you want to assign an expression to the $m$-th column of a matrix
1304: $x$, use $x[,m]=\var{expr}$ instead. Similarly, use $x[m,]=\var{expr}$ to
1305: assign an expression to the $m$-th row of $x$. This process is recursive, so
1306: if $x$ is a matrix of matrices of \dots, an expression such as
1307: $x[1,1][,3][4]=1$ would be perfectly valid (assuming of course that all
1308: matrices along the way have the correct dimensions).
1309:
1310: \misctitle{Note:} We'll see in \secref{se:user_defined} that it is possible
1311: to restrict the use of a given variable by declaring it to be \tet{global} or
1312: \tet{local}. This can be useful to enforce clean programming style, but is in
1313: no way mandatory.
1314:
1.2 ! noro 1315: \misctitle{(Technical) Note:}
1.1 noro 1316: Each variable has a stack of values, implemented as a linked list. When a new
1317: scope is entered (during a function call which uses it as a parameter, or if
1318: the variable is used as a loop index, see \secref{se:user_defined} and
1319: \secref{se:programming}), the value of the actual parameter is pushed on the
1320: stack. If the parameter is not supplied, a special $0$ value called
1321: \teb{gnil} is pushed on the stack (this value is not printed if it is
1322: returned as the result of a GP expression sequence). Upon exit, the stack
1.2 ! noro 1323: decreases. You can \kbd{kill} a variable, decreasing the stack yourself.
! 1324: However, the stack has a bottom: the value of a variable is the monomial of
! 1325: degree 1 in this variable, as is natural for a mathematician.
! 1326:
! 1327: \subsec{Variable priorities:}\sidx{variable (priority)}\label{se:priority}
! 1328: PARI has no intelligent ``sparse'' representation of polynomials. So a
! 1329: multivariate polynomial in PARI is just a polynomial (in one variable), whose
! 1330: coefficients are themselves polynomials, arbitrary but for the fact that they
! 1331: do not involve the main variable. All computations are then just done
! 1332: formally on the coefficients as if the polynomial was univariate.
! 1333:
! 1334: This is not symmetrical. So if I enter \kbd{x + y} in a clean session,
! 1335: what happens ? This is understood as
! 1336: $$ x^1 + y*x^0 \in (\Z[y])[x] $$
! 1337: but how can GP decide that $x$ is ``more important'' than $y$ ? Why not
! 1338: $y^1 + x*y^0$, which is the same mathematical entity after all ?
! 1339:
! 1340: The answer is that variables are ordered implicitly by the GP interpreter:
! 1341: when a new identifier (e.g~$x$, or $y$ as above) is input, the corresponding
! 1342: variable is registered as having a strictly lower priority than any variable in
! 1343: use at this point\footnote{*}{This is not strictly true: if an
! 1344: identifier is interpreted as a user function, no variable is registered. Also,
! 1345: the variable $x$ is predefined and always has the highest possible priority.}
! 1346: %
! 1347: . To see the ordering used by GP at any given time, type $\tet{reorder}()$.
! 1348:
! 1349: Given such an ordering, multivariate polynomials are stored so that the
! 1350: variable with the highest priority is the main variable. And so on,
! 1351: recursively, until all variables are exhausted. A different storage pattern
! 1352: (which could only be obtained via library mode) would produce an illegal
! 1353: object, and eventually a disaster.
! 1354:
! 1355: In any case, if you are working with expressions involving several variables
! 1356: and want to have them ordered in a specific manner in the internal
! 1357: representation just described, the simplest is just to write down the
! 1358: variables one after the other under GP before starting any real computations.
! 1359: You could also define variables from your GPRC to have a consistant
! 1360: ordering of common variable names in all your GP sessions, e.g read in a file
! 1361: \kbd{variables.gp} containing
! 1362: \bprog
! 1363: x;y;z;t;a;b;c;d
! 1364: @eprog
! 1365:
! 1366: If you already have started working and want to change the names of the
! 1367: variables in an object, use the function \tet{changevar}. If you only want to
! 1368: have them ordered when the result is printed, you can also use the function
! 1369: \tet{reorder}, but this won't change anything to the internal representation,
! 1370: and is not recommended.
! 1371:
! 1372: \misctitle{Important note:} PARI allows Euclidean division of multivariate
! 1373: polynomials, but assumes that the computation takes place in the fraction
! 1374: field of the coefficient ring (if it is not an integral domain, the result
! 1375: will a priori not make sense). This can be very tricky; for instance
! 1376: assume $x$ has highest priority (which is always the case), then
! 1377: $y$:
! 1378: \bprog
! 1379: ? x % y
! 1380: %1 = 0
! 1381: ? y % x
! 1382: %2 = y \\@com these two take place in $\Q(y)[x]$
! 1383: ? x * Mod(1,y)
! 1384: %3 = Mod(1, y)*x \\@com in $(\Q(y)/y\Q(y))[x] \sim \Q[x]$
! 1385: ? Mod(x,y)
! 1386: %4 = 0
! 1387: @eprog
! 1388: \noindent In the last exemple, the division by $y$ takes place in
! 1389: $\Q(y)[x]$,
! 1390: hence the \kbd{Mod} object is a coset in $(\Q(y)[x]) / (y\Q(y)[x])$, which
! 1391: is the null ring since $y$ is invertible! So be very wary of variable
! 1392: ordering when your computations involve implicit divisions and many
! 1393: variables. This also affects functions like \tet{numerator}/\tet{denominator}
! 1394: or \tet{content}:
! 1395: \bprog
! 1396: ? denominator(x / y)
! 1397: %1 = 1
! 1398: ? denominator(y / x)
! 1399: %2 = x
! 1400: ? content(x / y)
! 1401: %3 = 1/y
! 1402: ? content(y / x)
! 1403: %4 = 1
! 1404: ? content(2 / x)
! 1405: %5 = 2
! 1406: @eprog
! 1407: \noindent Can you see why ? Hint: $x/y = (1/y) * x$ is in $\Q(y)[x]$ and
! 1408: denominator is taken with respect to $\Q(y)(x)$; $y/x = (y*x^0) / x$ is in
! 1409: $\Q(y)(x)$ so $y$ is invertible in the coefficient ring. On the other hand,
! 1410: $2/x$ involves a single variable and the coefficient ring is simply $\Z$.
! 1411:
! 1412: These problems arise because the variable ordering defines an {\it
! 1413: implicit} variable with respect to which division takes place. This is
! 1414: the price to pay to allow \kbd{\%} and \kbd{/} operators on polynomials
! 1415: instead of requiring a more cumbersome \kbd{divrem($x$, $y$, \var{var})}
! 1416: (which also exists). Unfortunately, in some functions like \tet{content} and
! 1417: \tet{denominator}, there is no way to set explicitly a main variable like in
! 1418: \tet{divrem} and remove the dependance on implicit orderings. This will
! 1419: hopefully be corrected in future versions.
1.1 noro 1420:
1421: \subsec{Expressions and expression sequences}.
1422:
1423: An \idx{expression}\sidx{expression sequence} is formed by combining the
1424: GP operators, functions (including user-defined functions, see below) and
1425: control statements. It may be preceded by an assignment statement '$=$'
1426: into a variable. It always has a value, which can be any PARI object.
1427:
1428: Several expressions can be combined on a single line by separating them
1429: with semicolons (';') and also with colons (':') for those who are used to
1430: BASIC. Such an expression sequence will be called simply a \var{seq}. A
1431: \var{seq} also has a value, which is the value of the last non-empty
1432: expression in the sequence. Under GP, the value of the \var{seq}, and only
1433: this last value, is always put on the stack (i.e. it will become the next
1434: object $\%n$). The values of the other expressions in the \var{seq} are
1435: discarded after the execution of the \var{seq} is complete, except of
1436: course if they were assigned into variables. In addition, the value of
1437: the \var{seq} (or of course of an expression if there is only one) is
1438: printed if the line does not end with a semicolon (';').
1439:
1440: \subsec{User defined functions}.\sidx{user defined functions}
1441: \label{se:user_defined}
1442:
1443: It is very easy to define a new function under GP, which can then be used
1444: like any other function. The syntax is as follows:
1445:
1446: \kbd{name(}\var{list of formal variables}\kbd{) = %
1447: local(}\var{list of local variables}\kbd{);} \var{seq}
1448:
1449: \noindent which looks better written on consecutive lines:
1450: \bprogpart
1451: name($x_0$, $x_1$, @dots) =
1452: {
1453: local($t_0$, $t_1$, @dots);
1454: local(@dots);
1455:
1456: @dots
1457: }
1458: @eprog
1459: \noindent (note that the first newline is disregarded due to the preceding
1460: \kbd{=} sign, and the others because of the enclosing braces). Both lists
1461: of variables are comma-separated and allowed to be empty. The \tet{local}
1462: statements can be omitted; as usual \var{seq} is any expression sequence.
1463:
1464: \kbd{name} is the name given to the function and is subject to the same
1465: restrictions as variable names. In addition, variable names are not valid
1466: function names, you have to \kbd{kill} the variable first (the converse is
1467: true: function names can't be used as variables, see \secref{se:kill}).
1468: Previously used function names can be recycled: you are just redefining the
1469: function (the previous definition is lost of course).
1470:
1471: \kbd{list of formal variables} is the list of variables corresponding to
1472: those which you will actually use when calling your function. The number of
1473: actual parameters supplied when calling the function has to be less than the
1474: number of formal variables.
1475:
1476: Uninitialized formal variables will be given a default value. An equal
1477: (\kbd{=}) sign following a variable name in the function definition,
1478: followed by any expression, gives the variable a default value. The
1479: said expression gets evaluated the moment the function is called, hence may
1480: involve the function parameters. A variable for which you supply no default
1481: value will be initialized to zero.
1482:
1483: \kbd{list of local variables} is the list of the additional local variables
1484: which are used in the function body. Note that if you omit some or all of
1485: these local variable declarations, the non-declared variables will become
1486: global, hence known outside of the function, and this may have undesirable
1487: side-effects. On the other hand, in some cases it may also be what you want.
1488: Local variables can be given a default value as the formal variables.
1489:
1490: \misctitle{Example:} For instance
1491: \bprog
1492: foo(x=1, y=2, z=3) = print(x ":" y ":" z)
1493: @eprog
1494: \noindent defines a function which prints its arguments (at most three of
1495: them), separated by colons. This then follows the rules of default
1496: arguments generation as explained at the beginning of
1497: \secref{se:functions}.
1498: \bprog
1499: ? foo(6,7)
1500: 6:7:3
1501: ? foo(,5)
1502: 1:5:3
1503: ? foo
1504: 1:2:3
1505: @eprog
1506:
1507: Once the function is defined using the above syntax, you can use it like
1508: any other function. In addition, you can also recall its definition exactly
1509: as you do for predefined functions, that is by writing \kbd{?\var{name}}.
1510: This will print the list of arguments, as well as their default values,
1511: the text of \var{seq}, and a short help text if one was provided using
1512: the \kbd{addhelp} function (see \secref{se:addhelp}). One small difference
1513: to predefined functions is that you can never redefine the built-in
1514: functions, while you can redefine a user-defined function as many times
1515: as you want.
1516:
1517: Typing \b{u} will output the list of user-defined functions.
1518:
1519: An amusing example of a user-defined function is the following. It is
1520: intended to illustrate both the use of user-defined functions and the power
1521: of the \kbd{sumalt} function. Although the \idx{Riemann zeta-function} is
1522: included in the standard functions, let us assume that this is not the case
1523: (or that we want another implementation). One way to define it, which is
1524: probably the simplest (but certainly not the most efficient), is as
1525: follows:\sidx{zeta function}
1526: \bprog
1527: zet(s) =
1528: {
1529: local(n); /* not needed, and possibly confusing (see below) */
1530: sumalt(n=1, (-1)^(n-1)*n^(-s)) / (1 - 2^(1-s))
1531: }
1532: @eprog
1533:
1534: \noindent This gives reasonably good accuracy and speed as long as you are
1535: not too far from the domain of convergence. Try it for $s$ integral between
1536: $-5$ and $5$, say, or for $s=0.5+i*t$ where $t=14.134\dots$
1537:
1538: The iterative constructs which use a variable name (\kbd{for$xxx$},
1539: \kbd{prod$xxx$}, \kbd{sum$xxx$}, \kbd{vector}, \kbd{matrix}, \kbd{plot},
1540: etc.) also consider the given variable to be local to the construct. A value
1541: is pushed on entry and pulled on exit. So, it is not necessary for a function
1542: using such a construct to declare the variable as a dummy formal parameter.
1543:
1544: In particular, since loop variables are not visible outside their loops,
1545: the variable \kbd{n} need not be declared in the protoype of our \kbd{zet}
1546: function above.
1547: \bprog
1548: zet(s) = sumalt(n=1, (-1)^(n-1)*n^(-s)) / (1 - 2^(1-s))
1549: @eprog
1550:
1551: \noindent would be a perfectly sensible (and in fact better) definition.
1552: Since local/global scope is a very tricky point, here's one more example.
1553: What's wrong with the following definition?
1554: \bprog
1555: ? first_prime_div(x) =
1556: {
1557: local(p);
1558: forprime(p=2, x, if (x%p == 0, break));
1559: p
1560: }
1561: ? first_prime_div(10)
1562: %1 = 0
1563: @eprog
1564:
1565: \misctitle{Answer:} the index $p$ in the \kbd{forprime} loop is local to
1566: the loop and is not visible to the outside world. Hence, it doesn't survive
1567: the \kbd{break} statement. More precisely, at this point the loop index is
1568: restored to its preceding value, which is 0 (local variables are
1569: initialized to 0 by default). To sum up, the routine returns the $p$
1570: declared local to it, not the one which was local to \kbd{forprime} and ran
1571: through consecutive prime numbers. Here's a corrected version:
1572: \bprog
1573: ? first_prime_div(x) = forprime(p=2, x, if (x%p == 0, return(p)))
1574: @eprog
1575:
1576: Again, it is strongly recommended to declare all other local variables that
1577: are used inside a function: if a function accesses a variable which is not
1578: one of its formal parameters, the value used will be the one which happens to
1579: be on top of the stack at the time of the call. This could be a ``global''
1580: value, or a local value belonging to any function higher in the call chain.
1581: So, be warned.
1582:
1583: Recursive functions\sidx{recursion} can easily be written as long as one
1584: pays proper attention to variable scope. Here's a last example, used to
1585: retrieve the coefficient array of a multivariate polynomial (a non-trivial
1586: task due to PARI's unsophisticated representation for those objects):
1587: \sidx{multivariate polynomial}
1588: \bprog
1589: coeffs(P, nbvar) =
1590: {
1591: local(v);
1592:
1593: if (type(P) != "t_POL",
1594: for (i=0, nbvar-1, P = [P]);
1595: return (P)
1596: );
1597: v = vector(poldegree(P)+1, i, polcoeff(P,i-1));
1598: vector(length(v), i, coeffs(v[i], nbvar-1))
1599: }
1600: @eprog
1601:
1602: \noindent If $P$ is a polynomial in $k$ variables, show that after the
1603: assignment {\tt v = coeffs(P,k)}, the coefficient of $x_1^{n_1}\dots
1604: x_k^{n_k}$ in P is given by {\tt v[$n_1$+1][\dots][$n_k$+1]}. What would
1605: happen if the declaration {\tt local(v)} had been omitted ?
1606:
1607: The operating system will automatically limit the \idx{recursion depth}:
1608: \bprog
1609: ? dive(n) = if (n, dive(n-1))
1610: ? dive(5000);
1611: *** deep recursion: if(n,dive(n-1))
1612: ^---------------
1613: @eprog
1614: There's no way to increase the recursion limit (which may be different on
1615: your machine) from within, since it would simply crash the GP process. To
1616: increase it before launching GP, you can use \tet{ulimit} or \tet{limit},
1617: depending on your shell, to raise the process available stack space
1618: (increase \tet{stacksize}).
1619:
1620: \misctitle{Function which take functions as parameters ?} This is easy
1621: in GP using the following trick (neat example due to Bill Daly):
1622:
1623: \bprog
1624: calc(f, x) = eval(Str( f "(x)"))
1625: @eprog
1626:
1627: \noindent If you call this with \kbd{calc("sin", 1)}, it will
1628: return $\sin(1)$ (evaluated!).
1629:
1630: \misctitle{Restrictions on variable use:} it is not allowed to use the same
1631: variable name for different parameters of your function. Or to use a given
1632: variable both as a formal parameter and a local variable in a given function.
1633: Hence
1634: \bprog
1635: ? f(x,x) = 1
1636: *** user function f: variable x declared twice.
1637: @eprog
1638:
1639: Also, the statement \sidx{global}\kbd{global(x, y, z, t)} (see
1640: \secref{se:global}) declares the corresponding variables to be global. It
1641: is then forbidden to use them as formal parameters or loop indexes as
1642: described above, since the parameter would ``shadow'' the variable.
1643:
1644: \misctitle{Implementation note.} For the curious reader, here is how these
1645: stacks are handled: a \idx{hashing function} is computed from the identifier,
1646: and used as an index in \tet{hashtable}, a table of pointers. Each of
1647: these pointers begins a linked list of structures (type \tet{entree}).
1648: The linked list is searched linearly for the identifier (each list will
1649: typically have less than 7 components or so). When the correct \kbd{entree}
1650: is found, it points to the top of the stack of values for that identifier if
1651: it is a variable, to the function itself if it is a predefined function, and
1652: to a copy of the text of the function if it is a user-defined function. When
1653: an error occurs, all of this maze (rather a tree, in fact) is searched and
1654: (hopefully) restored to the state preceding the last call of the main
1655: evaluator.
1656:
1657: \misctitle{Note:} The above syntax (using the \tet{local} keyword) was
1658: introduced in version 2.0.13. The old syntax
1659:
1660: \kbd{name(}\var{list of true formal variables, list of local variables}%
1661: \kbd{) = }{\var{seq}}
1662:
1663: \noindent is still recognized but is deprecated since genuine arguments and
1664: local variables become undistinguishable.
1665:
1666: \subsec{Member functions}.\sidx{member functions}
1.2 ! noro 1667: \label{se:member}
1.1 noro 1668:
1669: Member functions use the `dot' notation to retrieve information from
1670: complicated structures (by default: types \tet{ell}, \tet{nf}, \tet{bnf},
1671: \tet{bnr} and prime ideals). The syntax \kbd{structure.member} is taken to
1672: mean: retrieve \kbd{member} from \kbd{structure}, e.g.~\kbd{ell.j} returns
1673: the $j$-invariant of the elliptic curve \kbd{ell} (or outputs an error
1674: message if \kbd{ell} doesn't have the correct type).
1675:
1676: To define your own member functions, use the syntax \var{structure.member =
1677: function text}, where \var{function text} is written as the \var{seq} in a
1678: standard user function (without local variables), whose only argument would
1679: be \kbd{structure}. For instance, the current implementation of the
1680: \kbd{ell} type is simply an horizontal vector, the $j$-invariant being the
1681: thirteenth component. This could be implemented as
1682:
1683: \bprog
1684: x.j =
1685: {
1686: if (type(x) != "t_VEC" || length(x) < 14,
1687: error("this is not a proper elliptic curve: " x)
1688: );
1689: x[13]
1690: }
1691: @eprog
1692:
1693: You can redefine one of your own member functions simply by typing a new
1694: definition for it. On the other hand, as a safety measure, you can't redefine
1695: the built-in member functions, so typing the above text would in fact produce
1696: an error (you'd have to call it e.g.~\kbd{x.j2} in order for GP to accept it).
1697:
1698: \misctitle{Warning:} contrary to user functions arguments, the structure
1699: accessed by a member function is \var{not} copied before being used.
1700: Any modification to the structure's components will be permanent.
1701:
1702: \misctitle{Note:} Member functions were not meant to be too complicated or to
1703: depend on any data that wouldn't be global. Hence they do no have parameters
1704: (besides the implicit \kbd{structure}) or local variables. Of course, if you
1705: need some preprocessing work in there, there's nothing to prevent you from
1706: calling your own functions (using freely their local variables) from a member
1707: function. For instance, one could implement (a dreadful idea as far as
1708: efficiency goes):
1709:
1710: \bprog
1711: correct_ell_if_needed(x) =
1712: {
1713: local(tmp);
1714: if (type(x) != "t_VEC", tmp = ellinit(x))
1715: \\ @com some further checks
1716: tmp
1717: }
1718: x.j = correct_ell_if_needed(x)[13];
1719: @eprog
1720: Typing \b{um} will output the list of user-defined member functions.
1721:
1722: \subsec{Strings and Keywords}\sidx{string}\sidx{keyword}
1723: \label{se:strings}
1724:
1725: \noindent
1726: GP variables can now hold values of type character string (internal type
1727: \typ{STR}). This section describes how they are actually used, as well as
1728: some convenient tricks (automatic concatenation and expansion, keywords)
1729: valid in string context.
1730:
1731: As explained above, the general way to input a string is to enclose
1732: characters between quotes~\kbd{"}. This is the only input construct where
1733: whitespace characters are significant: the string will contain the exact
1734: number of spaces you typed in. Besides, you can ``escape'' characters by
1735: putting a \kbd{\bs} just before them; the translation is as follows
1736: \bprog
1737: \e: <Escape>
1738: \n: <Newline>
1739: \t: <Tab>
1740: @eprog
1741: For any other character $x$, \b{$x$} is expanded to $x$. In particular, the
1742: only way to put a \kbd{"} into a string is to escape it. Thus, for
1743: instance, \kbd{"\bs"a\bs""} would produce the string whose content is
1744: ``a''. This is definitely \var{not} the same thing as typing \kbd{"a"},
1745: whose content is merely the one-letter string a.
1746:
1747: You can concatenate two strings using the \tet{concat} function. If either
1748: argument is a string, the other is automatically converted to a string if
1749: necessary (it will be evaluated first).
1750:
1751: \bprog
1752: ? concat("ex", 1+1)
1753: %1 = "ex2"
1754: ? a = 2; b = "ex"; concat(b, a)
1755: %2 = "ex2"
1756: ? concat(a, b)
1757: %3 = "2ex"
1758: @eprog
1759:
1760: Some functions expect strings for some of their arguments: \tet{print} would
1761: be an obvious example, \tet{Str} is a less obvious but very useful one (see
1762: the end of this section for a complete list). While typing in such an
1763: argument, you will be said to be in \tev{string context}. The rest of
1764: this section is devoted to special syntactical tricks which can be used with
1765: such arguments (and only here; you will get an error message if you try these
1766: outside of string context):
1767:
1768: $\bullet$ Writing two strings alongside one another will just concatenate
1769: them, producing a longer string. Thus it is equivalent to type in
1770: \kbd{"a " "b"} or \kbd{"a b"}. A little tricky point in the first expression:
1771: the first whitespace is enclosed between quotes, and so is part of a string;
1772: while the second (before the \kbd{"b"}) is completely optional and GP
1773: actually suppresses it, as it would with any number of whitespace characters
1774: at this point (i.e.~outside of any string).
1775:
1.2 ! noro 1776: $\bullet$ If you insert any expression when GP expects a string, it gets
! 1777: ``expanded'': it is evaluated as a standard GP expression, and the final
! 1778: result (as would have been printed if you had typed it by itself) is then
! 1779: converted to a string, as if you had typed it directly. For instance \kbd{"a"
! 1780: 1+1 "b"} is equivalent to \kbd{"a2b"}: three strings get created, the middle
! 1781: one being the expansion of \kbd{1+1}, and these are then concatenated
! 1782: according to the rule described above. Another tricky point here: assume you
! 1783: did not assign a value to \kbd{aaa} in a GP expression before. Then typing
! 1784: \kbd{aaa} by itself in a string context will actually produce the correct
! 1785: output (i.e.~the string whose content is aaa), but in a fortuitous way. This
! 1786: \kbd{aaa} gets expanded to the monomial of degree one in the variable
! 1787: \kbd{aaa}, which is of course printed as \kbd{aaa}, and thus will expand to
! 1788: the three letters you were expecting.
! 1789:
! 1790: \misctitle{Warning:} expression involving strings are not handled in a
! 1791: special way; even in string context, the largest possible expression is
! 1792: evaluated, hence \kbd{print("a"[1])} is incorrect since \kbd{"a"} is not an
! 1793: object whose first component can be extracted. On the other hand
! 1794: \kbd{print("a", [1])} is correct (two distinct argument, each converted to a
! 1795: string), and so is \kbd{print("a" 1)} (since \kbd{"a"1} is not a valid
! 1796: expression, only \kbd{"a"} gets expanded, then \kbd{1}, and the result is
! 1797: concatenated as explained above).
1.1 noro 1798:
1799: $\bullet$ Since there are cases where expansion is not really desirable, we
1800: now distinguish between ``Keywords'' and ``Strings''. String is what has been
1801: described so far. Keywords are special relatives of Strings which are
1802: automatically assumed to be quoted, whether you actually type in the quotes
1803: or not. Thus expansion is never performed on them. They get concatenated,
1804: though. The analyzer supplies automatically the quotes you have ``forgotten''
1805: and treats Keywords just as normal strings otherwise. For instance, if you
1806: type \kbd{"a"b+b} in Keyword context, you will get the string whose contents
1807: are ab+b. In String context, on the other hand, you would get a2\kbd{*}b.
1808:
1809: All GP functions have prototypes (described in Chapter~3 below) which
1810: specify the types of arguments they expect: either generic PARI objects
1811: (GEN), or strings, or keywords, or unevaluated expression sequences. In the
1812: keyword case, only a very small set of words will actually be meaningful
1813: (the \kbd{default} function is a prominent example).
1814:
1815: Let's now try some not-so-stupid exercises to get the hang of it. Try to
1816: guess the results of the following commands without actually typing them,
1817: assuming that the \kbd{print} command evaluates and prints its (string)
1818: arguments in left-to-right order, ending with a newline (and returns 0
1819: as an unprinted result):
1820:
1821: \bprog
1822: print()
1823: print(1+3"a,3" ,4)
1824: print(a=3, (1 + ((a-3)==print())) (a = (a == 5\/2)))
1825: @eprog
1826:
1827: \noindent Here is a less artificial example, used to create generic
1828: matrices\sidx{generic matrix}\sidx{matrix}:
1829:
1830: \bprog
1831: ? genmat(u,v,s="x") = matrix(u,v,i,j, eval(Str(s "" i "" j)))
1832: ? genmat(2,3) + genmat(2,3,"m")
1833: %1 =
1834: [x11 + m11 x12 + m12 x13 + m13]
1835: [x21 + m21 x22 + m22 x23 + m23]
1836: @eprog
1837:
1838: \noindent
1839: Note that the argument of \kbd{Str} is evaluated in string context, and
1840: really consists of 5 pieces (exercise: why are the empty strings
1841: necessary?). This part could also have been written as
1842: \kbd{concat(concat(Str(s), i), j)} (but \var{not} as \kbd{concat(Str(s),
1843: concat(i,j))}!). More simply, we could have written \kbd{concat([Str(s),
1844: i,j])}, or even \kbd{concat([s,i,j])}, silently assuming that \kbd{s} will
1845: indeed be a string. In practice \kbd{Str} is much more efficient, if
1846: slightly more cryptic.
1847:
1848: \noindent And here's a final one: the function \kbd{hist} returns all history
1849: entries from \kbd{\%$a$} to \kbd{\%$b$} neatly packed into a single vector
1850: \bprog
1851: ? hist(a,b) = vector(b-a+1, i, eval(Str("%" a-1+i)))
1852: @eprog
1853:
1854: \noindent The arguments of the following functions are processed in string
1855: context:
1856:
1857: \settabs\+\indent&\cr
1858: \+&\tet{Str}\cr
1859: \+&\tet{addhelp} (second argument)\cr
1860: \+&\tet{default} (second argument)\cr
1861: \+&\tet{error}\cr
1862: \+&\tet{extern}\cr
1863: \+&\tet{plotstring} (second argument)\cr
1864: \+&\tet{plotterm} (first argument)\cr
1865: \+&\tet{read}\cr
1866: \+&\tet{system}\cr
1867: \+&all the \tet{print}\var{xxx} functions\cr
1868: \+&all the \tet{write}\var{xxx} functions\cr
1869:
1870: \noindent The arguments of the following functions are processed as keywords:
1871:
1872: \+&\tet{alias}\cr
1873: \+&\tet{default} (first argument)\cr
1874: \+&\tet{install} (all arguments but the last)\cr
1875: \+&\tet{trap} (first argument)\cr
1876: \+&\tet{type} (second argument)\cr
1877: \+&\tet{whatnow}\cr
1878:
1879: \section{Interfacing GP with other languages}
1880: \noindent
1881: The PARI library was meant to be interfaced with C programs. This specific
1882: use will be dealt with extensively in Chapter~4. GP itself provides a
1883: convenient, if simple-minded, interpreter, which enables you to execute
1884: rather intricate scripts (see \secref{se:programming}).
1885:
1886: Scripts, when properly written, tend to be shorter and much clearer than C
1887: programs, and are certainly easier to write, maintain or debug. You don't
1888: need to deal with memory management, garbage collection, pointers,
1889: declarations, and so on. Because of their intrinsic simplicity, they are more
1890: robust as well. They are unfortunately somewhat slower. Thus their use will
1891: remain complementary: it is suggested that you test and debug your algorithms
1892: using scripts, before actually coding them in C for the sake of speed.
1893:
1894: \unix{Note that the \kbd{install} command enables you to concentrate on
1895: critical parts of your programs only (which can of course be written with the
1896: help of other mathematical libraries than PARI!), and to easily and
1897: efficiently import foreign functions for use under GP
1898: (see~\secref{se:install}).}
1899:
1900: We are aware of three PARI-related public domain libraries. {\it We neither
1901: endorse nor support any of them}. You might want to give them a try if you
1902: are familiar with the languages they are based on. First, there are
1903: \tet{PariPerl}%
1904: \footnote{*}{
1905: see \kbd{%
1906: http://nswt.tuwien.ac.at:8000/htdocs/internet/unix/perl/math-pari.html}},
1907: %
1908: written by Ilya Zakharevich (\kbd{ilya@math.ohio-state.edu}),
1909: and \tet{PariPython}%
1910: \footnote{**}{
1911: see \kbd{http://www.math.jussieu.fr/\til{}fermigie/PariPython/readme.html}},
1912: %
1913: by St\'efane Fermigier (\kbd{fermigie@math.jussieu.fr}). Finaly, Michael Stoll
1914: (\kbd{Michael\_Stoll@math.uni-bonn.de}) has integrated PARI into \tet{CLISP},
1915: which is a Common Lisp implementation by Bruno Haible, Marcus Daniels and
1916: others. These provide interfaces to GP functions for use in \kbd{perl},
1917: \kbd{python} or \kbd{Lisp} programs.\sidx{Perl}\sidx{Python}\sidx{Lisp}
1918: To our knowledge, only the \kbd{python} and \kbd{perl} interfaces have been
1919: upgraded to version 2.0 of PARI, the \kbd{CLISP} one being still based on
1920: version 1.39.$xx$.
1921:
1.2 ! noro 1922: \section{The preferences file}\sidx{startup}\sidx{preferences file}
1.1 noro 1923: \label{se:gprc}
1924:
1.2 ! noro 1925: This file, called \tet{gprc} in the sequel, is used to modify or extend GP
! 1926: default behaviour, in all GP sessions: e.g customize \kbd{default} values or
! 1927: load common user functions and aliases. GP opens the \kbd{gprc} file and
! 1928: processes the commands in there, \var{before} doing anything else,
! 1929: e.g.~creating the PARI stack. If the file does not exist or cannot be read,
! 1930: GP will proceed to the initialization phase at once, eventually emitting a
! 1931: prompt. If any explicit command line switches are given, they override the
! 1932: values read from the preferences file.
! 1933:
! 1934: \subsec{Where is it?}
1.1 noro 1935: When GP is started, it looks for a customization file, or \kbd{gprc} in the
1.2 ! noro 1936: following places (in this order, only the first one found will be loaded):
1.1 noro 1937:
1938: \noindent$\bullet$ On the Macintosh (only), GP looks in the directory which
1939: contains the GP executable itself for a file called \kbd{gprc}. No other places
1940: are examined.
1941:
1942: \noindent$\bullet$ If the operating system supports environment variables
1943: (essentially, anything but MacOS), GP checks whether the environment variable
1944: \tet{GPRC} is set. Under DOS, you can set it in \kbd{AUTOEXEC.BAT}.
1945: On Unix, this can be done with something like:
1946: \smallskip
1947:
1948: \settabs\+\indent&\kbd{GPRC=/my/dir/anyname; export GPRC}\quad&\cr
1949:
1950: \+&\kbd{GPRC=/my/dir/anyname; export GPRC}\quad&in \kbd{sh} syntax
1951: (for instance in your \kbd{.profile}),\cr
1952:
1953: \+&\kbd{setenv GPRC /my/dir/anyname} &in \kbd{csh} syntax
1954: (in your \kbd{.login} or \kbd{.cshrc} file).\cr
1955:
1956: \noindent If so, the file named by \kbd{\$GPRC} is the \kbd{gprc}.
1957:
1958: \noindent$\bullet$ If \kbd{GPRC} is not set, and if the environment variable
1959: \kbd{HOME} is defined, GP then tries
1960:
1961: \kbd{\$HOME/.gprc} on a Unix system
1962:
1963: \kbd{\$HOME\bs\_$\,$gprc} on a DOS, OS/2, or Windows system.
1964:
1965: \noindent$\bullet$ If \kbd{HOME} also leaves us clueless, we try
1966:
1967: \strut\kbd{\til/.gprc} on a Unix system (where as usual \kbd{\til} stands for
1968: your home directory), or
1969:
1970: \kbd{\b{\_}$\,$gprc} on a DOS, OS/2, or Windows system.
1971:
1972: \noindent$\bullet$ Finally, if no gprc was found among the user files
1973: mentioned above we look for \kbd{/etc/gprc} (\kbd{\bs etc\bs gprc})
1.2 ! noro 1974: for a system-wide gprc file (you will need root privileges to set up such a
1.1 noro 1975: file yourself).
1976:
1977: Note that on Unix systems, the \kbd{gprc}'s default name starts with a '.' and
1978: thus is hidden to regular \kbd{ls} commands; you need to type \kbd{ls -a} to
1.2 ! noro 1979: list it.
! 1980:
! 1981: \subsec{Syntax}
1.1 noro 1982:
1.2 ! noro 1983: The syntax in the \kbd{gprc} file (and valid in this file only) is
! 1984: simple-minded, but should be sufficient for most purposes. The file is read
! 1985: line by line; as usual, white space is ignored unless surrounded by quotes
! 1986: and the standard multiline constructions using braces, \kbd{\bs}, or \kbd{=}
! 1987: are available (multiline comments between \kbd{/*~\dots~*/} are also
! 1988: recognized).
! 1989:
! 1990: \subsubsec{Preprocessor:}
! 1991: Two types of lines are first dealt with by a preprocessor:
1.1 noro 1992:
1993: $\bullet$ comments are removed. This applies to all text surrounded by
1.2 ! noro 1994: \kbd{/*~\dots~*/} as well as to everything following \kbd{\bs\bs} on a given
1.1 noro 1995: line.
1996:
1.2 ! noro 1997: $\bullet$ lines starting with \kbd{\#if} \var{boolean} are treated as
! 1998: comments if \var{boolean} evaluates to \kbd{false}, and read normally
! 1999: otherwise. The condition can be negated using either \kbd{\#if not} (or
! 2000: \kbd{\#if !}). If the rest of the current line is empty, the test applies to
! 2001: the next line (same behaviour as \kbd{=} under GP). Only three tests can be
! 2002: performed:
1.1 noro 2003:
1.2 ! noro 2004: \kbd{EMACS}: \kbd{true} if GP is running in an Emacs or TeXmacs shell (see
1.1 noro 2005: \secref{se:emacs}).
2006:
1.2 ! noro 2007: \kbd{READL}: \kbd{true} if GP is compiled with \kbd{readline} support (see
1.1 noro 2008: \secref{se:readline}).
2009:
1.2 ! noro 2010: \kbd{VERSION} \var{op} \var{number}: where \var{op} is in the set
! 2011: $\{ \kbd{>}, \kbd{<}, \kbd{<=}, \kbd{>=} \}$, and \var{number} is a PARI
! 2012: version number of the form \var{Major}.\var{Minor}.\var{patch}, where the
! 2013: last two components can be omitted (i.e.~$1$ is understood as versio $1.0.0$).
! 2014: This is \kbd{true} if GP's version number satisfies the required
! 2015: inequality.
! 2016:
! 2017: \subsubsec{Commands:}
! 2018: After the preprocessing the remaining lines are executed as
! 2019: sequence of expressions (as usual, separated by \kbd{;} if necessary). Only
! 2020: two kinds of expressions are recognized:
! 2021:
! 2022: $\bullet$ \var{default} \kbd{=} \var{value}, where \var{default} is one of
! 2023: the available defaults (see \secref{se:defaults}), which will be set to
! 2024: \var{value} on actual startup. Don't forget the quotes around strings
! 2025: (e.g.~for \kbd{prompt} or \kbd{help}).
! 2026:
! 2027: $\bullet$ \kbd{read "\var{some\_GP\_file}"} where \kbd{\var{some\_GP\_file}}
! 2028: is a regular GP script this time, which will be read just before GP prompts
! 2029: you for commands, but after initializing the defaults. In particular, file
! 2030: input is delayed until the \kbd{gprc} has been fully loaded. This is the
! 2031: right place to input files containing \kbd{alias} commands, or your favorite
! 2032: macros.
! 2033:
! 2034: \noindent For instance you could set your prompt in the following portable way:
1.1 noro 2035: \bprog
2036: \\ self modifying prompt looking like @com\hbox{\rm(18:03) \key{gp}\kbd{ >}}
2037: prompt = "(\%R) \e[1mgp\e[m > "
2038:
2039: \\ readline wants non-printing characters to be braced between ^A/^B pairs
1.2 ! noro 2040: #if READL prompt = "(%R) ^A\e[1m^Bgp^A\e[m^B > "
1.1 noro 2041:
2042: \\ escape sequences not supported under emacs
1.2 ! noro 2043: #if EMACS prompt = "(%R) gp > "
1.1 noro 2044: @eprog
2045:
1.2 ! noro 2046: \noindent Note that any of the last two lines could be broken in the
! 2047: following way
! 2048: \bprog
! 2049: #if EMACS
! 2050: prompt = "(%R) gp > "
! 2051: @eprog
! 2052: \noindent since the preprocessor directive applies to the next line if the
! 2053: current one is empty.
1.1 noro 2054:
1.2 ! noro 2055: A sample \kbd{gprc} file called \kbd{misc/gprc.dft} is provided in the
! 2056: standard distribution. It is a good idea to have a look at it and customize
! 2057: it to your needs. Since this file does not use multiline constructs, here is
! 2058: one (note the terminating \kbd{;} to separate the expressions):
! 2059: \bprog
! 2060: #if VERSION > 2.2.3
! 2061: {
! 2062: read "my_scripts"; \\ syntax errors in older versions
! 2063: new_galois_format = 1; \\ default introduced in 2.2.4
! 2064: }
! 2065: #if ! EMACS
! 2066: {
! 2067: colors = "9, 5, no, no, 4, 1, 2";
! 2068: help = "gphelp -detex -ch 4 -cb 0 -cu 2";
! 2069: }
! 2070: @eprog
1.1 noro 2071:
2072: \section{Using GP under GNU Emacs}
2073: \label{se:emacs}
2074:
2075: Thanks to the initial help of Annette Hoffman from the University of
2076: Saarbr\"ucken, and David Carlisle from the University of Manchester, it is
2077: possible to use GP as a subprocess of GNU \idx{Emacs}. (Of course, you need
2078: GNU Emacs to be installed on your machine!). To use this, you should
2079: include in your \kbd{.emacs} file the following lines:
2080: \bprog
2081: (defconst pari-el-file "@miscdir/emacs/pari")
2082: (autoload 'gp-mode pari-el-file nil t)
2083: (autoload 'gp-script-mode pari-el-file nil t)
2084: (autoload 'gp pari-el-file nil t)
2085: (autoload 'gpman pari-el-file nil t)
2086: (setq auto-mode-alist
2087: (cons '("\\.gp$" . gp-script-mode) auto-mode-alist))
2088: @eprog
2089:
2090: \noindent where \kbd{\miscdir/emacs/pari.el} is the name of the file that
2091: will have to be loaded by GNU Emacs (if you have changed the name, or if
2092: you have the file in a different directory, you must of course supply the
2093: correct name). This file is included in the PARI distribution and probably
2094: has been installed at the same time as GP.
2095:
2096: Once this is done, under GNU Emacs if you type \kbd{M-x gp} (where as usual
2097: \kbd{M} is the \kbd{Meta} key, i.e.~Escape, or on SUN keyboards, the Left
2098: key), a special shell will be started, which in particular launches GP with
2099: the default stack size, prime limit and input buffer size. If you type
2100: instead \kbd{C-u M-x gp}, you will be asked for the name of the GP
2101: executable, the stack size and the prime limit before the execution of GP
2102: begins. If for any of these you simply type return, the default value will
2103: be used. On UNIX machines it will be the place you told \kbd{Configure}
2104: (usually \kbd{/usr/local/bin/gp}) for the executable, \kbd{10M} for the
2105: stack and \kbd{500k} for the prime limit.
2106:
2107: \smallskip
2108: You can then work as usual under GP, but with two notable advantages (which
2109: don't really matter if readline is available to you, see below). First and
2110: foremost, you have at your disposal all the facilities of a text editor like
2111: Emacs, in particular for correcting or copying blocks. Second, you can have
2112: an on-line help which is much more complete than what you obtain by typing
2113: \kbd{?name}. This is done by typing \kbd{M-?}. In the minibuffer, Emacs asks
2114: what function you want to describe, and after your reply you obtain the
2115: description which is in the users manual, including the description of
2116: functions (such as \kbd{\bs}, \kbd{\%}) which use special symbols.
2117:
2118: This help system can also be menu-driven, by using the command
2119: \kbd{M-\char`\\ c} which opens a help menu window which enables you to choose
2120: the category of commands for which you want an explanation.
2121:
2122: Nevertheless, if extended help is available on your system (see
2123: \secref{se:exthelp}), you should use it instead of the above, since it's
2124: nicer (it ran through \TeX) and understands many more keywords.
2125:
2126: Finally you can use command completion in the following way. After the
2127: prompt, type the first few letters of the command, then \kbd{<TAB>} where
2128: \kbd{<TAB>} is the TAB key. If there exists a unique command starting with
2129: the letters you have typed, the command name will be completed. If not,
2130: either the list of commands starting with the letters you typed will be
2131: displayed in a separate window (which you can then kill by typing as usual
2132: \kbd{C-x 1} or by typing in more letters), or ``no match found'' will be
2133: displayed in the Emacs command line. If your GP was linked with the readline
2134: library, read the section on completion in the section below (the paragraph
2135: on online help is not relevant).
2136:
2137: Note that if for some reason the session crashes (due to a bug in your
2138: program or in the PARI system), you will usually stay under Emacs, but the GP
2139: buffer will be killed. To recover it, simply type again \kbd{M-x gp} (or
2140: \kbd{C-u M-x gp}), and a new session of GP will be started after the old one,
2141: so you can recover what you have typed. Note that this will of course
2142: \var{not} work if for some reason you kill Emacs and start a new session.
2143:
2144: \smallskip
2145: You also have at your disposal a few other commands and many possible
2146: customizations (colours, prompt). Read the file \kbd{emacs/pariemacs.txt} in
2147: standard distribution for details.
2148:
2149:
2150: \section{Using GP with readline}
2151: \sidx{line editor}\sidx{completion}
2152:
2153: Thanks to the initial help of Ilya Zakharevich, there is a possibility of
2154: line editing and command name completion outside of an Emacs buffer
2155: \var{if} you have compiled GP with the GNU \idx{readline} library. If you
2156: don't have Emacs available, or can't stand using it, we really advise you
2157: to make sure you get this very useful library before configuring or
2158: compiling GP. In fact, with \kbd{readline}, even line editing becomes
2159: \var{more} powerful outside an Emacs buffer!
2160:
2161: \subsec{A (too) short introduction to readline}:
2162: \label{se:readline}
2163: The basics are as follows (read the readline user manual~!), assume that
2164: \kbd{C-} stands for ``the \kbd{Control} key combined with another'' and the
2165: same for \kbd{M-} with the \kbd{Meta} key (generally \kbd{C-} combinations
2166: act on characters, while the \kbd{M-} ones operate on words). The \kbd{Meta}
2167: key might be called \kbd{Alt} on some keyboards, will display a black diamond
2168: on most others, and can safely be replaced by \kbd{Esc} in any case. Typing
2169: any ordinary key inserts text where the cursor stands, the arrow keys
2170: enabling you to move in the line. There are many more movement commands,
2171: which will be familiar to the Emacs user, for instance \kbd{C-a}/\kbd{C-e}
2172: will take you to the start/end of the line, \kbd{M-b}/\kbd{M-f} move the
2173: cursor backward/forward by a word, etc. Just press the \kbd{Return} key at
2174: any point to send your command to GP.
2175:
2176: All the commands you type in are stored in a history (with multiline
2177: commands being saved as single concatenated lines). The Up and Down arrows (or
2178: \kbd{C-p}/\kbd{C-n}) will move you through it, \kbd{M-<}/\kbd{M->} sending
2179: you to the start/end of the history. \kbd{C-r}/\kbd{C-s} will start an
2180: incremental backward/forward search. You can kill text (\kbd{C-k} kills till
2181: the end of line, \kbd{M-d} to the end of current word) which you can then
2182: yank back using the \kbd{C-y} key (\kbd{M-y} will rotate the kill-ring).
2183: \kbd{C-\_} will undo your last changes incrementally (\kbd{M-r} undoes all
2184: changes made to the current line). \kbd{C-t} and \kbd{M-t} will transpose
2185: the character (word) preceding the cursor and the one under the cursor.
2186:
2187: Keeping the \kbd{M-} key down while you enter an integer (a minus sign
2188: meaning reverse behaviour) gives an argument to your next readline command
2189: (for instance \kbd{M-- C-k} will kill text back to the start of line). If you
2190: prefer \idx{Vi}--style editing, \kbd{M-C-j} will toggle you to Vi mode.
2191:
2192: Of course you can change all these default bindings. For that you need to
2193: create a file named \kbd{.inputrc} in your home directory. For instance
2194: (notice the embedding conditional in case you would want specific bindings
2195: for GP):
2196: %
2197: \bprog
2198: $if Pari-GP
2199: set show-all-if-ambiguous
2200: "\C-h": backward-delete-char
2201: "\e\C-h": backward-kill-word
2202: "\C-xd": dump-functions
2203: (: "\C-v()\C-b" #@com can be annoying when copy-pasting !
2204: [: "\C-v[]\C-b"
2205: $endif
2206: @eprog
2207: \noindent\kbd{C-x C-r} will re-read this init file, incorporating any
2208: changes made to it during the current session.
2209:
2210: \misctitle{Note:} By default, \kbd{(} and \kbd{[} are bound to the function
2211: \kbd{pari-matched-insert} which, if ``electric parentheses'' are enabled
2212: (default: off) will automatically insert the matching closure (respectively
2213: \kbd{)} and \kbd{]}). This behaviour can be toggled on and off by giving
2214: the numeric argument $-2$ to \kbd{(} (\kbd{M--2(}), which is useful if you
2215: want, e.g to copy-paste some text into the calculator. If you don't want a
2216: toggle, you can use \kbd{M--0} / \kbd{M--1} to specifically switch it on or
2217: off).
2218:
2219: \misctitle{Note:} In recent versions of readline (2.1 for instance), the
2220: \kbd{Alt} or \kbd{Meta} key can give funny results (output 8-bit accented
2221: characters for instance). If you don't want to fall back to the \kbd{Esc}
2222: combination, put the following two lines in your \kbd{.inputrc}:
2223: %
2224: \bprog
2225: set convert-meta on
2226: set output-meta off
2227: @eprog
2228:
2229: % don't remove this leading space (needed by gphelp)
2230: \subsec{Command completion and online help}
2231:
2232: As in the Emacs shell, \kbd{<TAB>} will complete words for you. But, under
2233: readline, this mechanism will be context-dependent: GP will strive to only
2234: give you meaningful completions in a given context (it will fail sometimes,
2235: but only under rare and restricted conditions).
2236:
2237: For instance, shortly after a \kbd{\til}, we expect a user name, then a
2238: path to some file. Directly after \kbd{default(} has been typed, we would
2239: expect one of the \kbd{default} keywords. After \kbd{whatnow(} , we expect
2240: the name of an old function, which may well have disappeared from this
2241: version. After a '.', we expect a member keyword. And generally of course, we
2242: expect any GP symbol which may be found in the hashing lists: functions (both
2243: yours and GP's), and variables.
2244:
2245: If, at any time, only one completion is meaningful, GP will provide it
2246: together with
2247:
2248: $\bullet$ an ending comma if we're completing a default,
2249:
2250: $\bullet$ a pair of parentheses if we're completing a function name. In
2251: that case hitting \kbd{<TAB>} again will provide the argument list as given
2252: by the online help\footnote{*}{recall that you can always undo the effect
2253: of the preceding keys by hitting \kbd{C-\_}}.
2254:
2255: Otherwise, hitting \kbd{<TAB>} once more will give you the list of possible
2256: completions. Just experiment with this mechanism as often as possible,
2257: you'll probably find it very convenient. For instance, you can obtain
2258: \kbd{default(seriesprecision,10)}, just by hitting \kbd{def<TAB>se<TAB>10},
2259: which saves 18 keystrokes (out of 27).
2260:
2261: Hitting \kbd{M-h} will give you the usual short online help concerning the
2262: word directly beneath the cursor, \kbd{M-H} will yield the extended help
2263: corresponding to the \kbd{help} default program (usually opens a \idx{dvi}
2264: previewer, or runs a primitive tex-to-ASCII program). None of these disturb
2265: the line you were editing.
2266: \vfill\eject
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>