Pari/GP Reference Documentation | Contents - Global index - GP keyboard shortcuts |
Strchr Strexpand Strprintf Strtex addhelp alarm alias allocatemem apply arity call default errname error export exportall extern externstr fileclose fileextern fileflush fileopen fileread filereadstr filewrite filewrite1 fold getabstime getcache getenv getheap getlocalbitprec getlocalprec getrand getstack gettime getwalltime global inline input install kill listcreate listinsert listkill listpop listput listsort localbitprec localprec mapapply mapdelete mapget mapisdefined mapput print print1 printf printp printsep printsep1 printtex quit read readstr readvec select self setrand strchr strexpand strjoin strprintf strsplit strtex strtime system trap type unexport unexportall uninline version warning whatnow write write1 writebin writetex | |
In addition to the general PARI functions, it is necessary to have some
functions which will be of use specifically for
| |
Strchr(x) | |
Deprecated alias for strchr.
The library syntax is
| |
Strexpand({x}*) | |
Deprecated alias for strexpand
The library syntax is
| |
Strprintf(fmt, {x}*) | |
Deprecated alias for strprintf.
The library syntax is
| |
Strtex({x}*) | |
Deprecated alias for strtex.
The library syntax is
| |
addhelp(sym, str) | |
Changes the help message for the symbol
You can attach a help text to an alias, but it will never be
shown: aliases are expanded by the
Without
gp> f(x) = x^2; gp> ?f f = (x)->x^2 Once addhelp is applied to f, the function code is no longer included. It can still be consulted by typing the function name:
gp> addhelp(f, "Square") gp> ?f Square gp> f %2 = (x)->x^2
The library syntax is
| |
alarm({s = 0}, {code}) | |
If code is omitted, trigger an e_ALARM exception after s seconds (wall-clock time), cancelling any previously set alarm; stop a pending alarm if s = 0 or is omitted.
Otherwise, if s is positive, the function evaluates code,
aborting after s seconds. The return value is the value of code if
it ran to completion before the alarm timeout, and a
? p = nextprime(10^25); q = nextprime(10^26); N = p*q; ? E = alarm(1, factor(N)); ? type(E) %3 = "t_ERROR" ? print(E) %4 = error("alarm interrupt after 964 ms.") ? alarm(10, factor(N)); \\ enough time %5 = [ 10000000000000000000000013 1] [100000000000000000000000067 1]
Here is a more involved example: the function
\\ Time-bounded partial factorization default(factor_add_primes,1); timefact(N,sec)= { F = alarm(sec, factor(N)); if (type(F) == "t_ERROR", factor(N, 2^24), F); }
We either return the factorization directly, or replace the
Caveat. It is not possible to set a new alarm within
another
Caveat2. In a parallel-enabled
The library syntax is
| |
alias(newsym, sym) | |
Defines the symbol newsym as an alias for 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 `
? 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
The library syntax is
| |
allocatemem({s = 0}) | |
This special operation changes the stack size after initialization. The argument s must be a nonnegative integer. If s > 0, a new stack of at least s bytes is allocated. We may allocate more than s bytes if s is way too small, or for alignment reasons: the current formula is max(16*ceil{s/16}, 500032) bytes. If s = 0, the size of the new stack is twice the size of the old one.
This command is much more useful if
* a virtual stack size,
* the desired typical stack size,
* the current stack size, which is less that
The
? \gm2 debugmem = 2 ? default(parisize,"32M") *** Warning: new stack size = 32000000 (30.518 Mbytes). ? bnfinit('x^2+10^30-1) *** bnfinit: collecting garbage in hnffinal, i = 1. *** bnfinit: collecting garbage in hnffinal, i = 2. *** bnfinit: collecting garbage in hnffinal, i = 3.
and so on for hundred of lines. Then, provided the
In most cases,
Deprecated: when
Thus, increasing
allocatemem(); x = 1; \\ This will not set
In fact, all loops are immediately exited, user functions terminated, and
the rest of the sequence following
read("file.gp"); x = 1
were
The reason for these unfortunate side-effects is that, with
The library syntax is
| |
apply(f, A) | |
Apply the
* If
* If
* If
? 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 + 4 ? apply(sign, 2 - 3* x + 4*x^2 + O(x^3)) %4 = 1 - x + x^2 + O(x^3)
Note that many functions already act componentwise on
vectors or matrices, but they almost never act on lists; in this case,
? 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])
Remark. For v a
[g(x) | x <- v, f(x)] [x | x <- v, f(x)] [g(x) | x <- v] are available as shortcuts for
apply(g, select(f, Vec(v))) select(f, Vec(v)) apply(g, Vec(v)) respectively:
? L = List([Mod(1,3), Mod(2,4)]); ? [ lift(x) | x<-L ] %2 = [1, 2]
The library syntax is
| |
arity(C) | |
Return the arity of the closure C, i.e., the number of its arguments.
? f1(x,y=0)=x+y; ? arity(f1) %1 = 2 ? f2(t,s[..])=print(t,":",s); ? arity(f2) %2 = 2
Note that a variadic argument, such as s in
The library syntax is
| |
call(f, A) | |
A = [a1,..., an] being a vector and f being a function,
returns the evaluation of f(a1,...,an).
f can also be the name of a built-in GP function.
If # A = 1, This function is useful * when writing a variadic function, to call another one:
fprintf(file,format,args[..]) = write(file, call(strprintf,[format,args])) * when dealing with function arguments with unspecified arity. The function below implements a global memoization interface:
memo=Map(); memoize(f,A[..])= { my(res); if(!mapisdefined(memo, [f,A], &res), res = call(f,A); mapput(memo,[f,A],res)); res; } for example:
? memoize(factor,2^128+1) %3 = [59649589127497217,1;5704689200685129054721,1] ? ## *** last result computed in 76 ms. ? memoize(factor,2^128+1) %4 = [59649589127497217,1;5704689200685129054721,1] ? ## *** last result computed in 0 ms. ? memoize(ffinit,3,3) %5 = Mod(1,3)*x^3+Mod(1,3)*x^2+Mod(1,3)*x+Mod(2,3) ? fibo(n)=if(n==0,0,n==1,1,memoize(fibo,n-2)+memoize(fibo,n-1)); ? fibo(100) %7 = 354224848179261915075
* to call operators through their internal names without using
matnbelts(M) = call("_*_",matsize(M))
The library syntax is
| |
default({key}, {val}) | |
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
The library syntax is
| |
errname(E) | |
Returns the type of the error message
? iferr(1 / 0, E, print(errname(E))) e_INV ? ?? e_INV [...] * "e_INV". Tried to invert a noninvertible object x in function s. [...]
The library syntax is
| |
error({str}*) | |
Outputs its argument list (each of
them interpreted as a string), then interrupts the running
error("n = ", n, " is not squarefree!")
The library syntax is
The variadic version
| |
export(x{ = ...}, ..., z{ = ...}) | |
Export the variables x,..., z to the parallel world.
Such variables are visible inside parallel sections in place of global
variables, but cannot be modified inside a parallel section.
? fun(x)=x^2+1; ? parvector(10,i,fun(i)) *** mt: please use export(fun). ? export(fun) ? parvector(10,i,fun(i)) %4 = [2,5,10,17,26,37,50,65,82,101]
| |
exportall() | |
Declare all current dynamic variables as exported variables. Such variables are visible inside parallel sections in place of global variables.
? fun(x)=x^2+1; ? parvector(10,i,fun(i)) *** mt: please use export(fun). ? exportall() ? parvector(10,i,fun(i)) %4 = [2,5,10,17,26,37,50,65,82,101]
The library syntax is
| |
extern(str) | |
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
The library syntax is
| |
externstr(str) | |
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.
The library syntax is
| |
fileclose(n) | |
Close the file descriptor n, created via
? n = 0; while(n++, fileopen("/tmp/test", "w")) *** at top-level: n=0;while(n++,fileopen("/tmp/test","w")) *** ^ — — — — — — — — -- *** fileopen: error opening requested file: `/tmp/test'. *** Break loop: type 'break' to go back to GP prompt break> n 65533
This is a limitation of the operating system and does not
depend on PARI: if you open too many files in
On files opened for writing, this function also forces a write of all
buffered data to the file system and completes all pending write operations.
This function is implicitly called for all open file descriptors when
exiting
? n = fileopen("./here"); ? while(l = fileread(n), print(l)); ? fileclose(n); ? n = fileopen("./there", "w"); ? for (i = 1, 100, filewrite(n, i^2+1)) ? fileclose(n)
Until a Closing a file twice raises an exception:
? n = fileopen("/tmp/test"); ? fileclose(n) ? fileclose(n) *** at top-level: fileclose(n) *** ^ — — — — *** fileclose: invalid file descriptor 0
The library syntax is
| |
fileextern(str) | |
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 the function returns a file descriptor attached to the command output as if it were read from a file.
? n = fileextern("ls -l"); ? while(l = filereadstr(n), print(l)) ? fileclose(n)
If the
The library syntax is
| |
fileflush({n}) | |
Flushes the file descriptor n, created via If n is omitted, flush all descriptors to output streams.
? n = fileopen("./here", "w"); ? for (i = 1, 10^5, \ filewrite(n, i^2+1); \ if (i % 10000 == 0, fileflush(n)))
Until a
The library syntax is
| |
fileopen(path, mode) | |
Open the file pointed to by 'path' and return a file descriptor which can be used with other file functions. The mode can be
*
*
*
Eventually, the file should be closed and the descriptor recycled using
? n = fileopen("./here"); \\ "r" by default ? while (l = filereadstr(n), print(l)) \\ print successive lines ? fileclose(n) \\ done In read mode, raise an exception if the file does not exist or the user does not have read permission. In write mode, raise an exception if the file cannot be written to. Trying to read or write to a file that was not opend with the right mode raises an exception.
? n = fileopen("./read", "r"); ? filewrite(n, "test") \\ not open for writing *** at top-level: filewrite(n,"test") *** ^ — — — — — — - *** filewrite: invalid file descriptor 0
The library syntax is
| |
fileread(n) | |
Read a logical line from the file attached to the descriptor n, opened
for reading with
A logical line is a full command as it is prepared by gp's
preprocessor (skipping blanks and comments or assembling multiline commands
between braces) before being fed to the interpreter. The function
Compare raw lines
? n = fileopen("examples/bench.gp"); ? while(l = filereadstr(n), print(l)); { u=v=p=q=1; for (k=1, 2000, [u,v] = [v,u+v]; p *= v; q = lcm(q,v); if (k%50 == 0, print(k, " ", log(p)/log(q)) ) ) } and logical lines
? n = fileopen("examples/bench.gp"); ? while(l = fileread(n), print(l)); u=v=p=q=1;for(k=1,2000,[u,v]=[v,u+v];p*=v;q=lcm(q,v);[...]
The library syntax is
| |
filereadstr(n) | |
Read a raw line from the file attached to the descriptor n, opened
for reading with
The library syntax is
| |
filewrite(n, s) | |
Write the string s to the file attached to descriptor n, ending with
a newline. The file must have been opened with
If the newline is not desired, use
Variant. The high-level function
? f = "/tmp/bigfile"; ? for (i = 1, 10^5, write(f, i^2+1)) time = 240 ms. ? v = vector(10^5, i, i^2+1); time = 10 ms. \\ computing the values is fast ? write("/tmp/bigfile2",v) time = 12 ms. \\ writing them in one operation is fast ? n = fileopen("/tmp/bigfile", "w"); ? for (i = 1, 10^5, filewrite(n, i^2+1)) time = 24 ms. \\ low-level write is ten times faster ? fileclose(n);
In the final example, the file needs not be in a consistent
state until the ending
? v = []; for (i = 1, 10^5, v = concat(v,i)) time = 1min, 41,456 ms.
The library syntax is
| |
filewrite1(n, s) | |
Write the string s to the file attached to descriptor n.
The file must have been opened with
If you want to append a newline at the end of s, you can use
The library syntax is
| |
fold(f, A) | |
Apply the
? fold((x,y)->x*y, [1,2,3,4]) %1 = 24 ? fold((x,y)->[x,y], [1,2,3,4]) %2 = [[[1, 2], 3], 4] ? fold((x,f)->f(x), [2,sqr,sqr,sqr]) %3 = 256 ? fold((x,y)->(x+y)/(1-x*y),[1..5]) %4 = -9/19 ? bestappr(tan(sum(i=1,5,atan(i)))) %5 = -9/19
The library syntax is
| |
getabstime() | |
Returns the CPU time (in milliseconds) elapsed since
my (t = getabstime()); ... print("Time: ", strtime(getabstime() - t));
For a version giving wall-clock time, see
The library syntax is
| |
getcache() | |
Returns information about various auto-growing caches. For each resource, we report its name, its size, the number of cache misses (since the last extension), the largest cache miss and the size of the cache in bytes. The caches are initially empty, then set automatically to a small inexpensive default value, then grow on demand up to some maximal value. Their size never decreases, they are only freed on exit. The current caches are * Hurwitz class numbers H(D) for |D| ≤ N, computed in time O(N3/2) using O(N) space. * Factorizations of small integers up to N, computed in time O(N1+ϵ) using O(Nlog N) space. * Divisors of small integers up to N, computed in time O(N1+ϵ) using O(Nlog N) space. * Coredisc's of negative integers down to -N, computed in time O(N1+ϵ) using O(N) space. * Primitive dihedral forms of weight 1 and level up to N, computed in time O(N2+ϵ) and space O(N2).
? getcache() \\ on startup, all caches are empty %1 = [ "Factors" 0 0 0 0] [ "Divisors" 0 0 0 0] [ "H" 0 0 0 0] ["CorediscF" 0 0 0 0] [ "Dihedral" 0 0 0 0] ? mfdim([500,1,0],0); \\ nontrivial computation time = 540 ms. ? getcache() %3 = [ "Factors" 50000 0 0 4479272] ["Divisors" 50000 1 100000 5189808] [ "H" 50000 0 0 400008] ["Dihedral" 1000 0 0 2278208]
The library syntax is
| |
getenv(s) | |
Return the value of the environment variable
The library syntax is
| |
getheap() | |
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
| |
getlocalbitprec() | |
Returns the current dynamic bit precision.
| |
getlocalprec() | |
Returns the current dynamic precision, in decimal digits.
| |
getrand() | |
Returns the current value of the seed used by the
pseudo-random number generator
The library syntax is
| |
getstack() | |
Returns the current value of
The library syntax is
| |
gettime() | |
Returns the CPU time (in milliseconds) used since either the last call to
For a reentrant version, see
For a version giving wall-clock time, see
The library syntax is
| |
getwalltime() | |
Returns the time (in milliseconds) elapsed since 00:00:00 UTC Thursday 1, January 1970 (the Unix epoch).
my (t = getwalltime()); ... print("Time: ", strtime(getwalltime() - t));
The library syntax is
| |
global(list of variables) | |
Obsolete. Scheduled for deletion.
| |
inline(x, ..., z) | |
Declare x,..., z as inline variables. Such variables
behave like lexically scoped variable (see my()) but with unlimited scope.
It is however possible to exit the scope by using
| |
input() | |
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
The library syntax is
| |
install(name, code, {gpname}, {lib}) | |
Loads from dynamic library lib the function name. Assigns to it
the name gpname in this
Most importantly,
GEN addii(GEN x, GEN y)
adds two PARI integers, and is not directly accessible under
? install("addii", "GG") ? addii(1, 2) %1 = 3
It also allows to add external functions to the
? install(system, vs, sys,/*omitted*/) ? sys("ls gp*") gp.c gp.h gp_rl.c
This works because 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 if the latter has been recompiled.
Prototype. We only give a simplified description here, covering
most functions, but there are many more possibilities. The full documentation
is available in
??prototype
* First character
* One letter for each mandatory argument, in the same order as they appear
in the argument list:
* We also have special constructs for optional arguments and default values:
*
*
* For instance the prototype corresponding to
long issquareall(GEN x, GEN *n = NULL)
is
Caution. This function may not work on all systems, especially
when
The library syntax is
| |
kill(sym) | |
Restores the symbol
? 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
If the symbol is attached to a variable — user functions being an
important special case — , one may use the quote operator
? 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,
? alias(fun, sin); ? kill(fun); ? install(addii, GG); ? kill(addii);
The library syntax is
| |
listcreate({n}) | |
This function is obsolete, use Creates an empty list. This routine used to have a mandatory argument, which is now ignored (for backward compatibility).
| |
listinsert(~L, x, n) | |
Inserts the object x at
position n in L (which must be of type
? L = List([1,2,3]); ? listput(~L, 4); L \\ listput inserts at end %4 = List([1, 2, 3, 4]) ? listinsert(~L, 5, 1); L \ ∈ sert at position 1 %5 = List([5, 1, 2, 3, 4]) ? listinsert(~L, 6, 1000); L \\ trying to insert beyond position #L %6 = List([5, 1, 2, 3, 4, 6]) \\ ... inserts at the end
Note the
The library syntax is
| |
listkill(~L) | |
Obsolete, retained for backward compatibility. Just use
The library syntax is
| |
listpop(~list, {n}) | |
Removes the n-th element of the list
list (which must be of type
? L = List([1,2,3,4]); ? listpop(~L); L \\ remove last entry %2 = List([1, 2, 3]) ? listpop(~L, 1); L \\ remove first entry %3 = List([2, 3])
Note the
The library syntax is
| |
listput(~list, x, {n}) | |
Sets the n-th element of the list
list (which must be of type
? L = List(); ? listput(~L, 1) ? listput(~L, 2) ? L %4 = List([1, 2])
Note the
You may put an element into an occupied cell (not changing the
list length), but it is easier to use the standard
? listput(~L, 3, 1) \\ insert at position 1 ? L %6 = List([3, 2]) ? L[2] = 4 \\ simpler %7 = List([3, 4]) ? L[10] = 1 \\ can't insert beyond the end of the list *** at top-level: L[10]=1 *** ^ — — *** nonexistent component: index > 2 ? listput(L, 1, 10) \\ but listput can ? L %9 = List([3, 2, 1])
This function runs in time O(#L) in the worst case (when the list must
be reallocated), but in time O(1) on average: any number of successive
The library syntax is
| |
listsort(~L, {flag = 0}) | |
Sorts the
? L = List([1,2,4,1,3,-1]); listsort(~L); L %1 = List([-1, 1, 1, 2, 3, 4]) ? setsearch(L, 4) %2 = 6 ? setsearch(L, -2) %3 = 0 ? listsort(~L, 1); L \\ remove duplicates %4 = List([-1, 1, 2, 3, 4])
Note the
? v = vector(100,i,random); L = List(v); ? for(i=1,10^4, vecsort(v)) time = 162 ms. ? for(i=1,10^4, vecsort(L)) time = 162 ms. ? for(i=1,10^4, listsort(~L)) time = 63 ms.
The library syntax is
| |
localbitprec(p) | |
Set the real precision to p bits in the dynamic scope.
All computations are performed as if
my(bit = default(realbitprecision)); default(realbitprecision,p); ... default(realbitprecision, bit);
but is both less cumbersome, cleaner (no need to manipulate
a global variable, which in fact never changes and is only temporarily masked)
and more robust: if the above computation is interrupted or an exception
occurs,
Such
? f()=bitprecision(1.0); ? f() %2 = 128 ? localbitprec(1000); f() %3 = 1024
Note that the bit precision of data (
Warning. Changing
? \p38 ? localprec(19); default(realprecision,1000); Pi %1 = 3.141592653589793239 ? \p realprecision = 1001 significant digits (1000 digits displayed)
Indeed,
| |
localprec(p) | |
Set the real precision to p in the dynamic scope and return p.
All computations are performed as if
my(prec = default(realprecision)); default(realprecision,p); ... default(realprecision, prec);
but is both less cumbersome, cleaner (no need to manipulate
a global variable, which in fact never changes and is only temporarily masked)
and more robust: if the above computation is interrupted or an exception
occurs,
Such
? f()=precision(1.); ? f() %2 = 38 ? localprec(19); f() %3 = 19
Warning. Changing
? \p38 ? localprec(19); default(realprecision,100); Pi %1 = 3.141592653589793239 ? \p realprecision = 115 significant digits (100 digits displayed)
Indeed,
| |
mapapply(~M, x, f, {u}) | |
Applies the closure f to the image y of x by the map M
and returns the evaluation f(y). The closure f is allowed to
modify the components of y in place. If M is not defined at x, and
the optional argument
To apply f to all entries (values) of M, use
* performing a computation on a value directly, without using
? M = Map(); mapput(~M, "a", mathilbert(2000)); ? matsize(mapget(M, "a")) \\ Slow because mapget(M, "a") copies the value %2 = [2000, 2000] time = 101 ms. ? mapapply(~M, "a", matsize) \\ Fast time = 0 ms. %3 = [2000, 2000]
* modifying a value in place, for example to append an element to a value
in a map of lists. This requires to use
? maplistput(~M, k, v) = mapapply(~M, k, (~y)->listput(~y,v), ()->List(v)); ? M = Map(); %2 = Map([;]) ? maplistput(~M, "a", 1); M %3 = Map(["a", List([1])]) ? maplistput(~M, "a", 2); M %4 = Map(["a", List([1, 2])]) ? maplistput(~M, "b", 3); M %5 = Map(["a", List([1, 2]); "b", List([3])]) ? maplistput(~M, "a", 4); M %6 = Map(["a", List([1, 2, 4]); "b", List([])])
The library syntax is
| |
mapdelete(~M, x) | |
Removes x from the domain of the map M.
? M = Map(["a",1; "b",3; "c",7]); ? mapdelete(M,"b"); ? Mat(M) ["a" 1] ["c" 7]
The library syntax is
| |
mapget(M, x) | |
Returns the image of x by the map M.
? M=Map(["a",23;"b",43]); ? mapget(M,"a") %2 = 23 ? mapget(M,"b") %3 = 43 Raises an exception when the key x is not present in M.
? mapget(M,"c") *** at top-level: mapget(M,"c") *** ^ — — — — - *** mapget: nonexistent component in mapget: index not in map
The library syntax is
| |
mapisdefined(M, x, {&z}) | |
Returns true (1) if x has an image by the map M, false (0) otherwise. If z is present, set z to the image of x, if it exists.
? M1 = Map([1, 10; 2, 20]); ? mapisdefined(M1,3) %1 = 0 ? mapisdefined(M1, 1, &z) %2 = 1 ? z %3 = 10
? M2 = Map(); N = 19; ? for (a=0, N-1, mapput(M2, a^3%N, a)); ? {for (a=0, N-1, if (mapisdefined(M2, a, &b), printf("%d is the cube of %d mod %d\n",a,b,N)));} 0 is the cube of 0 mod 19 1 is the cube of 11 mod 19 7 is the cube of 9 mod 19 8 is the cube of 14 mod 19 11 is the cube of 17 mod 19 12 is the cube of 15 mod 19 18 is the cube of 18 mod 19
The library syntax is
| |
mapput(~M, x, y) | |
Associates x to y in the map M. The value y can be retrieved
with
? M = Map(); ? mapput(~M, "foo", 23); ? mapput(~M, 7718, "bill"); ? mapget(M, "foo") %4 = 23 ? mapget(M, 7718) %5 = "bill" ? Vec(M) \\ keys %6 = [7718, "foo"] ? Mat(M) %7 = [ 7718 "bill"] ["foo" 23]
The library syntax is
| |
print({str}*) | |
Outputs its arguments in raw format ending with a newline. The arguments are converted to strings following the rules in Section se:strings.
? m = matid(2); ? print(m) \\ raw format [1, 0; 0, 1] ? printp(m) \\ prettymatrix format [1 0] [0 1]
The library syntax is
| |
print1({str}*) | |
Outputs its arguments in raw
format, without ending with a newline. Note that you can still embed newlines
within your strings, using the
The library syntax is
| |
printf(fmt, {x}*) | |
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
* conversions specifications (
More precisely, a conversion specification consists in a
The flag characters. The character
*
*
*
*
*
The field width. An optional decimal digit string (whose first
digit is nonzero) 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
The precision. An optional precision in the form of a period
(`
The length modifier. This is ignored under
*
* The conversion specifier. A character that specifies the type of conversion to be applied.
*
*
*
*
*
*
*
*
* 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 complex numbers, 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] ? printf("%.3g", Pi+I) 3.14+1.00I
Technical note. Our implementation of
* whenever a precision is missing, the current
* in conversion style
* in conversion style
* in conversion
The library syntax is
The variadic version
| |
printp({str}*) | |
Outputs its arguments in prettymatrix format, ending with a newline. The arguments are converted to strings following the rules in Section se:strings.
? m = matid(2); ? print(m) \\ raw format [1, 0; 0, 1] ? printp(m) \\ prettymatrix format [1 0] [0 1]
The library syntax is
| |
printsep(sep, {str}*) | |
Outputs its arguments in raw format, ending with a newline. The arguments are converted to strings following the rules in Section se:strings. Successive entries are separated by sep:
? printsep(":", 1,2,3,4) 1:2:3:4
The library syntax is
| |
printsep1(sep, {str}*) | |
Outputs its arguments in raw format, without ending with a newline. The arguments are converted to strings following the rules in Section se:strings. Successive entries are separated by sep:
? printsep1(":", 1,2,3,4);print("|") 1:2:3:4|
The library syntax is
| |
printtex({str}*) | |
Outputs its arguments in TeX format. This output can then be
used in a TeX manuscript, see
Another possibility is to enable the
default(logfile, "new.tex"); default(log, 1); printtex(result);
The library syntax is
| |
quit({status = 0}) | |
Exits
| |
read({filename}) | |
Reads in the file
filename (subject to string expansion). If filename is
omitted, re-reads the last file that was fed into
If a GP
In case the file you read in contains an
Variants.
The library syntax is
| |
readstr({filename}) | |
Reads in the file filename and return a vector of GP strings,
each component containing one line from the file. If filename is
omitted, re-reads the last file that was fed into
The library syntax is
| |
readvec({filename}) | |
Reads in the file
filename (subject to string expansion). If filename is
omitted, re-reads the last file that was fed into
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
The library syntax is
| |
select(f, A, {flag = 0}) | |
We first describe the default behavior, when flag is 0 or omitted.
Given a vector or list
? 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 i2+1 for some i ≤ 50,
then the elements less than 100 in the preceding result. The
Remark. For v a
[g(x) | x <- v, f(x)] [x | x <- v, f(x)] [g(x) | x <- v] are available as shortcuts for
apply(g, select(f, Vec(v))) select(f, Vec(v)) apply(g, Vec(v)) respectively:
? [ x | x <- vector(50,i,i^2+1), isprime(x) ] %1 = [2, 5, 17, 37, 101, 197, 257, 401, 577, 677, 1297, 1601] If flag = 1, this function returns instead the indices of the selected elements, and not the elements themselves (indirect selection):
? V = vector(50,i,i^2+1); ? select(x->isprime(x), V, 1) %2 = Vecsmall([1, 2, 4, 6, 10, 14, 16, 20, 24, 26, 36, 40]) ? vecextract(V, %) %3 = [2, 5, 17, 37, 101, 197, 257, 401, 577, 677, 1297, 1601] The following function lists the elements in (ℤ/Nℤ)*:
? invertibles(N) = select(x->gcd(x,N) == 1, [1..N]) Finally
? select(x->x, M)
selects the nonzero entries in
? select(x->!isprime(x), vector(50,i,i^2+1))
The library syntax is
| |
self() | |
Return the calling function or closure as a
? (n -> if(n==0,1,n*self()(n-1)))(5) %1 = 120 \\ 5! ? (n -> if(n<=1, n, self()(n-1)+self()(n-2)))(20) %2 = 6765 \\ Fibonacci(20)
The library syntax is
| |
setrand(n) | |
Reseeds the random number generator using the seed n. No value is
returned. The seed is a small positive integer 0 < n < 264 used to
generate deterministically a suitable state array. All gp session start
by an implicit
In the other direction, including a call to
For debugging purposes, one can also record a particular random state
using
? state = getrand(); \\ record seed ... ? setrand(state); \\ we can now replay the exact same computations
The library syntax is
| |
strchr(x) | |
Converts integer or vector of integers x to a string, translating each integer (in the range [1,255]) into a character using ASCII encoding.
? strchr(97) %1 = "a" ? Vecsmall("hello world") %2 = Vecsmall([104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]) ? strchr(%) %3 = "hello world"
The library syntax is
| |
strexpand({x}*) | |
Converts its argument list into a
single character string (type
? strexpand("$HOME/doc") %1 = "/home/pari/doc" ? module = "aprcl"; n = 10; ? strexpand("$HOME/doc/", module, n, ".tex") %3 = "/home/pari/doc/aprcl10.tex" The individual arguments are read in string context, see Section se:strings.
The library syntax is
| |
strjoin(v, {p = ""}) | |
Joins the strings in vector v, separating them with delimiter p.
The reverse operation is
? v = ["abc", "def", "ghi"] ? strjoin(v, "/") %2 = "abc/def/ghi" ? strjoin(v) %3 = "abcdefghi"
The library syntax is
| |
strprintf(fmt, {x}*) | |
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
? dir = "/home/pari"; file = "aprcl"; n = 10; ? strprintf("%s/%s%ld.tex", dir, file, n) %2 = "/home/pari/aprcl10.tex"
The library syntax is
The variadic version
| |
strsplit(s, {p = ""}) | |
Splits the string s into a vector of strings, with p acting as a delimiter. If p is empty or omitted, split the string into characters.
? strsplit("abc::def::ghi", "::") %1 = ["abc", "def", "ghi"] ? strsplit("abc", "") %2 = ["a", "b", "c"] ? strsplit("aba", "a") If s starts (resp. ends) with the pattern p, then the first (resp. last) entry in the vector is the empty string:
? strsplit("aba", "a") %3 = ["", "b", ""]
The library syntax is
| |
strtex({x}*) | |
Translates its arguments to TeX format, and concatenates the results into a
single character string (type The individual arguments are read in string context, see Section se:strings.
? v = [1, 2, 3] %1 [1, 2, 3] ? strtex(v) %2 = "\\pmatrix{ 1&2&3\\cr}\n"
TeX-nical notes. The TeX output engine was originally written
for plain TeX and designed for maximal portability. Unfortunately later
* if you enabled bit 4 in
* if you use plain TeX only: you must define
\def\frac#1#2{{#1\over#2}}
* if you use LaTeX and
The library syntax is
| |
strtime(t) | |
Return a string describing the time t in milliseconds in the format used by the GP timer.
? print(strtime(12345678)) 3h, 25min, 45,678 ms ? { my(t=getabstime()); F=factor(2^256+1);t=getabstime()-t; print("factor(2^256+1) took ",strtime(t)); } factor(2^256+1) took 1,320 ms
The library syntax is
| |
system(str) | |
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("test -d /") \\ test if '/' is a directory (true) %1 = 0 ? system("test -f /") \\ test if '/' is a file (false) %2 = 1
The library syntax is
| |
trap({e}, {rec}, seq) | |
This function is obsolete, use
This function 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 se:errorrec for an introduction to error recovery
under
? \\ trap division by 0 ? inv(x) = trap (e_INV, 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.17.0, 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
The library syntax is
| |
type(x) | |
This is useful only under
The library syntax is
| |
unexport(x, ..., z) | |
Remove x,..., z from the list of variables exported to the parallel world. See export.
| |
unexportall() | |
Empty the list of variables exported to the parallel world.
The library syntax is
| |
uninline() | |
Exit the scope of all current
| |
version() | |
Returns the current version number as a 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
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,
%1 = [2, 3, 4] \\ released version, stable branch %1 = [2, 4, 3] \\ released version, testing branch %1 = [2, 6, 1, 15174, ""505ab9b"] \\ development In particular, if you are only working with released versions, the first line of the gp introductory message can be emulated by
[M,m,p] = version(); printf("GP/PARI CALCULATOR Version %s.%s.%s", M,m,p); If you are working with many development versions of PARI/GP, the 4th and/or 5th components can be profitably included in the name of your logfiles, for instance.
Technical note. For development versions obtained via
The library syntax is
| |
warning({str}*) | |
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.")
The library syntax is
| |
whatnow(key) | |
If keyword key is the name of a function that was present in GP version 1.39.15, outputs the new function name and syntax, if it changed at all. Functions that where introduced since then, then modified are also recognized.
? whatnow("mu") New syntax: mu(n) ===> moebius(n) moebius(x): Moebius function of x. ? whatnow("sin") This function did not change When a function was removed and the underlying functionality is not available under a compatible interface, no equivalent is mentioned:
? whatnow("buchfu") This function no longer exists
(The closest equivalent would be to set
| |
write(filename, {str}*) | |
Writes (appends) to filename the remaining arguments, and appends a
newline (same output as
Variant. The high-level function
The library syntax is
| |
write1(filename, {str}*) | |
Writes (appends) to filename the remaining arguments without a
trailing newline (same output as
The library syntax is
| |
writebin(filename, {x}) | |
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
If x is omitted, saves all user variables from the session, together with
their names. Reading such a "named object" back in a
x = 1; writebin("log")
reading
Just as a regular input file, a binary file can be compressed
using
In the present implementation, the binary files are architecture dependent
and compatibility with future versions of
The library syntax is
| |
writetex(filename, {str}*) | |
As
The library syntax is
| |