returns a string built from the remaining arguments according to the format fmt. The format consists of ordinary characters (not %), printed unchanged, and conversions specifications. See printf.
changes the help message for the symbol sym. The string str is expanded on the spot and stored as the online help for sym. If sym is a function you have defined, its definition will still be printed before the message str. It is recommended that you document global variables and user functions in this way. Of course gp will not protest if you skip this. It is possible to attach a help text to an alias, but it will never be shown: aliases are expanded by the ? help operator and we get the help of the functions the alias points to.
Nothing prevents you from modifying the help of built-in PARI functions. But if you do, we would like to hear why you needed to do it!
The library syntax is void addhelp(const char *sym, const char *str).
trigger an alarmer exception after s seconds, cancelling any previously set alarm. Stop a pending alarm if s = 0 or is omitted.
For example, the function timefact(N,sec) below will try to factor N and give up after sec seconds, returning a partial factorisation.
default(factor_add_primes,1);
default(primelimit,16777216);
timefact(N,sec)=
{
trap(alarmer,factor(N,0),alarm(sec);my(F=factor(N));alarm(0);F);
}
defines the symbol newsym as an alias for the the symbol sym:
? alias("det", "matdet");
? det([1,2;3,4])
%1 = -2
You are not restricted to ordinary functions, as in the above example: to alias (from/to) member functions, prefix them with ` _.'; to alias operators, use their internal name, obtained by writing _ in lieu of the operators argument: for instance, _! and !_ are the internal names of the factorial and the logical negation, respectively.
? alias("mod", "_.mod");
? alias("add", "_+_");
? alias("_.sin", "sin");
? mod(Mod(x,x^4+1))
%2 = x^4 + 1
? add(4,6)
%3 = 10
? Pi.sin
%4 = 0.E-37
Alias expansion is performed directly by the internal GP compiler. Note that since alias is performed at compilation-time, it does not require any run-time processing, however it only affects GP code compiled after the alias command is evaluated. A slower but more flexible alternative is to use variables. Compare
? fun = sin; ? g(a,b) = intnum(t=a,b,fun(t)); ? g(0, Pi) %3 = 2.0000000000000000000000000000000000000 ? fun = cos; ? g(0, Pi) %5 = 1.8830410776607851098 E-39
with
? alias(fun, sin); ? g(a,b) = intnum(t=a,b,fun(t)); ? g(0,Pi) %2 = 2.0000000000000000000000000000000000000 ? alias(fun, cos); \\ Oops. Does not affect *previous* definition! ? g(0,Pi) %3 = 2.0000000000000000000000000000000000000 ? g(a,b) = intnum(t=a,b,fun(t)); \\ Redefine, taking new alias into account ? g(0,Pi) %5 = 1.8830410776607851098 E-39
A sample alias file misc/gpalias is provided with the standard distribution.
The library syntax is void alias0(const char *newsym, const char *sym).
this very special operation allows the user to change the stack size after initialization. x must be a non-negative integer. If x != 0, a new stack of size 16*ceil{x/16} bytes is allocated. If x = 0, the size of the new stack is twice the size of the old one. The old stack is discarded.
Warning. This function should be typed at the gp prompt in interactive usage, or left by itself at the start of batch files. It cannot be used meaningfully in loop-like constructs, or as part of a larger expression sequence, e.g
allocatemem(); x = 1; \\ This will not set x!
In fact, all loops are immediately exited, user functions terminated, and the rest of the sequence following allocatemem() is silently discarded, as well as all pending sequences of instructions. We just go on reading the next instruction sequence from the file we're in (or from the user). In particular, we have the following possibly unexpected behavior: in
read("file.gp"); x = 1
were
file.gp contains an
allocatemem statement,
the
x = 1 is never executed, since all pending instructions in the
current sequence are discarded.
The technical reason is that this routine moves the stack, so temporary objects created during the current expression evaluation are not correct anymore. (In particular byte-compiled expressions, which are allocated on the stack.) To avoid accessing obsolete pointers to the old stack, this routine ends by a longjmp.
Apply the t_CLOSURE f to the entries of A. If A is a scalar, return f(A). If A is a polynomial or power series, apply f on all coefficients. If A is a vector or list, return the elements f(x) where x runs through A. If A is a matrix, return the matrix whose entries are the f( A[i,j]).
? apply(x->x^2, [1,2,3,4]) %1 = [1, 4, 9, 16] ? apply(x->x^2, [1,2;3,4]) %2 = [1 4] [9 16] ? apply(x->x^2, 4*x^2 + 3*x+ 2) %3 = 16*x^2 + 9*x + 4Note that many functions already act componentwise on vectors or matrices, but they almost never act on lists; in this case, apply is a good solution:
? L = List([Mod(1,3), Mod(2,4)]); ? lift(L) *** at top-level: lift(L) *** ^------- *** lift: incorrect type in lift. ? apply(lift, L); %2 = List([1, 2])
The library syntax is genapply(void *E, GEN (*fun)(void*,GEN), GEN a).
returns the default corresponding to keyword key. If val is present, sets the default to val first (which is subject to string expansion first). Typing default() (or \d) yields the complete default list as well as their current values. See Section [Label: se:defaults] for an introduction to GP defaults, Section [Label: se:gp_defaults] for a list of available defaults, and Section [Label: se:meta] for some shortcut alternatives. Note that the shortcuts are meant for interactive use and usually display more information than default.
The library syntax is GEN default0(const char *key = NULL, const char *val = NULL).
outputs its argument list (each of them interpreted as a string), then interrupts the running gp program, returning to the input prompt. For instance
error("n = ", n, " is not squarefree !")
the string str is the name of an external command (i.e.one you would type from your UNIX shell prompt). This command is immediately run and its output fed into gp, just as if read from a file.
the string str is the name of an external command (i.e.one you would type from your UNIX shell prompt). This command is immediately run and its output is returned as a vector of GP strings, one component per output line.
returns a two-component row vector giving the number of objects on the heap and the amount of memory they occupy in long words. Useful mainly for debugging purposes.
The library syntax is GEN getheap().
returns the current value of the seed used by the pseudo-random number generator random. Useful mainly for debugging purposes, to reproduce a specific chain of computations. The returned value is technical (reproduces an internal state array), and can only be used as an argument to setrand.
The library syntax is GEN getrand().
returns the current value of top- avma, i.e.the number of bytes used up to now on the stack. Useful mainly for debugging purposes.
The library syntax is long getstack().
returns the time (in milliseconds) elapsed since either the last call to gettime, or to the beginning of the containing GP instruction (if inside gp), whichever came last.
The library syntax is long gettime().
obsolete. Scheduled for deletion.
reads a string, interpreted as a GP expression, from the input file, usually standard input (i.e.the keyboard). If a sequence of expressions is given, the result is the result of the last expression of the sequence. When using this instruction, it is useful to prompt for the string by using the print1 function. Note that in the present version 2.19 of pari.el, when using gp under GNU Emacs (see Section [Label: se:emacs]) one must prompt for the string, with a string which ends with the same prompt as any of the previous ones (a "? " will do for instance).
loads from dynamic library lib the function name. Assigns to it the name gpname in this gp session, with argument code code (see the Libpari Manual for an explanation of those). If lib is omitted, uses libpari.so. If gpname is omitted, uses name.
This function is useful for adding custom functions to the gp interpreter, or picking useful functions from unrelated libraries. For instance, it makes the function system obsolete:
? install(system, vs, sys, "libc.so")
? sys("ls gp*")
gp.c gp.h gp_rl.c
But it also gives you access to all (non static) functions defined in the PARI library. For instance, the function GEN addii(GEN x, GEN y) adds two PARI integers, and is not directly accessible under gp (it is eventually called by the + operator of course):
? install("addii", "GG")
? addii(1, 2)
%1 = 3
Re-installing a function will print a warning and update the prototype code if needed. However, it will not reload a symbol from the library, even it the latter has been recompiled.
Caution. This function may not work on all systems, especially when gp has been compiled statically. In that case, the first use of an installed function will provoke a Segmentation Fault, i.e.a major internal blunder (this should never happen with a dynamically linked executable). Hence, if you intend to use this function, please check first on some harmless example such as the ones above that it works properly on your machine.
restores the symbol sym to its "undefined" status, and deletes any help messages associated to sym using addhelp. Variable names remain known to the interpreter and keep their former priority: you cannot make a variable "less important" by killing it!
? z = y = 1; y %1 = 1 ? kill(y) ? y \\ restored to ``undefined'' status %2 = y ? variable() %3 = [x, y, z] \\ but the variable name y is still known, with y > z !
For the same reason, killing a user function (which is an ordinary variable holding a t_CLOSURE) does not remove its name from the list of variable names.
If the symbol is associated to a variable --- user functions being an important special case ---, one may use the quote operator a = 'a to reset variables to their starting values. However, this will not delete a help message associated to a, and is also slightly slower than kill(a).
? x = 1; addhelp(x, "foo"); x %1 = 1 ? x = 'x; x \\ same as 'kill', except we don't delete help. %2 = x ? ?x foo
On the other hand, kill is the only way to remove aliases and installed functions.
? alias(fun, sin); ? kill(fun); ? install(addii, GG); ? kill(addii);
The library syntax is void kill0(const char *sym).
outputs its (string) arguments in raw format, ending with a newline.
outputs its (string) arguments in raw format, without ending with a newline. Note that you can still embed newlines within your strings, using the \n notation!
This function is based on the C library command of the same name. It prints its arguments according to the format fmt, which specifies how subsequent arguments are converted for output. The format is a character string composed of zero or more directives:
* ordinary characters (not %), printed unchanged,
* conversions specifications ( % followed by some characters) which fetch one argument from the list and prints it according to the specification.
More precisely, a conversion specification consists in a %, one or more optional flags (among #, 0, -, +, ` '), an optional decimal digit string specifying a minimal field width, an optional precision in the form of a period (` .') followed by a decimal digit string, and the conversion specifier (among d, i, o, u, x, X, p, e, E, f, g, G, s).
The flag characters. The character % is followed by zero or more of the following flags:
* #: The value is converted to an "alternate form". For o conversion (octal), a 0 is prefixed to the string. For x and X conversions (hexa), respectively 0x and 0X are prepended. For other conversions, the flag is ignored.
* 0: The value should be zero padded. For d, i, o, u, x, X e, E, f, F, g, and G conversions, the value is padded on the left with zeros rather than blanks. (If the 0 and - flags both appear, the 0 flag is ignored.)
* -: The value is left adjusted on the field boundary. (The default is right justification.) The value is padded on the right with blanks, rather than on the left with blanks or zeros. A - overrides a 0 if both are given.
* ` ' (a space): A blank is left before a positive number produced by a signed conversion.
* +: A sign (+ or -) is placed before a number produced by a signed conversion. A + overrides a space if both are used.
The field width. An optional decimal digit string (whose first digit is non-zero) specifying a minimum field width. If the value has fewer characters than the field width, it is padded with spaces on the left (or right, if the left-adjustment flag has been given). In no case does a small field width cause truncation of a field; if the value is wider than the field width, the field is expanded to contain the conversion result. Instead of a decimal digit string, one may write * to specify that the field width is given in the next argument.
The precision. An optional precision in the form of a period (` .') followed by a decimal digit string. This gives the number of digits to appear after the radix character for e, E, f, and F conversions, the maximum number of significant digits for g and G conversions, and the maximum number of characters to be printed from an s conversion. Instead of a decimal digit string, one may write * to specify that the field width is given in the next argument.
The length modifier. This is ignored under gp, but necessary for libpari programming. Description given here for completeness:
* l: argument is a long integer.
* P: argument is a GEN.
The conversion specifier. A character that specifies the type of conversion to be applied.
* d, i: A signed integer.
* o, u, x, X: An unsigned integer, converted to unsigned octal ( o), decimal ( u) or hexadecimal ( x or X) notation. The letters abcdef are used for x conversions; the letters ABCDEF are used for X conversions.
* e, E: The (real) argument is converted in the style [ -]d.ddd e[ -]dd, where there is one digit before the decimal point, and the number of digits after it is equal to the precision; if the precision is missing, use the current realprecision for the total number of printed digits. If the precision is explicitly 0, no decimal-point character appears. An E conversion uses the letter E rather than e to introduce the exponent.
* f, F: The (real) argument is converted in the style [ -]ddd.ddd, where the number of digits after the decimal point is equal to the precision; if the precision is missing, use the current realprecision for the total number of printed digits. If the precision is explicitly 0, no decimal-point character appears. If a decimal point appears, at least one digit appears before it.
* g, G: The (real) argument is converted in style e or f (or E or F for G conversions) [ -]ddd.ddd, where the total number of digits printed is equal to the precision; if the precision is missing, use the current realprecision. If the precision is explicitly 0, it is treated as 1. Style e is used when the decimal exponent is < -4, to print 0., or when the integer part cannot be decided given the known significant digits, and the f format otherwise.
* c: The integer argument is converted to an unsigned char, and the resulting character is written.
* s: Convert to a character string. If a precision is given, no more than the specified number of characters are written.
* p: Print the address of the argument in hexadecimal (as if by %#x).
* %: A % is written. No argument is converted. The complete conversion specification is %%.
Examples:
? printf("floor: %d, field width 3: %3d, with sign: %+3d\n", Pi, 1, 2);
floor: 3, field width 3: 1, with sign: +2
? printf("%.5g %.5g %.5g\n",123,123/456,123456789);
123.00 0.26974 1.2346 e8
? printf("%-2.5s:%2.5s:%2.5s\n", "P", "PARI", "PARIGP");
P :PARI:PARIG
\\ min field width and precision given by arguments
? x = 23; y=-1/x; printf("x=%+06.2f y=%+0*.*f\n", x, 6, 2, y);
x=+23.00 y=-00.04
\\ minimum fields width 5, pad left with zeroes
? for (i = 2, 5, printf("%05d\n", 10^i))
00100
01000
10000
100000 \\ don't truncate fields whose length is larger than the minimum width
? printf("%.2f |%06.2f|", Pi,Pi)
3.14 | 3.14|
All numerical conversions apply recursively to the entries
of vectors and matrices:
? printf("%4d", [1,2,3]);
[ 1, 2, 3]
? printf("%5.2f", mathilbert(3));
[ 1.00 0.50 0.33]
[ 0.50 0.33 0.25]
[ 0.33 0.25 0.20]
Technical note. Our implementation of printf deviates from the C89 and C99 standards in a few places:
* whenever a precision is missing, the current realprecision is used to determine the number of printed digits (C89: use 6 decimals after the radix character).
* in conversion style e, we do not impose that the exponent has at least two digits; we never write a + sign in the exponent; 0 is printed in a special way, always as 0.Eexp.
* in conversion style f, we switch to style e if the exponent is greater or equal to the precision.
* in conversion g and G, we do not remove trailing zeros from the fractional part of the result; nor a trailing decimal point; 0 is printed in a special way, always as 0.Eexp.
outputs its (string) arguments in TeX format. This output can then be used in a TeX manuscript. The printing is done on the standard output. If you want to print it to a file you should use writetex (see there).
Another possibility is to enable the log default (seeSection [Label: se:defaults]). You could for instance do:
default(logfile, "new.tex"); default(log, 1); printtex(result);
exits gp and return to the system with exit status status, a small integer. A non-zero exit status normally indicates abnormal termination. (Note: the system actually sees only status mod 256, see your man pages for exit(3) or wait(2)).
reads in the file filename (subject to string expansion). If filename is omitted, re-reads the last file that was fed into gp. The return value is the result of the last expression evaluated.
If a GP binary file is read using this command (see Section [Label: se:writebin]), the file is loaded and the last object in the file is returned.
In case the file you read in contains an allocatemem statement (to be generally avoided), you should leave read instructions by themselves, and not part of larger instruction sequences.
reads in the file filename (subject to string expansion). If filename is omitted, re-reads the last file that was fed into gp. The return value is a vector whose components are the evaluation of all sequences of instructions contained in the file. For instance, if file contains
1 2 3
then we will get:
? \r a %1 = 1 %2 = 2 %3 = 3 ? read(a) %4 = 3 ? readvec(a) %5 = [1, 2, 3]
In general a sequence is just a single line, but as usual braces and \ may be used to enter multiline sequences.
The library syntax is GEN gp_readvec_file(const char *filename). The underlying library function GEN gp_readvec_stream(FILE *f) is usually more flexible.
Given a vector, list or matrix A and a t_CLOSURE f, returns the elements x of A such that f(x) is non-zero. In other words, f is seen as a selection function returning a boolean value.
? select(x->isprime(x), vector(50,i,i^2+1)) %1 = [2, 5, 17, 37, 101, 197, 257, 401, 577, 677, 1297, 1601] ? select(x->(x<100), %) %2 = [2, 5, 17, 37]returns the primes of the form i^2+1 for some i <= 50, then the elements less than 100 in the preceding result. The following function lists the elements in (Z/NZ)^*:
? invertibles(N) = select(x->gcd(x,N) == 1, vector(N,i,i))
Finally
? select(x->x, M)selects the non-0 entries in M. If the latter is a t_MAT, we extract the matrix of non-0 columns. Note that removing entries instead of selecting them just involves replacing the selection function f with its negation:
? select(x->!isprime(x), vector(50,i,i^2+1))
The library syntax is genselect(void *E, long (*fun)(void*,GEN), GEN a).
reseeds the random number generator using the seed n. No value is returned. The seed is either a technical array output by getrand, or a small positive integer, used to generate deterministically a suitable state array. For instance, running a randomized computation starting by setrand(1) twice will generate the exact same output.
The library syntax is void setrand(GEN n).
str is a string representing a system command. This command is executed, its output written to the standard output (this won't get into your logfile), and control returns to the PARI system. This simply calls the C system command.
tries to evaluate seq, trapping runtime error e, that is effectively preventing it from aborting computations in the usual way; the recovery sequence rec is executed if the error occurs and the evaluation of rec becomes the result of the command. If e is omitted, all exceptions are trapped. See Section [Label: se:errorrec] for an introduction to error recovery under gp.
? \\ trap division by 0? inv(x) = trap (gdiver, INFINITY, 1/x) ? inv(2) %1 = 1/2 ? inv(0) %2 = INFINITY
Note that seq is effectively evaluated up to the point that produced the error, and the recovery sequence is evaluated starting from that same context, it does not "undo" whatever happened in the other branch (restore the evaluation context):
? x = 1; trap (, /* recover: */ x, /* try: */ x = 0; 1/x) %1 = 0
Note. The interface is currently not adequate for trapping individual exceptions. In the current version 2.5.1, the following keywords are recognized, but the name list will be expanded and changed in the future (all library mode errors can be trapped: it's a matter of defining the keywords to gp):
alarmer: alarm time-out
archer: not available on this architecture or operating system
errpile: the PARI stack overflows
gdiver: division by 0
impl: not yet implemented
invmoder: impossible inverse modulo
overflower: all forms of arithmetic overflow, including length or exponent overflow (when a larger value is supplied than the implementation can handle).
syntaxer: syntax error
talker: miscellaneous error
typeer: wrong type
user: user error (from the error function)
The library syntax is GEN trap0(const char *e = NULL, GEN rec = NULL, GEN seq = NULL).
this is useful only under gp. Returns the internal type name of the PARI object x as a string. Check out existing type names with the metacommand \t. For example type(1) will return " t_INT".
The library syntax is GEN type0(GEN x). The macro typ is usually simpler to use since it returns a long that can easily be matched with the symbols t_*. The name type was avoided since it is a reserved identifier for some compilers.
returns the current version number as a t_VEC with three integer components (major version number, minor version number and patchlevel); if your sources were obtained through our version control system, this will be followed by a more precise version string, e.g. git-commit hash.
This function is present in all versions of PARI following releases 2.3.4 (stable) and 2.4.3 (testing).
Unless you are working with multiple development versions, you probably only care about the 3 first numeric components. In any case, the lex function offers a clever way to check against a particular version number, since it will compare each successive vector entry, numerically or as strings, and will not mind if the vectors it compares have different lengths :
if (lex(version(), [2,3,5]) >= 0, \\ code to be executed if we are running 2.3.5 or more recent. , \\ compatibility code );On a number of different machines, version() could return either of
%1 = [2, 3, 4] \\ released version, stable branch %1 = [2, 4, 3] \\ released version, testing branch %1 = [2, 6, 0, "git-2cce227"] \\ development
In particular the first line of the gp introductory message can be essentially emulated by
v = version();
n = Str(v[1], ".", v[2], ".", v[3]);
s = if (#v > 3, v[4], "");
print("GP/PARI CALCULATOR Version ", n, " (", s, ")");
If you are working with many development versions of
PARI/GP, the last component can be profitably included in the name of
your logfile, for instance.
The library syntax is GEN pari_version().
outputs the message "user warning" and the argument list (each of them interpreted as a string). If colors are enabled, this warning will be in a different color, making it easy to distinguish.
warning(n, " is very large, this might take a while.")
if keyword key is the name of a function that was present in GP version 1.39.15 or lower, outputs the new function name and syntax, if it changed at all (387 out of 560 did).
writes (appends) to filename the remaining arguments, and appends a newline (same output as print).
writes (appends) to filename the remaining arguments without a trailing newline (same output as print1).
writes (appends) to filename the object x in binary format. This format is not human readable, but contains the exact internal structure of x, and is much faster to save/load than a string expression, as would be produced by write. The binary file format includes a magic number, so that such a file can be recognized and correctly input by the regular read or \r function. If saved objects refer to (polynomial) variables that are not defined in the new session, they will be displayed in a funny way (see Section [Label: se:kill]).
If x is omitted, saves all user variables from the session, together with their names. Reading such a "named object" back in a gp session will set the corresponding user variable to the saved value. E.g after
x = 1; writebin("log")
reading log into a clean session will set x to 1. The relative variables priorities (see Section [Label: se:priority]) of new variables set in this way remain the same (preset variables retain their former priority, but are set to the new value). In particular, reading such a session log into a clean session will restore all variables exactly as they were in the original one.
User functions, installed functions and history objects can not be saved via this function. Just as a regular input file, a binary file can be compressed using gzip, provided the file name has the standard .gz extension.
In the present implementation, the binary files are architecture dependent and compatibility with future versions of gp is not guaranteed. Hence binary files should not be used for long term storage (also, they are larger and harder to compress than text files).
The library syntax is void gpwritebin(const char *filename, GEN x = NULL).
as write, in TeX format.