As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) TeX and LaTeX source code syntax highlighting (style: standard) with prefixed line numbers.
Alternatively you can here view or download the uninterpreted source code file.

1 % Copyright (c) 2000 The PARI Group 2 % 3 % This file is part of the PARI/GP documentation 4 % 5 % Permission is granted to copy, distribute and/or modify this document 6 % under the terms of the GNU General Public License 7 \chapter{Functions and Operations Available in PARI and GP} 8 \label{se:functions} 9 10 The functions and operators available in PARI and in the GP/PARI calculator 11 are numerous and ever-expanding. Here is a description of the ones available 12 in version \vers. It should be noted that many of these functions accept 13 quite different types as arguments, but others are more restricted. The list 14 of acceptable types will be given for each function or class of functions. 15 Except when stated otherwise, it is understood that a function or operation 16 which should make natural sense is legal. 17 18 On the other hand, many routines list explicit preconditions for some of their 19 argument, e.g. $p$ is a prime number, or $q$ is a positive definite quadratic 20 form. For reasons of efficiency, all trust the user input and only perform 21 minimal sanity checks. When a precondition is not satisfied, any of the 22 following may occur: a regular exception is raised, the PARI stack overflows, a 23 \kbd{SIGSEGV} or \kbd{SIGBUS} signal is generated, or we enter an infinite 24 loop. The function can also quietly return a mathematically meaningless 25 result: junk in, junk out. 26 27 In this chapter, we will describe the functions according to a rough 28 classification. The general entry looks something like: 29 30 \key{foo}$(x,\{\fl=0\})$: short description. 31 32 The library syntax is \kbd{GEN foo(GEN x, long fl = 0)}. 33 34 \noindent 35 This means that the GP function \kbd{foo} has one mandatory argument $x$, and 36 an optional one, $\fl$, whose default value is 0. (The $\{\}$ should not be 37 typed, it is just a convenient notation we will use throughout to denote 38 optional arguments.) That is, you can type \kbd{foo(x,2)}, or \kbd{foo(x)}, 39 which is then understood to mean \kbd{foo(x,0)}. As well, a comma or closing 40 parenthesis, where an optional argument should have been, signals to GP it 41 should use the default. Thus, the syntax \kbd{foo(x,)} is also accepted as a 42 synonym for our last expression. When a function has more than one optional 43 argument, the argument list is filled with user supplied values, in order. 44 When none are left, the defaults are used instead. Thus, assuming that 45 \kbd{foo}'s prototype had been 46 $$\hbox{% 47 \key{foo}$(\{x=1\},\{y=2\},\{z=3\})$,% 48 }$$ 49 typing in \kbd{foo(6,4)} would give 50 you \kbd{foo(6,4,3)}. In the rare case when you want to set some far away 51 argument, and leave the defaults in between as they stand, you can use the 52 ``empty arg'' trick alluded to above: \kbd{foo(6,,1)} would yield 53 \kbd{foo(6,2,1)}. By the way, \kbd{foo()} by itself yields 54 \kbd{foo(1,2,3)} as was to be expected. 55 56 In this rather special case of a function having no mandatory argument, you 57 can even omit the $()$: a standalone \kbd{foo} would be enough (though we 58 do not recommend it for your scripts, for the sake of clarity). In defining 59 GP syntax, we strove to put optional arguments at the end of the argument 60 list (of course, since they would not make sense otherwise), and in order of 61 decreasing usefulness so that, most of the time, you will be able to ignore 62 them. 63 64 Finally, an optional argument (between braces) followed by a star, like 65 $\{\var{x}\}*$, means that any number of such arguments (possibly none) can 66 be given. This is in particular used by the various \kbd{print} routines. 67 68 \misctitle{Flags} A \tev{flag} is an argument which, rather than conveying 69 actual information to the routine, instructs it to change its default 70 behavior, e.g.~return more or less information. All such 71 flags are optional, and will be called \fl\ in the function descriptions to 72 follow. There are two different kind of flags 73 74 \item generic: all valid values for the flag are individually 75 described (``If \fl\ is equal to $1$, then\dots''). 76 77 \item binary:\sidx{binary flag} use customary binary notation as a 78 compact way to represent many toggles with just one integer. Let 79 $(p_0,\dots,p_n)$ be a list of switches (i.e.~of properties which take either 80 the value $0$ or~$1$), the number $2^3 + 2^5 = 40$ means that $p_3$ and $p_5$ 81 are set (that is, set to $1$), and none of the others are (that is, they 82 are set to $0$). This is announced as ``The binary digits of $\fl$ mean 1: 83 $p_0$, 2: $p_1$, 4: $p_2$'', and so on, using the available consecutive 84 powers of~$2$. 85 86 \misctitle{Mnemonics for binary flags} Numeric flags as mentioned above are 87 obscure, error-prone, and quite rigid: should the authors want to adopt a new 88 flag numbering scheme, it would break backward compatibility. The only 89 advantage of explicit numeric values is that they are fast to type, so their 90 use is only advised when using the calculator \kbd{gp}. 91 92 As an alternative, one can replace a binary flag by a character string 93 containing symbolic identifiers (mnemonics). In the function description, 94 mnemonics corresponding to the various toggles are given after each of them. 95 They can be negated by prepending \kbd{no\_} to the mnemonic, or by removing 96 such a prefix. These toggles are grouped together using any punctuation 97 character (such as ',' or ';'). For instance (taken from description of 98 $\tet{ploth}(X=a,b,\var{expr},\{\fl=0\},\{n=0\})$) 99 100 \centerline{Binary digits of flags mean: $1=\kbd{Parametric}$, 101 $2=\kbd{Recursive}$, \dots} 102 103 \noindent so that, instead of $1$, one could use the mnemonic 104 \kbd{"Parametric; no\_Recursive"}, or simply \kbd{"Parametric"} since 105 \kbd{Recursive} is unset by default (default value of $\fl$ is $0$, 106 i.e.~everything unset). People used to the bit-or notation in languages like 107 C may also use the form \kbd{"Parametric | no\_Recursive"}. 108 109 \misctitle{Pointers} \varsidx{pointer} If a parameter in the function 110 prototype is prefixed with a \& sign, as in 111 112 \key{foo}$(x,\&e)$ 113 114 \noindent it means that, besides the normal return value, the function may 115 assign a value to $e$ as a side effect. When passing the argument, the \& 116 sign has to be typed in explicitly. As of version \vers, this \tev{pointer} 117 argument is optional for all documented functions, hence the \& will always 118 appear between brackets as in \kbd{Z\_issquare}$(x,\{\&e\})$. 119 120 \misctitle{About library programming} 121 The \var{library} function \kbd{foo}, as defined at the beginning of this 122 section, is seen to have two mandatory arguments, $x$ and \fl: no function 123 seen in the present chapter has been implemented so as to accept a variable 124 number of arguments, so all arguments are mandatory when programming with the 125 library (usually, variants are provided corresponding to the various flag values). 126 We include an \kbd{= default value} token in the prototype to signal how a missing 127 argument should be encoded. Most of the time, it will be a \kbd{NULL} pointer, or 128 -1 for a variable number. Refer to the \emph{User's Guide to the PARI library} 129 for general background and details. 130 131 \section{Programming in GP: control statements} 132 \sidx{programming}\label{se:programming} 133 134 A number of control statements are available in GP. They are simpler and 135 have a syntax slightly different from their C counterparts, but are quite 136 powerful enough to write any kind of program. Some of them are specific to 137 GP, since they are made for number theorists. As usual, $X$ will denote any 138 simple variable name, and \var{seq} will always denote a sequence of 139 expressions, including the empty sequence. 140 141 \misctitle{Caveat} In constructs like 142 \bprog 143 for (X = a,b, seq) 144 @eprog\noindent 145 the variable \kbd{X} is lexically scoped to the loop, leading to possibly 146 unexpected behavior: 147 \bprog 148 n = 5; 149 for (n = 1, 10, 150 if (something_nice(), break); 151 ); 152 \\ @com at this point \kbd{n} is 5 ! 153 @eprog\noindent 154 If the sequence \kbd{seq} modifies the loop index, then the loop 155 is modified accordingly: 156 \bprog 157 ? for (n = 1, 10, n += 2; print(n)) 158 3 159 6 160 9 161 12 162 @eprog 163 164 \subsec{break$(\{n=1\})$}\kbdsidx{break}\label{se:break} 165 Interrupts execution of current \var{seq}, and 166 immediately exits from the $n$ innermost enclosing loops, within the 167 current function call (or the top level loop); the integer $n$ must be 168 positive. If $n$ is greater than the number of enclosing loops, all 169 enclosing loops are exited. 170 171 \subsec{breakpoint$()$}\kbdsidx{breakpoint}\label{se:breakpoint} 172 Interrupt the program and enter the breakloop. The program continues when 173 the breakloop is exited. 174 \bprog 175 ? f(N,x)=my(z=x^2+1);breakpoint();gcd(N,z^2+1-z); 176 ? f(221,3) 177 *** at top-level: f(221,3) 178 *** ^-------- 179 *** in function f: my(z=x^2+1);breakpoint();gcd(N,z 180 *** ^-------------------- 181 *** Break loop: type <Return> to continue; 'break' to go back to GP 182 break> z 183 10 184 break> 185 %2 = 13 186 @eprog 187 188 \subsec{dbg\_down$(\{n=1\})$}\kbdsidx{dbg_down}\label{se:dbg_down} 189 (In the break loop) go down n frames. This allows to cancel a previous 190 call to \kbd{dbg\_up}. 191 \bprog 192 ? x = 0; 193 ? g(x) = x-3; 194 ? f(x) = 1 / g(x+1); 195 ? for (x = 1, 5, f(x+1)) 196 *** at top-level: for(x=1,5,f(x+1)) 197 *** ^------- 198 *** in function f: 1/g(x+1) 199 *** ^------- 200 *** _/_: impossible inverse in gdiv: 0. 201 *** Break loop: type 'break' to go back to GP prompt 202 break> dbg_up(3) \\ go up 3 frames 203 *** at top-level: for(x=1,5,f(x+1)) 204 *** ^----------------- 205 break> x 206 0 207 break> dbg_down() 208 *** at top-level: for(x=1,5,f(x+1)) 209 *** ^------- 210 break> x 211 1 212 break> dbg_down() 213 *** at top-level: for(x=1,5,f(x+1)) 214 *** ^------- 215 break> x 216 1 217 break> dbg_down() 218 *** at top-level: for(x=1,5,f(x+1)) 219 *** ^------- 220 *** in function f: 1/g(x+1) 221 *** ^------- 222 break> x 223 2 224 @eprog\noindent The above example shows that the notion of GP frame is 225 finer than the usual stack of function calls (as given for instance by the 226 GDB \kbd{backtrace} command): GP frames are attached to variable scopes 227 and there are frames attached to control flow instructions such as a 228 \kbd{for} loop above. 229 230 \subsec{dbg\_err$()$}\kbdsidx{dbg_err}\label{se:dbg_err} 231 In the break loop, return the error data of the current error, if any. 232 See \tet{iferr} for details about error data. Compare: 233 \bprog 234 ? iferr(1/(Mod(2,12019)^(6!)-1),E,Vec(E)) 235 %1 = ["e_INV", "Fp_inv", Mod(119, 12019)] 236 ? 1/(Mod(2,12019)^(6!)-1) 237 *** at top-level: 1/(Mod(2,12019)^(6!)- 238 *** ^-------------------- 239 *** _/_: impossible inverse in Fp_inv: Mod(119, 12019). 240 *** Break loop: type 'break' to go back to GP prompt 241 break> Vec(dbg_err()) 242 ["e_INV", "Fp_inv", Mod(119, 12019)] 243 @eprog 244 245 \subsec{dbg\_up$(\{n=1\})$}\kbdsidx{dbg_up}\label{se:dbg_up} 246 (In the break loop) go up n frames, which allows to inspect data of the 247 parent function. To cancel a \tet{dbg_up} call, use \tet{dbg_down}. 248 \bprog 249 ? x = 0; 250 ? g(x) = x-3; 251 ? f(x) = 1 / g(x+1); 252 ? for (x = 1, 5, f(x+1)) 253 *** at top-level: for(x=1,5,f(x+1)) 254 *** ^------- 255 *** in function f: 1/g(x+1) 256 *** ^------- 257 *** _/_: impossible inverse in gdiv: 0. 258 *** Break loop: type 'break' to go back to GP prompt 259 break> x 260 2 261 break> dbg_up() 262 *** at top-level: for(x=1,5,f(x+1)) 263 *** ^------- 264 break> x 265 1 266 break> dbg_up() 267 *** at top-level: for(x=1,5,f(x+1)) 268 *** ^------- 269 break> x 270 1 271 break> dbg_up() 272 *** at top-level: for(x=1,5,f(x+1)) 273 *** ^----------------- 274 break> x 275 0 276 break> dbg_down() \\ back up once 277 *** at top-level: for(x=1,5,f(x+1)) 278 *** ^------- 279 break> x 280 1 281 @eprog\noindent The above example shows that the notion of GP frame is 282 finer than the usual stack of function calls (as given for instance by the 283 GDB \kbd{backtrace} command): GP frames are attached to variable scopes 284 and there are frames attached to control flow instructions such as a 285 \kbd{for} loop above. 286 287 \subsec{dbg\_x$(A,\{n\})$}\kbdsidx{dbg_x}\label{se:dbg_x} 288 Print the inner structure of \kbd{A}, complete if \kbd{n} is omitted, up 289 to level \kbd{n} otherwise. This is useful for debugging. This is similar to 290 \b{x} but does not require \kbd{A} to be an history entry. In particular, 291 it can be used in the break loop. 292 293 \subsec{for$(X=a,b,\var{seq})$}\kbdsidx{for}\label{se:for} 294 Evaluates \var{seq}, where 295 the formal variable $X$ goes from $a$ to $b$. Nothing is done if $a>b$. 296 $a$ and $b$ must be in $\R$. If $b$ is set to \kbd{+oo}, the loop will not 297 stop; it is expected that the caller will break out of the loop itself at some 298 point, using \kbd{break} or \kbd{return}. 299 300 \subsec{forcomposite$(n=a,\{b\},\var{seq})$}\kbdsidx{forcomposite}\label{se:forcomposite} 301 Evaluates \var{seq}, 302 where the formal variable $n$ ranges over the composite numbers between the 303 nonnegative real numbers $a$ to $b$, including $a$ and $b$ if they are 304 composite. Nothing is done if $a>b$. 305 \bprog 306 ? forcomposite(n = 0, 10, print(n)) 307 4 308 6 309 8 310 9 311 10 312 @eprog\noindent Omitting $b$ means we will run through all composites $\geq a$, 313 starting an infinite loop; it is expected that the user will break out of 314 the loop himself at some point, using \kbd{break} or \kbd{return}. 315 316 Note that the value of $n$ cannot be modified within \var{seq}: 317 \bprog 318 ? forcomposite(n = 2, 10, n = []) 319 *** at top-level: forcomposite(n=2,10,n=[]) 320 *** ^--- 321 *** index read-only: was changed to []. 322 @eprog 323 324 \subsec{fordiv$(n,X,\var{seq})$}\kbdsidx{fordiv}\label{se:fordiv} 325 Evaluates \var{seq}, where 326 the formal variable $X$ ranges through the divisors of $n$ 327 (see \tet{divisors}, which is used as a subroutine). It is assumed that 328 \kbd{factor} can handle $n$, without negative exponents. Instead of $n$, 329 it is possible to input a factorization matrix, i.e. the output of 330 \kbd{factor(n)}. 331 332 This routine uses \kbd{divisors} as a subroutine, then loops over the 333 divisors. In particular, if $n$ is an integer, divisors are sorted by 334 increasing size. 335 336 To avoid storing all divisors, possibly using a lot of memory, the following 337 (slower) routine loops over the divisors using essentially constant space: 338 \bprog 339 FORDIV(N)= 340 { my(F = factor(N), P = F[,1], E = F[,2]); 341 342 forvec(v = vector(#E, i, [0,E[i]]), X = factorback(P, v)); 343 } 344 ? for(i=1, 10^6, FORDIV(i)) 345 time = 11,180 ms. 346 ? for(i=1, 10^6, fordiv(i, d, )) 347 time = 2,667 ms. 348 @eprog\noindent Of course, the divisors are no longer sorted by inreasing 349 size. 350 351 \subsec{fordivfactored$(n,X,\var{seq})$}\kbdsidx{fordivfactored}\label{se:fordivfactored} 352 Evaluates \var{seq}, where 353 the formal variable $X$ ranges through $[d, \kbd{factor}(d)]$, 354 where $d$ is a divisors of $n$ 355 (see \tet{divisors}, which is used as a subroutine). Note that such a pair 356 is accepted as argument to all multiplicative functions. 357 358 It is assumed that 359 \kbd{factor} can handle $n$, without negative exponents. Instead of $n$, 360 it is possible to input a factorization matrix, i.e. the output of 361 \kbd{factor(n)}. This routine uses \kbd{divisors}$(,1)$ as a subroutine, 362 then loops over the divisors. In particular, if $n$ is an integer, divisors 363 are sorted by increasing size. 364 365 This function is particularly useful when $n$ is hard to factor and one 366 must evaluate multiplicative function on its divisors: we avoid 367 refactoring each divisor in turn. It also provides a small speedup 368 when $n$ is easy to factor; compare 369 \bprog 370 ? A = 10^8; B = A + 10^5; 371 ? for (n = A, B, fordiv(n, d, eulerphi(d))); 372 time = 2,091 ms. 373 ? for (n = A, B, fordivfactored(n, d, eulerphi(d))); 374 time = 1,298 ms. \\ avoid refactoring the divisors 375 ? forfactored (n = A, B, fordivfactored(n, d, eulerphi(d))); 376 time = 1,270 ms. \\ also avoid factoring the consecutive n's ! 377 @eprog 378 379 \subsec{foreach$(V,X,\var{seq})$}\kbdsidx{foreach}\label{se:foreach} 380 Evaluates \var{seq}, where the formal variable $X$ ranges through the 381 components of $V$ (\typ{VEC}, \typ{COL}, \typ{LIST} or \typ{MAT}). A matrix 382 argument is interpreted as a vector containing column vectors, as in 383 \kbd{Vec}$(V)$. 384 385 \subsec{forell$(E,a,b,\var{seq},\{\fl=0\})$}\kbdsidx{forell}\label{se:forell} 386 Evaluates \var{seq}, where the formal variable $E = [\var{name}, M, G]$ 387 ranges through all elliptic curves of conductors from $a$ to $b$. In this 388 notation \var{name} is the curve name in Cremona's elliptic curve database, 389 $M$ is the minimal model, $G$ is a $\Z$-basis of the free part of the 390 Mordell-Weil group $E(\Q)$. If flag is nonzero, select 391 only the first curve in each isogeny class. 392 \bprog 393 ? forell(E, 1, 500, my([name,M,G] = E); \ 394 if (#G > 1, print(name))) 395 389a1 396 433a1 397 446d1 398 ? c = 0; forell(E, 1, 500, c++); c \\ number of curves 399 %2 = 2214 400 ? c = 0; forell(E, 1, 500, c++, 1); c \\ number of isogeny classes 401 %3 = 971 402 @eprog\noindent 403 The \tet{elldata} database must be installed and contain data for the 404 specified conductors. 405 406 \synt{forell}{void *data, long (*f)(void*,GEN), long a, long b, long flag}. 407 408 \subsec{forfactored$(N=a,b,\var{seq})$}\kbdsidx{forfactored}\label{se:forfactored} 409 Evaluates \var{seq}, where 410 the formal variable $N$ is $[n, \kbd{factor}(n)]$ and $n$ goes from 411 $a$ to $b$; $a$ and $b$ must be integers. Nothing is done if $a>b$. 412 413 This function is only implemented for $|a|, |b| < 2^{64}$ ($2^{32}$ on a 32-bit 414 machine). It uses a sieve and runs in time $O(\sqrt{b} + b-a)$. It should 415 be at least 3 times faster than regular factorization as long as the interval 416 length $b-a$ is much larger than $\sqrt{b}$ and get relatively faster as 417 the bounds increase. The function slows down dramatically 418 if $\kbd{primelimit} < \sqrt{b}$. 419 420 \bprog 421 ? B = 10^9; 422 ? for (N = B, B+10^6, factor(N)) 423 time = 4,538 ms. 424 ? forfactored (N = B, B+10^6, [n,fan] = N) 425 time = 1,031 ms. 426 427 ? B = 10^11; 428 ? for (N = B, B+10^6, factor(N)) 429 time = 15,575 ms. 430 ? forfactored (N = B, B+10^6, [n,fan] = N) 431 time = 2,375 ms. 432 433 ? B = 10^14; 434 ? for (N = B, B+10^6, factor(N)) 435 time = 1min, 4,948 ms. 436 ? forfactored (N = B, B+10^6, [n,fan] = N) 437 time = 58,601 ms. 438 @eprog\noindent The last timing is with the default \kbd{primelimit} 439 (500000) which is much less than $\sqrt{B+10^6}$; it goes down 440 to \kbd{26,750ms} if \kbd{primelimit} gets bigger than that bound. 441 In any case $\sqrt{B+10^6}$ is much larger than the interval length $10^6$ 442 so \kbd{forfactored} gets relatively slower for that reason as well. 443 444 Note that all PARI multiplicative functions accept the \kbd{[n,fan]} 445 argument natively: 446 \bprog 447 ? s = 0; forfactored(N = 1, 10^7, s += moebius(N)*eulerphi(N)); s 448 time = 6,001 ms. 449 %1 = 6393738650 450 ? s = 0; for(N = 1, 10^7, s += moebius(N)*eulerphi(N)); s 451 time = 28,398 ms. \\ slower, we must factor N. Twice. 452 %2 = 6393738650 453 @eprog 454 455 The following loops over the fundamental dicriminants less than $X$: 456 \bprog 457 ? X = 10^8; 458 ? forfactored(d=1,X, if (isfundamental(d),)); 459 time = 34,030 ms. 460 ? for(d=1,X, if (isfundamental(d),)) 461 time = 1min, 24,225 ms. 462 @eprog 463 464 \subsec{forpart$(X=k,\var{seq},\{a=k\},\{n=k\})$}\kbdsidx{forpart}\label{se:forpart} 465 Evaluate \var{seq} over the partitions $X=[x_1,\dots x_n]$ of the 466 integer $k$, i.e.~increasing sequences $x_1\leq x_2\dots \leq x_n$ of sum 467 $x_1+\dots + x_n=k$. By convention, $0$ admits only the empty partition and 468 negative numbers have no partitions. A partition is given by a 469 \typ{VECSMALL}, where parts are sorted in nondecreasing order. The 470 partitions are listed by increasing size and in lexicographic order when 471 sizes are equal: 472 \bprog 473 ? forpart(X=4, print(X)) 474 Vecsmall([4]) 475 Vecsmall([1, 3]) 476 Vecsmall([2, 2]) 477 Vecsmall([1, 1, 2]) 478 Vecsmall([1, 1, 1, 1]) 479 @eprog\noindent Optional parameters $n$ and $a$ are as follows: 480 481 \item $n=\var{nmax}$ (resp. $n=[\var{nmin},\var{nmax}]$) restricts 482 partitions to length less than $\var{nmax}$ (resp. length between 483 $\var{nmin}$ and $nmax$), where the \emph{length} is the number of nonzero 484 entries. 485 486 \item $a=\var{amax}$ (resp. $a=[\var{amin},\var{amax}]$) restricts the parts 487 to integers less than $\var{amax}$ (resp. between $\var{amin}$ and 488 $\var{amax}$). 489 490 By default, parts are positive and we remove zero entries unless $amin\leq0$, 491 in which case we fix the size $\#X = \var{nmax}$: 492 \bprog 493 \\ at most 3 nonzero parts, all <= 4 494 ? forpart(v=5,print(Vec(v)), 4, 3) 495 [1, 4] 496 [2, 3] 497 [1, 1, 3] 498 [1, 2, 2] 499 500 \\ between 2 and 4 parts less than 5, fill with zeros 501 ? forpart(v=5,print(Vec(v)),[0,5],[2,4]) 502 [0, 0, 1, 4] 503 [0, 0, 2, 3] 504 [0, 1, 1, 3] 505 [0, 1, 2, 2] 506 [1, 1, 1, 2] 507 508 \\ no partitions of 1 with 2 to 4 nonzero parts 509 ? forpart(v=1,print(v),[0,5],[2,4]) 510 ? 511 @eprog\noindent 512 The behavior is unspecified if $X$ is modified inside the loop. 513 514 \synt{forpart}{void *data, long (*call)(void*,GEN), long k, GEN a, GEN n}. 515 516 \subsec{forperm$(a,p,\var{seq})$}\kbdsidx{forperm}\label{se:forperm} 517 Evaluates \var{seq}, where the formal variable $p$ goes through some 518 permutations given by a \typ{VECSMALL}. If $a$ is a positive integer then 519 $P$ goes through the permutations of $\{1, 2, ..., a\}$ in lexicographic 520 order and if $a$ is a small vector then $p$ goes through the 521 (multi)permutations lexicographically larger than or equal to $a$. 522 \bprog 523 ? forperm(3, p, print(p)) 524 Vecsmall([1, 2, 3]) 525 Vecsmall([1, 3, 2]) 526 Vecsmall([2, 1, 3]) 527 Vecsmall([2, 3, 1]) 528 Vecsmall([3, 1, 2]) 529 Vecsmall([3, 2, 1]) 530 @eprog\noindent 531 532 When $a$ is itself a \typ{VECSMALL} or a \typ{VEC} then $p$ iterates through 533 multipermutations 534 \bprog 535 ? forperm([2,1,1,3], p, print(p)) 536 Vecsmall([2, 1, 1, 3]) 537 Vecsmall([2, 1, 3, 1]) 538 Vecsmall([2, 3, 1, 1]) 539 Vecsmall([3, 1, 1, 2]) 540 Vecsmall([3, 1, 2, 1]) 541 Vecsmall([3, 2, 1, 1]) 542 @eprog\noindent 543 544 \subsec{forprime$(p=a,\{b\},\var{seq})$}\kbdsidx{forprime}\label{se:forprime} 545 Evaluates \var{seq}, 546 where the formal variable $p$ ranges over the prime numbers between the real 547 numbers $a$ to $b$, including $a$ and $b$ if they are prime. More precisely, 548 the value of 549 $p$ is incremented to \kbd{nextprime($p$ + 1)}, the smallest prime strictly 550 larger than $p$, at the end of each iteration. Nothing is done if $a>b$. 551 \bprog 552 ? forprime(p = 4, 10, print(p)) 553 5 554 7 555 @eprog\noindent Setting $b$ to \kbd{+oo} means we will run through all primes 556 $\geq a$, starting an infinite loop; it is expected that the caller will break 557 out of the loop itself at some point, using \kbd{break} or \kbd{return}. 558 559 Note that the value of $p$ cannot be modified within \var{seq}: 560 \bprog 561 ? forprime(p = 2, 10, p = []) 562 *** at top-level: forprime(p=2,10,p=[]) 563 *** ^--- 564 *** prime index read-only: was changed to []. 565 @eprog 566 567 \subsec{forprimestep$(p=a,b,q,\var{seq})$}\kbdsidx{forprimestep}\label{se:forprimestep} 568 Evaluates \var{seq}, 569 where the formal variable $p$ ranges over the prime numbers $p$ 570 in an arithmetic progression in $[a,b]$: $q$ is either an integer 571 ($p \equiv a \pmod{q}$) or an intmod \kbd{Mod(c,N)} and we restrict 572 to that congruence class. Nothing is done if $a>b$. 573 \bprog 574 ? forprimestep(p = 4, 30, 5, print(p)) 575 19 576 29 577 ? forprimestep(p = 4, 30, Mod(1,5), print(p)) 578 11 579 @eprog\noindent Setting $b$ to \kbd{+oo} means we will run through all primes 580 $\geq a$, starting an infinite loop; it is expected that the caller will break 581 out of the loop itself at some point, using \kbd{break} or \kbd{return}. 582 583 The current implementation restricts the modulus of the arithmetic 584 progression to an unsigned long (64 or 32 bits). 585 \bprog 586 ? forprimestep(p=2,oo,2^64,print(p)) 587 *** at top-level: forprimestep(p=2,oo,2^64,print(p)) 588 *** ^---------------------------------- 589 *** forprimestep: overflow in t_INT-->ulong assignment. 590 @eprog 591 592 Note that the value of $p$ cannot be modified within \var{seq}: 593 \bprog 594 ? forprimestep(p = 2, 10, 3, p = []) 595 *** at top-level: forprimestep(p=2,10,3,p=[]) 596 *** ^--- 597 *** prime index read-only: was changed to []. 598 @eprog 599 600 \subsec{forsquarefree$(N=a,b,\var{seq})$}\kbdsidx{forsquarefree}\label{se:forsquarefree} 601 Evaluates \var{seq}, where the formal variable $N$ is $[n, 602 \kbd{factor}(n)]$ and $n$ goes through squarefree integers from $a$ to $b$; 603 $a$ and $b$ must be integers. Nothing is done if $a>b$. 604 605 \bprog 606 ? forsquarefree(N=-3,9,print(N)) 607 [-3, [-1, 1; 3, 1]] 608 [-2, [-1, 1; 2, 1]] 609 [-1, Mat([-1, 1])] 610 [1, matrix(0,2)] 611 [2, Mat([2, 1])] 612 [3, Mat([3, 1])] 613 [5, Mat([5, 1])] 614 [6, [2, 1; 3, 1]] 615 [7, Mat([7, 1])] 616 @eprog 617 618 This function is only implemented for $|a|, |b| < 2^{64}$ ($2^{32}$ on a 32-bit 619 machine). It uses a sieve and runs in time $O(\sqrt{b} + b-a)$. It should 620 be at least 5 times faster than regular factorization as long as the interval 621 length $b-a$ is much larger than $\sqrt{b}$ and get relatively faster as 622 the bounds increase. The function slows down dramatically 623 if $\kbd{primelimit} < \sqrt{b}$. It is comparable to \kbd{forfactored}, but 624 about $\zeta(2) = \pi^2/6$ times faster due to the relative density 625 of squarefree integers. 626 627 \bprog 628 ? B = 10^9; 629 ? for (N = B, B+10^6, factor(N)) 630 time = 4,392 ms. 631 ? forfactored (N = B, B+10^6, [n,fan] = N) 632 time = 915 ms. 633 ? forsquarefree (N = B, B+10^6, [n,fan] = N) 634 time = 532 ms. 635 636 ? B = 10^11; 637 ? for (N = B, B+10^6, factor(N)) 638 time = 13,053 ms. 639 ? forfactored (N = B, B+10^6, [n,fan] = N) 640 time = 1,976 ms. 641 ? forsquarefree (N = B, B+10^6, [n,fan] = N) 642 time = 1,245 ms. 643 644 ? B = 10^14; 645 ? for (N = B, B+10^6, factor(N)) 646 time = 50,612 ms. 647 ? forsquarefree (N = B, B+10^6, [n,fan] = N) 648 time = 46,309 ms. 649 @eprog\noindent The last timing is with the default \kbd{primelimit} 650 (500000) which is much less than $\sqrt{B+10^6}$; it goes down 651 to \kbd{20,396ms} if \kbd{primelimit} gets bigger than that bound. 652 In any case $\sqrt{B+10^6}$ is much larger than the interval length $10^6$ 653 so \kbd{forsquarefree} gets relatively slower for that reason as well. 654 655 Note that all PARI multiplicative functions accept the \kbd{[n,fan]} 656 argument natively: 657 \bprog 658 ? s = 0; forsquarefree(N = 1, 10^7, s += moebius(N)*eulerphi(N)); s 659 time = 3,788 ms. 660 %1 = 6393738650 661 ? s = 0; for(N = 1, 10^7, s += moebius(N)*eulerphi(N)); s 662 time = 28,630 ms. \\ slower, we must factor N. Twice. 663 %2 = 6393738650 664 @eprog 665 666 The following loops over the fundamental dicriminants less than $X$: 667 \bprog 668 ? X = 10^8; 669 ? for(d=1,X, if (isfundamental(d),)) 670 time = 1min, 29,066 ms. 671 ? forfactored(d=1,X, if (isfundamental(d),)); 672 time = 42,387 ms. 673 ? forsquarefree(d=1,X, D = quaddisc(d); if (D <= X, )); 674 time = 32,479 ms. 675 @eprog\noindent Note that in the last loop, the fundamental discriminants 676 $D$ are not evaluated in order (since \kbd{quaddisc(d)} for squarefree $d$ 677 is either $d$ or $4d$). This is the price we pay for a faster evaluation, 678 and the set of numbers we run through is the same. 679 680 We can run through negative fundamental discriminants in the same way 681 \bprog 682 ? forsquarefree(d=-X,-1, D = quaddisc(d); if (D >= -X, )); 683 @eprog 684 685 \subsec{forstep$(X=a,b,s,\var{seq})$}\kbdsidx{forstep}\label{se:forstep} 686 Evaluates \var{seq}, where the formal variable $X$ goes from $a$ to $b$ 687 in increments of $s$. Nothing is done if $s>0$ and $a>b$ or if $s<0$ 688 and $a<b$. $s$ must be in $\R^*$ or an intmod \kbd{Mod(c,N)} (restrict to 689 the corresponding arithmetic progression) or a vector of steps 690 $[s_1,\dots,s_n]$ (the successive steps in $\R^*$ are used in the order they 691 appear in $s$). 692 693 \bprog 694 ? forstep(x=5, 10, 2, print(x)) 695 5 696 7 697 9 698 ? forstep(x=5, 10, Mod(1,3), print(x)) 699 7 700 10 701 ? forstep(x=5, 10, [1,2], print(x)) 702 5 703 6 704 8 705 9 706 @eprog\noindent Setting $b$ to \kbd{+oo} will start an infinite loop; it is 707 expected that the caller will break out of the loop itself at some point, 708 using \kbd{break} or \kbd{return}. 709 710 \subsec{forsubgroup$(H=G,\{\var{bound}\},\var{seq})$}\kbdsidx{forsubgroup}\label{se:forsubgroup} 711 Evaluates \var{seq} for 712 each subgroup $H$ of the \emph{abelian} group $G$ (given in 713 SNF\sidx{Smith normal form} form or as a vector of elementary divisors). 714 715 If \var{bound} is present, and is a positive integer, restrict the output to 716 subgroups of index less than \var{bound}. If \var{bound} is a vector 717 containing a single positive integer $B$, then only subgroups of index 718 exactly equal to $B$ are computed 719 720 The subgroups are not ordered in any 721 obvious way, unless $G$ is a $p$-group in which case Birkhoff's algorithm 722 produces them by decreasing index. A \idx{subgroup} is given as a matrix 723 whose columns give its generators on the implicit generators of $G$. For 724 example, the following prints all subgroups of index less than 2 in $G = 725 \Z/2\Z g_1 \times \Z/2\Z g_2$: 726 727 \bprog 728 ? G = [2,2]; forsubgroup(H=G, 2, print(H)) 729 [1; 1] 730 [1; 2] 731 [2; 1] 732 [1, 0; 1, 1] 733 @eprog\noindent 734 The last one, for instance is generated by $(g_1, g_1 + g_2)$. This 735 routine is intended to treat huge groups, when \tet{subgrouplist} is not an 736 option due to the sheer size of the output. 737 738 For maximal speed the subgroups have been left as produced by the algorithm. 739 To print them in canonical form (as left divisors of $G$ in HNF form), one 740 can for instance use 741 \bprog 742 ? G = matdiagonal([2,2]); forsubgroup(H=G, 2, print(mathnf(concat(G,H)))) 743 [2, 1; 0, 1] 744 [1, 0; 0, 2] 745 [2, 0; 0, 1] 746 [1, 0; 0, 1] 747 @eprog\noindent 748 Note that in this last representation, the index $[G:H]$ is given by the 749 determinant. See \tet{galoissubcyclo} and \tet{galoisfixedfield} for 750 applications to \idx{Galois} theory. 751 752 \synt{forsubgroup}{void *data, long (*call)(void*,GEN), GEN G, GEN bound}. 753 754 \subsec{forsubset$(\var{nk}, s, \var{seq})$}\kbdsidx{forsubset}\label{se:forsubset} 755 If \var{nk} is a nonnegative integer $n$, evaluates \kbd{seq}, where 756 the formal variable $s$ goes through all subsets of $\{1, 2, \ldots, n\}$; 757 if \var{nk} is a pair $[n,k]$ of integers, $s$ goes through subsets 758 of size $k$ of $\{1, 2, \ldots, n\}$. In both cases $s$ goes through subsets 759 in lexicographic order among subsets of the same size and smaller subsets 760 come first. 761 \bprog 762 ? forsubset([5,3], s, print(s)) 763 Vecsmall([1, 2, 3]) 764 Vecsmall([1, 2, 4]) 765 Vecsmall([1, 2, 5]) 766 Vecsmall([1, 3, 4]) 767 Vecsmall([1, 3, 5]) 768 Vecsmall([1, 4, 5]) 769 Vecsmall([2, 3, 4]) 770 Vecsmall([2, 3, 5]) 771 Vecsmall([2, 4, 5]) 772 Vecsmall([3, 4, 5]) 773 @eprog 774 775 \bprog 776 ? forsubset(3, s, print(s)) 777 Vecsmall([]) 778 Vecsmall([1]) 779 Vecsmall([2]) 780 Vecsmall([3]) 781 Vecsmall([1, 2]) 782 Vecsmall([1, 3]) 783 Vecsmall([2, 3]) 784 Vecsmall([1, 2, 3]) 785 @eprog\noindent The running time is proportional to the number 786 of subsets enumerated, respectively $2^n$ and \kbd{binomial}$(n,k)$: 787 \bprog 788 ? c = 0; forsubset([40,35],s,c++); c 789 time = 128 ms. 790 %4 = 658008 791 ? binomial(40,35) 792 %5 = 658008 793 @eprog 794 795 \subsec{forvec$(X=v,\var{seq},\{\fl=0\})$}\kbdsidx{forvec}\label{se:forvec} 796 Let $v$ be an $n$-component vector (where $n$ is arbitrary) of 797 two-component vectors $[a_i,b_i]$ for $1\le i\le n$, where all entries $a_i$, 798 $b_i$ are real numbers. This routine lets $X$ vary over the $n$-dimensional 799 box given by $v$ with unit steps: $X$ is an $n$-dimensional vector whose $i$-th 800 entry $X[i]$ runs through $a_i, a_i+1, a_i+2, \dots $ stopping with the 801 first value greater than $b_i$ (note that neither $a_i$ nor $b_i - a_i$ 802 are required to be integers). The values of $X$ are ordered 803 lexicographically, like embedded \kbd{for} loops, and the expression 804 \var{seq} is evaluated with the successive values of $X$. The type of $X$ is 805 the same as the type of $v$: \typ{VEC} or \typ{COL}. 806 807 If $\fl=1$, generate only nondecreasing vectors $X$, and 808 if $\fl=2$, generate only strictly increasing vectors $X$. 809 \bprog 810 ? forvec (X=[[0,1],[-1,1]], print(X)); 811 [0, -1] 812 [0, 0] 813 [0, 1] 814 [1, -1] 815 [1, 0] 816 [1, 1] 817 ? forvec (X=[[0,1],[-1,1]], print(X), 1); 818 [0, 0] 819 [0, 1] 820 [1, 1] 821 ? forvec (X=[[0,1],[-1,1]], print(X), 2) 822 [0, 1] 823 @eprog 824 825 \subsec{if$(a,\{\var{seq1}\},\{\var{seq2}\})$}\kbdsidx{if}\label{se:if} 826 Evaluates the expression sequence \var{seq1} if $a$ is nonzero, otherwise 827 the expression \var{seq2}. Of course, \var{seq1} or \var{seq2} may be empty: 828 829 \kbd{if ($a$,\var{seq})} evaluates \var{seq} if $a$ is not equal to zero 830 (you don't have to write the second comma), and does nothing otherwise, 831 832 \kbd{if ($a$,,\var{seq})} evaluates \var{seq} if $a$ is equal to zero, and 833 does nothing otherwise. You could get the same result using the \kbd{!} 834 (\kbd{not}) operator: \kbd{if (!$a$,\var{seq})}. 835 836 The value of an \kbd{if} statement is the value of the branch that gets 837 evaluated: for instance 838 \bprog 839 x = if(n % 4 == 1, y, z); 840 @eprog\noindent sets $x$ to $y$ if $n$ is $1$ modulo $4$, and to $z$ 841 otherwise. 842 843 Successive 'else' blocks can be abbreviated in a single compound \kbd{if} 844 as follows: 845 \bprog 846 if (test1, seq1, 847 test2, seq2, 848 ... 849 testn, seqn, 850 seqdefault); 851 @eprog\noindent is equivalent to 852 \bprog 853 if (test1, seq1 854 , if (test2, seq2 855 , ... 856 if (testn, seqn, seqdefault)...)); 857 @eprog For instance, this allows to write traditional switch / case 858 constructions: 859 \bprog 860 if (x == 0, do0(), 861 x == 1, do1(), 862 x == 2, do2(), 863 dodefault()); 864 @eprog 865 866 \misctitle{Remark} 867 The boolean operators \kbd{\&\&} and \kbd{||} are evaluated 868 according to operator precedence as explained in \secref{se:operators}, but, 869 contrary to other operators, the evaluation of the arguments is stopped 870 as soon as the final truth value has been determined. For instance 871 \bprog 872 if (x != 0 && f(1/x), ...) 873 @eprog 874 \noindent is a perfectly safe statement. 875 876 \misctitle{Remark} Functions such as \kbd{break} and \kbd{next} operate on 877 \emph{loops}, such as \kbd{for$xxx$}, \kbd{while}, \kbd{until}. The \kbd{if} 878 statement is \emph{not} a loop. (Obviously!) 879 880 \subsec{iferr$(\var{seq1},E,\var{seq2},\{\var{pred}\})$}\kbdsidx{iferr}\label{se:iferr} 881 Evaluates the expression sequence \var{seq1}. If an error occurs, 882 set the formal parameter \var{E} set to the error data. 883 If \var{pred} is not present or evaluates to true, catch the error 884 and evaluate \var{seq2}. Both \var{pred} and \var{seq2} can reference \var{E}. 885 The error type is given by \kbd{errname(E)}, and other data can be 886 accessed using the \tet{component} function. The code \var{seq2} should check 887 whether the error is the one expected. In the negative the error can be 888 rethrown using \tet{error(E)} (and possibly caught by an higher \kbd{iferr} 889 instance). The following uses \kbd{iferr} to implement Lenstra's ECM factoring 890 method 891 \bprog 892 ? ecm(N, B = 1000!, nb = 100)= 893 { 894 for(a = 1, nb, 895 iferr(ellmul(ellinit([a,1]*Mod(1,N)), [0,1]*Mod(1,N), B), 896 E, return(gcd(lift(component(E,2)),N)), 897 errname(E)=="e_INV" && type(component(E,2)) == "t_INTMOD")) 898 } 899 ? ecm(2^101-1) 900 %2 = 7432339208719 901 @eprog 902 The return value of \kbd{iferr} itself is the value of \var{seq2} if an 903 error occurs, and the value of \var{seq1} otherwise. We now describe the 904 list of valid error types, and the attached error data \var{E}; in each 905 case, we list in order the components of \var{E}, accessed via 906 \kbd{component(E,1)}, \kbd{component(E,2)}, etc. 907 908 \misctitle{Internal errors, ``system'' errors} 909 910 \item \kbd{"e\_ARCH"}. A requested feature $s$ is not available on this 911 architecture or operating system. 912 \var{E} has one component (\typ{STR}): the missing feature name $s$. 913 914 \item \kbd{"e\_BUG"}. A bug in the PARI library, in function $s$. 915 \var{E} has one component (\typ{STR}): the function name $s$. 916 917 \item \kbd{"e\_FILE"}. Error while trying to open a file. 918 \var{E} has two components, 1 (\typ{STR}): the file type (input, output, 919 etc.), 2 (\typ{STR}): the file name. 920 921 \item \kbd{"e\_IMPL"}. A requested feature $s$ is not implemented. 922 \var{E} has one component, 1 (\typ{STR}): the feature name $s$. 923 924 \item \kbd{"e\_PACKAGE"}. Missing optional package $s$. 925 \var{E} has one component, 1 (\typ{STR}): the package name $s$. 926 927 \misctitle{Syntax errors, type errors} 928 929 \item \kbd{"e\_DIM"}. The dimensions of arguments $x$ and $y$ submitted 930 to function $s$ does not match up. 931 E.g., multiplying matrices of inconsistent dimension, adding vectors of 932 different lengths,\dots 933 \var{E} has three component, 1 (\typ{STR}): the function name $s$, 2: the 934 argument $x$, 3: the argument $y$. 935 936 \item \kbd{"e\_FLAG"}. A flag argument is out of bounds in function $s$. 937 \var{E} has one component, 1 (\typ{STR}): the function name $s$. 938 939 \item \kbd{"e\_NOTFUNC"}. Generated by the PARI evaluator; tried to use a 940 \kbd{GEN} $x$ which is not a \typ{CLOSURE} in a function call syntax (as in 941 \kbd{f = 1; f(2);}). 942 \var{E} has one component, 1: the offending \kbd{GEN} $x$. 943 944 \item \kbd{"e\_OP"}. Impossible operation between two objects than cannot 945 be typecast to a sensible common domain for deeper reasons than a type 946 mismatch, usually for arithmetic reasons. As in \kbd{O(2) + O(3)}: it is 947 valid to add two \typ{PADIC}s, provided the underlying prime is the same; so 948 the addition is not forbidden a priori for type reasons, it only becomes so 949 when inspecting the objects and trying to perform the operation. 950 \var{E} has three components, 1 (\typ{STR}): the operator name \var{op}, 951 2: first argument, 3: second argument. 952 953 \item \kbd{"e\_TYPE"}. An argument $x$ of function $s$ had an unexpected type. 954 (As in \kbd{factor("blah")}.) 955 \var{E} has two components, 1 (\typ{STR}): the function name $s$, 956 2: the offending argument $x$. 957 958 \item \kbd{"e\_TYPE2"}. Forbidden operation between two objects than cannot be 959 typecast to a sensible common domain, because their types do not match up. 960 (As in \kbd{Mod(1,2) + Pi}.) 961 \var{E} has three components, 1 (\typ{STR}): the operator name \var{op}, 962 2: first argument, 3: second argument. 963 964 \item \kbd{"e\_PRIORITY"}. Object $o$ in function $s$ contains 965 variables whose priority is incompatible with the expected operation. 966 E.g.~\kbd{Pol([x,1], 'y)}: this raises an error because it's not possible to 967 create a polynomial whose coefficients involve variables with higher priority 968 than the main variable. $E$ has four components: 1 (\typ{STR}): the function 969 name $s$, 2: the offending argument $o$, 3 (\typ{STR}): an operator 970 $\var{op}$ describing the priority error, 4 (\typ{POL}): 971 the variable $v$ describing the priority error. The argument 972 satisfies $\kbd{variable}(x)~\var{op} \kbd{variable}(v)$. 973 974 \item \kbd{"e\_VAR"}. The variables of arguments $x$ and $y$ submitted 975 to function $s$ does not match up. E.g., considering the algebraic number 976 \kbd{Mod(t,t\pow2+1)} in \kbd{nfinit(x\pow2+1)}. 977 \var{E} has three component, 1 (\typ{STR}): the function name $s$, 2 978 (\typ{POL}): the argument $x$, 3 (\typ{POL}): the argument $y$. 979 980 \misctitle{Overflows} 981 982 \item \kbd{"e\_COMPONENT"}. Trying to access an inexistent component in a 983 vector/matrix/list in a function: the index is less than $1$ or greater 984 than the allowed length. 985 \var{E} has four components, 986 1 (\typ{STR}): the function name 987 2 (\typ{STR}): an operator $\var{op}$ ($<$ or $>$), 988 2 (\typ{GEN}): a numerical limit $l$ bounding the allowed range, 989 3 (\kbd{GEN}): the index $x$. It satisfies $x$ \var{op} $l$. 990 991 \item \kbd{"e\_DOMAIN"}. An argument is not in the function's domain. 992 \var{E} has five components, 1 (\typ{STR}): the function name, 993 2 (\typ{STR}): the mathematical name of the out-of-domain argument 994 3 (\typ{STR}): an operator $\var{op}$ describing the domain error, 995 4 (\typ{GEN}): the numerical limit $l$ describing the domain error, 996 5 (\kbd{GEN}): the out-of-domain argument $x$. The argument satisfies $x$ 997 \var{op} $l$, which prevents it from belonging to the function's domain. 998 999 \item \kbd{"e\_MAXPRIME"}. A function using the precomputed list of prime 1000 numbers ran out of primes. 1001 \var{E} has one component, 1 (\typ{INT}): the requested prime bound, which 1002 overflowed \kbd{primelimit} or $0$ (bound is unknown). 1003 1004 \item \kbd{"e\_MEM"}. A call to \tet{pari_malloc} or \tet{pari_realloc} 1005 failed. \var{E} has no component. 1006 1007 \item \kbd{"e\_OVERFLOW"}. An object in function $s$ becomes too large to be 1008 represented within PARI's hardcoded limits. (As in \kbd{2\pow2\pow2\pow10} or 1009 \kbd{exp(1e100)}, which overflow in \kbd{lg} and \kbd{expo}.) 1010 \var{E} has one component, 1 (\typ{STR}): the function name $s$. 1011 1012 \item \kbd{"e\_PREC"}. Function $s$ fails because input accuracy is too low. 1013 (As in \kbd{floor(1e100)} at default accuracy.) 1014 \var{E} has one component, 1 (\typ{STR}): the function name $s$. 1015 1016 \item \kbd{"e\_STACK"}. The PARI stack overflows. 1017 \var{E} has no component. 1018 1019 \misctitle{Errors triggered intentionally} 1020 1021 \item \kbd{"e\_ALARM"}. A timeout, generated by the \tet{alarm} function. 1022 \var{E} has one component (\typ{STR}): the error message to print. 1023 1024 \item \kbd{"e\_USER"}. A user error, as triggered by 1025 \tet{error}($g_1,\dots,g_n)$. 1026 \var{E} has one component, 1 (\typ{VEC}): the vector of $n$ arguments given 1027 to \kbd{error}. 1028 1029 \misctitle{Mathematical errors} 1030 1031 \item \kbd{"e\_CONSTPOL"}. An argument of function $s$ is a constant 1032 polynomial, which does not make sense. (As in \kbd{galoisinit(Pol(1))}.) 1033 \var{E} has one component, 1 (\typ{STR}): the function name $s$. 1034 1035 \item \kbd{"e\_COPRIME"}. Function $s$ expected coprime arguments, 1036 and did receive $x,y$, which were not. 1037 \var{E} has three component, 1 (\typ{STR}): the function name $s$, 1038 2: the argument $x$, 3: the argument $y$. 1039 1040 \item \kbd{"e\_INV"}. Tried to invert a noninvertible object $x$ in 1041 function $s$. 1042 \var{E} has two components, 1 (\typ{STR}): the function name $s$, 1043 2: the noninvertible $x$. If $x = \kbd{Mod}(a,b)$ 1044 is a \typ{INTMOD} and $a$ is not $0$ mod $b$, this allows to factor 1045 the modulus, as \kbd{gcd}$(a,b)$ is a nontrivial divisor of $b$. 1046 1047 \item \kbd{"e\_IRREDPOL"}. Function $s$ expected an irreducible polynomial, 1048 and did receive $T$, which was not. (As in \kbd{nfinit(x\pow2-1)}.) 1049 \var{E} has two component, 1 (\typ{STR}): the function name $s$, 1050 2 (\typ{POL}): the polynomial $x$. 1051 1052 \item \kbd{"e\_MISC"}. Generic uncategorized error. 1053 \var{E} has one component (\typ{STR}): the error message to print. 1054 1055 \item \kbd{"e\_MODULUS"}. moduli $x$ and $y$ submitted to function $s$ are 1056 inconsistent. As in 1057 \bprog 1058 nfalgtobasis(nfinit(t^3-2), Mod(t,t^2+1) 1059 @eprog\noindent 1060 \var{E} has three component, 1 (\typ{STR}): the function $s$, 1061 2: the argument $x$, 3: the argument $x$. 1062 1063 \item \kbd{"e\_PRIME"}. Function $s$ expected a prime number, 1064 and did receive $p$, which was not. (As in \kbd{idealprimedec(nf, 4)}.) 1065 \var{E} has two component, 1 (\typ{STR}): the function name $s$, 1066 2: the argument $p$. 1067 1068 \item \kbd{"e\_ROOTS0"}. An argument of function $s$ is a zero polynomial, 1069 and we need to consider its roots. (As in \kbd{polroots(0)}.) \var{E} has 1070 one component, 1 (\typ{STR}): the function name $s$. 1071 1072 \item \kbd{"e\_SQRTN"}. Trying to compute an $n$-th root of $x$, which does 1073 not exist, in function $s$. (As in \kbd{sqrt(Mod(-1,3))}.) 1074 \var{E} has two components, 1 (\typ{STR}): the function name $s$, 1075 2: the argument $x$. 1076 1077 \subsec{next$(\{n=1\})$}\kbdsidx{next}\label{se:next} 1078 Interrupts execution of current $seq$, 1079 resume the next iteration of the innermost enclosing loop, within the 1080 current function call (or top level loop). If $n$ is specified, resume at 1081 the $n$-th enclosing loop. If $n$ is bigger than the number of enclosing 1082 loops, all enclosing loops are exited. 1083 1084 \subsec{return$(\{x=0\})$}\kbdsidx{return}\label{se:return} 1085 Returns from current subroutine, with 1086 result $x$. If $x$ is omitted, return the \kbd{(void)} value (return no 1087 result, like \kbd{print}). 1088 1089 \subsec{until$(a,\var{seq})$}\kbdsidx{until}\label{se:until} 1090 Evaluates \var{seq} until $a$ is not 1091 equal to 0 (i.e.~until $a$ is true). If $a$ is initially not equal to 0, 1092 \var{seq} is evaluated once (more generally, the condition on $a$ is tested 1093 \emph{after} execution of the \var{seq}, not before as in \kbd{while}). 1094 1095 \subsec{while$(a,\var{seq})$}\kbdsidx{while}\label{se:while} 1096 While $a$ is nonzero, evaluates the expression sequence \var{seq}. The 1097 test is made \emph{before} evaluating the $seq$, hence in particular if $a$ 1098 is initially equal to zero the \var{seq} will not be evaluated at all. 1099 1100 \section{Programming in GP: other specific functions} 1101 \label{se:gp_program} 1102 1103 In addition to the general PARI functions, it is necessary to have some 1104 functions which will be of use specifically for \kbd{gp}, though a few of these 1105 can be accessed under library mode. Before we start describing these, we recall 1106 the difference between \emph{strings} and \emph{keywords} (see 1107 \secref{se:strings}): the latter don't get expanded at all, and you can type 1108 them without any enclosing quotes. The former are dynamic objects, where 1109 everything outside quotes gets immediately expanded. 1110 1111 \subsec{Strchr$(x)$}\kbdsidx{Strchr}\label{se:Strchr} 1112 Deprecated alias for strchr. 1113 1114 The library syntax is \fun{GEN}{pari_strchr}{GEN x}. 1115 1116 \subsec{Strexpand$(\{x\}*)$}\kbdsidx{Strexpand}\label{se:Strexpand} 1117 Deprecated alias for strexpand 1118 1119 The library syntax is \fun{GEN}{strexpand}{const char *x*}. 1120 1121 \subsec{Strprintf$(\var{fmt},\{x\}*)$}\kbdsidx{Strprintf}\label{se:Strprintf} 1122 Deprecated alias for strprintf. 1123 1124 The library syntax is \fun{GEN}{Strprintf}{const char *fmt, const char *x*}. 1125 1126 \subsec{Strtex$(\{x\}*)$}\kbdsidx{Strtex}\label{se:Strtex} 1127 Deprecated alias for strtex. 1128 1129 The library syntax is \fun{GEN}{strtex}{const char *x*}. 1130 1131 \subsec{addhelp$(\var{sym},\var{str})$}\kbdsidx{addhelp}\label{se:addhelp} 1132 Changes the help message for the symbol \kbd{sym}. The string \var{str} 1133 is expanded on the spot and stored as the online help for \kbd{sym}. It is 1134 recommended to document global variables and user functions in this way, 1135 although \kbd{gp} will not protest if you don't. 1136 1137 You can attach a help text to an alias, but it will never be 1138 shown: aliases are expanded by the \kbd{?} help operator and we get the help 1139 of the symbol the alias points to. Nothing prevents you from modifying the 1140 help of built-in PARI functions. But if you do, we would like to hear why you 1141 needed it! 1142 1143 Without \tet{addhelp}, the standard help for user functions consists of its 1144 name and definition. 1145 \bprog 1146 gp> f(x) = x^2; 1147 gp> ?f 1148 f = 1149 (x)->x^2 1150 1151 @eprog\noindent Once addhelp is applied to $f$, the function code is no 1152 longer included. It can still be consulted by typing the function name: 1153 \bprog 1154 gp> addhelp(f, "Square") 1155 gp> ?f 1156 Square 1157 1158 gp> f 1159 %2 = (x)->x^2 1160 @eprog 1161 1162 The library syntax is \fun{void}{addhelp}{const char *sym, const char *str}. 1163 1164 \subsec{alarm$(\{s = 0\},\{\var{code}\})$}\kbdsidx{alarm}\label{se:alarm} 1165 If \var{code} is omitted, trigger an \var{e\_ALARM} exception after $s$ 1166 seconds (wall-clock time), cancelling any previously set alarm; stop a pending 1167 alarm if $s = 0$ or is omitted. 1168 1169 Otherwise, if $s$ is positive, the function evaluates \var{code}, 1170 aborting after $s$ seconds. The return value is the value of \var{code} if 1171 it ran to completion before the alarm timeout, and a \typ{ERROR} object 1172 otherwise. 1173 \bprog 1174 ? p = nextprime(10^25); q = nextprime(10^26); N = p*q; 1175 ? E = alarm(1, factor(N)); 1176 ? type(E) 1177 %3 = "t_ERROR" 1178 ? print(E) 1179 %4 = error("alarm interrupt after 964 ms.") 1180 ? alarm(10, factor(N)); \\ enough time 1181 %5 = 1182 [ 10000000000000000000000013 1] 1183 1184 [100000000000000000000000067 1] 1185 @eprog\noindent Here is a more involved example: the function 1186 \kbd{timefact(N,sec)} below tries to factor $N$ and gives up after \var{sec} 1187 seconds, returning a partial factorization. 1188 \bprog 1189 \\ Time-bounded partial factorization 1190 default(factor_add_primes,1); 1191 timefact(N,sec)= 1192 { 1193 F = alarm(sec, factor(N)); 1194 if (type(F) == "t_ERROR", factor(N, 2^24), F); 1195 } 1196 @eprog\noindent We either return the factorization directly, or replace the 1197 \typ{ERROR} result by a simple bounded factorization \kbd{factor(N, 2\pow 24)}. 1198 Note the \tet{factor_add_primes} trick: any prime larger than $2^{24}$ 1199 discovered while attempting the initial factorization is stored and 1200 remembered. When the alarm rings, the subsequent bounded factorization finds 1201 it right away. 1202 1203 \misctitle{Caveat} It is not possible to set a new alarm \emph{within} 1204 another \kbd{alarm} code: the new timer erases the parent one. 1205 1206 The library syntax is \fun{GEN}{gp_alarm}{long s, GEN code = NULL}. 1207 1208 \subsec{alias$(\var{newsym},\var{sym})$}\kbdsidx{alias}\label{se:alias} 1209 Defines the symbol \var{newsym} as an alias for the symbol \var{sym}: 1210 \bprog 1211 ? alias("det", "matdet"); 1212 ? det([1,2;3,4]) 1213 %1 = -2 1214 @eprog\noindent 1215 You are not restricted to ordinary functions, as in the above example: 1216 to alias (from/to) member functions, prefix them with `\kbd{\_.}'; 1217 to alias operators, use their internal name, obtained by writing 1218 \kbd{\_} in lieu of the operators argument: for instance, \kbd{\_!} and 1219 \kbd{!\_} are the internal names of the factorial and the 1220 logical negation, respectively. 1221 \bprog 1222 ? alias("mod", "_.mod"); 1223 ? alias("add", "_+_"); 1224 ? alias("_.sin", "sin"); 1225 ? mod(Mod(x,x^4+1)) 1226 %2 = x^4 + 1 1227 ? add(4,6) 1228 %3 = 10 1229 ? Pi.sin 1230 %4 = 0.E-37 1231 @eprog 1232 Alias expansion is performed directly by the internal GP compiler. 1233 Note that since alias is performed at compilation-time, it does not 1234 require any run-time processing, however it only affects GP code 1235 compiled \emph{after} the alias command is evaluated. A slower but more 1236 flexible alternative is to use variables. Compare 1237 \bprog 1238 ? fun = sin; 1239 ? g(a,b) = intnum(t=a,b,fun(t)); 1240 ? g(0, Pi) 1241 %3 = 2.0000000000000000000000000000000000000 1242 ? fun = cos; 1243 ? g(0, Pi) 1244 %5 = 1.8830410776607851098 E-39 1245 @eprog\noindent 1246 with 1247 \bprog 1248 ? alias(fun, sin); 1249 ? g(a,b) = intnum(t=a,b,fun(t)); 1250 ? g(0,Pi) 1251 %2 = 2.0000000000000000000000000000000000000 1252 ? alias(fun, cos); \\ Oops. Does not affect *previous* definition! 1253 ? g(0,Pi) 1254 %3 = 2.0000000000000000000000000000000000000 1255 ? g(a,b) = intnum(t=a,b,fun(t)); \\ Redefine, taking new alias into account 1256 ? g(0,Pi) 1257 %5 = 1.8830410776607851098 E-39 1258 @eprog 1259 1260 A sample alias file \kbd{misc/gpalias} is provided with 1261 the standard distribution. 1262 1263 The library syntax is \fun{void}{alias0}{const char *newsym, const char *sym}. 1264 1265 \subsec{allocatemem$(\{s=0\})$}\kbdsidx{allocatemem}\label{se:allocatemem} 1266 This special operation changes the stack size \emph{after} 1267 initialization. The argument $s$ must be a nonnegative integer. 1268 If $s > 0$, a new stack of at least $s$ bytes is allocated. We may allocate 1269 more than $s$ bytes if $s$ is way too small, or for alignment reasons: the 1270 current formula is $\max(16*\ceil{s/16}, 500032)$ bytes. 1271 1272 If $s=0$, the size of the new stack is twice the size of the old one. 1273 1274 This command is much more useful if \tet{parisizemax} is nonzero, and we 1275 describe this case first. With \kbd{parisizemax} enabled, there are three 1276 sizes of interest: 1277 1278 \item a virtual stack size, \tet{parisizemax}, which is an absolute upper 1279 limit for the stack size; this is set by \kbd{default(parisizemax, ...)}. 1280 1281 \item the desired typical stack size, \tet{parisize}, that will grow as 1282 needed, up to \tet{parisizemax}; this is set by \kbd{default(parisize, ...)}. 1283 1284 \item the current stack size, which is less that \kbd{parisizemax}, 1285 typically equal to \kbd{parisize} but possibly larger and increasing 1286 dynamically as needed; \kbd{allocatemem} allows to change that one 1287 explicitly. 1288 1289 The \kbd{allocatemem} command forces stack 1290 usage to increase temporarily (up to \kbd{parisizemax} of course); for 1291 instance if you notice using \kbd{\bs gm2} that we seem to collect garbage a 1292 lot, e.g. 1293 \bprog 1294 ? \gm2 1295 debugmem = 2 1296 ? default(parisize,"32M") 1297 *** Warning: new stack size = 32000000 (30.518 Mbytes). 1298 ? bnfinit('x^2+10^30-1) 1299 *** bnfinit: collecting garbage in hnffinal, i = 1. 1300 *** bnfinit: collecting garbage in hnffinal, i = 2. 1301 *** bnfinit: collecting garbage in hnffinal, i = 3. 1302 @eprog\noindent and so on for hundred of lines. Then, provided the 1303 \tet{breakloop} default is set, you can interrupt the computation, type 1304 \kbd{allocatemem(100*10\pow6)} at the break loop prompt, then let the 1305 computation go on by typing \kbd{<Enter>}. Back at the \kbd{gp} prompt, 1306 the desired stack size of \kbd{parisize} is restored. Note that changing either 1307 \kbd{parisize} or \kbd{parisizemax} at the break loop prompt would interrupt 1308 the computation, contrary to the above. 1309 1310 In most cases, \kbd{parisize} will increase automatically (up to 1311 \kbd{parisizemax}) and there is no need to perform the above maneuvers. 1312 But that the garbage collector is sufficiently efficient that 1313 a given computation can still run without increasing the stack size, 1314 albeit very slowly due to the frequent garbage collections. 1315 1316 \misctitle{Deprecated: when \kbd{parisizemax} is unset} 1317 This is currently still the default behavior in order not to break backward 1318 compatibility. The rest of this section documents the 1319 behavior of \kbd{allocatemem} in that (deprecated) situation: it becomes a 1320 synonym for \kbd{default(parisize,...)}. In that case, there is no 1321 notion of a virtual stack, and the stack size is always equal to 1322 \kbd{parisize}. If more memory is needed, the PARI stack overflows, aborting 1323 the computation. 1324 1325 Thus, increasing \kbd{parisize} via \kbd{allocatemem} or 1326 \kbd{default(parisize,...)} before a big computation is important. 1327 Unfortunately, either must be typed at the \kbd{gp} prompt in 1328 interactive usage, or left by itself at the start of batch files. 1329 They cannot be used meaningfully in loop-like constructs, or as part of a 1330 larger expression sequence, e.g 1331 \bprog 1332 allocatemem(); x = 1; \\@com This will not set \kbd{x}! 1333 @eprog\noindent 1334 In fact, all loops are immediately exited, user functions terminated, and 1335 the rest of the sequence following \kbd{allocatemem()} is silently 1336 discarded, as well as all pending sequences of instructions. We just go on 1337 reading the next instruction sequence from the file we are in (or from the 1338 user). In particular, we have the following possibly unexpected behavior: in 1339 \bprog 1340 read("file.gp"); x = 1 1341 @eprog\noindent were \kbd{file.gp} contains an \kbd{allocatemem} statement, 1342 the \kbd{x = 1} is never executed, since all pending instructions in the 1343 current sequence are discarded. 1344 1345 The reason for these unfortunate side-effects is that, with 1346 \kbd{parisizemax} disabled, increasing the stack size physically 1347 moves the stack, so temporary objects created during the current expression 1348 evaluation are not correct anymore. (In particular byte-compiled expressions, 1349 which are allocated on the stack.) To avoid accessing obsolete pointers to 1350 the old stack, this routine ends by a \kbd{longjmp}. 1351 1352 The library syntax is \fun{void}{gp_allocatemem}{GEN s = NULL}. 1353 1354 \subsec{apply$(f, A)$}\kbdsidx{apply}\label{se:apply} 1355 Apply the \typ{CLOSURE} \kbd{f} to the entries of \kbd{A}. 1356 1357 \item If \kbd{A} is a scalar, return \kbd{f(A)}. 1358 1359 \item If \kbd{A} is a polynomial or power series $\sum a_i x^i$ ($+ 1360 O(x^N)$), apply \kbd{f} on all coefficients and return $\sum f(a_i) x^i$ ($+ 1361 O(x^N)$). 1362 1363 \item If \kbd{A} is a vector or list $[a_1,\dots,a_n]$, return the vector 1364 or list $[f(a_1),\dots, f(a_n)]$. If \kbd{A} is a matrix, return the matrix 1365 whose entries are the $f(\kbd{A[i,j]})$. 1366 1367 \bprog 1368 ? apply(x->x^2, [1,2,3,4]) 1369 %1 = [1, 4, 9, 16] 1370 ? apply(x->x^2, [1,2;3,4]) 1371 %2 = 1372 [1 4] 1373 1374 [9 16] 1375 ? apply(x->x^2, 4*x^2 + 3*x+ 2) 1376 %3 = 16*x^2 + 9*x + 4 1377 ? apply(sign, 2 - 3* x + 4*x^2 + O(x^3)) 1378 %4 = 1 - x + x^2 + O(x^3) 1379 @eprog\noindent Note that many functions already act componentwise on 1380 vectors or matrices, but they almost never act on lists; in this case, 1381 \kbd{apply} is a good solution: 1382 \bprog 1383 ? L = List([Mod(1,3), Mod(2,4)]); 1384 ? lift(L) 1385 *** at top-level: lift(L) 1386 *** ^------- 1387 *** lift: incorrect type in lift. 1388 ? apply(lift, L); 1389 %2 = List([1, 2]) 1390 @eprog 1391 \misctitle{Remark} For $v$ a \typ{VEC}, \typ{COL}, \typ{VECSMALL}, 1392 \typ{LIST} or \typ{MAT}, the alternative set-notations 1393 \bprog 1394 [g(x) | x <- v, f(x)] 1395 [x | x <- v, f(x)] 1396 [g(x) | x <- v] 1397 @eprog\noindent 1398 are available as shortcuts for 1399 \bprog 1400 apply(g, select(f, Vec(v))) 1401 select(f, Vec(v)) 1402 apply(g, Vec(v)) 1403 @eprog\noindent respectively: 1404 \bprog 1405 ? L = List([Mod(1,3), Mod(2,4)]); 1406 ? [ lift(x) | x<-L ] 1407 %2 = [1, 2] 1408 @eprog 1409 1410 \synt{genapply}{void *E, GEN (*fun)(void*,GEN), GEN a}. 1411 1412 \subsec{arity$(C)$}\kbdsidx{arity}\label{se:arity} 1413 Return the arity of the closure $C$, i.e., the number of its arguments. 1414 \bprog 1415 ? f1(x,y=0)=x+y; 1416 ? arity(f1) 1417 %1 = 2 1418 ? f2(t,s[..])=print(t,":",s); 1419 ? arity(f2) 1420 %2 = 2 1421 @eprog\noindent Note that a variadic argument, such as $s$ in \kbd{f2} above, 1422 is counted as a single argument. 1423 1424 The library syntax is \fun{GEN}{arity0}{GEN C}. 1425 1426 \subsec{call$(f, A)$}\kbdsidx{call}\label{se:call} 1427 $A=[a_1,\dots, a_n]$ being a vector and $f$ being a function, returns the 1428 evaluation of $f(a_1,\dots,a_n)$. 1429 $f$ can also be the name of a built-in GP function. 1430 If $\# A =1$, \tet{call}($f,A$) = \tet{apply}($f,A$)[1]. 1431 If $f$ is variadic, the variadic arguments must grouped in a vector in 1432 the last component of $A$. 1433 1434 This function is useful 1435 1436 \item when writing a variadic function, to call another one: 1437 \bprog 1438 fprintf(file,format,args[..]) = write(file,call(strprintf,[format,args])) 1439 @eprog 1440 1441 \item when dealing with function arguments with unspecified arity 1442 1443 The function below implements a global memoization interface: 1444 \bprog 1445 memo=Map(); 1446 memoize(f,A[..])= 1447 { 1448 my(res); 1449 if(!mapisdefined(memo, [f,A], &res), 1450 res = call(f,A); 1451 mapput(memo,[f,A],res)); 1452 res; 1453 } 1454 @eprog 1455 for example: 1456 \bprog 1457 ? memoize(factor,2^128+1) 1458 %3 = [59649589127497217,1;5704689200685129054721,1] 1459 ? ## 1460 *** last result computed in 76 ms. 1461 ? memoize(factor,2^128+1) 1462 %4 = [59649589127497217,1;5704689200685129054721,1] 1463 ? ## 1464 *** last result computed in 0 ms. 1465 ? memoize(ffinit,3,3) 1466 %5 = Mod(1,3)*x^3+Mod(1,3)*x^2+Mod(1,3)*x+Mod(2,3) 1467 ? fibo(n)=if(n==0,0,n==1,1,memoize(fibo,n-2)+memoize(fibo,n-1)); 1468 ? fibo(100) 1469 %7 = 354224848179261915075 1470 @eprog 1471 1472 \item to call operators through their internal names without using 1473 \kbd{alias} 1474 \bprog 1475 matnbelts(M) = call("_*_",matsize(M)) 1476 @eprog 1477 1478 The library syntax is \fun{GEN}{call0}{GEN f, GEN A}. 1479 1480 \subsec{default$(\{\var{key}\},\{\var{val}\})$}\kbdsidx{default}\label{se:default} 1481 Returns the default corresponding to keyword \var{key}. If \var{val} is 1482 present, sets the default to \var{val} first (which is subject to string 1483 expansion first). Typing \kbd{default()} (or \b{d}) yields the complete 1484 default list as well as their current values. See \secref{se:defaults} for an 1485 introduction to GP defaults, \secref{se:gp_defaults} for a 1486 list of available defaults, and \secref{se:meta} for some shortcut 1487 alternatives. Note that the shortcuts are meant for interactive use and 1488 usually display more information than \kbd{default}. 1489 1490 The library syntax is \fun{GEN}{default0}{const char *key = NULL, const char *val = NULL}. 1491 1492 \subsec{errname$(E)$}\kbdsidx{errname}\label{se:errname} 1493 Returns the type of the error message \kbd{E} as a string. 1494 \bprog 1495 ? iferr(1 / 0, E, print(errname(E))) 1496 e_INV 1497 ? ?? e_INV 1498 [...] 1499 * "e_INV". Tried to invert a noninvertible object x in function s. 1500 [...] 1501 @eprog 1502 1503 The library syntax is \fun{GEN}{errname}{GEN E}. 1504 1505 \subsec{error$(\{\var{str}\}*)$}\kbdsidx{error}\label{se:error} 1506 Outputs its argument list (each of 1507 them interpreted as a string), then interrupts the running \kbd{gp} program, 1508 returning to the input prompt. For instance 1509 \bprog 1510 error("n = ", n, " is not squarefree!") 1511 @eprog\noindent 1512 % \syn{NO} 1513 1514 \subsec{export$(x\{=...\},...,z\{=...\})$}\kbdsidx{export}\label{se:export} 1515 Export the variables $x,\ldots, z$ to the parallel world. 1516 Such variables are visible inside parallel sections in place of global 1517 variables, but cannot be modified inside a parallel section. 1518 \kbd{export(a)} set the variable $a$ in the parallel world to current value of $a$. 1519 \kbd{export(a=z)} set the variable $a$ in the parallel world to $z$, without 1520 affecting the current value of $a$. 1521 \bprog 1522 ? fun(x)=x^2+1; 1523 ? parvector(10,i,fun(i)) 1524 *** mt: please use export(fun). 1525 ? export(fun) 1526 ? parvector(10,i,fun(i)) 1527 %4 = [2,5,10,17,26,37,50,65,82,101] 1528 @eprog 1529 1530 \subsec{exportall$()$}\kbdsidx{exportall}\label{se:exportall} 1531 Declare all current dynamic variables as exported variables. 1532 Such variables are visible inside parallel sections in place of global variables. 1533 \bprog 1534 ? fun(x)=x^2+1; 1535 ? parvector(10,i,fun(i)) 1536 *** mt: please use export(fun). 1537 ? exportall() 1538 ? parvector(10,i,fun(i)) 1539 %4 = [2,5,10,17,26,37,50,65,82,101] 1540 @eprog 1541 1542 The library syntax is \fun{void}{exportall}{}. 1543 1544 \subsec{extern$(\var{str})$}\kbdsidx{extern}\label{se:extern} 1545 The string \var{str} is the name of an external command (i.e.~one you 1546 would type from your UNIX shell prompt). This command is immediately run and 1547 its output fed into \kbd{gp}, just as if read from a file. 1548 1549 The library syntax is \fun{GEN}{gpextern}{const char *str}. 1550 1551 \subsec{externstr$(\var{str})$}\kbdsidx{externstr}\label{se:externstr} 1552 The string \var{str} is the name of an external command (i.e.~one you 1553 would type from your UNIX shell prompt). This command is immediately run and 1554 its output is returned as a vector of GP strings, one component per output 1555 line. 1556 1557 The library syntax is \fun{GEN}{externstr}{const char *str}. 1558 1559 \subsec{fileclose$(n)$}\kbdsidx{fileclose}\label{se:fileclose} 1560 Close the file descriptor $n$, created via \kbd{fileopen} or 1561 \kbd{fileextern}. Finitely many files can be opened at a given time, 1562 closing them recycles file descriptors and avoids running out of them: 1563 \bprog 1564 ? n = 0; while(n++, fileopen("/tmp/test", "w")) 1565 *** at top-level: n=0;while(n++,fileopen("/tmp/test","w")) 1566 *** ^-------------------------- 1567 *** fileopen: error opening requested file: `/tmp/test'. 1568 *** Break loop: type 'break' to go back to GP prompt 1569 break> n 1570 65533 1571 @eprog\noindent This is a limitation of the operating system and does not 1572 depend on PARI: if you open too many files in \kbd{gp} without closing them, 1573 the operating system will also prevent unrelated applications from opening 1574 files. Independently, your operating system (e.g. Windows) may prevent other 1575 applications from accessing or deleting your file while it is opened by 1576 \kbd{gp}. Quitting \kbd{gp} implicitly calls this function on all opened 1577 file descriptors. 1578 1579 On files opened for writing, this function also forces a write of all 1580 buffered data to the file system and completes all pending write operations. 1581 This function is implicitly called for all open file descriptors when 1582 exiting \kbd{gp} but it is cleaner and safer to call it explicitly, for 1583 instance in case of a \kbd{gp} crash or general system failure, which could 1584 cause data loss. 1585 \bprog 1586 ? n = fileopen("./here"); 1587 ? while(l = fileread(n), print(l)); 1588 ? fileclose(n); 1589 1590 ? n = fileopen("./there", "w"); 1591 ? for (i = 1, 100, filewrite(n, i^2+1)) 1592 ? fileclose(n) 1593 @eprog Until a \kbd{fileclose}, there is no guarantee that the file on disk 1594 contains all the expected data from previous \kbd{filewrite}s. (And even 1595 then the operating system may delay the actual write to hardware.) 1596 1597 Closing a file twice raises an exception: 1598 \bprog 1599 ? n = fileopen("/tmp/test"); 1600 ? fileclose(n) 1601 ? fileclose(n) 1602 *** at top-level: fileclose(n) 1603 *** ^------------ 1604 *** fileclose: invalid file descriptor 0 1605 @eprog 1606 1607 The library syntax is \fun{void}{gp_fileclose}{long n}. 1608 1609 \subsec{fileextern$(\var{str})$}\kbdsidx{fileextern}\label{se:fileextern} 1610 The string \var{str} is the name of an external command, i.e.~one you 1611 would type from your UNIX shell prompt. This command is immediately run and 1612 the function returns a file descriptor attached to the command output as if 1613 it were read from a file. 1614 \bprog 1615 ? n = fileextern("ls -l"); 1616 ? while(l = filereadstr(n), print(l)) 1617 ? fileclose(n) 1618 @eprog\noindent If the \kbd{secure} default is set, this function will raise 1619 en exception. 1620 1621 The library syntax is \fun{long}{gp_fileextern}{const char *str}. 1622 1623 \subsec{fileflush$(\{n\})$}\kbdsidx{fileflush}\label{se:fileflush} 1624 Flushes the file descriptor $n$, created via \kbd{fileopen} or 1625 \kbd{fileextern}. On files opened for writing, this function forces a write 1626 of all buffered data to the file system and completes all pending write 1627 operations. This function is implicitly called by \kbd{fileclose} but you may 1628 want to call it explicitly at synchronization points, for instance after 1629 writing a large result to file and before printing diagnostics on screen. 1630 (In order to be sure that the file contains the expected content on 1631 inspection.) 1632 1633 If $n$ is omitted, flush all descriptors to output streams. 1634 1635 \bprog 1636 ? n = fileopen("./here", "w"); 1637 ? for (i = 1, 10^5, \ 1638 filewrite(n, i^2+1); \ 1639 if (i % 10000 == 0, fileflush(n))) 1640 @eprog Until a \kbd{fileflush} or \kbd{fileclose}, there is no guarantee 1641 that the file contains all the expected data from previous \kbd{filewrite}s. 1642 1643 The library syntax is \fun{void}{gp_fileflush0}{GEN n = NULL}. 1644 But the direct and more specific variant 1645 \fun{void}{gp_fileflush}{long n} is also available. 1646 1647 \subsec{fileopen$(\var{path}, \var{mode})$}\kbdsidx{fileopen}\label{se:fileopen} 1648 Open the file pointed to by 'path' and return a file descriptor which 1649 can be used with other file functions. 1650 1651 The mode can be 1652 1653 \item \kbd{"r"} (default): open for reading; allow \kbd{fileread} and 1654 \kbd{filereadstr}. 1655 1656 \item \kbd{"w"}: open for writing, discarding existing content; allow 1657 \kbd{filewrite}, \kbd{filewrite1}. 1658 1659 \item \kbd{"a"}: open for writing, appending to existing content; same 1660 operations allowed as \kbd{"w"}. 1661 1662 Eventually, the file should be closed and the descriptor recycled using 1663 \kbd{fileclose}. 1664 1665 \bprog 1666 ? n = fileopen("./here"); \\ "r" by default 1667 ? while (l = filereadstr(n), print(l)) \\ print successive lines 1668 ? fileclose(n) \\ done 1669 @eprog\noindent In \emph{read} mode, raise an exception if the file does not 1670 exist or the user does not have read permission. In \emph{write} mode, raise 1671 an exception if the file cannot be written to. Trying to read or write to a 1672 file that was not opend with the right mode raises an exception. 1673 \bprog 1674 ? n = fileopen("./read", "r"); 1675 ? filewrite(n, "test") \\ not open for writing 1676 *** at top-level: filewrite(n,"test") 1677 *** ^------------------- 1678 *** filewrite: invalid file descriptor 0 1679 @eprog 1680 1681 The library syntax is \fun{long}{gp_fileopen}{const char *path, const char *mode}. 1682 1683 \subsec{fileread$(n)$}\kbdsidx{fileread}\label{se:fileread} 1684 Read a logical line from the file attached to the descriptor $n$, opened 1685 for reading with \kbd{fileopen}. Return 0 at end of file. 1686 1687 A logical line is a full command as it is prepared by gp's 1688 preprocessor (skipping blanks and comments or assembling multiline commands 1689 between braces) before being fed to the interpreter. The function 1690 \kbd{filereadstr} would read a \emph{raw} line exactly as input, up to the 1691 next carriage return \kbd{\bs n}. 1692 1693 Compare raw lines 1694 \bprog 1695 ? n = fileopen("examples/bench.gp"); 1696 ? while(l = filereadstr(n), print(l)); 1697 { 1698 u=v=p=q=1; 1699 for (k=1, 2000, 1700 [u,v] = [v,u+v]; 1701 p *= v; q = lcm(q,v); 1702 if (k%50 == 0, 1703 print(k, " ", log(p)/log(q)) 1704 ) 1705 ) 1706 } 1707 @eprog\noindent and logical lines 1708 \bprog 1709 ? n = fileopen("examples/bench.gp"); 1710 ? while(l = fileread(n), print(l)); 1711 u=v=p=q=1;for(k=1,2000,[u,v]=[v,u+v];p*=v;q=lcm(q,v);[...] 1712 @eprog 1713 1714 The library syntax is \fun{GEN}{gp_fileread}{long n}. 1715 1716 \subsec{filereadstr$(n)$}\kbdsidx{filereadstr}\label{se:filereadstr} 1717 Read a raw line from the file attached to the descriptor $n$, opened 1718 for reading with \kbd{fileopen}, discarding the terminating newline. 1719 In other words the line is read exactly as input, up to the 1720 next carriage return \kbd{\bs n}. By comparison, \kbd{fileread} would 1721 read a logical line, as assembled by gp's preprocessor (skipping blanks 1722 and comments for instance). 1723 1724 The library syntax is \fun{GEN}{gp_filereadstr}{long n}. 1725 1726 \subsec{filewrite$(n, s)$}\kbdsidx{filewrite}\label{se:filewrite} 1727 Write the string $s$ to the file attached to descriptor $n$, ending with 1728 a newline. The file must have been opened with \kbd{fileopen} in 1729 \kbd{"w"} or \kbd{"a"} mode. There is no guarantee that $s$ is completely 1730 written to disk until \kbd{fileclose$(n)$} is executed, which is automatic 1731 when quitting \kbd{gp}. 1732 1733 If the newline is not desired, use \kbd{filewrite1}. 1734 1735 \misctitle{Variant} The high-level function \kbd{write} is expensive when many 1736 consecutive writes are expected because it cannot use buffering. The low-level 1737 interface \kbd{fileopen} / \kbd{filewrite} / \kbd{fileclose} is more efficient: 1738 \bprog 1739 ? f = "/tmp/bigfile"; 1740 ? for (i = 1, 10^5, write(f, i^2+1)) 1741 time = 240 ms. 1742 1743 ? v = vector(10^5, i, i^2+1); 1744 time = 10 ms. \\ computing the values is fast 1745 ? write("/tmp/bigfile2",v) 1746 time = 12 ms. \\ writing them in one operation is fast 1747 1748 ? n = fileopen("/tmp/bigfile", "w"); 1749 ? for (i = 1, 10^5, filewrite(n, i^2+1)) 1750 time = 24 ms. \\ low-level write is ten times faster 1751 ? fileclose(n); 1752 @eprog\noindent In the final example, the file needs not be in a consistent 1753 state until the ending \kbd{fileclose} is evaluated, e.g. some lines might be 1754 half-written or not present at all even though the corresponding 1755 \kbd{filewrite} was executed already. Both a single high-level \kbd{write} 1756 and a succession of low-level \kbd{filewrite}s achieve the same efficiency, 1757 but the latter is often more natural. In fact, concatenating naively 1758 the entries to be written is quadratic in the number of entries, hence 1759 much more expensive than the original write operations: 1760 \bprog 1761 ? v = []; for (i = 1, 10^5, v = concat(v,i)) 1762 time = 1min, 41,456 ms. 1763 @eprog 1764 1765 The library syntax is \fun{void}{gp_filewrite}{long n, const char *s}. 1766 1767 \subsec{filewrite1$(n, s)$}\kbdsidx{filewrite1}\label{se:filewrite1} 1768 Write the string $s$ to the file attached to descriptor $n$. 1769 The file must have been opened with \kbd{fileopen} in \kbd{"w"} or \kbd{"a"} 1770 mode. 1771 1772 If you want to append a newline at the end of $s$, you can use 1773 \kbd{Str(s,"\bs n")} or \kbd{filewrite}. 1774 1775 The library syntax is \fun{void}{gp_filewrite1}{long n, const char *s}. 1776 1777 \subsec{fold$(f, A)$}\kbdsidx{fold}\label{se:fold} 1778 Apply the \typ{CLOSURE} \kbd{f} of arity $2$ to the entries of \kbd{A}, 1779 in order to return \kbd{f(\dots f(f(A[1],A[2]),A[3])\dots ,A[\#A])}. 1780 \bprog 1781 ? fold((x,y)->x*y, [1,2,3,4]) 1782 %1 = 24 1783 ? fold((x,y)->[x,y], [1,2,3,4]) 1784 %2 = [[[1, 2], 3], 4] 1785 ? fold((x,f)->f(x), [2,sqr,sqr,sqr]) 1786 %3 = 256 1787 ? fold((x,y)->(x+y)/(1-x*y),[1..5]) 1788 %4 = -9/19 1789 ? bestappr(tan(sum(i=1,5,atan(i)))) 1790 %5 = -9/19 1791 @eprog 1792 1793 The library syntax is \fun{GEN}{fold0}{GEN f, GEN A}. 1794 Also available is 1795 \fun{GEN}{genfold}{void *E, GEN (*fun)(void*,GEN, GEN), GEN A}. 1796 1797 \subsec{getabstime$()$}\kbdsidx{getabstime}\label{se:getabstime} 1798 Returns the CPU time (in milliseconds) elapsed since \kbd{gp} startup. 1799 This provides a reentrant version of \kbd{gettime}: 1800 \bprog 1801 my (t = getabstime()); 1802 ... 1803 print("Time: ", strtime(getabstime() - t)); 1804 @eprog 1805 For a version giving wall-clock time, see \tet{getwalltime}. 1806 1807 The library syntax is \fun{long}{getabstime}{}. 1808 1809 \subsec{getenv$(s)$}\kbdsidx{getenv}\label{se:getenv} 1810 Return the value of the environment variable \kbd{s} if it is defined, otherwise return 0. 1811 1812 The library syntax is \fun{GEN}{gp_getenv}{const char *s}. 1813 1814 \subsec{getheap$()$}\kbdsidx{getheap}\label{se:getheap} 1815 Returns a two-component row vector giving the 1816 number of objects on the heap and the amount of memory they occupy in long 1817 words. Useful mainly for debugging purposes. 1818 1819 The library syntax is \fun{GEN}{getheap}{}. 1820 1821 \subsec{getlocalbitprec$()$}\kbdsidx{getlocalbitprec}\label{se:getlocalbitprec} 1822 Returns the current dynamic bit precision. 1823 %\syn{NO} 1824 1825 \subsec{getlocalprec$()$}\kbdsidx{getlocalprec}\label{se:getlocalprec} 1826 Returns the current dynamic precision, in decimal digits. 1827 %\syn{NO} 1828 1829 \subsec{getrand$()$}\kbdsidx{getrand}\label{se:getrand} 1830 Returns the current value of the seed used by the 1831 pseudo-random number generator \tet{random}. Useful mainly for debugging 1832 purposes, to reproduce a specific chain of computations. The returned value 1833 is technical (reproduces an internal state array), and can only be used as an 1834 argument to \tet{setrand}. 1835 1836 The library syntax is \fun{GEN}{getrand}{}. 1837 1838 \subsec{getstack$()$}\kbdsidx{getstack}\label{se:getstack} 1839 Returns the current value of $\kbd{top}-\kbd{avma}$, i.e.~the number of 1840 bytes used up to now on the stack. Useful mainly for debugging purposes. 1841 1842 The library syntax is \fun{long}{getstack}{}. 1843 1844 \subsec{gettime$()$}\kbdsidx{gettime}\label{se:gettime} 1845 Returns the CPU time (in milliseconds) used since either the last call to 1846 \kbd{gettime}, or to the beginning of the containing GP instruction (if 1847 inside \kbd{gp}), whichever came last. 1848 1849 For a reentrant version, see \tet{getabstime}. 1850 1851 For a version giving wall-clock time, see \tet{getwalltime}. 1852 1853 The library syntax is \fun{long}{gettime}{}. 1854 1855 \subsec{getwalltime$()$}\kbdsidx{getwalltime}\label{se:getwalltime} 1856 Returns the time (in milliseconds) elapsed since 1857 00:00:00 UTC Thursday 1, January 1970 (the Unix epoch). 1858 \bprog 1859 my (t = getwalltime()); 1860 ... 1861 print("Time: ", strtime(getwalltime() - t)); 1862 @eprog 1863 1864 The library syntax is \fun{GEN}{getwalltime}{}. 1865 1866 \subsec{global$(\var{list} \var{of} \var{variables})$}\kbdsidx{global}\label{se:global} 1867 Obsolete. Scheduled for deletion. 1868 % \syn{NO} 1869 1870 \subsec{inline$(x,...,z)$}\kbdsidx{inline}\label{se:inline} 1871 Declare $x,\ldots, z$ as inline variables. Such variables 1872 behave like lexically scoped variable (see my()) but with unlimited scope. 1873 It is however possible to exit the scope by using \kbd{uninline()}. 1874 When used in a GP script, it is recommended to call \kbd{uninline()} before 1875 the script's end to avoid inline variables leaking outside the script. 1876 DEPRECATED, use \kbd{export}. 1877 1878 \subsec{input$()$}\kbdsidx{input}\label{se:input} 1879 Reads a string, interpreted as a GP expression, 1880 from the input file, usually standard input (i.e.~the keyboard). If a 1881 sequence of expressions is given, the result is the result of the last 1882 expression of the sequence. When using this instruction, it is useful to 1883 prompt for the string by using the \kbd{print1} function. Note that in the 1884 present version 2.19 of \kbd{pari.el}, when using \kbd{gp} under GNU Emacs (see 1885 \secref{se:emacs}) one \emph{must} prompt for the string, with a string 1886 which ends with the same prompt as any of the previous ones (a \kbd{"? "} 1887 will do for instance). 1888 1889 The library syntax is \fun{GEN}{gp_input}{}. 1890 1891 \subsec{install$(\var{name},\var{code},\{\var{gpname}\},\{\var{lib}\})$}\kbdsidx{install}\label{se:install} 1892 Loads from dynamic library \var{lib} the function \var{name}. Assigns to it 1893 the name \var{gpname} in this \kbd{gp} session, with \emph{prototype} 1894 \var{code} (see below). If \var{gpname} is omitted, uses \var{name}. 1895 If \var{lib} is omitted, all symbols known to \kbd{gp} are available: this 1896 includes the whole of \kbd{libpari.so} and possibly others (such as 1897 \kbd{libc.so}). 1898 1899 Most importantly, \kbd{install} gives you access to all nonstatic functions 1900 defined in the PARI library. For instance, the function 1901 \bprog 1902 GEN addii(GEN x, GEN y) 1903 @eprog\noindent adds two PARI integers, and is not directly accessible under 1904 \kbd{gp} (it is eventually called by the \kbd{+} operator of course): 1905 \bprog 1906 ? install("addii", "GG") 1907 ? addii(1, 2) 1908 %1 = 3 1909 @eprog\noindent 1910 It also allows to add external functions to the \kbd{gp} interpreter. 1911 For instance, it makes the function \tet{system} obsolete: 1912 \bprog 1913 ? install(system, vs, sys,/*omitted*/) 1914 ? sys("ls gp*") 1915 gp.c gp.h gp_rl.c 1916 @eprog\noindent This works because \kbd{system} is part of \kbd{libc.so}, 1917 which is linked to \kbd{gp}. It is also possible to compile a shared library 1918 yourself and provide it to gp in this way: use \kbd{gp2c}, or do it manually 1919 (see the \kbd{modules\_build} variable in \kbd{pari.cfg} for hints). 1920 1921 Re-installing a function will print a warning and update the prototype code 1922 if needed. However, it will not reload a symbol from the library, even if the 1923 latter has been recompiled. 1924 1925 \misctitle{Prototype} We only give a simplified description here, covering 1926 most functions, but there are many more possibilities. The full documentation 1927 is available in \kbd{libpari.dvi}, see 1928 \bprog 1929 ??prototype 1930 @eprog 1931 1932 \item First character \kbd{i}, \kbd{l}, \kbd{v} : return type int / long / 1933 void. (Default: \kbd{GEN}) 1934 1935 \item One letter for each mandatory argument, in the same order as they appear 1936 in the argument list: \kbd{G} (\kbd{GEN}), \kbd{\&} 1937 (\kbd{GEN*}), \kbd{L} (\kbd{long}), \kbd{s} (\kbd{char *}), \kbd{n} 1938 (variable). 1939 1940 \item \kbd{p} to supply \kbd{realprecision} (usually \kbd{long prec} in the 1941 argument list), \kbd{P} to supply \kbd{seriesprecision} 1942 (usually \kbd{long precdl}). 1943 1944 \noindent We also have special constructs for optional arguments and default 1945 values: 1946 1947 \item \kbd{DG} (optional \kbd{GEN}, \kbd{NULL} if omitted), 1948 1949 \item \kbd{D\&} (optional \kbd{GEN*}, \kbd{NULL} if omitted), 1950 1951 \item \kbd{Dn} (optional variable, $-1$ if omitted), 1952 1953 For instance the prototype corresponding to 1954 \bprog 1955 long issquareall(GEN x, GEN *n = NULL) 1956 @eprog\noindent is \kbd{lGD\&}. 1957 1958 \misctitle{Caution} This function may not work on all systems, especially 1959 when \kbd{gp} has been compiled statically. In that case, the first use of an 1960 installed function will provoke a Segmentation Fault (this should never 1961 happen with a dynamically linked executable). If you intend to use this 1962 function, please check first on some harmless example such as the one above 1963 that it works properly on your machine. 1964 1965 The library syntax is \fun{void}{gpinstall}{const char *name, const char *code, const char *gpname, const char *lib}. 1966 1967 \subsec{kill$(\var{sym})$}\kbdsidx{kill}\label{se:kill} 1968 Restores the symbol \kbd{sym} to its ``undefined'' status, and deletes any 1969 help messages attached to \kbd{sym} using \kbd{addhelp}. Variable names 1970 remain known to the interpreter and keep their former priority: you cannot 1971 make a variable ``less important" by killing it! 1972 \bprog 1973 ? z = y = 1; y 1974 %1 = 1 1975 ? kill(y) 1976 ? y \\ restored to ``undefined'' status 1977 %2 = y 1978 ? variable() 1979 %3 = [x, y, z] \\ but the variable name y is still known, with y > z ! 1980 @eprog\noindent 1981 For the same reason, killing a user function (which is an ordinary 1982 variable holding a \typ{CLOSURE}) does not remove its name from the list of 1983 variable names. 1984 1985 If the symbol is attached to a variable --- user functions being an 1986 important special case ---, one may use the \idx{quote} operator 1987 \kbd{a = 'a} to reset variables to their starting values. However, this 1988 will not delete a help message attached to \kbd{a}, and is also slightly 1989 slower than \kbd{kill(a)}. 1990 \bprog 1991 ? x = 1; addhelp(x, "foo"); x 1992 %1 = 1 1993 ? x = 'x; x \\ same as 'kill', except we don't delete help. 1994 %2 = x 1995 ? ?x 1996 foo 1997 @eprog\noindent 1998 On the other hand, \kbd{kill} is the only way to remove aliases and installed 1999 functions. 2000 \bprog 2001 ? alias(fun, sin); 2002 ? kill(fun); 2003 2004 ? install(addii, GG); 2005 ? kill(addii); 2006 @eprog 2007 2008 The library syntax is \fun{void}{kill0}{const char *sym}. 2009 2010 \subsec{listcreate$(\{n\})$}\kbdsidx{listcreate}\label{se:listcreate} 2011 This function is obsolete, use \kbd{List}. 2012 2013 Creates an empty list. This routine used to have a mandatory argument, 2014 which is now ignored (for backward compatibility). 2015 % \syn{NO} 2016 2017 \subsec{listinsert$(~L,x,n)$}\kbdsidx{listinsert}\label{se:listinsert} 2018 Inserts the object $x$ at 2019 position $n$ in $L$ (which must be of type \typ{LIST}). 2020 This has complexity $O(\#L - n + 1)$: all the 2021 remaining elements of \var{list} (from position $n+1$ onwards) are shifted 2022 to the right. If $n$ is greater than the list length, appends $x$. 2023 \bprog 2024 ? L = List([1,2,3]); 2025 ? listput(~L, 4); L \\ listput inserts at end 2026 %4 = List([1, 2, 3, 4]) 2027 ? listinsert(~L, 5, 1); L \\insert at position 1 2028 %5 = List([5, 1, 2, 3, 4]) 2029 ? listinsert(~L, 6, 1000); L \\ trying to insert beyond position #L 2030 %6 = List([5, 1, 2, 3, 4, 6]) \\ ... inserts at the end 2031 @eprog\noindent Note the \kbd{\til L}: this means that the function is 2032 called with a \emph{reference} to \kbd{L} and changes \kbd{L} in place. 2033 2034 The library syntax is \fun{GEN}{listinsert}{GEN ~L, GEN x, long n}. 2035 2036 \subsec{listkill$(~L)$}\kbdsidx{listkill}\label{se:listkill} 2037 Obsolete, retained for backward compatibility. Just use \kbd{L = List()} 2038 instead of \kbd{listkill(L)}. In most cases, you won't even need that, e.g. 2039 local variables are automatically cleared when a user function returns. 2040 2041 The library syntax is \fun{void}{listkill}{GEN ~L}. 2042 2043 \subsec{listpop$(~\var{list},\{n\})$}\kbdsidx{listpop}\label{se:listpop} 2044 Removes the $n$-th element of the list 2045 \var{list} (which must be of type \typ{LIST}). If $n$ is omitted, 2046 or greater than the list current length, removes the last element. 2047 If the list is already empty, do nothing. This runs in time $O(\#L - n + 1)$. 2048 \bprog 2049 ? L = List([1,2,3,4]); 2050 ? listpop(~L); L \\ remove last entry 2051 %2 = List([1, 2, 3]) 2052 ? listpop(~L, 1); L \\ remove first entry 2053 %3 = List([2, 3]) 2054 @eprog\noindent Note the \kbd{\til L}: this means that the function is 2055 called with a \emph{reference} to \kbd{L} and changes \kbd{L} in place. 2056 2057 The library syntax is \fun{void}{listpop0}{GEN ~list, long n}. 2058 2059 \subsec{listput$(~\var{list},x,\{n\})$}\kbdsidx{listput}\label{se:listput} 2060 Sets the $n$-th element of the list 2061 \var{list} (which must be of type \typ{LIST}) equal to $x$. If $n$ is omitted, 2062 or greater than the list length, appends $x$. The function returns the 2063 inserted element. 2064 \bprog 2065 ? L = List(); 2066 ? listput(~L, 1) 2067 %2 = 1 2068 ? listput(~L, 2) 2069 %3 = 2 2070 ? L 2071 %4 = List([1, 2]) 2072 @eprog\noindent Note the \kbd{\til L}: this means that the function is 2073 called with a \emph{reference} to \kbd{L} and changes \kbd{L} in place. 2074 2075 You may put an element into an occupied cell (not changing the 2076 list length), but it is easier to use the standard \kbd{list[n] = x} 2077 construct. 2078 \bprog 2079 ? listput(~L, 3, 1) \\ insert at position 1 2080 %5 = 3 2081 ? L 2082 %6 = List([3, 2]) 2083 ? L[2] = 4 \\ simpler 2084 %7 = List([3, 4]) 2085 ? L[10] = 1 \\ can't insert beyond the end of the list 2086 *** at top-level: L[10]=1 2087 *** ^------ 2088 *** nonexistent component: index > 2 2089 ? listput(L, 1, 10) \\ but listput can 2090 %8 = 1 2091 ? L 2092 %9 = List([3, 2, 1]) 2093 @eprog 2094 2095 This function runs in time $O(\#L)$ in the worst case (when the list must 2096 be reallocated), but in time $O(1)$ on average: any number of successive 2097 \kbd{listput}s run in time $O(\#L)$, where $\#L$ denotes the list 2098 \emph{final} length. 2099 2100 The library syntax is \fun{GEN}{listput0}{GEN ~list, GEN x, long n}. 2101 2102 \subsec{listsort$(~L,\{\fl=0\})$}\kbdsidx{listsort}\label{se:listsort} 2103 Sorts the \typ{LIST} \var{list} in place, with respect to the (somewhat 2104 arbitrary) universal comparison function \tet{cmp}. In particular, the 2105 ordering is the same as for sets and \tet{setsearch} can be used on a sorted 2106 list. No value is returned. If $\fl$ is nonzero, suppresses all repeated 2107 coefficients. 2108 \bprog 2109 ? L = List([1,2,4,1,3,-1]); listsort(~L); L 2110 %1 = List([-1, 1, 1, 2, 3, 4]) 2111 ? setsearch(L, 4) 2112 %2 = 6 2113 ? setsearch(L, -2) 2114 %3 = 0 2115 ? listsort(~L, 1); L \\ remove duplicates 2116 %4 = List([-1, 1, 2, 3, 4]) 2117 @eprog\noindent Note the \kbd{\til L}: this means that the function is 2118 called with a \emph{reference} to \kbd{L} and changes \kbd{L} in place: 2119 this is faster than the \kbd{vecsort} command since the list 2120 is sorted in place and we avoid unnecessary copies. 2121 \bprog 2122 ? v = vector(100,i,random); L = List(v); 2123 ? for(i=1,10^4, vecsort(v)) 2124 time = 162 ms. 2125 ? for(i=1,10^4, vecsort(L)) 2126 time = 162 ms. 2127 ? for(i=1,10^4, listsort(~L)) 2128 time = 63 ms. 2129 @eprog 2130 2131 The library syntax is \fun{void}{listsort}{GEN ~L, long flag}. 2132 2133 \subsec{localbitprec$(p)$}\kbdsidx{localbitprec}\label{se:localbitprec} 2134 Set the real precision to $p$ bits in the dynamic scope. 2135 All computations are performed as if \tet{realbitprecision} was $p$: 2136 transcendental constants (e.g.~\kbd{Pi}) and 2137 conversions from exact to floating point inexact data use $p$ bits, as well as 2138 iterative routines implicitly using a floating point 2139 accuracy as a termination criterion (e.g.~\tet{solve} or \tet{intnum}). 2140 But \kbd{realbitprecision} itself is unaffected 2141 and is ``unmasked'' when we exit the dynamic (\emph{not} lexical) scope. 2142 In effect, this is similar to 2143 \bprog 2144 my(bit = default(realbitprecision)); 2145 default(realbitprecision,p); 2146 ... 2147 default(realbitprecision, bit); 2148 @eprog\noindent but is both less cumbersome, cleaner (no need to manipulate 2149 a global variable, which in fact never changes and is only temporarily masked) 2150 and more robust: if the above computation is interrupted or an exception 2151 occurs, \kbd{realbitprecision} will not be restored as intended. 2152 2153 Such \kbd{localbitprec} statements can be nested, the innermost one taking 2154 precedence as expected. Beware that \kbd{localbitprec} follows the semantic of 2155 \tet{local}, not \tet{my}: a subroutine called from \kbd{localbitprec} scope 2156 uses the local accuracy: 2157 \bprog 2158 ? f()=bitprecision(1.0); 2159 ? f() 2160 %2 = 128 2161 ? localbitprec(1000); f() 2162 %3 = 1024 2163 @eprog\noindent Note that the bit precision of \emph{data} (\kbd{1.0} in the 2164 above example) increases by steps of 64 (32 on a 32-bit machine) so we get 2165 $1024$ instead of the expected $1000$; \kbd{localbitprec} bounds the 2166 relative error exactly as specified in functions that support that 2167 granularity (e.g.~\kbd{lfun}), and rounded to the next multiple of 64 2168 (resp.~32) everywhere else. 2169 2170 \misctitle{Warning} Changing \kbd{realbitprecision} or \kbd{realprecision} 2171 in programs is deprecated in favor of \kbd{localbitprec} and 2172 \kbd{localprec}. Think about the \kbd{realprecision} and 2173 \kbd{realbitprecision} defaults as interactive commands for the \kbd{gp} 2174 interpreter, best left out of GP programs. Indeed, the above rules imply that 2175 mixing both constructs yields surprising results: 2176 2177 \bprog 2178 ? \p38 2179 ? localprec(19); default(realprecision,1000); Pi 2180 %1 = 3.141592653589793239 2181 ? \p 2182 realprecision = 1001 significant digits (1000 digits displayed) 2183 @eprog\noindent Indeed, \kbd{realprecision} itself is ignored within 2184 \kbd{localprec} scope, so \kbd{Pi} is computed to a low accuracy. And when 2185 we leave the \kbd{localprec} scope, \kbd{realprecision} only regains precedence, 2186 it is not ``restored'' to the original value. 2187 %\syn{NO} 2188 2189 \subsec{localprec$(p)$}\kbdsidx{localprec}\label{se:localprec} 2190 Set the real precision to $p$ in the dynamic scope and return $p$. 2191 All computations are performed as if \tet{realprecision} was $p$: 2192 transcendental constants (e.g.~\kbd{Pi}) and 2193 conversions from exact to floating point inexact data use $p$ decimal 2194 digits, as well as iterative routines implicitly using a floating point 2195 accuracy as a termination criterion (e.g.~\tet{solve} or \tet{intnum}). 2196 But \kbd{realprecision} itself is unaffected 2197 and is ``unmasked'' when we exit the dynamic (\emph{not} lexical) scope. 2198 In effect, this is similar to 2199 \bprog 2200 my(prec = default(realprecision)); 2201 default(realprecision,p); 2202 ... 2203 default(realprecision, prec); 2204 @eprog\noindent but is both less cumbersome, cleaner (no need to manipulate 2205 a global variable, which in fact never changes and is only temporarily masked) 2206 and more robust: if the above computation is interrupted or an exception 2207 occurs, \kbd{realprecision} will not be restored as intended. 2208 2209 Such \kbd{localprec} statements can be nested, the innermost one taking 2210 precedence as expected. Beware that \kbd{localprec} follows the semantic of 2211 \tet{local}, not \tet{my}: a subroutine called from \kbd{localprec} scope 2212 uses the local accuracy: 2213 \bprog 2214 ? f()=precision(1.); 2215 ? f() 2216 %2 = 38 2217 ? localprec(19); f() 2218 %3 = 19 2219 @eprog\noindent 2220 \misctitle{Warning} Changing \kbd{realprecision} itself in programs is 2221 now deprecated in favor of \kbd{localprec}. Think about the 2222 \kbd{realprecision} default as an interactive command for the \kbd{gp} 2223 interpreter, best left out of GP programs. Indeed, the above rules 2224 imply that mixing both constructs yields surprising results: 2225 \bprog 2226 ? \p38 2227 ? localprec(19); default(realprecision,100); Pi 2228 %1 = 3.141592653589793239 2229 ? \p 2230 realprecision = 115 significant digits (100 digits displayed) 2231 @eprog\noindent Indeed, \kbd{realprecision} itself is ignored within 2232 \kbd{localprec} scope, so \kbd{Pi} is computed to a low accuracy. And when 2233 we leave \kbd{localprec} scope, \kbd{realprecision} only regains precedence, 2234 it is not ``restored'' to the original value. 2235 %\syn{NO} 2236 2237 \subsec{mapdelete$(~M,x)$}\kbdsidx{mapdelete}\label{se:mapdelete} 2238 Removes $x$ from the domain of the map $M$. 2239 \bprog 2240 ? M = Map(["a",1; "b",3; "c",7]); 2241 ? mapdelete(M,"b"); 2242 ? Mat(M) 2243 ["a" 1] 2244 2245 ["c" 7] 2246 @eprog 2247 2248 The library syntax is \fun{void}{mapdelete}{GEN ~M, GEN x}. 2249 2250 \subsec{mapget$(M,x)$}\kbdsidx{mapget}\label{se:mapget} 2251 Returns the image of $x$ by the map $M$. 2252 \bprog 2253 ? M=Map(["a",23;"b",43]); 2254 ? mapget(M,"a") 2255 %2 = 23 2256 ? mapget(M,"b") 2257 %3 = 43 2258 @eprog\noindent Raises an exception when the key $x$ is not present in $M$. 2259 \bprog 2260 ? mapget(M,"c") 2261 *** at top-level: mapget(M,"c") 2262 *** ^------------- 2263 *** mapget: nonexistent component in mapget: index not in map 2264 @eprog 2265 2266 The library syntax is \fun{GEN}{mapget}{GEN M, GEN x}. 2267 2268 \subsec{mapisdefined$(M,x,\{\&z\})$}\kbdsidx{mapisdefined}\label{se:mapisdefined} 2269 Returns true ($1$) if \kbd{x} has an image by the map $M$, false ($0$) 2270 otherwise. If \kbd{z} is present, set \kbd{z} to the image of $x$, if it exists. 2271 \bprog 2272 ? M1 = Map([1, 10; 2, 20]); 2273 ? mapisdefined(M1,3) 2274 %1 = 0 2275 ? mapisdefined(M1, 1, &z) 2276 %2 = 1 2277 ? z 2278 %3 = 10 2279 @eprog 2280 2281 \bprog 2282 ? M2 = Map(); N = 19; 2283 ? for (a=0, N-1, mapput(M2, a^3%N, a)); 2284 ? {for (a=0, N-1, 2285 if (mapisdefined(M2, a, &b), 2286 printf("%d is the cube of %d mod %d\n",a,b,N)));} 2287 0 is the cube of 0 mod 19 2288 1 is the cube of 11 mod 19 2289 7 is the cube of 9 mod 19 2290 8 is the cube of 14 mod 19 2291 11 is the cube of 17 mod 19 2292 12 is the cube of 15 mod 19 2293 18 is the cube of 18 mod 19 2294 @eprog 2295 2296 The library syntax is \fun{GEN}{mapisdefined}{GEN M, GEN x, GEN *z = NULL}. 2297 2298 \subsec{mapput$(~M,x,y)$}\kbdsidx{mapput}\label{se:mapput} 2299 Associates $x$ to $y$ in the map $M$. The value $y$ can be retrieved 2300 with \tet{mapget}. 2301 \bprog 2302 ? M = Map(); 2303 ? mapput(~M, "foo", 23); 2304 ? mapput(~M, 7718, "bill"); 2305 ? mapget(M, "foo") 2306 %4 = 23 2307 ? mapget(M, 7718) 2308 %5 = "bill" 2309 ? Vec(M) \\ keys 2310 %6 = [7718, "foo"] 2311 ? Mat(M) 2312 %7 = 2313 [ 7718 "bill"] 2314 2315 ["foo" 23] 2316 @eprog 2317 2318 The library syntax is \fun{void}{mapput}{GEN ~M, GEN x, GEN y}. 2319 2320 \subsec{print$(\{\var{str}\}*)$}\kbdsidx{print}\label{se:print} 2321 Outputs its arguments in raw format ending with a newline. 2322 The arguments are converted to strings following the rules in 2323 \secref{se:strings}. 2324 \bprog 2325 ? m = matid(2); 2326 ? print(m) \\ raw format 2327 [1, 0; 0, 1] 2328 ? printp(m) \\ prettymatrix format 2329 2330 [1 0] 2331 2332 [0 1] 2333 @eprog 2334 %\syn{NO} 2335 2336 \subsec{print1$(\{\var{str}\}*)$}\kbdsidx{print1}\label{se:print1} 2337 Outputs its arguments in raw 2338 format, without ending with a newline. Note that you can still embed newlines 2339 within your strings, using the \b{n} notation~! 2340 The arguments are converted to strings following the rules in 2341 \secref{se:strings}. 2342 %\syn{NO} 2343 2344 \subsec{printf$(\var{fmt},\{x\}*)$}\kbdsidx{printf}\label{se:printf} 2345 This function is based on the C library command of the same name. 2346 It prints its arguments according to the format \var{fmt}, which specifies how 2347 subsequent arguments are converted for output. The format is a 2348 character string composed of zero or more directives: 2349 2350 \item ordinary characters (not \kbd{\%}), printed unchanged, 2351 2352 \item conversions specifications (\kbd{\%} followed by some characters) 2353 which fetch one argument from the list and prints it according to the 2354 specification. 2355 2356 More precisely, a conversion specification consists in a \kbd{\%}, one or more 2357 optional flags (among \kbd{\#}, \kbd{0}, \kbd{-}, \kbd{+}, ` '), an optional 2358 decimal digit string specifying a minimal field width, an optional precision 2359 in the form of a period (`\kbd{.}') followed by a decimal digit string, and 2360 the conversion specifier (among \kbd{d},\kbd{i}, \kbd{o}, \kbd{u}, 2361 \kbd{x},\kbd{X}, \kbd{p}, \kbd{e},\kbd{E}, \kbd{f}, \kbd{g},\kbd{G}, \kbd{s}). 2362 2363 \misctitle{The flag characters} The character \kbd{\%} is followed by zero or 2364 more of the following flags: 2365 2366 \item \kbd{\#}: the value is converted to an ``alternate form''. For 2367 \kbd{o} conversion (octal), a \kbd{0} is prefixed to the string. For \kbd{x} 2368 and \kbd{X} conversions (hexa), respectively \kbd{0x} and \kbd{0X} are 2369 prepended. For other conversions, the flag is ignored. 2370 2371 \item \kbd{0}: the value should be zero padded. For 2372 \kbd{d}, 2373 \kbd{i}, 2374 \kbd{o}, 2375 \kbd{u}, 2376 \kbd{x}, 2377 \kbd{X} 2378 \kbd{e}, 2379 \kbd{E}, 2380 \kbd{f}, 2381 \kbd{F}, 2382 \kbd{g}, and 2383 \kbd{G} conversions, the value is padded on the left with zeros rather than 2384 blanks. (If the \kbd{0} and \kbd{-} flags both appear, the \kbd{0} flag is 2385 ignored.) 2386 2387 \item \kbd{-}: the value is left adjusted on the field boundary. (The 2388 default is right justification.) The value is padded on the right with 2389 blanks, rather than on the left with blanks or zeros. A \kbd{-} overrides a 2390 \kbd{0} if both are given. 2391 2392 \item \kbd{` '} (a space): a blank is left before a positive number 2393 produced by a signed conversion. 2394 2395 \item \kbd{+}: a sign (+ or -) is placed before a number produced by a 2396 signed conversion. A \kbd{+} overrides a space if both are used. 2397 2398 \misctitle{The field width} An optional decimal digit string (whose first 2399 digit is nonzero) specifying a \emph{minimum} field width. If the value has 2400 fewer characters than the field width, it is padded with spaces on the left 2401 (or right, if the left-adjustment flag has been given). In no case does a 2402 small field width cause truncation of a field; if the value is wider than 2403 the field width, the field is expanded to contain the conversion result. 2404 Instead of a decimal digit string, one may write \kbd{*} to specify that the 2405 field width is given in the next argument. 2406 2407 \misctitle{The precision} An optional precision in the form of a period 2408 (`\kbd{.}') followed by a decimal digit string. This gives 2409 the number of digits to appear after the radix character for \kbd{e}, 2410 \kbd{E}, \kbd{f}, and \kbd{F} conversions, the maximum number of significant 2411 digits for \kbd{g} and \kbd{G} conversions, and the maximum number of 2412 characters to be printed from an \kbd{s} conversion. 2413 Instead of a decimal digit string, one may write \kbd{*} to specify that the 2414 field width is given in the next argument. 2415 2416 \misctitle{The length modifier} This is ignored under \kbd{gp}, but 2417 necessary for \kbd{libpari} programming. Description given here for 2418 completeness: 2419 2420 \item \kbd{l}: argument is a \kbd{long} integer. 2421 2422 \item \kbd{P}: argument is a \kbd{GEN}. 2423 2424 \misctitle{The conversion specifier} A character that specifies the type of 2425 conversion to be applied. 2426 2427 \item \kbd{d}, \kbd{i}: a signed integer. 2428 2429 \item \kbd{o}, \kbd{u}, \kbd{x}, \kbd{X}: an unsigned integer, converted 2430 to unsigned octal (\kbd{o}), decimal (\kbd{u}) or hexadecimal (\kbd{x} or 2431 \kbd{X}) notation. The letters \kbd{abcdef} are used for \kbd{x} 2432 conversions; the letters \kbd{ABCDEF} are used for \kbd{X} conversions. 2433 2434 \item \kbd{e}, \kbd{E}: the (real) argument is converted in the style 2435 \kbd{[ -]d.ddd e[ -]dd}, where there is one digit before the decimal point, 2436 and the number of digits after it is equal to the precision; if the 2437 precision is missing, use the current \kbd{realprecision} for the total 2438 number of printed digits. If the precision is explicitly 0, no decimal-point 2439 character appears. An \kbd{E} conversion uses the letter \kbd{E} rather 2440 than \kbd{e} to introduce the exponent. 2441 2442 \item \kbd{f}, \kbd{F}: the (real) argument is converted in the style 2443 \kbd{[ -]ddd.ddd}, where the number of digits after the decimal point 2444 is equal to the precision; if the precision is missing, use the current 2445 \kbd{realprecision} for the total number of printed digits. If the precision 2446 is explicitly 0, no decimal-point character appears. If a decimal point 2447 appears, at least one digit appears before it. 2448 2449 \item \kbd{g}, \kbd{G}: the (real) argument is converted in style 2450 \kbd{e} or \kbd{f} (or \kbd{E} or \kbd{F} for \kbd{G} conversions) 2451 \kbd{[ -]ddd.ddd}, where the total number of digits printed 2452 is equal to the precision; if the precision is missing, use the current 2453 \kbd{realprecision}. If the precision is explicitly 0, it is treated as 1. 2454 Style \kbd{e} is used when 2455 the decimal exponent is $< -4$, to print \kbd{0.}, or when the integer 2456 part cannot be decided given the known significant digits, and the \kbd{f} 2457 format otherwise. 2458 2459 \item \kbd{c}: the integer argument is converted to an unsigned char, and the 2460 resulting character is written. 2461 2462 \item \kbd{s}: convert to a character string. If a precision is given, no 2463 more than the specified number of characters are written. 2464 2465 \item \kbd{p}: print the address of the argument in hexadecimal (as if by 2466 \kbd{\%\#x}). 2467 2468 \item \kbd{\%}: a \kbd{\%} is written. No argument is converted. The complete 2469 conversion specification is \kbd{\%\%}. 2470 2471 \noindent Examples: 2472 2473 \bprog 2474 ? printf("floor: %d, field width 3: %3d, with sign: %+3d\n", Pi, 1, 2); 2475 floor: 3, field width 3: 1, with sign: +2 2476 2477 ? printf("%.5g %.5g %.5g\n",123,123/456,123456789); 2478 123.00 0.26974 1.2346 e8 2479 2480 ? printf("%-2.5s:%2.5s:%2.5s\n", "P", "PARI", "PARIGP"); 2481 P :PARI:PARIG 2482 2483 \\ min field width and precision given by arguments 2484 ? x = 23; y=-1/x; printf("x=%+06.2f y=%+0*.*f\n", x, 6, 2, y); 2485 x=+23.00 y=-00.04 2486 2487 \\ minimum fields width 5, pad left with zeroes 2488 ? for (i = 2, 5, printf("%05d\n", 10^i)) 2489 00100 2490 01000 2491 10000 2492 100000 \\@com don't truncate fields whose length is larger than the minimum width 2493 ? printf("%.2f |%06.2f|", Pi,Pi) 2494 3.14 | 3.14| 2495 @eprog\noindent All numerical conversions apply recursively to the entries 2496 of vectors and matrices: 2497 \bprog 2498 ? printf("%4d", [1,2,3]); 2499 [ 1, 2, 3] 2500 ? printf("%5.2f", mathilbert(3)); 2501 [ 1.00 0.50 0.33] 2502 2503 [ 0.50 0.33 0.25] 2504 2505 [ 0.33 0.25 0.20] 2506 @eprog 2507 \misctitle{Technical note} Our implementation of \tet{printf} 2508 deviates from the C89 and C99 standards in a few places: 2509 2510 \item whenever a precision is missing, the current \kbd{realprecision} is 2511 used to determine the number of printed digits (C89: use 6 decimals after 2512 the radix character). 2513 2514 \item in conversion style \kbd{e}, we do not impose that the 2515 exponent has at least two digits; we never write a \kbd{+} sign in the 2516 exponent; 0 is printed in a special way, always as \kbd{0.E\var{exp}}. 2517 2518 \item in conversion style \kbd{f}, we switch to style \kbd{e} if the 2519 exponent is greater or equal to the precision. 2520 2521 \item in conversion \kbd{g} and \kbd{G}, we do not remove trailing zeros 2522 from the fractional part of the result; nor a trailing decimal point; 2523 0 is printed in a special way, always as \kbd{0.E\var{exp}}. 2524 %\syn{NO} 2525 2526 \subsec{printp$(\{\var{str}\}*)$}\kbdsidx{printp}\label{se:printp} 2527 Outputs its arguments in prettymatrix format, ending with a 2528 newline. The arguments are converted to strings following the rules in 2529 \secref{se:strings}. 2530 \bprog 2531 ? m = matid(2); 2532 ? print(m) \\ raw format 2533 [1, 0; 0, 1] 2534 ? printp(m) \\ prettymatrix format 2535 2536 [1 0] 2537 2538 [0 1] 2539 @eprog 2540 %\syn{NO} 2541 2542 \subsec{printsep$(\var{sep},\{\var{str}\}*)$}\kbdsidx{printsep}\label{se:printsep} 2543 Outputs its arguments in raw format, ending with a newline. 2544 The arguments are converted to strings following the rules in 2545 \secref{se:strings}. Successive entries are separated by \var{sep}: 2546 \bprog 2547 ? printsep(":", 1,2,3,4) 2548 1:2:3:4 2549 @eprog 2550 %\syn{NO} 2551 2552 \subsec{printsep1$(\var{sep},\{\var{str}\}*)$}\kbdsidx{printsep1}\label{se:printsep1} 2553 Outputs its arguments in raw format, without ending with a 2554 newline. The arguments are converted to strings following the rules in 2555 \secref{se:strings}. Successive entries are separated by \var{sep}: 2556 \bprog 2557 ? printsep1(":", 1,2,3,4);print("|") 2558 1:2:3:4| 2559 @eprog 2560 %\syn{NO} 2561 2562 \subsec{printtex$(\{\var{str}\}*)$}\kbdsidx{printtex}\label{se:printtex} 2563 Outputs its arguments in \TeX\ format. This output can then be 2564 used in a \TeX\ manuscript, see \kbd{strtex} for details. The arguments are 2565 converted to strings following the rules in \secref{se:strings}. The printing 2566 is done on the standard output. If you want to print it to a file you should 2567 use \kbd{writetex} (see there). 2568 2569 Another possibility is to enable the \tet{log} default 2570 (see~\secref{se:defaults}). 2571 You could for instance do:\sidx{logfile} 2572 % 2573 \bprog 2574 default(logfile, "new.tex"); 2575 default(log, 1); 2576 printtex(result); 2577 @eprog 2578 %\syn{NO} 2579 2580 \subsec{quit$(\{\var{status} = 0\})$}\kbdsidx{quit}\label{se:quit} 2581 Exits \kbd{gp} and return to the system with exit status 2582 \kbd{status}, a small integer. A nonzero exit status normally indicates 2583 abnormal termination. (Note: the system actually sees only 2584 \kbd{status} mod $256$, see your man pages for \kbd{exit(3)} or \kbd{wait(2)}). 2585 2586 \subsec{read$(\{\var{filename}\})$}\kbdsidx{read}\label{se:read} 2587 Reads in the file 2588 \var{filename} (subject to string expansion). If \var{filename} is 2589 omitted, re-reads the last file that was fed into \kbd{gp}. The return 2590 value is the result of the last expression evaluated. 2591 2592 If a GP \tet{binary file} is read using this command (see 2593 \secref{se:writebin}), the file is loaded and the last object in the file 2594 is returned. 2595 2596 In case the file you read in contains an \tet{allocatemem} statement (to be 2597 generally avoided), you should leave \kbd{read} instructions by themselves, 2598 and not part of larger instruction sequences. 2599 2600 \misctitle{Variants} \kbd{readvec} allows to read a whole file at once; 2601 \kbd{fileopen} followed by either \kbd{fileread} (evaluated lines) or 2602 \kbd{filereadstr} (lines as nonevaluated strings) allows to read a file 2603 one line at a time. 2604 2605 The library syntax is \fun{GEN}{gp_read_file}{const char *filename}. 2606 2607 \subsec{readstr$(\{\var{filename}\})$}\kbdsidx{readstr}\label{se:readstr} 2608 Reads in the file \var{filename} and return a vector of GP strings, 2609 each component containing one line from the file. If \var{filename} is 2610 omitted, re-reads the last file that was fed into \kbd{gp}. 2611 2612 The library syntax is \fun{GEN}{readstr}{const char *filename}. 2613 2614 \subsec{readvec$(\{\var{filename}\})$}\kbdsidx{readvec}\label{se:readvec} 2615 Reads in the file 2616 \var{filename} (subject to string expansion). If \var{filename} is 2617 omitted, re-reads the last file that was fed into \kbd{gp}. The return 2618 value is a vector whose components are the evaluation of all sequences 2619 of instructions contained in the file. For instance, if \var{file} contains 2620 \bprog 2621 1 2622 2 2623 3 2624 @eprog\noindent 2625 then we will get: 2626 \bprog 2627 ? \r a 2628 %1 = 1 2629 %2 = 2 2630 %3 = 3 2631 ? read(a) 2632 %4 = 3 2633 ? readvec(a) 2634 %5 = [1, 2, 3] 2635 @eprog 2636 In general a sequence is just a single line, but as usual braces and 2637 \kbd{\bs} may be used to enter multiline sequences. 2638 2639 The library syntax is \fun{GEN}{gp_readvec_file}{const char *filename}. 2640 The underlying library function 2641 \fun{GEN}{gp_readvec_stream}{FILE *f} is usually more flexible. 2642 2643 \subsec{select$(f, A, \{\fl = 0\})$}\kbdsidx{select}\label{se:select} 2644 We first describe the default behavior, when $\fl$ is 0 or omitted. 2645 Given a vector or list \kbd{A} and a \typ{CLOSURE} \kbd{f}, \kbd{select} 2646 returns the elements $x$ of \kbd{A} such that $f(x)$ is nonzero. In other 2647 words, \kbd{f} is seen as a selection function returning a boolean value. 2648 \bprog 2649 ? select(x->isprime(x), vector(50,i,i^2+1)) 2650 %1 = [2, 5, 17, 37, 101, 197, 257, 401, 577, 677, 1297, 1601] 2651 ? select(x->(x<100), %) 2652 %2 = [2, 5, 17, 37] 2653 @eprog\noindent returns the primes of the form $i^2+1$ for some $i\leq 50$, 2654 then the elements less than 100 in the preceding result. The \kbd{select} 2655 function also applies to a matrix \kbd{A}, seen as a vector of columns, i.e. it 2656 selects columns instead of entries, and returns the matrix whose columns are 2657 the selected ones. 2658 2659 \misctitle{Remark} For $v$ a \typ{VEC}, \typ{COL}, \typ{VECSMALL}, 2660 \typ{LIST} or \typ{MAT}, the alternative set-notations 2661 \bprog 2662 [g(x) | x <- v, f(x)] 2663 [x | x <- v, f(x)] 2664 [g(x) | x <- v] 2665 @eprog\noindent 2666 are available as shortcuts for 2667 \bprog 2668 apply(g, select(f, Vec(v))) 2669 select(f, Vec(v)) 2670 apply(g, Vec(v)) 2671 @eprog\noindent respectively: 2672 \bprog 2673 ? [ x | x <- vector(50,i,i^2+1), isprime(x) ] 2674 %1 = [2, 5, 17, 37, 101, 197, 257, 401, 577, 677, 1297, 1601] 2675 @eprog 2676 2677 \noindent If $\fl = 1$, this function returns instead the \emph{indices} of 2678 the selected elements, and not the elements themselves (indirect selection): 2679 \bprog 2680 ? V = vector(50,i,i^2+1); 2681 ? select(x->isprime(x), V, 1) 2682 %2 = Vecsmall([1, 2, 4, 6, 10, 14, 16, 20, 24, 26, 36, 40]) 2683 ? vecextract(V, %) 2684 %3 = [2, 5, 17, 37, 101, 197, 257, 401, 577, 677, 1297, 1601] 2685 @eprog\noindent 2686 The following function lists the elements in $(\Z/N\Z)^*$: 2687 \bprog 2688 ? invertibles(N) = select(x->gcd(x,N) == 1, [1..N]) 2689 @eprog 2690 2691 \noindent Finally 2692 \bprog 2693 ? select(x->x, M) 2694 @eprog\noindent selects the nonzero entries in \kbd{M}. If the latter is a 2695 \typ{MAT}, we extract the matrix of nonzero columns. Note that \emph{removing} 2696 entries instead of selecting them just involves replacing the selection 2697 function \kbd{f} with its negation: 2698 \bprog 2699 ? select(x->!isprime(x), vector(50,i,i^2+1)) 2700 @eprog 2701 2702 \synt{genselect}{void *E, long (*fun)(void*,GEN), GEN a}. Also available 2703 is \fun{GEN}{genindexselect}{void *E, long (*fun)(void*, GEN), GEN a}, 2704 corresponding to $\fl = 1$. 2705 2706 \subsec{self$()$}\kbdsidx{self}\label{se:self} 2707 Return the calling function or closure as a \typ{CLOSURE} object. 2708 This is useful for defining anonymous recursive functions. 2709 \bprog 2710 ? (n -> if(n==0,1,n*self()(n-1)))(5) 2711 %1 = 120 \\ 5! 2712 2713 ? (n -> if(n<=1, n, self()(n-1)+self()(n-2)))(20) 2714 %2 = 6765 \\ Fibonacci(20) 2715 @eprog 2716 2717 The library syntax is \fun{GEN}{pari_self}{}. 2718 2719 \subsec{setrand$(n)$}\kbdsidx{setrand}\label{se:setrand} 2720 Reseeds the random number generator using the seed $n$. No value is 2721 returned. The seed is a small positive integer $0 < n < 2^{64}$ used to 2722 generate deterministically a suitable state array. All gp session start 2723 by an implicit \kbd{setrand(1)}, so resetting the seed to this value allows 2724 to replay all computations since the session start. Alternatively, 2725 running a randomized computation starting by \kbd{setrand}($n$) 2726 twice with the same $n$ will generate the exact same output. 2727 2728 In the other direction, including a call to \kbd{setrand(getwalltime())} 2729 from your gprc will cause GP to produce different streams of random numbers 2730 in each session. (Unix users may want to use \kbd{/dev/urandom} instead 2731 of \kbd{getwalltime}.) 2732 2733 For debugging purposes, one can also record a particular random state 2734 using \kbd{getrand} (the value is encoded as a huge integer) and feed it to 2735 \kbd{setrand}: 2736 \bprog 2737 ? state = getrand(); \\ record seed 2738 ... 2739 ? setrand(state); \\ we can now replay the exact same computations 2740 @eprog 2741 2742 The library syntax is \fun{void}{setrand}{GEN n}. 2743 2744 \subsec{strchr$(x)$}\kbdsidx{strchr}\label{se:strchr} 2745 Converts integer or vector of integers $x$ to a string, translating each 2746 integer (in the range $[1,255]$) into a character using ASCII encoding. 2747 \bprog 2748 ? strchr(97) 2749 %1 = "a" 2750 ? Vecsmall("hello world") 2751 %2 = Vecsmall([104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]) 2752 ? strchr(%) 2753 %3 = "hello world" 2754 @eprog 2755 2756 The library syntax is \fun{GEN}{pari_strchr}{GEN x}. 2757 2758 \subsec{strexpand$(\{x\}*)$}\kbdsidx{strexpand}\label{se:strexpand} 2759 Converts its argument list into a 2760 single character string (type \typ{STR}, the empty string if $x$ is omitted). 2761 Then perform \idx{environment expansion}, see \secref{se:envir}. 2762 This feature can be used to read \idx{environment variable} values. 2763 \bprog 2764 ? strexpand("$HOME/doc") 2765 %1 = "/home/pari/doc" 2766 2767 ? module = "aprcl"; n = 10; 2768 ? strexpand("$HOME/doc/", module, n, ".tex") 2769 %3 = "/home/pari/doc/aprcl10.tex" 2770 @eprog 2771 2772 The individual arguments are read in string context, see \secref{se:strings}. 2773 %\syn{NO} 2774 2775 \subsec{strjoin$(v,\{p = ""\})$}\kbdsidx{strjoin}\label{se:strjoin} 2776 Joins the strings in vector $v$, separating them with delimiter $p$. 2777 The reverse operation is \kbd{strsplit}. 2778 \bprog 2779 ? v = ["abc", "def", "ghi"] 2780 ? strjoin(v, "/") 2781 %2 = "abc/def/ghi" 2782 ? strjoin(v) 2783 %3 = "abcdefghi" 2784 @eprog 2785 2786 The library syntax is \fun{GEN}{strjoin}{GEN v, GEN p = NULL}. 2787 2788 \subsec{strprintf$(\var{fmt},\{x\}*)$}\kbdsidx{strprintf}\label{se:strprintf} 2789 Returns a string built from the remaining arguments according to the 2790 format fmt. The format consists of ordinary characters (not \%), printed 2791 unchanged, and conversions specifications. See \kbd{printf}. 2792 \bprog 2793 ? dir = "/home/pari"; file = "aprcl"; n = 10; 2794 ? strprintf("%s/%s%ld.tex", dir, file, n) 2795 %2 = "/home/pari/aprcl10.tex" 2796 @eprog 2797 %\syn{NO} 2798 2799 \subsec{strsplit$(s,\{p = ""\})$}\kbdsidx{strsplit}\label{se:strsplit} 2800 Splits the string $s$ into a vector of strings, with $p$ acting as a 2801 delimiter. If $p$ is empty or omitted, split the string into characters. 2802 \bprog 2803 ? strsplit("abc::def::ghi", "::") 2804 %1 = ["abc", "def", "ghi"] 2805 ? strsplit("abc", "") 2806 %2 = ["a", "b", "c"] 2807 ? strsplit("aba", "a") 2808 @eprog\noindent If $s$ starts (resp.~ends) with the pattern $p$, then the 2809 first (resp.~last) entry in the vector is the empty string: 2810 \bprog 2811 ? strsplit("aba", "a") 2812 %3 = ["", "b", ""] 2813 @eprog 2814 2815 The library syntax is \fun{GEN}{strsplit}{GEN s, GEN p = NULL}. 2816 2817 \subsec{strtex$(\{x\}*)$}\kbdsidx{strtex}\label{se:strtex} 2818 Translates its arguments to TeX format, and concatenates the results into a 2819 single character string (type \typ{STR}, the empty string if $x$ is omitted). 2820 2821 The individual arguments are read in string context, see \secref{se:strings}. 2822 \bprog 2823 ? v = [1, 2, 3] 2824 %1 [1, 2, 3] 2825 ? strtex(v) 2826 %2 = "\\pmatrix{ 1&2&3\\cr}\n" 2827 @eprog 2828 2829 \misctitle{\TeX-nical notes} The TeX output engine was originally written 2830 for plain TeX and designed for maximal portability. Unfortunately later 2831 \kbd{LaTeX} packages have obsoleted valid \TeX\ primitives, leading us 2832 to replace TeX's \kbd{\bs{}over} by LaTeX's \kbd{\bs{}frac} in PARI's TeX 2833 output. We have decided not to update further our TeX markup and let the 2834 users of various LaTeX engines customize their preambles. The following 2835 documents the precise changes you may need to include in your style files to 2836 incorporate PARI TeX output verbatim: 2837 2838 \item if you enabled bit 4 in \tet{TeXstyle} default, you must define 2839 \kbd{\bs{}PARIbreak}; see \kbd{??TeXstyle}; 2840 2841 \item if you use plain TeX only: you must define \kbd{\bs{}frac} as follows 2842 \bprog 2843 \def\frac#1#2{{#1\over#2}} 2844 @eprog 2845 2846 \item if you use LaTeX and \kbd{amsmath}, \kbd{\bs{}pmatrix} is 2847 obsoleted in favor of the \kbd{pmatrix} environment; see 2848 \kbd{examples/parigp.sty} for how to re-enable the deprecated construct. 2849 2850 %\syn{NO} 2851 2852 \subsec{strtime$(t)$}\kbdsidx{strtime}\label{se:strtime} 2853 Return a string describing the time t in milliseconds in the format used by 2854 the GP timer. 2855 \bprog 2856 ? print(strtime(12345678)) 2857 3h, 25min, 45,678 ms 2858 ? { 2859 my(t=getabstime()); 2860 F=factor(2^256+1);t=getabstime()-t; 2861 print("factor(2^256+1) took ",strtime(t)); 2862 } 2863 factor(2^256+1) took 1,320 ms 2864 @eprog 2865 2866 The library syntax is \fun{GEN}{strtime}{long t}. 2867 2868 \subsec{system$(\var{str})$}\kbdsidx{system}\label{se:system} 2869 \var{str} is a string representing a system command. This command is 2870 executed, its output written to the standard output (this won't get into your 2871 logfile), and control returns to the PARI system. This simply calls the C 2872 \kbd{system} command. 2873 2874 The library syntax is \fun{void}{gpsystem}{const char *str}. 2875 2876 \subsec{trap$(\{e\}, \{\var{rec}\}, \var{seq})$}\kbdsidx{trap}\label{se:trap} 2877 This function is obsolete, use \tet{iferr}, which has a nicer and much 2878 more powerful interface. For compatibility's sake we now describe the 2879 \emph{obsolete} function \tet{trap}. 2880 2881 This function tries to 2882 evaluate \var{seq}, trapping runtime error $e$, that is effectively preventing 2883 it from aborting computations in the usual way; the recovery sequence 2884 \var{rec} is executed if the error occurs and the evaluation of \var{rec} 2885 becomes the result of the command. If $e$ is omitted, all exceptions are 2886 trapped. See \secref{se:errorrec} for an introduction to error recovery 2887 under \kbd{gp}. 2888 2889 \bprog 2890 ? \\@com trap division by 0 2891 ? inv(x) = trap (e_INV, INFINITY, 1/x) 2892 ? inv(2) 2893 %1 = 1/2 2894 ? inv(0) 2895 %2 = INFINITY 2896 @eprog\noindent 2897 Note that \var{seq} is effectively evaluated up to the point that produced 2898 the error, and the recovery sequence is evaluated starting from that same 2899 context, it does not "undo" whatever happened in the other branch (restore 2900 the evaluation context): 2901 \bprog 2902 ? x = 1; trap (, /* recover: */ x, /* try: */ x = 0; 1/x) 2903 %1 = 0 2904 @eprog 2905 2906 \misctitle{Note} The interface is currently not adequate for trapping 2907 individual exceptions. In the current version \vers, the following keywords 2908 are recognized, but the name list will be expanded and changed in the 2909 future (all library mode errors can be trapped: it's a matter of defining 2910 the keywords to \kbd{gp}): 2911 2912 \kbd{e\_ALARM}: alarm time-out 2913 2914 \kbd{e\_ARCH}: not available on this architecture or operating system 2915 2916 \kbd{e\_STACK}: the PARI stack overflows 2917 2918 \kbd{e\_INV}: impossible inverse 2919 2920 \kbd{e\_IMPL}: not yet implemented 2921 2922 \kbd{e\_OVERFLOW}: all forms of arithmetic overflow, including length 2923 or exponent overflow (when a larger value is supplied than the 2924 implementation can handle). 2925 2926 \kbd{e\_SYNTAX}: syntax error 2927 2928 \kbd{e\_MISC}: miscellaneous error 2929 2930 \kbd{e\_TYPE}: wrong type 2931 2932 \kbd{e\_USER}: user error (from the \kbd{error} function) 2933 2934 The library syntax is \fun{GEN}{trap0}{const char *e = NULL, GEN rec = NULL, GEN seq = NULL}. 2935 2936 \subsec{type$(x)$}\kbdsidx{type}\label{se:type} 2937 This is useful only under \kbd{gp}. Returns the internal type name of 2938 the PARI object $x$ as a string. Check out existing type names with the 2939 metacommand \b{t}. For example \kbd{type(1)} will return "\typ{INT}". 2940 2941 The library syntax is \fun{GEN}{type0}{GEN x}. 2942 The macro \kbd{typ} is usually simpler to use since it returns a 2943 \kbd{long} that can easily be matched with the symbols \typ{*}. The name 2944 \kbd{type} was avoided since it is a reserved identifier for some compilers. 2945 2946 \subsec{unexport$(x,...,z)$}\kbdsidx{unexport}\label{se:unexport} 2947 Remove $x,\ldots, z$ from the list of variables exported 2948 to the parallel world. See \key{export}. 2949 2950 \subsec{unexportall$()$}\kbdsidx{unexportall}\label{se:unexportall} 2951 Empty the list of variables exported to the parallel world. 2952 2953 The library syntax is \fun{void}{unexportall}{}. 2954 2955 \subsec{uninline$()$}\kbdsidx{uninline}\label{se:uninline} 2956 Exit the scope of all current \kbd{inline} variables. DEPRECATED, use 2957 \kbd{export} / \kbd{unexport}. 2958 2959 \subsec{version$()$}\kbdsidx{version}\label{se:version} 2960 Returns the current version number as a \typ{VEC} with three integer 2961 components (major version number, minor version number and patchlevel); 2962 if your sources were obtained through our version control system, this will 2963 be followed by further more precise arguments, including 2964 e.g.~a~\kbd{git} \emph{commit hash}. 2965 2966 This function is present in all versions of PARI following releases 2.3.4 2967 (stable) and 2.4.3 (testing). 2968 2969 Unless you are working with multiple development versions, you probably only 2970 care about the 3 first numeric components. In any case, the \kbd{lex} function 2971 offers a clever way to check against a particular version number, since it will 2972 compare each successive vector entry, numerically or as strings, and will not 2973 mind if the vectors it compares have different lengths: 2974 \bprog 2975 if (lex(version(), [2,3,5]) >= 0, 2976 \\ code to be executed if we are running 2.3.5 or more recent. 2977 , 2978 \\ compatibility code 2979 ); 2980 @eprog\noindent On a number of different machines, \kbd{version()} could return either of 2981 \bprog 2982 %1 = [2, 3, 4] \\ released version, stable branch 2983 %1 = [2, 4, 3] \\ released version, testing branch 2984 %1 = [2, 6, 1, 15174, ""505ab9b"] \\ development 2985 @eprog 2986 2987 In particular, if you are only working with released versions, the first 2988 line of the gp introductory message can be emulated by 2989 \bprog 2990 [M,m,p] = version(); 2991 printf("GP/PARI CALCULATOR Version %s.%s.%s", M,m,p); 2992 @eprog\noindent If you \emph{are} working with many development versions of 2993 PARI/GP, the 4th and/or 5th components can be profitably included in the 2994 name of your logfiles, for instance. 2995 2996 \misctitle{Technical note} For development versions obtained via \kbd{git}, 2997 the 4th and 5th components are liable to change eventually, but we document 2998 their current meaning for completeness. The 4th component counts the number 2999 of reachable commits in the branch (analogous to \kbd{svn}'s revision 3000 number), and the 5th is the \kbd{git} commit hash. In particular, \kbd{lex} 3001 comparison still orders correctly development versions with respect to each 3002 others or to released versions (provided we stay within a given branch, 3003 e.g. \kbd{master})! 3004 3005 The library syntax is \fun{GEN}{pari_version}{}. 3006 3007 \subsec{warning$(\{\var{str}\}*)$}\kbdsidx{warning}\label{se:warning} 3008 Outputs the message ``user warning'' 3009 and the argument list (each of them interpreted as a string). 3010 If colors are enabled, this warning will be in a different color, 3011 making it easy to distinguish. 3012 \bprog 3013 warning(n, " is very large, this might take a while.") 3014 @eprog 3015 % \syn{NO} 3016 3017 \subsec{whatnow$(\var{key})$}\kbdsidx{whatnow}\label{se:whatnow} 3018 If keyword \var{key} is the name of a function that was present in GP 3019 version 1.39.15, outputs the new function name and syntax, if it 3020 changed at all. Functions that where introduced since then, then modified 3021 are also recognized. 3022 \bprog 3023 ? whatnow("mu") 3024 New syntax: mu(n) ===> moebius(n) 3025 3026 moebius(x): Moebius function of x. 3027 3028 ? whatnow("sin") 3029 This function did not change 3030 @eprog When a function was removed and the underlying functionality 3031 is not available under a compatible interface, no equivalent is mentioned: 3032 \bprog 3033 ? whatnow("buchfu") 3034 This function no longer exists 3035 @eprog\noindent (The closest equivalent would be to set \kbd{K = bnfinit(T)} 3036 then access \kbd{K.fu}.) 3037 3038 \subsec{write$(\var{filename},\{\var{str}\}*)$}\kbdsidx{write}\label{se:write} 3039 Writes (appends) to \var{filename} the remaining arguments, and appends a 3040 newline (same output as \kbd{print}). 3041 3042 \misctitle{Variant} The high-level function \kbd{write} is expensive when many 3043 consecutive writes are expected because it cannot use buffering. The low-level 3044 interface \kbd{fileopen} / \kbd{filewrite} / \kbd{fileclose} is more efficient. 3045 It also allows to truncate existing files and replace their contents. 3046 %\syn{NO} 3047 3048 \subsec{write1$(\var{filename},\{\var{str}\}*)$}\kbdsidx{write1}\label{se:write1} 3049 Writes (appends) to \var{filename} the remaining arguments without a 3050 trailing newline (same output as \kbd{print1}). 3051 %\syn{NO} 3052 3053 \subsec{writebin$(\var{filename},\{x\})$}\kbdsidx{writebin}\label{se:writebin} 3054 Writes (appends) to 3055 \var{filename} the object $x$ in binary format. This format is not human 3056 readable, but contains the exact internal structure of $x$, and is much 3057 faster to save/load than a string expression, as would be produced by 3058 \tet{write}. The binary file format includes a magic number, so that such a 3059 file can be recognized and correctly input by the regular \tet{read} or \b{r} 3060 function. If saved objects refer to polynomial variables that are not 3061 defined in the new session, they will be displayed as \kbd{t$n$} for some 3062 integer $n$ (the attached variable number). 3063 Installed functions and history objects can not be saved via this function. 3064 3065 If $x$ is omitted, saves all user variables from the session, together with 3066 their names. Reading such a ``named object'' back in a \kbd{gp} session will set 3067 the corresponding user variable to the saved value. E.g after 3068 \bprog 3069 x = 1; writebin("log") 3070 @eprog\noindent 3071 reading \kbd{log} into a clean session will set \kbd{x} to $1$. 3072 The relative variables priorities (see \secref{se:priority}) of new variables 3073 set in this way remain the same (preset variables retain their former 3074 priority, but are set to the new value). In particular, reading such a 3075 session log into a clean session will restore all variables exactly as they 3076 were in the original one. 3077 3078 Just as a regular input file, a binary file can be compressed 3079 using \tet{gzip}, provided the file name has the standard \kbd{.gz} 3080 extension.\sidx{binary file} 3081 3082 In the present implementation, the binary files are architecture dependent 3083 and compatibility with future versions of \kbd{gp} is not guaranteed. Hence 3084 binary files should not be used for long term storage (also, they are 3085 larger and harder to compress than text files). 3086 3087 The library syntax is \fun{void}{gpwritebin}{const char *filename, GEN x = NULL}. 3088 3089 \subsec{writetex$(\var{filename},\{\var{str}\}*)$}\kbdsidx{writetex}\label{se:writetex} 3090 As \kbd{write}, in \TeX\ format. See \tet{strtex} for details: 3091 this function is essentially equivalent to calling \kbd{strtex} on remaining 3092 arguments and writing them to file. 3093 %\syn{NO} 3094 3095 \section{Parallel programming} 3096 3097 These function are only available if PARI was configured using 3098 \kbd{Configure --mt=\dots}. Two multithread interfaces are supported: 3099 3100 \item POSIX threads 3101 3102 \item Message passing interface (MPI) 3103 3104 As a rule, POSIX threads are well-suited for single systems, while MPI is used 3105 by most clusters. However the parallel GP interface does not depend on the 3106 chosen multithread interface: a properly written GP program will work 3107 identically with both. 3108 3109 \subsec{parapply$(f, x)$}\kbdsidx{parapply}\label{se:parapply} 3110 Parallel evaluation of \kbd{f} on the elements of \kbd{x}. 3111 The function \kbd{f} must not access global variables or variables 3112 declared with local(), and must be free of side effects. 3113 \bprog 3114 parapply(factor,[2^256 + 1, 2^193 - 1]) 3115 @eprog 3116 factors $2^{256} + 1$ and $2^{193} - 1$ in parallel. 3117 \bprog 3118 { 3119 my(E = ellinit([1,3]), V = vector(12,i,randomprime(2^200))); 3120 parapply(p->ellcard(E,p), V) 3121 } 3122 @eprog 3123 computes the order of $E(\F_p)$ for $12$ random primes of $200$ bits. 3124 3125 The library syntax is \fun{GEN}{parapply}{GEN f, GEN x}. 3126 3127 \subsec{pareval$(x)$}\kbdsidx{pareval}\label{se:pareval} 3128 Parallel evaluation of the elements of \kbd{x}, where \kbd{x} is a 3129 vector of closures. The closures must be of arity $0$, must not access 3130 global variables or variables declared with \kbd{local} and must be 3131 free of side effects. 3132 3133 Here is an artificial example explaining the MOV attack on the elliptic 3134 discrete log problem (by reducing it to a standard discrete log over a 3135 finite field): 3136 \bprog 3137 { 3138 my(q = 2^30 + 3, m = 40 * q; p = 1 + m^2); \\ p, q are primes 3139 my(E = ellinit([0,0,0,1,0] * Mod(1,p))); 3140 my([P, Q] = ellgenerators(E)); 3141 \\ E(F_p) ~ Z/m P + Z/m Q and the order of the 3142 \\ Weil pairing <P,Q> in (Z/p)^* is m 3143 my(F = [m,factor(m)], e = random(m), R, wR, wQ); 3144 R = ellpow(E, Q, e); 3145 wR = ellweilpairing(E,P,R,m); 3146 wQ = ellweilpairing(E,P,Q,m); \\ wR = wQ^e 3147 pareval([()->znlog(wR,wQ,F), ()->elllog(E,R,Q), ()->e]) 3148 } 3149 @eprog\noindent Note the use of \kbd{my} to pass "arguments" to the 3150 functions we need to evaluate while satisfying the listed requirements: 3151 closures of arity $0$ and no global variables (another possibility would be 3152 to use \kbd{export}). As a result, the final three statements satisfy all 3153 the listed requirements and are run in parallel. (Which is silly for 3154 this computation but illustrates the use of pareval.) The function 3155 \kbd{parfor} is more powerful but harder to use. 3156 3157 The library syntax is \fun{GEN}{pareval}{GEN x}. 3158 3159 \subsec{parfor$(i=a,\{b\},\var{expr1},\{r\},\{\var{expr2}\})$}\kbdsidx{parfor}\label{se:parfor} 3160 Evaluates in parallel the expression \kbd{expr1} in the formal 3161 argument $i$ running from $a$ to $b$. 3162 If $b$ is set to \kbd{+oo}, the loop runs indefinitely. 3163 If $r$ and \kbd{expr2} are present, the expression \kbd{expr2} in the 3164 formal variables $r$ and $i$ is evaluated with $r$ running through all 3165 the different results obtained for \kbd{expr1} and $i$ takes the 3166 corresponding argument. 3167 3168 The computations of \kbd{expr1} are \emph{started} in increasing order 3169 of $i$; otherwise said, the computation for $i=c$ is started after those 3170 for $i=1, \ldots, c-1$ have been started, but before the computation for 3171 $i=c+1$ is started. Notice that the order of \emph{completion}, that is, 3172 the order in which the different $r$ become available, may be different; 3173 \kbd{expr2} is evaluated sequentially on each $r$ as it appears. 3174 3175 The following example computes the sum of the squares of the integers 3176 from $1$ to $10$ by computing the squares in parallel and is equivalent 3177 to \kbd{parsum (i=1, 10, i\^{}2)}: 3178 \bprog 3179 ? s=0; 3180 ? parfor (i=1, 10, i^2, r, s=s+r) 3181 ? s 3182 %3 = 385 3183 @eprog 3184 More precisely, apart from a potentially different order of evaluation 3185 due to the parallelism, the line containing \kbd{parfor} is equivalent to 3186 \bprog 3187 ? my (r); for (i=1, 10, r=i^2; s=s+r) 3188 @eprog 3189 The sequentiality of the evaluation of \kbd{expr2} ensures that the 3190 variable \kbd{s} is not modified concurrently by two different additions, 3191 although the order in which the terms are added is nondeterministic. 3192 3193 It is allowed for \kbd{expr2} to exit the loop using 3194 \kbd{break}/\kbd{next}/\kbd{return}. If that happens for $i=c$, 3195 then the evaluation of \kbd{expr1} and \kbd{expr2} is continued 3196 for all values $i<c$, and the return value is the one obtained for 3197 the smallest $i$ causing an interruption in \kbd{expr2} (it may be 3198 undefined if this is a \kbd{break}/\kbd{next}). 3199 In that case, using side-effects 3200 in \kbd{expr2} may lead to undefined behavior, as the exact 3201 number of values of $i$ for which it is executed is nondeterministic. 3202 The following example computes \kbd{nextprime(1000)} in parallel: 3203 \bprog 3204 ? parfor (i=1000, , isprime (i), r, if (r, return (i))) 3205 %1 = 1009 3206 @eprog 3207 3208 %\syn{NO} 3209 3210 \subsec{parforeach$(V,x,\var{expr1},\{r\},\{\var{expr2}\})$}\kbdsidx{parforeach}\label{se:parforeach} 3211 Evaluates in parallel the expression \kbd{expr1} in the formal 3212 argument $x$, where $x$ runs through all components of $V$. 3213 If $r$ and \kbd{expr2} are present, evaluate sequentially the expression 3214 \kbd{expr2}, in which the formal variables $x$ and $r$ are replaced 3215 by the successive arguments and corresponding values. The sequential 3216 evaluation ordering is not specified: 3217 \bprog 3218 ? parforeach([50..100], x,isprime(x), r, if(r,print(x))) 3219 53 3220 67 3221 71 3222 79 3223 83 3224 89 3225 97 3226 73 3227 59 3228 61 3229 @eprog 3230 %\syn{NO} 3231 3232 \subsec{parforprime$(p=a,\{b\},\var{expr1},\{r\},\{\var{expr2}\})$}\kbdsidx{parforprime}\label{se:parforprime} 3233 Behaves exactly as \kbd{parfor}, but loops only over prime values $p$. 3234 Precisely, the functions evaluates in parallel the expression \kbd{expr1} 3235 in the formal 3236 argument $p$ running through the primes from $a$ to $b$. 3237 If $b$ is set to \kbd{+oo}, the loop runs indefinitely. 3238 If $r$ and \kbd{expr2} are present, the expression \kbd{expr2} in the 3239 formal variables $r$ and $p$ is evaluated with $r$ running through all 3240 the different results obtained for \kbd{expr1} and $p$ takes the 3241 corresponding argument. 3242 3243 It is allowed fo \kbd{expr2} to exit the loop using 3244 \kbd{break}/\kbd{next}/\kbd{return}; see the remarks in the documentation 3245 of \kbd{parfor} for details. 3246 3247 %\syn{NO} 3248 3249 \subsec{parforprimestep$(p=a,\{b\},q,\var{expr1},\{r\},\{\var{expr2}\})$}\kbdsidx{parforprimestep}\label{se:parforprimestep} 3250 Behaves exactly as \kbd{parfor}, but loops only over prime values $p$ 3251 in an arithmetic progression 3252 Precisely, the functions evaluates in parallel the expression \kbd{expr1} 3253 in the formal argument $p$ running through the primes from $a$ to $b$ 3254 in an arithmetic progression of the form $a + k\*q$. 3255 ($p \equiv a \pmod{q}$) or an intmod \kbd{Mod(c,N)}. 3256 If $b$ is set to \kbd{+oo}, the loop runs indefinitely. 3257 If $r$ and \kbd{expr2} are present, the expression \kbd{expr2} in the 3258 formal variables $r$ and $p$ is evaluated with $r$ running through all 3259 the different results obtained for \kbd{expr1} and $p$ takes the 3260 corresponding argument. 3261 3262 It is allowed fo \kbd{expr2} to exit the loop using 3263 \kbd{break}/\kbd{next}/\kbd{return}; see the remarks in the documentation 3264 of \kbd{parfor} for details. 3265 3266 %\syn{NO} 3267 3268 \subsec{parforvec$(X=v,\var{expr1},\{j\},\{\var{expr2}\},\{\fl\})$}\kbdsidx{parforvec}\label{se:parforvec} 3269 Evaluates the sequence \kbd{expr2} (dependent on $X$ and $j$) for $X$ 3270 as generated by \kbd{forvec}, in random order, computed in parallel. Substitute 3271 for $j$ the value of \kbd{expr1} (dependent on $X$). 3272 3273 It is allowed fo \kbd{expr2} to exit the loop using 3274 \kbd{break}/\kbd{next}/\kbd{return}, however in that case, \kbd{expr2} will 3275 still be evaluated for all remaining value of $p$ less than the current one, 3276 unless a subsequent \kbd{break}/\kbd{next}/\kbd{return} happens. 3277 %\syn{NO} 3278 3279 \subsec{parselect$(f, A, \{\fl = 0\})$}\kbdsidx{parselect}\label{se:parselect} 3280 Selects elements of $A$ according to the selection function $f$, done in 3281 parallel. If \fl is $1$, return the indices of those elements (indirect 3282 selection) The function \kbd{f} must not access global variables or 3283 variables declared with local(), and must be free of side effects. 3284 3285 The library syntax is \fun{GEN}{parselect}{GEN f, GEN A, long flag}. 3286 3287 \subsec{parsum$(i=a,b,\var{expr})$}\kbdsidx{parsum}\label{se:parsum} 3288 Sum of expression \var{expr}, the formal parameter 3289 going from $a$ to $b$, evaluated in parallel in random order. 3290 The expression \kbd{expr} must not access global variables or 3291 variables declared with \kbd{local()}, and must be free of side effects. 3292 \bprog 3293 ? parsum(i=1,1000,ispseudoprime(2^prime(i)-1)) 3294 cpu time = 1min, 26,776 ms, real time = 5,854 ms. 3295 %1 = 20 3296 @eprog 3297 returns the number of prime numbers among the first $1000$ Mersenne numbers. 3298 %\syn{NO} 3299 3300 \subsec{parvector$(N,i,\var{expr})$}\kbdsidx{parvector}\label{se:parvector} 3301 As \kbd{vector(N,i,expr)} but the evaluations of \kbd{expr} are done in 3302 parallel. The expression \kbd{expr} must not access global variables or 3303 variables declared with \kbd{local()}, and must be free of side effects. 3304 \bprog 3305 parvector(10,i,quadclassunit(2^(100+i)+1).no) 3306 @eprog\noindent 3307 computes the class numbers in parallel. 3308 %\syn{NO} 3309 3310 \section{GP defaults} 3311 \label{se:gp_defaults} This section documents the GP defaults, 3312 that can be set either by the GP function \tet{default} or in your GPRC. 3313 Be sure to check out \tet{parisize} and \tet{parisizemax} ! 3314 3315 \subsec{TeXstyle}\kbdsidx{TeXstyle}\label{se:def,TeXstyle} 3316 The bits of this default allow 3317 \kbd{gp} to use less rigid TeX formatting commands in the logfile. This 3318 default is only taken into account when $\kbd{log} = 3$. The bits of 3319 \kbd{TeXstyle} have the following meaning 3320 3321 2: insert \kbd{{\bs}right} / \kbd{{\bs}left} pairs where appropriate. 3322 3323 4: insert discretionary breaks in polynomials, to enhance the probability of 3324 a good line break. You \emph{must} then define \kbd{{\bs}PARIbreak} as 3325 follows: 3326 \bprog 3327 \def\PARIbreak{\hskip 0pt plus \hsize\relax\discretionary{}{}{}} 3328 @eprog 3329 3330 The default value is \kbd{0}. 3331 3332 \subsec{breakloop}\kbdsidx{breakloop}\label{se:def,breakloop} 3333 If true, enables the ``break loop'' debugging mode, see 3334 \secref{se:break_loop}. 3335 3336 The default value is \kbd{1} if we are running an interactive \kbd{gp} 3337 session, and \kbd{0} otherwise. 3338 3339 \subsec{colors}\kbdsidx{colors}\label{se:def,colors} 3340 This default is only usable if \kbd{gp} 3341 is running within certain color-capable terminals. For instance \kbd{rxvt}, 3342 \kbd{color\_xterm} and modern versions of \kbd{xterm} under X Windows, or 3343 standard Linux/DOS text consoles. It causes \kbd{gp} to use a small palette of 3344 colors for its output. With xterms, the colormap used corresponds to the 3345 resources \kbd{Xterm*color$n$} where $n$ ranges from $0$ to $15$ (see the 3346 file \kbd{misc/color.dft} for an example). Accepted values for this 3347 default are strings \kbd{"$a_1$,\dots,$a_k$"} where $k\le7$ and each 3348 $a_i$ is either 3349 3350 \noindent\item the keyword \kbd{no} (use the default color, usually 3351 black on transparent background) 3352 3353 \noindent\item an integer between 0 and 15 corresponding to the 3354 aforementioned colormap 3355 3356 \noindent\item a triple $[c_0,c_1,c_2]$ where $c_0$ stands for foreground 3357 color, $c_1$ for background color, and $c_2$ for attributes (0 is default, 1 3358 is bold, 4 is underline). 3359 3360 The output objects thus affected are respectively error messages, 3361 history numbers, prompt, input line, output, help messages, timer (that's 3362 seven of them). If $k < 7$, the remaining $a_i$ are assumed to be $no$. For 3363 instance 3364 % 3365 \bprog 3366 default(colors, "9, 5, no, no, 4") 3367 @eprog 3368 \noindent 3369 typesets error messages in color $9$, history numbers in color $5$, output in 3370 color $4$, and does not affect the rest. 3371 3372 A set of default colors for dark (reverse video or PC console) and light 3373 backgrounds respectively is activated when \kbd{colors} is set to 3374 \kbd{darkbg}, resp.~\kbd{lightbg} (or any proper prefix: \kbd{d} is 3375 recognized as an abbreviation for \kbd{darkbg}). A bold variant of 3376 \kbd{darkbg}, called \kbd{boldfg}, is provided if you find the former too 3377 pale. 3378 3379 \emacs In the present version, this default is incompatible with PariEmacs. 3380 Changing it will just fail silently (the alternative would be to display 3381 escape sequences as is, since Emacs will refuse to interpret them). 3382 You must customize color highlighting from the PariEmacs side, see its 3383 documentation. 3384 3385 The default value is \kbd{""} (no colors). 3386 3387 \subsec{compatible}\kbdsidx{compatible}\label{se:def,compatible} 3388 Obsolete. This default is now a no-op. 3389 3390 \subsec{datadir}\kbdsidx{datadir}\label{se:def,datadir} 3391 The name of directory containing the optional data files. For now, 3392 this includes the \kbd{elldata}, \kbd{galdata}, \kbd{galpol}, \kbd{seadata} 3393 packages. 3394 3395 The default value is \kbd{/usr/local/share/pari}, or the override specified 3396 via \kbd{Configure --datadir=}. 3397 3398 \misctitle{Windows-specific note} On Windows operating systems, the 3399 special value \kbd{@} stands for ``the directory where the \kbd{gp} 3400 binary is installed''. This is the default value. 3401 3402 \subsec{debug}\kbdsidx{debug}\label{se:def,debug} 3403 Debugging level. If it is nonzero, some extra messages may be printed, 3404 according to what is going on (see~\b{g}). 3405 3406 The default value is \kbd{0} (no debugging messages). 3407 3408 \subsec{debugfiles}\kbdsidx{debugfiles}\label{se:def,debugfiles} 3409 File usage debugging level. If it is nonzero, \kbd{gp} will print 3410 information on file descriptors in use, from PARI's point of view 3411 (see~\b{gf}). 3412 3413 The default value is \kbd{0} (no debugging messages). 3414 3415 \subsec{debugmem}\kbdsidx{debugmem}\label{se:def,debugmem} 3416 Memory debugging level (see \b{gm}). If this is nonzero, \kbd{gp} will 3417 print increasingly precise notifications about memory use: 3418 3419 \item $\kbd{debugmem} > 0$, notify when \kbd{parisize} changes (within the 3420 boundaries set by \kbd{parisizemax}); 3421 3422 \item $\kbd{debugmem} > 1$, indicate any important garbage collection and the 3423 function it is taking place in; 3424 3425 \item $\kbd{debugmem} > 2$, indicate the creation/destruction of 3426 ``blocks'' (or clones); expect lots of messages. 3427 3428 \noindent {\bf Important Note:} 3429 if you are running a version compiled for debugging (see Appendix~A) and 3430 $\kbd{debugmem} > 1$, \kbd{gp} will further regularly print information on 3431 memory usage, notifying whenever stack usage goes up or down by 1 MByte. 3432 This functionality is disabled on non-debugging builds as it noticeably 3433 slows down the performance. 3434 3435 The default value is \kbd{1}. 3436 3437 \subsec{echo}\kbdsidx{echo}\label{se:def,echo} 3438 This default can be 0 (off), 1 (on) or 2 (on, raw). When \kbd{echo} 3439 mode is on, each command is reprinted before being executed. This can be 3440 useful when reading a file with the \b{r} or \kbd{read} commands. For 3441 example, it is turned on at the beginning of the test files used to check 3442 whether \kbd{gp} has been built correctly (see \b{e}). When \kbd{echo} is set 3443 to 1 the input is cleaned up, removing white space and comments and uniting 3444 multi-line input. When set to 2 (raw), the input is written as-is, without any 3445 pre-processing. 3446 3447 The default value is \kbd{0} (no echo). 3448 3449 \subsec{factor\_add\_primes}\kbdsidx{def,factor_add_primes}\label{se:def,factor_add_primes} 3450 This toggle is either 1 (on) or 0 (off). If on, 3451 the integer factorization machinery calls \tet{addprimes} on prime 3452 factors that were difficult to find (larger than $2^{24}$), so they are 3453 automatically tried first in other factorizations. If a routine is performing 3454 (or has performed) a factorization and is interrupted by an error or via 3455 Control-C, this lets you recover the prime factors already found. The 3456 downside is that a huge \kbd{addprimes} table unrelated to the current 3457 computations will slow down arithmetic functions relying on integer 3458 factorization; one should then empty the table using \tet{removeprimes}. 3459 3460 The default value is \kbd{0}. 3461 3462 \subsec{factor\_proven}\kbdsidx{def,factor_proven}\label{se:def,factor_proven} 3463 This toggle is either 1 (on) or 0 (off). By 3464 default, the factors output by the integer factorization machinery are 3465 only pseudo-primes, not proven primes. If this toggle is 3466 set, a primality proof is done for each factor and all results depending on 3467 integer factorization are fully proven. This flag does not affect partial 3468 factorization when it is explicitly requested. It also does not affect the 3469 private table managed by \tet{addprimes}: its entries are included as is in 3470 factorizations, without being tested for primality. 3471 3472 The default value is \kbd{0}. 3473 3474 \subsec{format}\kbdsidx{format}\label{se:def,format} 3475 Of the form x$.n$, where x (conversion style) 3476 is a letter in $\{\kbd{e},\kbd{f},\kbd{g}\}$, and $n$ (precision) is an 3477 integer; this affects the way real numbers are printed: 3478 3479 \item If the conversion style is \kbd{e}, real numbers are printed in 3480 \idx{scientific format}, always with an explicit exponent, 3481 e.g.~\kbd{3.3 E-5}. 3482 3483 \item In style \kbd{f}, real numbers are generally printed in 3484 \idx{fixed floating point format} without exponent, e.g.~\kbd{0.000033}. A 3485 large real number, whose integer part is not well defined (not enough 3486 significant digits), is printed in style~\kbd{e}. For instance 3487 \kbd{10.\pow 100} known to ten significant digits is always printed in style 3488 \kbd{e}. 3489 3490 \item In style \kbd{g}, nonzero real numbers are printed in \kbd{f} format, 3491 except when their decimal exponent is $< -4$, in which case they are printed 3492 in \kbd{e} format. Real zeroes (of arbitrary exponent) are printed in \kbd{e} 3493 format. 3494 3495 The precision $n$ is the number of significant digits printed for real 3496 numbers, except if $n<0$ where all the significant digits will be printed 3497 (initial default 28, or 38 for 64-bit machines). For more powerful formatting 3498 possibilities, see \tet{printf} and \tet{strprintf}. 3499 3500 The default value is \kbd{"g.28"} and \kbd{"g.38"} on 32-bit and 3501 64-bit machines, respectively. 3502 3503 \subsec{graphcolormap}\kbdsidx{graphcolormap}\label{se:def,graphcolormap} 3504 A vector of colors, to be used by hi-res graphing routines. Its length is 3505 arbitrary, but it must contain at least 3 entries: the first 3 colors are 3506 used for background, frame/ticks and axes respectively. All colors in the 3507 colormap may be freely used in \tet{plotcolor} calls. 3508 3509 A color is either given as in the default by character strings or by an RGB 3510 code. For valid color names, see the standard \kbd{rgb.txt} file in X11 3511 distributions, where we restrict to lowercase letters and remove all 3512 whitespace from color names. An RGB code is a vector with 3 integer entries 3513 between 0 and 255 or a \kbd{\#} followed by 6 hexadecimal digits. 3514 For instance \kbd{[250, 235, 215]}, \kbd{"\#faebd7"} and 3515 \kbd{"antiquewhite"} all represent the same color. 3516 3517 The default value is [\kbd{"white"}, \kbd{"black"}, \kbd{"blue"}, 3518 \kbd{"violetred"}, \kbd{"red"}, \kbd{"green"}, \kbd{"grey"}, 3519 \kbd{"gainsboro"}]. 3520 3521 \subsec{graphcolors}\kbdsidx{graphcolors}\label{se:def,graphcolors} 3522 Entries in the 3523 \tet{graphcolormap} that will be used to plot multi-curves. The successive 3524 curves are drawn in colors 3525 3526 \kbd{graphcolormap[graphcolors[1]]}, \kbd{graphcolormap[graphcolors[2]]}, 3527 \dots 3528 3529 cycling when the \kbd{graphcolors} list is exhausted. 3530 3531 The default value is \kbd{[4,5]}. 3532 3533 \subsec{help}\kbdsidx{help}\label{se:def,help} 3534 Name of the external help program to use from within \kbd{gp} when 3535 extended help is invoked, usually through a \kbd{??} or \kbd{???} request 3536 (see \secref{se:exthelp}), or \kbd{M-H} under readline (see 3537 \secref{se:readline}). 3538 3539 \misctitle{Windows-specific note} On Windows operating systems, if the 3540 first character of \kbd{help} is \kbd{@}, it is replaced by ``the directory 3541 where the \kbd{gp} binary is installed''. 3542 3543 The default value is the path to the \kbd{gphelp} script we install. 3544 3545 \subsec{histfile}\kbdsidx{histfile}\label{se:def,histfile} 3546 Name of a file where 3547 \kbd{gp} will keep a history of all \emph{input} commands (results are 3548 omitted). If this file exists when the value of \kbd{histfile} changes, 3549 it is read in and becomes part of the session history. Thus, setting this 3550 default in your gprc saves your readline history between sessions. Setting 3551 this default to the empty string \kbd{""} changes it to 3552 \kbd{$<$undefined$>$}. Note that, by default, the number of history entries 3553 saved is not limited: set \kbd{history-size} in readline's \kbd{.inputrc} 3554 to limit the file size. 3555 3556 The default value is \kbd{$<$undefined$>$} (no history file). 3557 3558 \subsec{histsize}\kbdsidx{histsize}\label{se:def,histsize} 3559 \kbd{gp} keeps a history of the last 3560 \kbd{histsize} results computed so far, which you can recover using the 3561 \kbd{\%} notation (see \secref{se:history}). When this number is exceeded, 3562 the oldest values are erased. Tampering with this default is the only way to 3563 get rid of the ones you do not need anymore. 3564 3565 The default value is \kbd{5000}. 3566 3567 \subsec{lines}\kbdsidx{lines}\label{se:def,lines} 3568 If set to a positive value, \kbd{gp} prints at 3569 most that many lines from each result, terminating the last line shown with 3570 \kbd{[+++]} if further material has been suppressed. The various \kbd{print} 3571 commands (see \secref{se:gp_program}) are unaffected, so you can always type 3572 \kbd{print(\%)} or \b{a} to view the full result. If the actual screen width 3573 cannot be determined, a ``line'' is assumed to be 80 characters long. 3574 3575 The default value is \kbd{0}. 3576 3577 \subsec{linewrap}\kbdsidx{linewrap}\label{se:def,linewrap} 3578 If set to a positive value, \kbd{gp} wraps every single line after 3579 printing that many characters. 3580 3581 The default value is \kbd{0} (unset). 3582 3583 \subsec{log}\kbdsidx{log}\label{se:def,log} 3584 This can be either 0 (off) or 1, 2, 3 3585 (on, see below for the various modes). When logging mode is turned on, \kbd{gp} 3586 opens a log file, whose exact name is determined by the \kbd{logfile} 3587 default. Subsequently, all the commands and results will be written to that 3588 file (see \b{l}). In case a file with this precise name already existed, it 3589 will not be erased: your data will be \emph{appended} at the end. 3590 3591 The specific positive values of \kbd{log} have the following meaning 3592 3593 1: plain logfile 3594 3595 2: emit color codes to the logfile (if \kbd{colors} is set). 3596 3597 3: write LaTeX output to the logfile (can be further customized using 3598 \tet{TeXstyle}). 3599 3600 The default value is \kbd{0}. 3601 3602 \misctitle{Note} Logging starts as soon as \kbd{log} is set to a nonzero 3603 value. In particular, when \kbd{log} is set in \kbd{gprc}, warnings and 3604 errors triggered from the rest of the file will be written in the logfile. 3605 For instance, on clean startup, the logfile will start by \kbd{Done.} 3606 (from the \kbd{Reading GPRC:\dots Done.} diagnostic printed when starting 3607 \kbd{gp}), then the \kbd{gp} header and prompt. 3608 3609 \subsec{logfile}\kbdsidx{logfile}\label{se:def,logfile} 3610 Name of the log file to be used when the \kbd{log} toggle is on. 3611 Environment and time expansion are performed. 3612 3613 The default value is \kbd{"pari.log"}. 3614 3615 \subsec{nbthreads}\kbdsidx{nbthreads}\label{se:def,nbthreads} 3616 This default is specific to the \emph{parallel} version of PARI and gp 3617 (built via \kbd{Configure --mt=prthread} or \kbd{mpi}) and is ignored 3618 otherwise. In parallel mode, it governs the number of threads to use for 3619 parallel computing. The exact meaning and default value depend on the 3620 \kbd{mt} engine used: 3621 3622 \item \kbd{single}: not used (always a single thread). 3623 3624 \item \kbd{pthread}: number of threads (unlimited, default: number of cores) 3625 3626 \item \kbd{mpi}: number of MPI processes to use (limited to the number 3627 allocated by \kbd{mpirun}, default: use all allocated processes). 3628 3629 See also \kbd{threadsize} and \kbd{threadsizemax}. 3630 3631 \subsec{new\_galois\_format}\kbdsidx{def,new_galois_format}\label{se:def,new_galois_format} 3632 This toggle is either 1 (on) or 0 (off). If on, 3633 the \tet{polgalois} command will use a different, more 3634 consistent, naming scheme for Galois groups. This default is provided to 3635 ensure that scripts can control this behavior and do not break unexpectedly. 3636 3637 The default value is \kbd{0}. This value will change to $1$ (set) in the next 3638 major version. 3639 3640 \subsec{output}\kbdsidx{output}\label{se:def,output} 3641 There are three possible values: 0 3642 (=~\var{raw}), 1 (=~\var{prettymatrix}), or 3 3643 (=~\var{external} \var{prettyprint}). This 3644 means that, independently of the default \kbd{format} for reals which we 3645 explained above, you can print results in three ways: 3646 3647 \item \tev{raw format}, i.e.~a format which is equivalent to what you 3648 input, including explicit multiplication signs, and everything typed on a 3649 line instead of two dimensional boxes. This can have several advantages, for 3650 instance it allows you to pick the result with a mouse or an editor, and to 3651 paste it somewhere else. 3652 3653 \item \tev{prettymatrix format}: this is identical to raw format, except 3654 that matrices are printed as boxes instead of horizontally. This is 3655 prettier, but takes more space and cannot be used for input. Column vectors 3656 are still printed horizontally. 3657 3658 \item \tev{external prettyprint}: pipes all \kbd{gp} 3659 output in TeX format to an external prettyprinter, according to the value of 3660 \tet{prettyprinter}. The default script (\tet{tex2mail}) converts its input 3661 to readable two-dimensional text. 3662 3663 Independently of the setting of this default, an object can be printed 3664 in any of the three formats at any time using the commands \b{a} and \b{m} 3665 and \b{B} respectively. 3666 3667 The default value is \kbd{1} (\var{prettymatrix}). 3668 3669 \subsec{parisize}\kbdsidx{parisize}\label{se:def,parisize} 3670 \kbd{gp}, and in fact any program using the PARI 3671 library, needs a \tev{stack} in which to do its computations; \kbd{parisize} 3672 is the stack size, in bytes. It is recommended to increase this 3673 default using a \tet{gprc}, to the value you believe PARI should be happy 3674 with, given your typical computation. We strongly recommend to also 3675 set \tet{parisizemax} to a much larger value in your \kbd{gprc}, about what 3676 you believe your machine can stand: PARI will then try to fit its 3677 computations within about \kbd{parisize} bytes, but will increase the stack 3678 size if needed (up to \kbd{parisizemax}). Once the memory intensive 3679 computation is over, PARI will restore the stack size to the originally 3680 requested \kbd{parisize}. 3681 3682 The default value is 4M, resp.~8M on a 32-bit, resp.~64-bit machine. 3683 3684 \subsec{parisizemax}\kbdsidx{parisizemax}\label{se:def,parisizemax} 3685 \kbd{gp}, and in fact any program using the PARI library, needs a 3686 \tev{stack} in which to do its computations. If nonzero, \tet{parisizemax} 3687 is the maximum size the stack can grow to, in bytes. If zero, the stack will 3688 not automatically grow, and will be limited to the value of \kbd{parisize}. 3689 3690 When \kbd{parisizemax} is set, PARI tries to fit its 3691 computations within about \kbd{parisize} bytes, but will increase the stack 3692 size if needed, roughly doubling it each time (up to \kbd{parisizemax} 3693 of course!) and printing a message such as \kbd{Warning: increasing stack size to} 3694 \var{some value}. Once the memory intensive computation is over, PARI 3695 will restore the stack size to the originally requested \kbd{parisize} 3696 without printing further messages. 3697 3698 We \emph{strongly} recommend to set \tet{parisizemax} permanently to a large 3699 nonzero value in your \tet{gprc}, about what you believe your machine can 3700 stand. It is possible to increase or decrease \kbd{parisizemax} inside a 3701 running \kbd{gp} session, just use \kbd{default} as usual. 3702 3703 The default value is $0$, for backward compatibility reasons. 3704 3705 \subsec{path}\kbdsidx{path}\label{se:def,path} 3706 This is a list of directories, separated by colons ':' 3707 (semicolons ';' in the DOS world, since colons are preempted for drive names). 3708 When asked to read a file whose name is not given by an absolute path 3709 (does not start with \kbd{/}, \kbd{./} or \kbd{../}), \kbd{gp} will look for 3710 it in these directories, in the order they were written in \kbd{path}. Here, 3711 as usual, \kbd{.} means the current directory, and \kbd{..} its immediate 3712 parent. Environment expansion is performed. 3713 3714 The default value is \kbd{".:\til:\til/gp"} on UNIX systems, 3715 \kbd{".;C:\bs;C:\bs GP"} on DOS, OS/2 and Windows, and \kbd{"."} otherwise. 3716 3717 \subsec{plothsizes}\kbdsidx{plothsizes}\label{se:def,plothsizes} 3718 If the graphic driver allows it, the array contains the size of the 3719 terminal, the size of the font, the size of the ticks. 3720 3721 \subsec{prettyprinter}\kbdsidx{prettyprinter}\label{se:def,prettyprinter} 3722 The name of an external prettyprinter to use when 3723 \kbd{output} is~3 (alternate prettyprinter). Note that the default 3724 \tet{tex2mail} looks much nicer than the built-in ``beautified 3725 format'' ($\kbd{output} = 2$). 3726 3727 The default value is \kbd{"tex2mail -TeX -noindent -ragged -by\_par"}. 3728 3729 \subsec{primelimit}\kbdsidx{primelimit}\label{se:def,primelimit} 3730 \kbd{gp} precomputes a list of 3731 all primes less than \kbd{primelimit} at initialization time, and can build 3732 fast sieves on demand to quickly iterate over primes up to the \emph{square} 3733 of \kbd{primelimit}. These are used by many arithmetic functions, usually for 3734 trial division purposes. The maximal value is $2^{32} - 2049$ (resp $2^{64} - 3735 2049$) on a 32-bit (resp.~64-bit) machine, but values beyond $10^8$, 3736 allowing to iterate over primes up to $10^{16}$, do not seem useful. 3737 3738 Since almost all arithmetic functions eventually require some table of prime 3739 numbers, PARI guarantees that the first 6547 primes, up to and 3740 including 65557, are precomputed, even if \kbd{primelimit} is $1$. 3741 3742 This default is only used on startup: changing it will not recompute a new 3743 table. 3744 3745 \misctitle{Deprecated feature} \kbd{primelimit} was used in some 3746 situations by algebraic number theory functions using the 3747 \tet{nf_PARTIALFACT} flag (\tet{nfbasis}, \tet{nfdisc}, \tet{nfinit}, \dots): 3748 this assumes that all primes $p > \kbd{primelimit}$ have a certain 3749 property (the equation order is $p$-maximal). This is never done by default, 3750 and must be explicitly set by the user of such functions. Nevertheless, 3751 these functions now provide a more flexible interface, and their use 3752 of the global default \kbd{primelimit} is deprecated. 3753 3754 \misctitle{Deprecated feature} \kbd{factor(N, 0)} was used to partially 3755 factor integers by removing all prime factors $\leq$ \kbd{primelimit}. 3756 Don't use this, supply an explicit bound: \kbd{factor(N, bound)}, 3757 which avoids relying on an unpredictable global variable. 3758 3759 The default value is \kbd{500k}. 3760 3761 \subsec{prompt}\kbdsidx{prompt}\label{se:def,prompt} 3762 A string that will be printed as 3763 prompt. Note that most usual escape sequences are available there: \b{e} for 3764 Esc, \b{n} for Newline, \dots, \kbd{\bs\bs} for \kbd{\bs}. Time expansion is 3765 performed. 3766 3767 This string is sent through the library function \tet{strftime} (on a 3768 Unix system, you can try \kbd{man strftime} at your shell prompt). This means 3769 that \kbd{\%} constructs have a special meaning, usually related to the time 3770 and date. For instance, \kbd{\%H} = hour (24-hour clock) and \kbd{\%M} = 3771 minute [00,59] (use \kbd{\%\%} to get a real \kbd{\%}). 3772 3773 If you use \kbd{readline}, escape sequences in your prompt will result in 3774 display bugs. If you have a relatively recent \kbd{readline} (see the comment 3775 at the end of \secref{se:def,colors}), you can brace them with special sequences 3776 (\kbd{\bs[} and \kbd{\bs]}), and you will be safe. If these just result in 3777 extra spaces in your prompt, then you'll have to get a more recent 3778 \kbd{readline}. See the file \kbd{misc/gprc.dft} for an example. 3779 3780 \emacs {\bf Caution}: PariEmacs needs to know about the prompt pattern to 3781 separate your input from previous \kbd{gp} results, without ambiguity. It is 3782 not a trivial problem to adapt automatically this regular expression to an 3783 arbitrary prompt (which can be self-modifying!). See PariEmacs's 3784 documentation. 3785 3786 The default value is \kbd{"? "}. 3787 3788 \subsec{prompt\_cont}\kbdsidx{def,prompt_cont}\label{se:def,prompt_cont} 3789 A string that will be printed 3790 to prompt for continuation lines (e.g. in between braces, or after a 3791 line-terminating backslash). Everything that applies to \kbd{prompt} 3792 applies to \kbd{prompt\_cont} as well. 3793 3794 The default value is \kbd{""}. 3795 3796 \subsec{psfile}\kbdsidx{psfile}\label{se:def,psfile} 3797 This default is obsolete, use one of plotexport, plothexport or 3798 plothrawexport functions and write the result to file. 3799 3800 \subsec{readline}\kbdsidx{readline}\label{se:def,readline} 3801 Switches readline line-editing 3802 facilities on and off. This may be useful if you are running \kbd{gp} in a Sun 3803 \tet{cmdtool}, which interacts badly with readline. Of course, until readline 3804 is switched on again, advanced editing features like automatic completion 3805 and editing history are not available. 3806 3807 The default value is \kbd{1}. 3808 3809 \subsec{realbitprecision}\kbdsidx{realbitprecision}\label{se:def,realbitprecision} 3810 The number of significant bits used to convert exact inputs given to 3811 transcendental functions (see \secref{se:trans}), or to create 3812 absolute floating point constants (input as \kbd{1.0} or \kbd{Pi} for 3813 instance). Unless you tamper with the \tet{format} default, this is also 3814 the number of significant bits used to print a \typ{REAL} number; 3815 \kbd{format} will override this latter behavior, and allow you to have a 3816 large internal precision while outputting few digits for instance. 3817 3818 Note that most PARI's functions currently handle precision on a word basis (by 3819 increments of 32 or 64 bits), hence bit precision may be a little larger 3820 than the number of bits you expected. For instance to get 10 bits of 3821 precision, you need one word of precision which, on a 64-bit machine, 3822 correspond to 64 bits. To make things even more confusing, this internal bit 3823 accuracy is converted to decimal digits when printing floating point numbers: 3824 now 64 bits correspond to 19 printed decimal digits 3825 ($19 < \log_{10}(2^{64}) < 20$). 3826 3827 The value returned when typing \kbd{default(realbitprecision)} is the internal 3828 number of significant bits, not the number of printed decimal digits: 3829 \bprog 3830 ? default(realbitprecision, 10) 3831 ? \pb 3832 realbitprecision = 64 significant bits 3833 ? default(realbitprecision) 3834 %1 = 64 3835 ? \p 3836 realprecision = 3 significant digits 3837 ? default(realprecision) 3838 %2 = 19 3839 @eprog\noindent Note that \tet{realprecision} and \kbd{\bs p} allow 3840 to view and manipulate the internal precision in decimal digits. 3841 3842 The default value is \kbd{128}, resp.~\kbd{96}, on a 64-bit, resp~.32-bit, 3843 machine. 3844 3845 \subsec{realprecision}\kbdsidx{realprecision}\label{se:def,realprecision} 3846 The number of significant digits used to convert exact inputs given to 3847 transcendental functions (see \secref{se:trans}), or to create 3848 absolute floating point constants (input as \kbd{1.0} or \kbd{Pi} for 3849 instance). Unless you tamper with the \tet{format} default, this is also 3850 the number of significant digits used to print a \typ{REAL} number; 3851 \kbd{format} will override this latter behavior, and allow you to have a 3852 large internal precision while outputting few digits for instance. 3853 3854 Note that PARI's internal precision works on a word basis (by increments of 3855 32 or 64 bits), hence may be a little larger than the number of decimal 3856 digits you expected. For instance to get 2 decimal digits you need one word 3857 of precision which, on a 64-bit machine, actually gives you 19 digits ($19 < 3858 \log_{10}(2^{64}) < 20$). The value returned when typing 3859 \kbd{default(realprecision)} is the internal number of significant digits, 3860 not the number of printed digits: 3861 \bprog 3862 ? default(realprecision, 2) 3863 realprecision = 19 significant digits (2 digits displayed) 3864 ? default(realprecision) 3865 %1 = 19 3866 @eprog 3867 The default value is \kbd{38}, resp.~\kbd{28}, on a 64-bit, resp.~32-bit, 3868 machine. 3869 3870 \subsec{recover}\kbdsidx{recover}\label{se:def,recover} 3871 This toggle is either 1 (on) or 0 (off). If you change this to $0$, any 3872 error becomes fatal and causes the gp interpreter to exit immediately. Can be 3873 useful in batch job scripts. 3874 3875 The default value is \kbd{1}. 3876 3877 \subsec{secure}\kbdsidx{secure}\label{se:def,secure} 3878 This toggle is either 1 (on) or 0 (off). If on, the \tet{system} and 3879 \tet{extern} command are disabled. These two commands are potentially 3880 dangerous when you execute foreign scripts since they let \kbd{gp} execute 3881 arbitrary UNIX commands. \kbd{gp} will ask for confirmation before letting 3882 you (or a script) unset this toggle. 3883 3884 The default value is \kbd{0}. 3885 3886 \subsec{seriesprecision}\kbdsidx{seriesprecision}\label{se:def,seriesprecision} 3887 Number of significant terms 3888 when converting a polynomial or rational function to a power series 3889 (see~\b{ps}). 3890 3891 The default value is \kbd{16}. 3892 3893 \subsec{simplify}\kbdsidx{simplify}\label{se:def,simplify} 3894 This toggle is either 1 (on) or 0 (off). When the PARI library computes 3895 something, the type of the 3896 result is not always the simplest possible. The only type conversions which 3897 the PARI library does automatically are rational numbers to integers (when 3898 they are of type \typ{FRAC} and equal to integers), and similarly rational 3899 functions to polynomials (when they are of type \typ{RFRAC} and equal to 3900 polynomials). This feature is useful in many cases, and saves time, but can 3901 be annoying at times. Hence you can disable this and, whenever you feel like 3902 it, use the function \kbd{simplify} (see Chapter 3) which allows you to 3903 simplify objects to the simplest possible types recursively (see~\b{y}). 3904 \sidx{automatic simplification} 3905 3906 The default value is \kbd{1}. 3907 3908 \subsec{sopath}\kbdsidx{sopath}\label{se:def,sopath} 3909 This is a list of directories, separated by colons ':' 3910 (semicolons ';' in the DOS world, since colons are preempted for drive names). 3911 When asked to \tet{install} an external symbol from a shared library whose 3912 name is not given by an absolute path (does not start with \kbd{/}, \kbd{./} 3913 or \kbd{../}), \kbd{gp} will look for it in these directories, in the order 3914 they were written in \kbd{sopath}. Here, as usual, \kbd{.} means the current 3915 directory, and \kbd{..} its immediate parent. Environment expansion is 3916 performed. 3917 3918 The default value is \kbd{""}, corresponding to an empty list of 3919 directories: \tet{install} will use the library name as input (and look in 3920 the current directory if the name is not an absolute path). 3921 3922 \subsec{strictargs}\kbdsidx{strictargs}\label{se:def,strictargs} 3923 This toggle is either 1 (on) or 0 (off). If on, all arguments to \emph{new} 3924 user functions are mandatory unless the function supplies an explicit default 3925 value. 3926 Otherwise arguments have the default value $0$. 3927 3928 In this example, 3929 \bprog 3930 fun(a,b=2)=a+b 3931 @eprog 3932 \kbd{a} is mandatory, while \kbd{b} is optional. If \kbd{strictargs} is on: 3933 \bprog 3934 ? fun() 3935 *** at top-level: fun() 3936 *** ^----- 3937 *** in function fun: a,b=2 3938 *** ^----- 3939 *** missing mandatory argument 'a' in user function. 3940 @eprog 3941 This applies to functions defined while \kbd{strictargs} is on. Changing \kbd{strictargs} 3942 does not affect the behavior of previously defined functions. 3943 3944 The default value is \kbd{0}. 3945 3946 \subsec{strictmatch}\kbdsidx{strictmatch}\label{se:def,strictmatch} 3947 Obsolete. This toggle is now a no-op. 3948 3949 \subsec{threadsize}\kbdsidx{threadsize}\label{se:def,threadsize} 3950 This default is specific to the \emph{parallel} version of PARI and gp 3951 (built via \kbd{Configure --mt=prthread} or \kbd{mpi}) and is ignored 3952 otherwise. In parallel mode, 3953 each thread allocates its own private \tev{stack} for its 3954 computations, see \kbd{parisize}. This value determines the size in bytes of 3955 the stacks of each thread, so the total memory allocated will be 3956 $\kbd{parisize}+\kbd{nbthreads}\times\kbd{threadsize}$. 3957 3958 If set to $0$, the value used is the same as \kbd{parisize}. It is not 3959 easy to estimate reliably a sufficient value for this parameter because PARI 3960 itself will parallelize computations and we recommend to not set this value 3961 explicitly unless it solves a specific problem for you. For instance if you 3962 see frequent messages of the form 3963 \bprog 3964 *** Warning: not enough memory, new thread stack 10000002048 3965 @eprog (Meaning that \kbd{threadsize} had to be temporarily increased.) 3966 On the other hand we strongly recommend to set \kbd{parisizemax} and 3967 \kbd{threadsizemax} to a nonzero value. 3968 3969 The default value is $0$. 3970 3971 \subsec{threadsizemax}\kbdsidx{threadsizemax}\label{se:def,threadsizemax} 3972 This default is specific to the \emph{parallel} version of PARI and gp 3973 (built via \kbd{Configure --mt=pthread} or \kbd{mpi}) and is ignored 3974 otherwise. In parallel mode, 3975 each threads allocates its own private \tev{stack} for 3976 its computations, see \kbd{parisize} and \kbd{parisizemax}. The 3977 values of \kbd{threadsize} and \kbd{threadsizemax} determine the usual 3978 and maximal size in bytes of the stacks of each thread, so the total memory 3979 allocated will 3980 be between $\kbd{parisize}+\kbd{nbthreads}\times\kbd{threadsize}$. and 3981 $\kbd{parisizemax}+\kbd{nbthreads}\times\kbd{threadsizemax}$. 3982 3983 If set to $0$, the value used is the same as \kbd{threadsize}. We strongy 3984 recommend to set both \kbd{parisizemax} and \kbd{threadsizemax} to a 3985 nonzero value. 3986 3987 The default value is $0$. 3988 3989 \subsec{timer}\kbdsidx{timer}\label{se:def,timer} 3990 This toggle is either 1 (on) or 0 (off). Every instruction sequence 3991 in the gp calculator (anything ended by a newline in your input) is timed, 3992 to some accuracy depending on the hardware and operating system. When 3993 \tet{timer} is on, each such timing is printed immediately before the 3994 output as follows: 3995 \bprog 3996 ? factor(2^2^7+1) 3997 time = 108 ms. \\ this line omitted if 'timer' is 0 3998 %1 = 3999 [ 59649589127497217 1] 4000 4001 [5704689200685129054721 1] 4002 @eprog\noindent (See also \kbd{\#} and \kbd{\#\#}.) 4003 4004 The time measured is the user \idx{CPU time}, \emph{not} including the time 4005 for printing the results. If the time is negligible ($< 1$ ms.), nothing is 4006 printed: in particular, no timing should be printed when defining a user 4007 function or an alias, or installing a symbol from the library. 4008 4009 The default value is \kbd{0} (off). 4010 4011 \section{Standard monadic or dyadic operators} 4012 4013 \subsec{Boolean operators}\sidx{Boolean operators} 4014 4015 Any nonzero value is interpreted as \var{true} and any zero as \var{false} 4016 (this includes empty vectors or matrices). The standard boolean operators 4017 \kbd{||} (\idx{inclusive or}), \kbd{\&\&} (\idx{and})\sidx{or} and \kbd{!} 4018 in prefix notation (\idx{not}) are available. 4019 Their value is $1$ (true) or $0$ (false): 4020 \bprog 4021 ? a && b \\ 1 iff a and b are nonzero 4022 ? a || b \\ 1 iff a or b is nonzero 4023 ? !a \\ 1 iff a is zero 4024 @eprog 4025 4026 \subsec{Comparison} 4027 The standard real \idx{comparison operators} \kbd{<=}, \kbd{<}, \kbd{>=}, 4028 \kbd{>}, are available in GP. The result is 1 if the comparison is true, 0 4029 if it is false. These operators allow to compare integers (\typ{INT}), 4030 rational (\typ{FRAC}) or real (\typ{REAL}) numbers, 4031 real quadratic numbers (\typ{QUAD} of positive discriminant) and infinity 4032 (\kbd{oo}, \typ{INFINITY}). 4033 4034 By extension, two character strings (\typ{STR}) are compared using 4035 the standard lexicographic order. Comparing a string to an object of a 4036 different type raises an exception. See also the \tet{cmp} universal 4037 comparison function. 4038 4039 \subsec{Equality} 4040 Two operators allow to test for equality: \kbd{==} (equality up to type 4041 coercion) and \kbd{===} (identity). The result is $1$ if equality is decided, 4042 else $0$. 4043 4044 The operator \kbd{===} is strict: objects of different type or length are 4045 never identical, polynomials in different variables are never identical, 4046 even if constant. On the contrary, \kbd{==} is very liberal: $a~\kbd{==}~b$ 4047 decides whether there is a natural map sending $a$ to the domain of $b$ 4048 or sending $b$ to the domain of $a$, such that the comparison makes sense 4049 and equality holds. For instance 4050 \bprog 4051 ? 4 == Mod(1,3) \\ equal 4052 %1 = 1 4053 ? 4 === Mod(1,3) \\ but not identical 4054 %2 = 0 4055 4056 ? 'x == 'y \\ not equal (nonconstant and different variables) 4057 %3 = 0 4058 ? Pol(0,'x) == Pol(0,'y) \\ equal (constant: ignore variable) 4059 %4 = 1 4060 ? Pol(0,'x) == Pol(0,'y) \\ not identical 4061 %5 = 0 4062 4063 ? 0 == Pol(0) \\ equal 4064 %6 = 1 4065 ? [0] == 0 \\ equal 4066 %7 = 1 4067 ? [0, 0] == 0 \\ equal 4068 %8 = 1 4069 ? [0] == [0,0] \\ not equal 4070 %9 = 1 4071 @eprog\noindent In particular \kbd{==} is not transitive in general; it is 4072 transitive when used to compare objects known to have the same type. The 4073 operator \kbd{===} is transitive. The \kbd{==} operator allows two 4074 equivalent negated forms: \kbd{!=} or \kbd{<>}; there is no negated form for 4075 \kbd{===}. 4076 4077 Do not mistake \kbd{=} for \kbd{==}: it is the assignment statement. 4078 4079 \subseckbd{+$/$-} The expressions \kbd{+}$x$ and \kbd{-}$x$ refer 4080 to monadic operators: the first does nothing, the second negates $x$. 4081 4082 The library syntax is \fun{GEN}{gneg}{GEN x} for \kbd{-}$x$. 4083 4084 \subseckbd{+} The expression $x$ \kbd{+} $y$ is the \idx{sum} of $x$ and $y$. 4085 Addition between a scalar type $x$ and a \typ{COL} or \typ{MAT} $y$ returns 4086 respectively $[y[1] + x, y[2],\dots]$ and $y + x \text{Id}$. Other additions 4087 between a scalar type and a vector or a matrix, or between vector/matrices of 4088 incompatible sizes are forbidden. 4089 4090 The library syntax is \fun{GEN}{gadd}{GEN x, GEN y}. 4091 4092 \subseckbd{-} The expression $x$ \kbd{-} $y$ is the \idx{difference} of $x$ 4093 and $y$. Subtraction between a scalar type $x$ and a \typ{COL} or \typ{MAT} 4094 $y$ returns respectively $[y[1] - x, y[2],\dots]$ and $y - x \text{Id}$. 4095 Other subtractions between a scalar type and a vector or a matrix, or 4096 between vector/matrices of incompatible sizes are forbidden. 4097 4098 The library syntax is \fun{GEN}{gsub}{GEN x, GEN y} for $x$ \kbd{-} $y$. 4099 4100 \subseckbd{*} The expression $x$ \kbd{*} $y$ is the \idx{product} of $x$ 4101 and $y$. Among the prominent impossibilities are multiplication between 4102 vector/matrices of incompatible sizes, between a \typ{INTMOD} or \typ{PADIC} 4103 Restricted to scalars, \kbd{*} is commutative; because of vector and matrix 4104 operations, it is not commutative in general. 4105 4106 Multiplication between two \typ{VEC}s or two \typ{COL}s is not 4107 allowed; to take the \idx{scalar product} of two vectors of the same length, 4108 transpose one of the vectors (using the operator \kbd{\til} or the function 4109 \kbd{mattranspose}, see \secref{se:linear_algebra}) and multiply a line vector 4110 by a column vector: 4111 \bprog 4112 ? a = [1,2,3]; 4113 ? a * a 4114 *** at top-level: a*a 4115 *** ^-- 4116 *** _*_: forbidden multiplication t_VEC * t_VEC. 4117 ? a * a~ 4118 %2 = 14 4119 @eprog 4120 4121 If $x,y$ are binary quadratic forms, compose them; see also 4122 \kbd{qfbnucomp} and \kbd{qfbnupow}. If $x,y$ are \typ{VECSMALL} of the same 4123 length, understand them as permutations and compose them. 4124 4125 The library syntax is \fun{GEN}{gmul}{GEN x, GEN y} for $x$ \kbd{*} $y$. 4126 Also available is \fun{GEN}{gsqr}{GEN x} for $x$ \kbd{*} $x$. 4127 4128 \subseckbd{/} The expression $x$ \kbd{/} $y$ is the \idx{quotient} of $x$ 4129 and $y$. In addition to the impossibilities for multiplication, note that if 4130 the divisor is a matrix, it must be an invertible square matrix, and in that 4131 case the result is $x*y^{-1}$. Furthermore note that the result is as exact 4132 as possible: in particular, division of two integers always gives a rational 4133 number (which may be an integer if the quotient is exact) and \emph{not} the 4134 Euclidean quotient (see $x$ \kbd{\bs} $y$ for that), and similarly the 4135 quotient of two polynomials is a rational function in general. To obtain the 4136 approximate real value of the quotient of two integers, add \kbd{0.} to the 4137 result; to obtain the approximate $p$-adic value of the quotient of two 4138 integers, add \kbd{O(p\pow k)} to the result; finally, to obtain the 4139 \idx{Taylor series} expansion of the quotient of two polynomials, add 4140 \kbd{O(X\pow k)} to the result or use the \kbd{taylor} function 4141 (see \secref{se:taylor}). \label{se:gdiv} 4142 4143 The library syntax is \fun{GEN}{gdiv}{GEN x, GEN y} for $x$ \kbd{/} $y$. 4144 4145 \subseckbd{\bs} The expression \kbd{$x$ \bs\ $y$} is the 4146 \idx{Euclidean quotient} of $x$ and $y$. If $y$ is a real scalar, this is 4147 defined as \kbd{floor($x$/$y$)} if $y > 0$, and \kbd{ceil($x$/$y$)} if 4148 $y < 0$ and the division is not exact. Hence the remainder 4149 \kbd{$x$ - ($x$\bs$y$)*$y$} is in $[0, |y|[$. 4150 4151 Note that when $y$ is an integer and $x$ a polynomial, $y$ is first promoted 4152 to a polynomial of degree $0$. When $x$ is a vector or matrix, the operator 4153 is applied componentwise. 4154 4155 The library syntax is \fun{GEN}{gdivent}{GEN x, GEN y} 4156 for $x$ \kbd{\bs} $y$. 4157 4158 \subseckbd{\bs/} The expression $x$ \b{/} $y$ evaluates to the rounded 4159 \idx{Euclidean quotient} of $x$ and $y$. This is the same as \kbd{$x$ \bs\ $y$} 4160 except for scalar division: the quotient is such that the corresponding 4161 remainder is smallest in absolute value and in case of a tie the quotient 4162 closest to $+\infty$ is chosen (hence the remainder would belong to 4163 $[{-}|y|/2, |y|/2[$). 4164 4165 When $x$ is a vector or matrix, the operator is applied componentwise. 4166 4167 The library syntax is \fun{GEN}{gdivround}{GEN x, GEN y} 4168 for $x$ \b{/} $y$. 4169 4170 \subseckbd{\%} The expression \kbd{$x$ \% $y$} evaluates to the modular 4171 \idx{Euclidean remainder} of $x$ and $y$, which we now define. When $x$ or $y$ 4172 is a nonintegral real number, \kbd{$x$\%$y$} is defined as 4173 \kbd{$x$ - ($x$\bs$y$)*$y$}. Otherwise, if $y$ is an integer, this is 4174 the smallest 4175 nonnegative integer congruent to $x$ modulo $y$. (This actually coincides 4176 with the previous definition if and only if $x$ is an integer.) If $y$ is a 4177 polynomial, this is the polynomial of smallest degree congruent to 4178 $x$ modulo $y$. For instance: 4179 \bprog 4180 ? (1/2) % 3 4181 %1 = 2 4182 ? 0.5 % 3 4183 %2 = 0.5000000000000000000000000000 4184 ? (1/2) % 3.0 4185 %3 = 1/2 4186 @eprog 4187 Note that when $y$ is an integer and $x$ a polynomial, $y$ is first promoted 4188 to a polynomial of degree $0$. When $x$ is a vector or matrix, the operator 4189 is applied componentwise. 4190 4191 The library syntax is \fun{GEN}{gmod}{GEN x, GEN y} 4192 for $x$ \kbd{\%} $y$. 4193 4194 \subseckbd{\var{op}=} When \var{op} is a binary arithmetic operator among 4195 \kbd{+}, \kbd{-}, \kbd{\%}, \kbd{/}, \kbd{\bs} or \kbd{\bs/}, the construct 4196 $x \var{op}= y$ is a shortcut for $x = x \var{op} y$. 4197 \bprog 4198 ? v[1] += 10 \\ increment v[1] by 10 4199 ? a /= 2 \\ divide a by 2 4200 @eprog 4201 4202 \subseckbd{++} \kbd{$x$++} is a shortcut for \kbd{$x$ = $x$ + 1}. 4203 4204 \subseckbd{--} \kbd{$x$--} is a shortcut for \kbd{$x$ = $x$ - 1}. 4205 4206 \subseckbd{\pow} The expression $x\hbox{\kbd{\pow}}n$ is \idx{powering}. 4207 4208 \item If the exponent $n$ is an integer, then exact operations are performed 4209 using binary (left-shift) powering techniques. By definition, $x^0$ is 4210 (an empty product interpreted as) an exact $1$ in the underlying prime 4211 ring: 4212 \bprog 4213 ? 0.0 ^ 0 4214 %1 = 1 4215 ? (1 + O(2^3)) ^ 0 4216 %2 = 1 4217 ? (1 + O(x)) ^ 0 4218 %3 = 1 4219 ? Mod(2,4)^0 4220 %4 = Mod(1,4) 4221 ? Mod(x,x^2)^0 4222 %5 = Mod(1, x^2) 4223 @eprog\noindent 4224 If $x$ is a $p$-adic number, its precision will increase if $v_p(n) > 0$ and 4225 $n \neq 0$. Powering a binary quadratic form (types \typ{QFI} and 4226 \typ{QFR}) returns a representative of the class, which is reduced if the 4227 input was. (In particular, \kbd{x \pow 1} returns $x$ itself, whether it is 4228 reduced or not.) 4229 4230 PARI rewrites the multiplication $x * x$ of two \emph{identical} 4231 objects as $x^2$. Here, identical means the operands are reference the same 4232 chunk of memory; no equality test is performed. This is no longer true when 4233 more than two arguments are involved. 4234 \bprog 4235 ? a = 1 + O(2); b = a; 4236 ? a * a \\ = a^2, precision increases 4237 %2 = 1 + O(2^3) 4238 ? a * b \\ not rewritten as a^2 4239 %3 = 1 + O(2) 4240 ? a*a*a \\ not rewritten as a^3 4241 %4 = 1 + O(2) 4242 @eprog 4243 4244 \item If the exponent is a rational number $p/q$ the behaviour depends 4245 on~$x$. If $x$ is a complex number, return $\exp(n \log x)$ (principal 4246 branch), in an exact form if possible: 4247 \bprog 4248 ? 4^(1/2) \\ 4 being a square, this is exact 4249 %1 = 2 4250 ? 2^(1/2) \\ now inexact 4251 %2 = 1.4142135623730950488016887242096980786 4252 ? (-1/4)^(1/2) \\ exact again 4253 %3 = 1/2*I 4254 ? (-1)^(1/3) 4255 %4 = 0.500...+ 0.866...*I 4256 @eprog\noindent Note that even though $-1$ is an exact cube root of $-1$, 4257 it is not $\exp(\log(-1)/3)$; the latter is returned. 4258 4259 Otherwise return a solution $y$ of $y^q = x^p$ if it exists; beware that 4260 this is defined up to $q$-th roots of 1 in the base field. Intmods modulo 4261 composite numbers are not supported. 4262 \bprog 4263 ? Mod(7,19)^(1/2) 4264 %1 = Mod(11, 19) \\ is any square root 4265 ? sqrt(Mod(7,19)) 4266 %2 = Mod(8, 19) \\ is the smallest square root 4267 ? Mod(1,4)^(1/2) 4268 *** at top-level: Mod(1,4)^(1/2) 4269 *** ^------ 4270 *** _^_: not a prime number in gpow: 4. 4271 @eprog 4272 4273 \item If the exponent is a negative integer or rational number, 4274 an \idx{inverse} must be computed. For noninvertible \typ{INTMOD} $x$, this 4275 will fail and (for $n$ an integer) implicitly exhibit a factor of the modulus: 4276 \bprog 4277 ? Mod(4,6)^(-1) 4278 *** at top-level: Mod(4,6)^(-1) 4279 *** ^----- 4280 *** _^_: impossible inverse modulo: Mod(2, 6). 4281 @eprog\noindent 4282 Here, a factor 2 is obtained directly. In general, take the gcd of the 4283 representative and the modulus. This is most useful when performing 4284 complicated operations modulo an integer $N$ whose factorization is 4285 unknown. Either the computation succeeds and all is well, or a factor $d$ 4286 is discovered and the computation may be restarted modulo $d$ or $N/d$. 4287 4288 For noninvertible \typ{POLMOD} $x$, the behavior is the same: 4289 \bprog 4290 ? Mod(x^2, x^3-x)^(-1) 4291 *** at top-level: Mod(x^2,x^3-x)^(-1) 4292 *** ^----- 4293 *** _^_: impossible inverse in RgXQ_inv: Mod(x^2, x^3 - x). 4294 @eprog\noindent Note that the underlying algorihm (subresultant) assumes 4295 that the base ring is a domain: 4296 \bprog 4297 ? a = Mod(3*y^3+1, 4); b = y^6+y^5+y^4+y^3+y^2+y+1; c = Mod(a,b); 4298 ? c^(-1) 4299 *** at top-level: Mod(a,b)^(-1) 4300 *** ^----- 4301 *** _^_: impossible inverse modulo: Mod(2, 4). 4302 @eprog\noindent 4303 In fact $c$ is invertible, but $\Z/4\Z$ is not a domain and the algorithm 4304 fails. It is possible for the algorithm to succeed in such situations 4305 and any returned result will be correct, but chances are that an error 4306 will occur first. In this specific case, one should work with $2$-adics. 4307 In general, one can also try the following approach 4308 \bprog 4309 ? inversemod(a, b) = 4310 { my(m, v = variable(b)); 4311 m = polsylvestermatrix(polrecip(a), polrecip(b)); 4312 m = matinverseimage(m, matid(#m)[,1]); 4313 Polrev(m[1..poldegree(b)], v); 4314 } 4315 ? inversemod(a,b) 4316 %2 = Mod(2,4)*y^5 + Mod(3,4)*y^3 + Mod(1,4)*y^2 + Mod(3,4)*y + Mod(2,4) 4317 @eprog\noindent 4318 This is not guaranteed to work either since \kbd{matinverseimage} must also 4319 invert pivots. See \secref{se:linear_algebra}. 4320 4321 For a \typ{MAT} $x$, the matrix is expected to be square and invertible, except 4322 in the special case \kbd{x\pow(-1)} which returns a left inverse if one exists 4323 (rectangular $x$ with full column rank). 4324 \bprog 4325 ? x = Mat([1;2]) 4326 %1 = 4327 [1] 4328 4329 [2] 4330 4331 ? x^(-1) 4332 %2 = 4333 [1 0] 4334 @eprog 4335 4336 \item Finally, if the exponent $n$ is not an rational number, powering is 4337 treated as the transcendental function $\exp(n\log x)$, although it will be 4338 more precise than the latter when $n$ and $x$ are exact: 4339 \bprog 4340 ? s = 1/2 + 10^14 * I 4341 ? localprec(200); z = 2^s \\ for reference 4342 ? exponent(2^s - z) 4343 %3 = -127 \\ perfect 4344 ? exponent(exp(s * log(2)) - z) 4345 %4 = -84 \\ not so good 4346 @eprog\noindent The second computation is less precise because $\log(2)$ is 4347 first computed to $38$ decimal digits, then multiplied by $s$, which has a 4348 huge imaginary part amplifying the error. 4349 4350 In this case, $x \mapsto x^n$ is treated as a transcendental function and 4351 and in particular acts 4352 componentwise on vector or matrices, even square matrices ! (See 4353 \secref{se:trans}.) If $x$ is $0$ and $n$ is an inexact $0$, this will raise 4354 an exception: 4355 \bprog 4356 ? 4 ^ 1.0 4357 %1 = 4.0000000000000000000000000000000000000 4358 ? 0^ 0.0 4359 *** at top-level: 0^0.0 4360 *** ^---- 4361 *** _^_: domain error in gpow(0,n): n <= 0 4362 @eprog 4363 4364 The library syntax is \fun{GEN}{gpow}{GEN x, GEN n, long prec} 4365 for $x\hbox{\kbd{\pow}}n$. 4366 4367 \subsec{cmp$(x,y)$}\kbdsidx{cmp}\label{se:cmp} 4368 Gives the result of a comparison between arbitrary objects $x$ and $y$ 4369 (as $-1$, $0$ or $1$). The underlying order relation is transitive, 4370 the function returns $0$ if and only if $x~\kbd{===}~y$. It has no 4371 mathematical meaning but satisfies the following properties when comparing 4372 entries of the same type: 4373 4374 \item two \typ{INT}s compare as usual (i.e. \kbd{cmp}$(x,y) < 0$ if and only 4375 if $x < y$); 4376 4377 \item two \typ{VECSMALL}s of the same length compare lexicographically; 4378 4379 \item two \typ{STR}s compare lexicographically. 4380 4381 In case all components are equal up to the smallest length of the operands, 4382 the more complex is considered to be larger. More precisely, the longest is 4383 the largest; when lengths are equal, we have matrix $>$ vector $>$ scalar. 4384 For example: 4385 \bprog 4386 ? cmp(1, 2) 4387 %1 = -1 4388 ? cmp(2, 1) 4389 %2 = 1 4390 ? cmp(1, 1.0) \\ note that 1 == 1.0, but (1===1.0) is false. 4391 %3 = -1 4392 ? cmp(x + Pi, []) 4393 %4 = -1 4394 @eprog\noindent This function is mostly useful to handle sorted lists or 4395 vectors of arbitrary objects. For instance, if $v$ is a vector, the 4396 construction \kbd{vecsort(v, cmp)} is equivalent to \kbd{Set(v)}. 4397 4398 The library syntax is \fun{GEN}{cmp_universal}{GEN x, GEN y}. 4399 4400 \subsec{divrem$(x,y,\{v\})$}\kbdsidx{divrem}\label{se:divrem} 4401 Creates a column vector with two components, the first being the Euclidean 4402 quotient (\kbd{$x$ \bs\ $y$}), the second the Euclidean remainder 4403 (\kbd{$x$ - ($x$\bs$y$)*$y$}), of the division of $x$ by $y$. This avoids the 4404 need to do two divisions if one needs both the quotient and the remainder. 4405 If $v$ is present, and $x$, $y$ are multivariate 4406 polynomials, divide with respect to the variable $v$. 4407 4408 Beware that \kbd{divrem($x$,$y$)[2]} is in general not the same as 4409 \kbd{$x$ \% $y$}; no GP operator corresponds to it: 4410 \bprog 4411 ? divrem(1/2, 3)[2] 4412 %1 = 1/2 4413 ? (1/2) % 3 4414 %2 = 2 4415 ? divrem(Mod(2,9), 3)[2] 4416 *** at top-level: divrem(Mod(2,9),3)[2 4417 *** ^-------------------- 4418 *** forbidden division t_INTMOD \ t_INT. 4419 ? Mod(2,9) % 6 4420 %3 = Mod(2,3) 4421 @eprog 4422 4423 The library syntax is \fun{GEN}{divrem}{GEN x, GEN y, long v = -1} where \kbd{v} is a variable number. 4424 Also available is \fun{GEN}{gdiventres}{GEN x, GEN y} when $v$ is 4425 not needed. 4426 4427 \subsec{lex$(x,y)$}\kbdsidx{lex}\label{se:lex} 4428 Gives the result of a lexicographic comparison 4429 between $x$ and $y$ (as $-1$, $0$ or $1$). This is to be interpreted in quite 4430 a wide sense: it is admissible to compare objects of different types 4431 (scalars, vectors, matrices), provided the scalars can be compared, as well 4432 as vectors/matrices of different lengths; finally, when comparing two scalars, 4433 a complex number $a + I*b$ is interpreted as a vector $[a,b]$ and a real 4434 number $a$ as $[a,0]$. The comparison is recursive. 4435 4436 In case all components are equal up to the smallest length of the operands, 4437 the more complex is considered to be larger. More precisely, the longest is 4438 the largest; when lengths are equal, we have matrix $>$ vector $>$ scalar. 4439 For example: 4440 \bprog 4441 ? lex([1,3], [1,2,5]) 4442 %1 = 1 4443 ? lex([1,3], [1,3,-1]) 4444 %2 = -1 4445 ? lex([1], [[1]]) 4446 %3 = -1 4447 ? lex([1], [1]~) 4448 %4 = 0 4449 ? lex(2 - I, 1) 4450 %5 = 1 4451 ? lex(2 - I, 2) 4452 %6 = 2 4453 @eprog 4454 4455 The library syntax is \fun{GEN}{lexcmp}{GEN x, GEN y}. 4456 4457 \subsec{max$(x,y)$}\kbdsidx{max}\label{se:max} 4458 Creates the maximum of $x$ and $y$ when they can be compared. 4459 4460 The library syntax is \fun{GEN}{gmax}{GEN x, GEN y}. 4461 4462 \subsec{min$(x,y)$}\kbdsidx{min}\label{se:min} 4463 Creates the minimum of $x$ and $y$ when they can be compared. 4464 4465 The library syntax is \fun{GEN}{gmin}{GEN x, GEN y}. 4466 4467 \subsec{shift$(x,n)$}\kbdsidx{shift}\label{se:shift} 4468 Shifts $x$ componentwise left by $n$ bits if $n\ge0$ and right by $|n|$ 4469 bits if $n<0$. May be abbreviated as $x$ \kbd{<<} $n$ or $x$ \kbd{>>} $(-n)$. 4470 A left shift by $n$ corresponds to multiplication by $2^n$. A right shift of an 4471 integer $x$ by $|n|$ corresponds to a Euclidean division of $x$ by $2^{|n|}$ 4472 with a remainder of the same sign as $x$, hence is not the same (in general) as 4473 $x \kbd{\bs} 2^n$. 4474 4475 The library syntax is \fun{GEN}{gshift}{GEN x, long n}. 4476 4477 \subsec{shiftmul$(x,n)$}\kbdsidx{shiftmul}\label{se:shiftmul} 4478 Multiplies $x$ by $2^n$. The difference with 4479 \kbd{shift} is that when $n<0$, ordinary division takes place, hence for 4480 example if $x$ is an integer the result may be a fraction, while for shifts 4481 Euclidean division takes place when $n<0$ hence if $x$ is an integer the result 4482 is still an integer. 4483 4484 The library syntax is \fun{GEN}{gmul2n}{GEN x, long n}. 4485 4486 \subsec{sign$(x)$}\kbdsidx{sign}\label{se:sign} 4487 \idx{sign} ($0$, $1$ or $-1$) of $x$, which must be of 4488 type integer, real or fraction; \typ{QUAD} with positive discriminants and 4489 \typ{INFINITY} are also supported. 4490 4491 The library syntax is \fun{GEN}{gsigne}{GEN x}. 4492 4493 \subsec{vecmax$(x,\{\&v\})$}\kbdsidx{vecmax}\label{se:vecmax} 4494 If $x$ is a vector or a matrix, returns the largest entry of $x$, 4495 otherwise returns a copy of $x$. Error if $x$ is empty. 4496 4497 If $v$ is given, set it to the index of a largest entry (indirect maximum), 4498 when $x$ is a vector. If $x$ is a matrix, set $v$ to coordinates $[i,j]$ 4499 such that $x[i,j]$ is a largest entry. This flag is ignored if $x$ is not a 4500 vector or matrix. 4501 4502 \bprog 4503 ? vecmax([10, 20, -30, 40]) 4504 %1 = 40 4505 ? vecmax([10, 20, -30, 40], &v); v 4506 %2 = 4 4507 ? vecmax([10, 20; -30, 40], &v); v 4508 %3 = [2, 2] 4509 @eprog 4510 4511 The library syntax is \fun{GEN}{vecmax0}{GEN x, GEN *v = NULL}. 4512 When $v$ is not needed, the function \fun{GEN}{vecmax}{GEN x} is 4513 also available. 4514 4515 \subsec{vecmin$(x,\{\&v\})$}\kbdsidx{vecmin}\label{se:vecmin} 4516 If $x$ is a vector or a matrix, returns the smallest entry of $x$, 4517 otherwise returns a copy of $x$. Error if $x$ is empty. 4518 4519 If $v$ is given, set it to the index of a smallest entry (indirect minimum), 4520 when $x$ is a vector. If $x$ is a matrix, set $v$ to coordinates $[i,j]$ such 4521 that $x[i,j]$ is a smallest entry. This is ignored if $x$ is not a vector or 4522 matrix. 4523 4524 \bprog 4525 ? vecmin([10, 20, -30, 40]) 4526 %1 = -30 4527 ? vecmin([10, 20, -30, 40], &v); v 4528 %2 = 3 4529 ? vecmin([10, 20; -30, 40], &v); v 4530 %3 = [2, 1] 4531 @eprog 4532 4533 The library syntax is \fun{GEN}{vecmin0}{GEN x, GEN *v = NULL}. 4534 When $v$ is not needed, the function \fun{GEN}{vecmin}{GEN x} is also 4535 available. 4536 4537 \section{Conversions and similar elementary functions or commands} 4538 \label{se:conversion} 4539 4540 \noindent 4541 Many of the conversion functions are rounding or truncating operations. In 4542 this case, if the argument is a rational function, the result is the 4543 Euclidean quotient of the numerator by the denominator, and if the argument 4544 is a vector or a matrix, the operation is done componentwise. This will not 4545 be restated for every function. 4546 4547 \subsec{Col$(x, \{n\})$}\kbdsidx{Col}\label{se:Col} 4548 Transforms the object $x$ into a column vector. The dimension of the 4549 resulting vector can be optionally specified via the extra parameter $n$. 4550 4551 If $n$ is omitted or $0$, the dimension depends on the type of $x$; the 4552 vector has a single component, except when $x$ is 4553 4554 \item a vector or a quadratic form (in which case the resulting vector 4555 is simply the initial object considered as a row vector), 4556 4557 \item a polynomial or a power series. In the case of a polynomial, the 4558 coefficients of the vector start with the leading coefficient of the 4559 polynomial, while for power series only the significant coefficients are 4560 taken into account, but this time by increasing order of degree. 4561 In this last case, \kbd{Vec} is the reciprocal function of \kbd{Pol} and 4562 \kbd{Ser} respectively, 4563 4564 \item a matrix (the column of row vector comprising the matrix is returned), 4565 4566 \item a character string (a vector of individual characters is returned). 4567 4568 In the last two cases (matrix and character string), $n$ is meaningless and 4569 must be omitted or an error is raised. Otherwise, if $n$ is given, $0$ 4570 entries are appended at the end of the vector if $n > 0$, and prepended at 4571 the beginning if $n < 0$. The dimension of the resulting vector is $|n|$. 4572 4573 See ??Vec for examples. 4574 4575 The library syntax is \fun{GEN}{gtocol0}{GEN x, long n}. 4576 \fun{GEN}{gtocol}{GEN x} is also available. 4577 4578 \subsec{Colrev$(x, \{n\})$}\kbdsidx{Colrev}\label{se:Colrev} 4579 As $\kbd{Col}(x, -n)$, then reverse the result. In particular, 4580 \kbd{Colrev} is the reciprocal function of \kbd{Polrev}: the 4581 coefficients of the vector start with the constant coefficient of the 4582 polynomial and the others follow by increasing degree. 4583 4584 The library syntax is \fun{GEN}{gtocolrev0}{GEN x, long n}. 4585 \fun{GEN}{gtocolrev}{GEN x} is also available. 4586 4587 \subsec{List$(\{x=[\,]\})$}\kbdsidx{List}\label{se:List} 4588 Transforms a (row or column) vector $x$ into a list, whose components are 4589 the entries of $x$. Similarly for a list, but rather useless in this case. 4590 For other types, creates a list with the single element $x$. 4591 4592 The library syntax is \fun{GEN}{gtolist}{GEN x = NULL}. 4593 The variant \fun{GEN}{mklist}{void} creates an empty list. 4594 4595 \subsec{Map$(\{x\})$}\kbdsidx{Map}\label{se:Map} 4596 A ``Map'' is an associative array, or dictionary: a data 4597 type composed of a collection of (\emph{key}, \emph{value}) pairs, such that 4598 each key appears just once in the collection. This function 4599 converts the matrix $[a_1,b_1;a_2,b_2;\dots;a_n,b_n]$ to the map $a_i\mapsto 4600 b_i$. 4601 \bprog 4602 ? M = Map(factor(13!)); 4603 ? mapget(M,3) 4604 %2 = 5 4605 @eprog\noindent If the argument $x$ is omitted, creates an empty map, which 4606 may be filled later via \tet{mapput}. 4607 4608 The library syntax is \fun{GEN}{gtomap}{GEN x = NULL}. 4609 4610 \subsec{Mat$(\{x=[\,]\})$}\kbdsidx{Mat}\label{se:Mat} 4611 Transforms the object $x$ into a matrix. 4612 If $x$ is already a matrix, a copy of $x$ is created. 4613 If $x$ is a row (resp. column) vector, this creates a 1-row (resp. 4614 1-column) matrix, \emph{unless} all elements are column (resp.~row) vectors 4615 of the same length, in which case the vectors are concatenated sideways 4616 and the attached big matrix is returned. 4617 If $x$ is a binary quadratic form, creates the attached $2\times 2$ 4618 matrix. Otherwise, this creates a $1\times 1$ matrix containing $x$. 4619 4620 \bprog 4621 ? Mat(x + 1) 4622 %1 = 4623 [x + 1] 4624 ? Vec( matid(3) ) 4625 %2 = [[1, 0, 0]~, [0, 1, 0]~, [0, 0, 1]~] 4626 ? Mat(%) 4627 %3 = 4628 [1 0 0] 4629 4630 [0 1 0] 4631 4632 [0 0 1] 4633 ? Col( [1,2; 3,4] ) 4634 %4 = [[1, 2], [3, 4]]~ 4635 ? Mat(%) 4636 %5 = 4637 [1 2] 4638 4639 [3 4] 4640 ? Mat(Qfb(1,2,3)) 4641 %6 = 4642 [1 1] 4643 4644 [1 3] 4645 @eprog 4646 4647 The library syntax is \fun{GEN}{gtomat}{GEN x = NULL}. 4648 4649 \subsec{Mod$(a,b)$}\kbdsidx{Mod}\label{se:Mod} 4650 In its basic form, create an intmod or a polmod $(a \mod b)$; $b$ must 4651 be an integer or a polynomial. We then obtain a \typ{INTMOD} and a 4652 \typ{POLMOD} respectively: 4653 \bprog 4654 ? t = Mod(2,17); t^8 4655 %1 = Mod(1, 17) 4656 ? t = Mod(x,x^2+1); t^2 4657 %2 = Mod(-1, x^2+1) 4658 @eprog\noindent If $a \% b$ makes sense and yields a result of the 4659 appropriate type (\typ{INT} or scalar/\typ{POL}), the operation succeeds as 4660 well: 4661 \bprog 4662 ? Mod(1/2, 5) 4663 %3 = Mod(3, 5) 4664 ? Mod(7 + O(3^6), 3) 4665 %4 = Mod(1, 3) 4666 ? Mod(Mod(1,12), 9) 4667 %5 = Mod(1, 3) 4668 ? Mod(1/x, x^2+1) 4669 %6 = Mod(-x, x^2+1) 4670 ? Mod(exp(x), x^4) 4671 %7 = Mod(1/6*x^3 + 1/2*x^2 + x + 1, x^4) 4672 @eprog 4673 If $a$ is a complex object, ``base change'' it to $\Z/b\Z$ or $K[x]/(b)$, 4674 which is equivalent to, but faster than, multiplying it by \kbd{Mod(1,b)}: 4675 \bprog 4676 ? Mod([1,2;3,4], 2) 4677 %8 = 4678 [Mod(1, 2) Mod(0, 2)] 4679 4680 [Mod(1, 2) Mod(0, 2)] 4681 ? Mod(3*x+5, 2) 4682 %9 = Mod(1, 2)*x + Mod(1, 2) 4683 ? Mod(x^2 + y*x + y^3, y^2+1) 4684 %10 = Mod(1, y^2 + 1)*x^2 + Mod(y, y^2 + 1)*x + Mod(-y, y^2 + 1) 4685 @eprog 4686 4687 This function is not the same as $x$ \kbd{\%} $y$, the result of which 4688 has no knowledge of the intended modulus $y$. Compare 4689 \bprog 4690 ? x = 4 % 5; x + 1 4691 %11 = 5 4692 ? x = Mod(4,5); x + 1 4693 %12 = Mod(0,5) 4694 @eprog Note that such ``modular'' objects can be lifted via \tet{lift} or 4695 \tet{centerlift}. The modulus of a \typ{INTMOD} or \typ{POLMOD} $z$ can 4696 be recovered via \kbd{$z$.mod}. 4697 4698 The library syntax is \fun{GEN}{gmodulo}{GEN a, GEN b}. 4699 4700 \subsec{Pol$(t,\{v='x\})$}\kbdsidx{Pol}\label{se:Pol} 4701 Transforms the object $t$ into a polynomial with main variable $v$. If $t$ 4702 is a scalar, this gives a constant polynomial. If $t$ is a power series with 4703 nonnegative valuation or a rational function, the effect is similar to 4704 \kbd{truncate}, i.e.~we chop off the $O(X^k)$ or compute the Euclidean 4705 quotient of the numerator by the denominator, then change the main variable 4706 of the result to $v$. 4707 4708 The main use of this function is when $t$ is a vector: it creates the 4709 polynomial whose coefficients are given by $t$, with $t[1]$ being the leading 4710 coefficient (which can be zero). It is much faster to evaluate 4711 \kbd{Pol} on a vector of coefficients in this way, than the corresponding 4712 formal expression $a_n X^n + \dots + a_0$, which is evaluated naively exactly 4713 as written (linear versus quadratic time in $n$). \tet{Polrev} can be used if 4714 one wants $x[1]$ to be the constant coefficient: 4715 \bprog 4716 ? Pol([1,2,3]) 4717 %1 = x^2 + 2*x + 3 4718 ? Polrev([1,2,3]) 4719 %2 = 3*x^2 + 2*x + 1 4720 @eprog\noindent 4721 The reciprocal function of \kbd{Pol} (resp.~\kbd{Polrev}) is \kbd{Vec} (resp.~ 4722 \kbd{Vecrev}). 4723 \bprog 4724 ? Vec(Pol([1,2,3])) 4725 %1 = [1, 2, 3] 4726 ? Vecrev( Polrev([1,2,3]) ) 4727 %2 = [1, 2, 3] 4728 @eprog\noindent 4729 4730 \misctitle{Warning} This is \emph{not} a substitution function. It will not 4731 transform an object containing variables of higher priority than~$v$. 4732 \bprog 4733 ? Pol(x + y, y) 4734 *** at top-level: Pol(x+y,y) 4735 *** ^---------- 4736 *** Pol: variable must have higher priority in gtopoly. 4737 @eprog 4738 4739 The library syntax is \fun{GEN}{gtopoly}{GEN t, long v = -1} where \kbd{v} is a variable number. 4740 4741 \subsec{Polrev$(t,\{v='x\})$}\kbdsidx{Polrev}\label{se:Polrev} 4742 Transform the object $t$ into a polynomial 4743 with main variable $v$. If $t$ is a scalar, this gives a constant polynomial. 4744 If $t$ is a power series, the effect is identical to \kbd{truncate}, i.e.~it 4745 chops off the $O(X^k)$. 4746 4747 The main use of this function is when $t$ is a vector: it creates the 4748 polynomial whose coefficients are given by $t$, with $t[1]$ being the 4749 constant term. \tet{Pol} can be used if one wants $t[1]$ to be the leading 4750 coefficient: 4751 \bprog 4752 ? Polrev([1,2,3]) 4753 %1 = 3*x^2 + 2*x + 1 4754 ? Pol([1,2,3]) 4755 %2 = x^2 + 2*x + 3 4756 @eprog 4757 The reciprocal function of \kbd{Pol} (resp.~\kbd{Polrev}) is \kbd{Vec} (resp.~ 4758 \kbd{Vecrev}). 4759 4760 The library syntax is \fun{GEN}{gtopolyrev}{GEN t, long v = -1} where \kbd{v} is a variable number. 4761 4762 \subsec{Qfb$(a,b,c,\{D=0.\})$}\kbdsidx{Qfb}\label{se:Qfb} 4763 Creates the binary quadratic form\sidx{binary quadratic form} 4764 $ax^2+bxy+cy^2$. If $b^2-4ac>0$, initialize \idx{Shanks}' distance 4765 function to $D$. Negative definite forms are not implemented, 4766 use their positive definite counterpart instead. 4767 4768 The library syntax is \fun{GEN}{Qfb0}{GEN a, GEN b, GEN c, GEN D = NULL, long prec}. 4769 Also available are 4770 \fun{GEN}{qfi}{GEN a, GEN b, GEN c} (assumes $b^2-4ac<0$) and 4771 \fun{GEN}{qfr}{GEN a, GEN b, GEN c, GEN D} (assumes $b^2-4ac>0$). 4772 4773 \subsec{Ser$(s,\{v='x\},\{d=\var{seriesprecision}\})$}\kbdsidx{Ser}\label{se:Ser} 4774 Transforms the object $s$ into a power series with main variable $v$ 4775 ($x$ by default) and precision (number of significant terms) equal to 4776 $d \geq 0$ ($d = \kbd{seriesprecision}$ by default). If $s$ is a 4777 scalar, this gives a constant power series in $v$ with precision \kbd{d}. 4778 If $s$ is a polynomial, the polynomial is truncated to $d$ terms if needed 4779 \bprog 4780 ? \ps 4781 seriesprecision = 16 significant terms 4782 ? Ser(1) \\ 16 terms by default 4783 %1 = 1 + O(x^16) 4784 ? Ser(1, 'y, 5) 4785 %2 = 1 + O(y^5) 4786 ? Ser(x^2,, 5) 4787 %3 = x^2 + O(x^7) 4788 ? T = polcyclo(100) 4789 %4 = x^40 - x^30 + x^20 - x^10 + 1 4790 ? Ser(T, 'x, 11) 4791 %5 = 1 - x^10 + O(x^11) 4792 @eprog\noindent The function is more or less equivalent with multiplication by 4793 $1 + O(v^d)$ in theses cases, only faster. 4794 4795 For the remaining types, vectors and power series, we first explain what 4796 occurs if $d$ is omitted. In this case, the function uses exactly the amount 4797 of information given in the input: 4798 4799 \item If $s$ is already a power series in $v$, we return it verbatim; 4800 4801 \item If $s$ is a vector, the coefficients of the vector are 4802 understood to be the coefficients of the power series starting from the 4803 constant term (as in \tet{Polrev}$(x)$); in other words we convert 4804 \typ{VEC} / \typ{COL} to the power series whose significant terms are exactly 4805 given by the vector entries. 4806 4807 On the other hand, if $d$ is explicitly given, we abide by its value 4808 and return a series, truncated or extended with zeros as needed, with 4809 $d$ significant terms. 4810 4811 \bprog 4812 ? v = [1,2,3]; 4813 ? Ser(v, t) \\ 3 terms: seriesprecision is ignored! 4814 %7 = 1 + 2*t + 3*t^2 + O(t^3) 4815 ? Ser(v, t, 7) \\ 7 terms as explicitly requested 4816 %8 = 1 + 2*t + 3*t^2 + O(t^7) 4817 ? s = 1+x+O(x^2); 4818 ? Ser(s) 4819 %10 = 1 + x + O(x^2) \\ 2 terms: seriesprecision is ignored 4820 ? Ser(s, x, 7) \\ extend to 7 terms 4821 %11 = 1 + x + O(x^7) 4822 ? Ser(s, x, 1) \\ truncate to 1 term 4823 %12 = 1 + O(x) 4824 @eprog\noindent 4825 The warning given for \kbd{Pol} also applies here: this is not a substitution 4826 function. 4827 4828 The library syntax is \fun{GEN}{Ser0}{GEN s, long v = -1, GEN d = NULL, long precdl} where \kbd{v} is a variable number. 4829 4830 \subsec{Set$(\{x=[\,]\})$}\kbdsidx{Set}\label{se:Set} 4831 Converts $x$ into a set, i.e.~into a row vector, with strictly increasing 4832 entries with respect to the (somewhat arbitrary) universal comparison function 4833 \tet{cmp}. Standard container types \typ{VEC}, \typ{COL}, \typ{LIST} and 4834 \typ{VECSMALL} are converted to the set with corresponding elements. All 4835 others are converted to a set with one element. 4836 \bprog 4837 ? Set([1,2,4,2,1,3]) 4838 %1 = [1, 2, 3, 4] 4839 ? Set(x) 4840 %2 = [x] 4841 ? Set(Vecsmall([1,3,2,1,3])) 4842 %3 = [1, 2, 3] 4843 @eprog 4844 4845 The library syntax is \fun{GEN}{gtoset}{GEN x = NULL}. 4846 4847 \subsec{Str$(\{x\}*)$}\kbdsidx{Str}\label{se:Str} 4848 Converts its argument list into a 4849 single character string (type \typ{STR}, the empty string if $x$ is omitted). 4850 To recover an ordinary \kbd{GEN} from a string, apply \kbd{eval} to it. The 4851 arguments of \kbd{Str} are evaluated in string context, see \secref{se:strings}. 4852 4853 \bprog 4854 ? x2 = 0; i = 2; Str(x, i) 4855 %1 = "x2" 4856 ? eval(%) 4857 %2 = 0 4858 @eprog\noindent 4859 This function is mostly useless in library mode. Use the pair 4860 \tet{strtoGEN}/\tet{GENtostr} to convert between \kbd{GEN} and \kbd{char*}. 4861 The latter returns a malloced string, which should be freed after usage. 4862 %\syn{NO} 4863 4864 \subsec{Vec$(x, \{n\})$}\kbdsidx{Vec}\label{se:Vec} 4865 Transforms the object $x$ into a row vector. The dimension of the 4866 resulting vector can be optionally specified via the extra parameter $n$. 4867 If $n$ is omitted or $0$, the dimension depends on the type of $x$; the 4868 vector has a single component, except when $x$ is 4869 4870 \item a vector or a quadratic form: returns the initial object considered as a 4871 row vector, 4872 4873 \item a polynomial or a power series: returns a vector consisting of the 4874 coefficients. In the case of a polynomial, the coefficients of the vector 4875 start with the leading coefficient of the polynomial, while for power series 4876 only the significant coefficients are taken into account, but this time by 4877 increasing order of degree. In particular the valuation is ignored 4878 (which makes the function useful for series of negative valuation): 4879 \bprog 4880 ? Vec(3*x^2 + x) 4881 %1 = [3, 1, 0] 4882 ? Vec(x^2 + 3*x^3 + O(x^5)) 4883 %2 = [1, 3, 0] 4884 ? Vec(x^-2 + 3*x^-1 + O(x)) 4885 %3 = [1, 3, 0] 4886 @eprog\noindent \kbd{Vec} is the reciprocal function of \kbd{Pol} for a 4887 polynomial and of \kbd{Ser} for power series of valuation $0$. 4888 4889 \item a matrix: returns the vector of columns comprising the matrix, 4890 \bprog 4891 ? m = [1,2,3;4,5,6] 4892 %4 = 4893 [1 2 3] 4894 4895 [4 5 6] 4896 ? Vec(m) 4897 %5 = [[1, 4]~, [2, 5]~, [3, 6]~] 4898 @eprog 4899 4900 \item a character string: returns the vector of individual characters, 4901 \bprog 4902 ? Vec("PARI") 4903 %6 = ["P", "A", "R", "I"] 4904 @eprog 4905 4906 \item a map: returns the vector of the domain of the map, 4907 4908 \item an error context (\typ{ERROR}): returns the error components, see 4909 \tet{iferr}. 4910 4911 In the last four cases (matrix, character string, map, error), $n$ is 4912 meaningless and must be omitted or an error is raised. Otherwise, if $n$ is 4913 given, $0$ entries are appended at the end of the vector if $n > 0$, and 4914 prepended at the beginning if $n < 0$. The dimension of the resulting vector 4915 is $|n|$. This allows to write a conversion function for series that 4916 takes positive valuations into account: 4917 \bprog 4918 ? serVec(s) = Vec(s, -serprec(s,variable(s))); 4919 ? Vec(x^2 + 3*x^3 + O(x^5)) 4920 %2 = [0, 0, 1, 3, 0] 4921 @eprog (That function is not intended for series of negative valuation.) 4922 4923 The library syntax is \fun{GEN}{gtovec0}{GEN x, long n}. 4924 \fun{GEN}{gtovec}{GEN x} is also available. 4925 4926 \subsec{Vecrev$(x, \{n\})$}\kbdsidx{Vecrev}\label{se:Vecrev} 4927 As $\kbd{Vec}(x, -n)$, then reverse the result. In particular, 4928 \kbd{Vecrev} is the reciprocal function of \kbd{Polrev}: the 4929 coefficients of the vector start with the constant coefficient of the 4930 polynomial and the others follow by increasing degree. 4931 4932 The library syntax is \fun{GEN}{gtovecrev0}{GEN x, long n}. 4933 \fun{GEN}{gtovecrev}{GEN x} is also available. 4934 4935 \subsec{Vecsmall$(x, \{n\})$}\kbdsidx{Vecsmall}\label{se:Vecsmall} 4936 Transforms the object $x$ into a row vector of type \typ{VECSMALL}. The 4937 dimension of the resulting vector can be optionally specified via the extra 4938 parameter $n$. 4939 4940 This acts as \kbd{Vec}$(x,n)$, but only on a limited set of objects: 4941 the result must be representable as a vector of small integers. 4942 If $x$ is a character string, a vector of individual characters in ASCII 4943 encoding is returned (\tet{strchr} yields back the character string). 4944 4945 The library syntax is \fun{GEN}{gtovecsmall0}{GEN x, long n}. 4946 \fun{GEN}{gtovecsmall}{GEN x} is also available. 4947 4948 \subsec{binary$(x)$}\kbdsidx{binary}\label{se:binary} 4949 Outputs the vector of the binary digits of $|x|$. Here $x$ can be an 4950 integer, a real number (in which case the result has two components, one for 4951 the integer part, one for the fractional part) or a vector/matrix. 4952 \bprog 4953 ? binary(10) 4954 %1 = [1, 0, 1, 0] 4955 4956 ? binary(3.14) 4957 %2 = [[1, 1], [0, 0, 1, 0, 0, 0, [...]] 4958 4959 ? binary([1,2]) 4960 %3 = [[1], [1, 0]] 4961 @eprog\noindent For integer $x\ge1$, the number of bits is 4962 $\kbd{logint}(x,2) + 1$. By convention, $0$ has no digits: 4963 \bprog 4964 ? binary(0) 4965 %4 = [] 4966 @eprog 4967 4968 The library syntax is \fun{GEN}{binaire}{GEN x}. 4969 4970 \subsec{bitand$(x,y)$}\kbdsidx{bitand}\label{se:bitand} 4971 Bitwise \tet{and} 4972 \sidx{bitwise and}of two integers $x$ and $y$, that is the integer 4973 $$\sum_i (x_i~\kbd{and}~y_i) 2^i$$ 4974 4975 Negative numbers behave $2$-adically, i.e.~the result is the $2$-adic limit 4976 of \kbd{bitand}$(x_n,y_n)$, where $x_n$ and $y_n$ are nonnegative integers 4977 tending to $x$ and $y$ respectively. (The result is an ordinary integer, 4978 possibly negative.) 4979 4980 \bprog 4981 ? bitand(5, 3) 4982 %1 = 1 4983 ? bitand(-5, 3) 4984 %2 = 3 4985 ? bitand(-5, -3) 4986 %3 = -7 4987 @eprog 4988 4989 The library syntax is \fun{GEN}{gbitand}{GEN x, GEN y}. 4990 Also available is 4991 \fun{GEN}{ibitand}{GEN x, GEN y}, which returns the bitwise \emph{and} 4992 of $|x|$ and $|y|$, two integers. 4993 4994 \subsec{bitneg$(x,\{n=-1\})$}\kbdsidx{bitneg}\label{se:bitneg} 4995 \idx{bitwise negation} of an integer $x$, 4996 truncated to $n$ bits, $n\geq 0$, that is the integer 4997 $$\sum_{i=0}^{n-1} \kbd{not}(x_i) 2^i.$$ 4998 The special case $n=-1$ means no truncation: an infinite sequence of 4999 leading $1$ is then represented as a negative number. 5000 5001 See \secref{se:bitand} for the behavior for negative arguments. 5002 5003 The library syntax is \fun{GEN}{gbitneg}{GEN x, long n}. 5004 5005 \subsec{bitnegimply$(x,y)$}\kbdsidx{bitnegimply}\label{se:bitnegimply} 5006 Bitwise negated imply of two integers $x$ and 5007 $y$ (or \kbd{not} $(x \Rightarrow y)$), that is the integer $$\sum 5008 (x_i~\kbd{and not}(y_i)) 2^i$$ 5009 5010 See \secref{se:bitand} for the behavior for negative arguments. 5011 5012 The library syntax is \fun{GEN}{gbitnegimply}{GEN x, GEN y}. 5013 Also available is 5014 \fun{GEN}{ibitnegimply}{GEN x, GEN y}, which returns the bitwise negated 5015 imply of $|x|$ and $|y|$, two integers. 5016 5017 \subsec{bitor$(x,y)$}\kbdsidx{bitor}\label{se:bitor} 5018 \sidx{bitwise inclusive or}bitwise (inclusive) 5019 \tet{or} of two integers $x$ and $y$, that is the integer $$\sum 5020 (x_i~\kbd{or}~y_i) 2^i$$ 5021 5022 See \secref{se:bitand} for the behavior for negative arguments. 5023 5024 The library syntax is \fun{GEN}{gbitor}{GEN x, GEN y}. 5025 Also available is 5026 \fun{GEN}{ibitor}{GEN x, GEN y}, which returns the bitwise \emph{or} 5027 of $|x|$ and $|y|$, two integers. 5028 5029 \subsec{bitprecision$(x,\{n\})$}\kbdsidx{bitprecision}\label{se:bitprecision} 5030 The function behaves differently according to whether $n$ is 5031 present or not. If $n$ is missing, the function returns 5032 the (floating point) precision in bits of the PARI object $x$. 5033 5034 If $x$ is an exact object, the function returns \kbd{+oo}. 5035 \bprog 5036 ? bitprecision(exp(1e-100)) 5037 %1 = 512 \\ 512 bits 5038 ? bitprecision( [ exp(1e-100), 0.5 ] ) 5039 %2 = 128 \\ minimal accuracy among components 5040 ? bitprecision(2 + x) 5041 %3 = +oo \\ exact object 5042 @eprog\noindent Use \kbd{getlocalbitprec()} to retrieve the 5043 working bit precision (as modified by possible \kbd{localbitprec} 5044 statements). 5045 5046 If $n$ is present and positive, the function creates a new object equal to $x$ 5047 with the new bit-precision roughly $n$. In fact, the smallest multiple of 64 5048 (resp.~32 on a 32-bit machine) larger than or equal to $n$. 5049 5050 For $x$ a vector or a matrix, the operation is 5051 done componentwise; for series and polynomials, the operation is done 5052 coefficientwise. For real $x$, $n$ is the number of desired significant 5053 \emph{bits}. If $n$ is smaller than the precision of $x$, $x$ is truncated, 5054 otherwise $x$ is extended with zeros. For exact or non-floating-point types, 5055 no change. 5056 \bprog 5057 ? bitprecision(Pi, 10) \\ actually 64 bits ~ 19 decimal digits 5058 %1 = 3.141592653589793239 5059 ? bitprecision(1, 10) 5060 %2 = 1 5061 ? bitprecision(1 + O(x), 10) 5062 %3 = 1 + O(x) 5063 ? bitprecision(2 + O(3^5), 10) 5064 %4 = 2 + O(3^5) 5065 @eprog\noindent 5066 5067 The library syntax is \fun{GEN}{bitprecision00}{GEN x, GEN n = NULL}. 5068 5069 \subsec{bittest$(x,n)$}\kbdsidx{bittest}\label{se:bittest} 5070 Outputs the $n^{\text{th}}$ bit of $x$ starting 5071 from the right (i.e.~the coefficient of $2^n$ in the binary expansion of $x$). 5072 The result is 0 or 1. For $x\ge1$, the highest 1-bit is at $n = 5073 \kbd{logint}(x)$ (and bigger $n$ gives $0$). 5074 \bprog 5075 ? bittest(7, 0) 5076 %1 = 1 \\ the bit 0 is 1 5077 ? bittest(7, 2) 5078 %2 = 1 \\ the bit 2 is 1 5079 ? bittest(7, 3) 5080 %3 = 0 \\ the bit 3 is 0 5081 @eprog\noindent 5082 See \secref{se:bitand} for the behavior at negative arguments. 5083 5084 The library syntax is \fun{GEN}{gbittest}{GEN x, long n}. 5085 For a \typ{INT} $x$, the variant \fun{long}{bittest}{GEN x, long n} is 5086 generally easier to use, and if furthermore $n\ge 0$ the low-level function 5087 \fun{ulong}{int_bit}{GEN x, long n} returns \kbd{bittest(abs(x),n)}. 5088 5089 \subsec{bitxor$(x,y)$}\kbdsidx{bitxor}\label{se:bitxor} 5090 Bitwise (exclusive) \tet{or} 5091 \sidx{bitwise exclusive or}of two integers $x$ and $y$, that is the integer 5092 $$\sum (x_i~\kbd{xor}~y_i) 2^i$$ 5093 5094 See \secref{se:bitand} for the behavior for negative arguments. 5095 5096 The library syntax is \fun{GEN}{gbitxor}{GEN x, GEN y}. 5097 Also available is 5098 \fun{GEN}{ibitxor}{GEN x, GEN y}, which returns the bitwise \emph{xor} 5099 of $|x|$ and $|y|$, two integers. 5100 5101 \subsec{ceil$(x)$}\kbdsidx{ceil}\label{se:ceil} 5102 Ceiling of $x$. When $x$ is in $\R$, the result is the 5103 smallest integer greater than or equal to $x$. Applied to a rational 5104 function, $\kbd{ceil}(x)$ returns the Euclidean quotient of the numerator by 5105 the denominator. 5106 5107 The library syntax is \fun{GEN}{gceil}{GEN x}. 5108 5109 \subsec{centerlift$(x,\{v\})$}\kbdsidx{centerlift}\label{se:centerlift} 5110 Same as \tet{lift}, except that \typ{INTMOD} and \typ{PADIC} components 5111 are lifted using centered residues: 5112 5113 \item for a \typ{INTMOD} $x\in \Z/n\Z$, the lift $y$ is such that 5114 $-n/2<y\le n/2$. 5115 5116 \item a \typ{PADIC} $x$ is lifted in the same way as above (modulo 5117 $p^\kbd{padicprec(x)}$) if its valuation $v$ is nonnegative; if not, returns 5118 the fraction $p^v$ \kbd{centerlift}$(x p^{-v})$; in particular, rational 5119 reconstruction is not attempted. Use \tet{bestappr} for this. 5120 5121 For backward compatibility, \kbd{centerlift(x,'v)} is allowed as an alias 5122 for \kbd{lift(x,'v)}. 5123 5124 \synt{centerlift}{GEN x}. 5125 5126 \subsec{characteristic$(x)$}\kbdsidx{characteristic}\label{se:characteristic} 5127 Returns the characteristic of the base ring over which $x$ is defined (as 5128 defined by \typ{INTMOD} and \typ{FFELT} components). The function raises an 5129 exception if incompatible primes arise from \typ{FFELT} and \typ{PADIC} 5130 components. 5131 \bprog 5132 ? characteristic(Mod(1,24)*x + Mod(1,18)*y) 5133 %1 = 6 5134 @eprog 5135 5136 The library syntax is \fun{GEN}{characteristic}{GEN x}. 5137 5138 \subsec{component$(x,n)$}\kbdsidx{component}\label{se:component} 5139 Extracts the $n^{\text{th}}$-component of $x$. This is to be understood 5140 as follows: every PARI type has one or two initial \idx{code words}. The 5141 components are counted, starting at 1, after these code words. In particular 5142 if $x$ is a vector, this is indeed the $n^{\text{th}}$-component of $x$, if 5143 $x$ is a matrix, the $n^{\text{th}}$ column, if $x$ is a polynomial, the 5144 $n^{\text{th}}$ coefficient (i.e.~of degree $n-1$), and for power series, 5145 the $n^{\text{th}}$ significant coefficient. 5146 5147 For polynomials and power series, one should rather use \tet{polcoeff}, and 5148 for vectors and matrices, the \kbd{[$\,$]} operator. Namely, if $x$ is a 5149 vector, then \tet{x[n]} represents the $n^{\text{th}}$ component of $x$. If 5150 $x$ is a matrix, \tet{x[m,n]} represents the coefficient of row \kbd{m} and 5151 column \kbd{n} of the matrix, \tet{x[m,]} represents the $m^{\text{th}}$ 5152 \emph{row} of $x$, and \tet{x[,n]} represents the $n^{\text{th}}$ 5153 \emph{column} of $x$. 5154 5155 Using of this function requires detailed knowledge of the structure of the 5156 different PARI types, and thus it should almost never be used directly. 5157 Some useful exceptions: 5158 \bprog 5159 ? x = 3 + O(3^5); 5160 ? component(x, 2) 5161 %2 = 81 \\ p^(p-adic accuracy) 5162 ? component(x, 1) 5163 %3 = 3 \\ p 5164 ? q = Qfb(1,2,3); 5165 ? component(q, 1) 5166 %5 = 1 5167 @eprog 5168 5169 The library syntax is \fun{GEN}{compo}{GEN x, long n}. 5170 5171 \subsec{conj$(x)$}\kbdsidx{conj}\label{se:conj} 5172 Conjugate of $x$. The meaning of this 5173 is clear, except that for real quadratic numbers, it means conjugation in the 5174 real quadratic field. This function has no effect on integers, reals, 5175 intmods, fractions or $p$-adics. The only forbidden type is polmod 5176 (see \kbd{conjvec} for this). 5177 5178 The library syntax is \fun{GEN}{gconj}{GEN x}. 5179 5180 \subsec{conjvec$(z)$}\kbdsidx{conjvec}\label{se:conjvec} 5181 Conjugate vector representation of $z$. If $z$ is a 5182 polmod, equal to \kbd{Mod}$(a,T)$, this gives a vector of length 5183 $\text{degree}(T)$ containing: 5184 5185 \item the complex embeddings of $z$ if $T$ has rational coefficients, 5186 i.e.~the $a(r[i])$ where $r = \kbd{polroots}(T)$; 5187 5188 \item the conjugates of $z$ if $T$ has some intmod coefficients; 5189 5190 \noindent if $z$ is a finite field element, the result is the vector of 5191 conjugates $[z,z^p,z^{p^2},\ldots,z^{p^{n-1}}]$ where $n=\text{degree}(T)$. 5192 5193 \noindent If $z$ is an integer or a rational number, the result is~$z$. If 5194 $z$ is a (row or column) vector, the result is a matrix whose columns are 5195 the conjugate vectors of the individual elements of $z$. 5196 5197 The library syntax is \fun{GEN}{conjvec}{GEN z, long prec}. 5198 5199 \subsec{denominator$(f,\{D\})$}\kbdsidx{denominator}\label{se:denominator} 5200 Denominator of $f$. The meaning of this is clear when $f$ is a rational number 5201 or function. If $f$ is an integer or a polynomial, it is treated as a rational 5202 number or function, respectively, and the result is equal to $1$. For 5203 polynomials, you probably want to use 5204 \bprog 5205 denominator( content(f) ) 5206 @eprog\noindent instead. As for modular objects, \typ{INTMOD} and \typ{PADIC} 5207 have denominator $1$, and the denominator of a \typ{POLMOD} is the 5208 denominator of its lift. 5209 5210 If $f$ is a recursive structure, for instance a vector or matrix, the lcm 5211 of the denominators of its components (a common denominator) is computed. 5212 This also applies for \typ{COMPLEX}s and \typ{QUAD}s. 5213 5214 \misctitle{Warning} Multivariate objects are created according to variable 5215 priorities, with possibly surprising side effects ($x/y$ is a polynomial, but 5216 $y/x$ is a rational function). See \secref{se:priority}. 5217 5218 The optional argument $D$ allows to control over which ring we compute the 5219 denominator and get a more predictable behaviour: 5220 5221 \item $1$: we only consider the underlying $\Q$-structure and the 5222 denominator is a (positive) rational integer 5223 5224 \item a simple variable, say \kbd{'x}: all entries as rational functions 5225 in $K(x)$ and the denominator is a polynomial in $x$. 5226 5227 \bprog 5228 ? f = x + 1/y + 1/2; 5229 ? denominator(f) \\ a t_POL in x 5230 %2 = 1 5231 ? denominator(f, 1) \\ Q-denominator 5232 %3 = 2 5233 ? denominator(f, x) \\ as a t_POL in x, seen above 5234 %4 = 1 5235 ? denominator(f, y) \\ as a rational function in y 5236 %5 = 2*y 5237 @eprog 5238 5239 The library syntax is \fun{GEN}{denominator}{GEN f, GEN D = NULL}. 5240 Also available are 5241 \fun{GEN}{denom}{GEN x} which implements the not very useful default 5242 behaviour ($D$ is \kbd{NULL}) and \fun{GEN}{Q_denom}{GEN x} ($D = 1$). 5243 5244 \subsec{digits$(x,\{b=10\})$}\kbdsidx{digits}\label{se:digits} 5245 Outputs the vector of the digits of $|x|$ in base $b$, where $x$ and $b$ are 5246 integers ($b = 10$ by default). For $x\ge1$, the number of digits is 5247 $\kbd{logint}(x,b) + 1$. See \kbd{fromdigits} for the reverse operation. 5248 \bprog 5249 ? digits(1230) 5250 %1 = [1, 2, 3, 0] 5251 5252 ? digits(10, 2) \\ base 2 5253 %2 = [1, 0, 1, 0] 5254 @eprog\noindent By convention, $0$ has no digits: 5255 \bprog 5256 ? digits(0) 5257 %3 = [] 5258 @eprog 5259 5260 The library syntax is \fun{GEN}{digits}{GEN x, GEN b = NULL}. 5261 5262 \subsec{exponent$(x)$}\kbdsidx{exponent}\label{se:exponent} 5263 When $x$ is a \typ{REAL}, the result is the binary exponent $e$ of $x$. 5264 For a nonzero $x$, this is the unique integer $e$ such that 5265 $2^e \leq |x| < 2^{e+1}$. For a real $0$, this returns the PARI exponent $e$ 5266 attached to $x$ (which may represent any floating-point number less than 5267 $2^e$ in absolute value). 5268 \bprog 5269 ? exponent(Pi) 5270 %1 = 1 5271 ? exponent(4.0) 5272 %2 = 2 5273 ? exponent(0.0) 5274 %3 = -128 5275 ? default(realbitprecision) 5276 %4 = 128 5277 @eprog\noindent This definition extends naturally to nonzero integers, 5278 and the exponent of an exact $0$ is $-\kbd{oo}$ by convention. 5279 5280 For convenience, we \emph{define} the exponent of a \typ{FRAC} $a/b$ as 5281 the difference of \kbd{exponent}$(a)$ and \kbd{exponent}$(b)$; note that, 5282 if $e'$ denotes the exponent of \kbd{$a/b$ * 1.0}, then the exponent $e$ 5283 we return is either $e'$ or $e'+1$, thus $2^{e+1}$ is an upper bound for 5284 $|a/b|$. 5285 \bprog 5286 ? [ exponent(9), exponent(10), exponent(9/10), exponent(9/10*1.) ] 5287 %5 = [3, 3, 0, -1] 5288 @eprog 5289 5290 For a PARI object of type \typ{COMPLEX}, \typ{POL}, \typ{SER}, \typ{VEC}, 5291 \typ{COL}, \typ{MAT} this returns the largest exponent found among the 5292 components of $x$. Hence $2^{e+1}$ is a quick upper bound for the sup norm 5293 of real matrices or polynomials; and $2^{e+(3/2)}$ for complex ones. 5294 5295 \bprog 5296 ? exponent(3*x^2 + 15*x - 100) 5297 %5 = 6 5298 ? exponent(0) 5299 %6 = -oo 5300 @eprog 5301 5302 The library syntax is \fun{GEN}{gpexponent}{GEN x}. 5303 5304 \subsec{floor$(x)$}\kbdsidx{floor}\label{se:floor} 5305 Floor of $x$. When $x$ is in $\R$, the result is the 5306 largest integer smaller than or equal to $x$. Applied to a rational function, 5307 $\kbd{floor}(x)$ returns the Euclidean quotient of the numerator by the 5308 denominator. 5309 5310 The library syntax is \fun{GEN}{gfloor}{GEN x}. 5311 5312 \subsec{frac$(x)$}\kbdsidx{frac}\label{se:frac} 5313 Fractional part of $x$. Identical to 5314 $x-\text{floor}(x)$. If $x$ is real, the result is in $[0,1[$. 5315 5316 The library syntax is \fun{GEN}{gfrac}{GEN x}. 5317 5318 \subsec{fromdigits$(x,\{b=10\})$}\kbdsidx{fromdigits}\label{se:fromdigits} 5319 Gives the integer formed by the elements of $x$ seen as the digits of a 5320 number in base $b$ ($b = 10$ by default). This is the reverse of \kbd{digits}: 5321 \bprog 5322 ? digits(1234,5) 5323 %1 = [1,4,4,1,4] 5324 ? fromdigits([1,4,4,1,4],5) 5325 %2 = 1234 5326 @eprog\noindent By convention, $0$ has no digits: 5327 \bprog 5328 ? fromdigits([]) 5329 %3 = 0 5330 @eprog 5331 5332 The library syntax is \fun{GEN}{fromdigits}{GEN x, GEN b = NULL}. 5333 5334 \subsec{imag$(x)$}\kbdsidx{imag}\label{se:imag} 5335 Imaginary part of $x$. When $x$ is a quadratic number, this is the 5336 coefficient of $\omega$ in the ``canonical'' integral basis $(1,\omega)$. 5337 \bprog 5338 ? imag(3 + I) 5339 %1 = 1 5340 ? x = 3 + quadgen(-23); 5341 ? imag(x) \\ as a quadratic number 5342 %3 = 1 5343 ? imag(x * 1.) \\ as a complex number 5344 %4 = 2.3979157616563597707987190320813469600 5345 @eprog 5346 5347 The library syntax is \fun{GEN}{gimag}{GEN x}. 5348 5349 \subsec{length$(x)$}\kbdsidx{length}\label{se:length} 5350 Length of $x$; \kbd{\#}$x$ is a shortcut for \kbd{length}$(x)$. 5351 This is mostly useful for 5352 5353 \item vectors: dimension (0 for empty vectors), 5354 5355 \item lists: number of entries (0 for empty lists), 5356 5357 \item maps: number of entries (0 for empty maps), 5358 5359 \item matrices: number of columns, 5360 5361 \item character strings: number of actual characters (without 5362 trailing \kbd{\bs 0}, should you expect it from $C$ \kbd{char*}). 5363 \bprog 5364 ? #"a string" 5365 %1 = 8 5366 ? #[3,2,1] 5367 %2 = 3 5368 ? #[] 5369 %3 = 0 5370 ? #matrix(2,5) 5371 %4 = 5 5372 ? L = List([1,2,3,4]); #L 5373 %5 = 4 5374 ? M = Map([a,b; c,d; e,f]); #M 5375 %6 = 3 5376 @eprog 5377 5378 The routine is in fact defined for arbitrary GP types, but is awkward and 5379 useless in other cases: it returns the number of non-code words in $x$, e.g. 5380 the effective length minus 2 for integers since the \typ{INT} type has two code 5381 words. 5382 5383 The library syntax is \fun{long}{glength}{GEN x}. 5384 5385 \subsec{lift$(x,\{v\})$}\kbdsidx{lift}\label{se:lift} 5386 If $v$ is omitted, lifts intmods from $\Z/n\Z$ in $\Z$, 5387 $p$-adics from $\Q_p$ to $\Q$ (as \tet{truncate}), and polmods to 5388 polynomials. Otherwise, lifts only polmods whose modulus has main 5389 variable~$v$. \typ{FFELT} are not lifted, nor are List elements: you may 5390 convert the latter to vectors first, or use \kbd{apply(lift,L)}. More 5391 generally, components for which such lifts are meaningless (e.g. character 5392 strings) are copied verbatim. 5393 \bprog 5394 ? lift(Mod(5,3)) 5395 %1 = 2 5396 ? lift(3 + O(3^9)) 5397 %2 = 3 5398 ? lift(Mod(x,x^2+1)) 5399 %3 = x 5400 ? lift(Mod(x,x^2+1)) 5401 %4 = x 5402 @eprog 5403 Lifts are performed recursively on an object components, but only 5404 by \emph{one level}: once a \typ{POLMOD} is lifted, the components of 5405 the result are \emph{not} lifted further. 5406 \bprog 5407 ? lift(x * Mod(1,3) + Mod(2,3)) 5408 %4 = x + 2 5409 ? lift(x * Mod(y,y^2+1) + Mod(2,3)) 5410 %5 = y*x + Mod(2, 3) \\@com do you understand this one? 5411 ? lift(x * Mod(y,y^2+1) + Mod(2,3), 'x) 5412 %6 = Mod(y, y^2 + 1)*x + Mod(Mod(2, 3), y^2 + 1) 5413 ? lift(%, y) 5414 %7 = y*x + Mod(2, 3) 5415 @eprog\noindent To recursively lift all components not only by one level, 5416 but as long as possible, use \kbd{liftall}. To lift only \typ{INTMOD}s and 5417 \typ{PADIC}s components, use \tet{liftint}. To lift only \typ{POLMOD}s 5418 components, use \tet{liftpol}. Finally, \tet{centerlift} allows to lift 5419 \typ{INTMOD}s and \typ{PADIC}s using centered residues (lift of smallest 5420 absolute value). 5421 5422 The library syntax is \fun{GEN}{lift0}{GEN x, long v = -1} where \kbd{v} is a variable number. 5423 Also available is \fun{GEN}{lift}{GEN x} corresponding to 5424 \kbd{lift0(x,-1)}. 5425 5426 \subsec{liftall$(x)$}\kbdsidx{liftall}\label{se:liftall} 5427 Recursively lift all components of $x$ from $\Z/n\Z$ to $\Z$, 5428 from $\Q_p$ to $\Q$ (as \tet{truncate}), and polmods to 5429 polynomials. \typ{FFELT} are not lifted, nor are List elements: you may 5430 convert the latter to vectors first, or use \kbd{apply(liftall,L)}. More 5431 generally, components for which such lifts are meaningless (e.g. character 5432 strings) are copied verbatim. 5433 \bprog 5434 ? liftall(x * (1 + O(3)) + Mod(2,3)) 5435 %1 = x + 2 5436 ? liftall(x * Mod(y,y^2+1) + Mod(2,3)*Mod(z,z^2)) 5437 %2 = y*x + 2*z 5438 @eprog 5439 5440 The library syntax is \fun{GEN}{liftall}{GEN x}. 5441 5442 \subsec{liftint$(x)$}\kbdsidx{liftint}\label{se:liftint} 5443 Recursively lift all components of $x$ from $\Z/n\Z$ to $\Z$ and 5444 from $\Q_p$ to $\Q$ (as \tet{truncate}). 5445 \typ{FFELT} are not lifted, nor are List elements: you may 5446 convert the latter to vectors first, or use \kbd{apply(liftint,L)}. More 5447 generally, components for which such lifts are meaningless (e.g. character 5448 strings) are copied verbatim. 5449 \bprog 5450 ? liftint(x * (1 + O(3)) + Mod(2,3)) 5451 %1 = x + 2 5452 ? liftint(x * Mod(y,y^2+1) + Mod(2,3)*Mod(z,z^2)) 5453 %2 = Mod(y, y^2 + 1)*x + Mod(Mod(2*z, z^2), y^2 + 1) 5454 @eprog 5455 5456 The library syntax is \fun{GEN}{liftint}{GEN x}. 5457 5458 \subsec{liftpol$(x)$}\kbdsidx{liftpol}\label{se:liftpol} 5459 Recursively lift all components of $x$ which are polmods to 5460 polynomials. \typ{FFELT} are not lifted, nor are List elements: you may 5461 convert the latter to vectors first, or use \kbd{apply(liftpol,L)}. More 5462 generally, components for which such lifts are meaningless (e.g. character 5463 strings) are copied verbatim. 5464 \bprog 5465 ? liftpol(x * (1 + O(3)) + Mod(2,3)) 5466 %1 = (1 + O(3))*x + Mod(2, 3) 5467 ? liftpol(x * Mod(y,y^2+1) + Mod(2,3)*Mod(z,z^2)) 5468 %2 = y*x + Mod(2, 3)*z 5469 @eprog 5470 5471 The library syntax is \fun{GEN}{liftpol}{GEN x}. 5472 5473 \subsec{norm$(x)$}\kbdsidx{norm}\label{se:norm} 5474 Algebraic norm of $x$, i.e.~the product of $x$ with 5475 its conjugate (no square roots are taken), or conjugates for polmods. For 5476 vectors and matrices, the norm is taken componentwise and hence is not the 5477 $L^2$-norm (see \kbd{norml2}). Note that the norm of an element of 5478 $\R$ is its square, so as to be compatible with the complex norm. 5479 5480 The library syntax is \fun{GEN}{gnorm}{GEN x}. 5481 5482 \subsec{numerator$(f,\{D\})$}\kbdsidx{numerator}\label{se:numerator} 5483 Numerator of $f$. This is defined as \kbd{f * denominator(f,D)}, see 5484 \kbd{denominator} for details. The optional argument $D$ allows to control 5485 over which ring we compute the denominator: 5486 5487 \item $1$: we only consider the underlying $\Q$-structure and the 5488 denominator is a (positive) rational integer 5489 5490 \item a simple variable, say \kbd{'x}: all entries as rational functions 5491 in $K(x)$ and the denominator is a polynomial in $x$. 5492 5493 \bprog 5494 ? f = x + 1/y + 1/2; 5495 ? numerator(f) \\ a t_POL in x 5496 %2 = x + ((y + 2)/(2*y)) 5497 ? numerator(f, 1) \\ Q-denominator is 2 5498 %3 = x + ((y + 2)/y) 5499 ? numerator(f, y) \\ as a rational function in y 5500 %5 = 2*y*x + (y + 2) 5501 @eprog 5502 5503 The library syntax is \fun{GEN}{numerator}{GEN f, GEN D = NULL}. 5504 Also available are 5505 \fun{GEN}{numer}{GEN x} which implements the not very useful default 5506 behaviour ($D$ is \kbd{NULL}) and 5507 \fun{GEN}{Q_remove_denom}{GEN x, GEN *ptd} ($D = 1$) and also returns the 5508 denominator (coding $1$ as \kbd{NULL}). 5509 5510 \subsec{oo}\kbdsidx{oo}\label{se:oo} 5511 Returns an object meaning $+\infty$, for use in functions such as 5512 \kbd{intnum}. It can be negated (\kbd{-oo} represents $-\infty$), and 5513 compared to real numbers (\typ{INT}, \typ{FRAC}, \typ{REAL}), with the 5514 expected meaning: $+\infty$ is greater than any real number and $-\infty$ is 5515 smaller. 5516 5517 The library syntax is \fun{GEN}{mkoo}{}. 5518 5519 \subsec{padicprec$(x,p)$}\kbdsidx{padicprec}\label{se:padicprec} 5520 Returns the absolute $p$-adic precision of the object $x$; this is the 5521 minimum precision of the components of $x$. The result is \tet{+oo} if $x$ 5522 is an exact object (as a $p$-adic): 5523 \bprog 5524 ? padicprec((1 + O(2^5)) * x + (2 + O(2^4)), 2) 5525 %1 = 4 5526 ? padicprec(x + 2, 2) 5527 %2 = +oo 5528 ? padicprec(2 + x + O(x^2), 2) 5529 %3 = +oo 5530 @eprog\noindent The function raises an exception if it encounters 5531 an object incompatible with $p$-adic computations: 5532 \bprog 5533 ? padicprec(O(3), 2) 5534 *** at top-level: padicprec(O(3),2) 5535 *** ^----------------- 5536 *** padicprec: inconsistent moduli in padicprec: 3 != 2 5537 5538 ? padicprec(1.0, 2) 5539 *** at top-level: padicprec(1.0,2) 5540 *** ^---------------- 5541 *** padicprec: incorrect type in padicprec (t_REAL). 5542 @eprog 5543 5544 The library syntax is \fun{GEN}{gppadicprec}{GEN x, GEN p}. 5545 Also available is the function \fun{long}{padicprec}{GEN x, GEN p}, 5546 which returns \tet{LONG_MAX} if $x = 0$ and the $p$-adic precision as a 5547 \kbd{long} integer. 5548 5549 \subsec{precision$(x,\{n\})$}\kbdsidx{precision}\label{se:precision} 5550 The function behaves differently according to whether $n$ is 5551 present or not. If $n$ is missing, the function returns 5552 the floating point precision in decimal digits of the PARI object $x$. If $x$ 5553 has no floating point component, the function returns \kbd{+oo}. 5554 \bprog 5555 ? precision(exp(1e-100)) 5556 %1 = 154 \\ 154 significant decimal digits 5557 ? precision(2 + x) 5558 %2 = +oo \\ exact object 5559 ? precision(0.5 + O(x)) 5560 %3 = 38 \\ floating point accuracy, NOT series precision 5561 ? precision( [ exp(1e-100), 0.5 ] ) 5562 %4 = 38 \\ minimal accuracy among components 5563 @eprog\noindent Using \kbd{getlocalprec()} allows to retrieve 5564 the working precision (as modified by possible \kbd{localprec} 5565 statements). 5566 5567 If $n$ is present, the function creates a new object equal to $x$ with a new 5568 floating point precision $n$: $n$ is the number of desired significant 5569 \emph{decimal} digits. If $n$ is smaller than the precision of a \typ{REAL} 5570 component of $x$, it is truncated, otherwise it is extended with zeros. 5571 For non-floating-point types, no change. 5572 5573 The library syntax is \fun{GEN}{precision00}{GEN x, GEN n = NULL}. 5574 Also available are \fun{GEN}{gprec}{GEN x, long n} and 5575 \fun{long}{precision}{GEN x}. In both, the accuracy is expressed in 5576 \emph{words} (32-bit or 64-bit depending on the architecture). 5577 5578 \subsec{random$(\{N=2^{31}\})$}\kbdsidx{random}\label{se:random} 5579 Returns a random element in various natural sets depending on the 5580 argument $N$. 5581 5582 \item \typ{INT}: returns an integer 5583 uniformly distributed between $0$ and $N-1$. Omitting the argument 5584 is equivalent to \kbd{random(2\pow31)}. 5585 5586 \item \typ{REAL}: returns a real number in $[0,1[$ with the same accuracy as 5587 $N$ (whose mantissa has the same number of significant words). 5588 5589 \item \typ{INTMOD}: returns a random intmod for the same modulus. 5590 5591 \item \typ{FFELT}: returns a random element in the same finite field. 5592 5593 \item \typ{VEC} of length $2$, $N = [a,b]$: returns an integer uniformly 5594 distributed between $a$ and $b$. 5595 5596 \item \typ{VEC} generated by \kbd{ellinit} over a finite field $k$ 5597 (coefficients are \typ{INTMOD}s modulo a prime or \typ{FFELT}s): returns a 5598 ``random'' $k$-rational \emph{affine} point on the curve. More precisely 5599 if the curve has a single point (at infinity!) we return it; otherwise 5600 we return an affine point by drawing an abscissa uniformly at 5601 random until \tet{ellordinate} succeeds. Note that this is definitely not a 5602 uniform distribution over $E(k)$, but it should be good enough for 5603 applications. 5604 5605 \item \typ{POL} return a random polynomial of degree at most the degree of $N$. 5606 The coefficients are drawn by applying \kbd{random} to the leading 5607 coefficient of $N$. 5608 5609 \bprog 5610 ? random(10) 5611 %1 = 9 5612 ? random(Mod(0,7)) 5613 %2 = Mod(1, 7) 5614 ? a = ffgen(ffinit(3,7), 'a); random(a) 5615 %3 = a^6 + 2*a^5 + a^4 + a^3 + a^2 + 2*a 5616 ? E = ellinit([3,7]*Mod(1,109)); random(E) 5617 %4 = [Mod(103, 109), Mod(10, 109)] 5618 ? E = ellinit([1,7]*a^0); random(E) 5619 %5 = [a^6 + a^5 + 2*a^4 + 2*a^2, 2*a^6 + 2*a^4 + 2*a^3 + a^2 + 2*a] 5620 ? random(Mod(1,7)*x^4) 5621 %6 = Mod(5, 7)*x^4 + Mod(6, 7)*x^3 + Mod(2, 7)*x^2 + Mod(2, 7)*x + Mod(5, 7) 5622 5623 @eprog 5624 These variants all depend on a single internal generator, and are 5625 independent from your operating system's random number generators. 5626 A random seed may be obtained via \tet{getrand}, and reset 5627 using \tet{setrand}: from a given seed, and given sequence of \kbd{random}s, 5628 the exact same values will be generated. The same seed is used at each 5629 startup, reseed the generator yourself if this is a problem. Note that 5630 internal functions also call the random number generator; adding such a 5631 function call in the middle of your code will change the numbers produced. 5632 5633 \misctitle{Technical note} 5634 Up to 5635 version 2.4 included, the internal generator produced pseudo-random numbers 5636 by means of linear congruences, which were not well distributed in arithmetic 5637 progressions. We now 5638 use Brent's XORGEN algorithm, based on Feedback Shift Registers, see 5639 \url{http://wwwmaths.anu.edu.au/~brent/random.html}. The generator has period 5640 $2^{4096}-1$, passes the Crush battery of statistical tests of L'Ecuyer and 5641 Simard, but is not suitable for cryptographic purposes: one can reconstruct 5642 the state vector from a small sample of consecutive values, thus predicting 5643 the entire sequence. 5644 5645 The library syntax is \fun{GEN}{genrand}{GEN N = NULL}. 5646 5647 Also available: \fun{GEN}{ellrandom}{GEN E} and \fun{GEN}{ffrandom}{GEN a}. 5648 5649 \subsec{real$(x)$}\kbdsidx{real}\label{se:real} 5650 Real part of $x$. When $x$ is a quadratic number, this is the 5651 coefficient of $1$ in the ``canonical'' integral basis $(1,\omega)$. 5652 \bprog 5653 ? real(3 + I) 5654 %1 = 3 5655 ? x = 3 + quadgen(-23); 5656 ? real(x) \\ as a quadratic number 5657 %3 = 3 5658 ? real(x * 1.) \\ as a complex number 5659 %4 = 3.5000000000000000000000000000000000000 5660 @eprog 5661 5662 The library syntax is \fun{GEN}{greal}{GEN x}. 5663 5664 \subsec{round$(x,\{\&e\})$}\kbdsidx{round}\label{se:round} 5665 If $x$ is in $\R$, rounds $x$ to the nearest integer (rounding to 5666 $+\infty$ in case of ties), then and sets $e$ to the number of error bits, 5667 that is the binary exponent of the difference between the original and the 5668 rounded value (the ``fractional part''). If the exponent of $x$ is too large 5669 compared to its precision (i.e.~$e>0$), the result is undefined and an error 5670 occurs if $e$ was not given. 5671 5672 \misctitle{Important remark} Contrary to the other truncation functions, 5673 this function operates on every coefficient at every level of a PARI object. 5674 For example 5675 $$\text{truncate}\left(\dfrac{2.4*X^2-1.7}{X}\right)=2.4*X,$$ 5676 whereas 5677 $$\text{round}\left(\dfrac{2.4*X^2-1.7}{X}\right)=\dfrac{2*X^2-2}{X}.$$ 5678 An important use of \kbd{round} is to get exact results after an approximate 5679 computation, when theory tells you that the coefficients must be integers. 5680 5681 The library syntax is \fun{GEN}{round0}{GEN x, GEN *e = NULL}. 5682 Also available are \fun{GEN}{grndtoi}{GEN x, long *e} and 5683 \fun{GEN}{ground}{GEN x}. 5684 5685 \subsec{serchop$(s,\{n=0\})$}\kbdsidx{serchop}\label{se:serchop} 5686 Remove all terms of degree strictly less than $n$ in series $s$. When 5687 the series contains no terms of degree $< n$, return $O(x^n)$. 5688 \bprog 5689 ? s = 1/x + x + 2*x^2 + O(x^3); 5690 ? serchop(s) 5691 %2 = x + 2*x^3 + O(x^3) 5692 ? serchop(s, 2) 5693 %3 = 2*x^2 + O(x^3) 5694 ? serchop(s, 100) 5695 %4 = O(x^100) 5696 @eprog 5697 5698 The library syntax is \fun{GEN}{serchop}{GEN s, long n}. 5699 5700 \subsec{serprec$(x,v)$}\kbdsidx{serprec}\label{se:serprec} 5701 Returns the absolute precision of $x$ with respect to power series 5702 in the variable $v$; this is the 5703 minimum precision of the components of $x$. The result is \tet{+oo} if $x$ 5704 is an exact object (as a series in $v$): 5705 \bprog 5706 ? serprec(x + O(y^2), y) 5707 %1 = 2 5708 ? serprec(x + 2, x) 5709 %2 = +oo 5710 ? serprec(2 + x + O(x^2), y) 5711 %3 = +oo 5712 @eprog 5713 5714 The library syntax is \fun{GEN}{gpserprec}{GEN x, long v} where \kbd{v} is a variable number. 5715 Also available is \fun{long}{serprec}{GEN x, GEN p}, which returns 5716 \tet{LONG_MAX} if $x = 0$, otherwise the series precision as a \kbd{long} integer. 5717 5718 \subsec{simplify$(x)$}\kbdsidx{simplify}\label{se:simplify} 5719 This function simplifies $x$ as much as it can. Specifically, a complex or 5720 quadratic number whose imaginary part is the integer 0 (i.e.~not \kbd{Mod(0,2)} 5721 or \kbd{0.E-28}) is converted to its real part, and a polynomial of degree $0$ 5722 is converted to its constant term. Simplifications occur recursively. 5723 5724 This function is especially useful before using arithmetic functions, 5725 which expect integer arguments: 5726 \bprog 5727 ? x = 2 + y - y 5728 %1 = 2 5729 ? isprime(x) 5730 *** at top-level: isprime(x) 5731 *** ^---------- 5732 *** isprime: not an integer argument in an arithmetic function 5733 ? type(x) 5734 %2 = "t_POL" 5735 ? type(simplify(x)) 5736 %3 = "t_INT" 5737 @eprog 5738 Note that GP results are simplified as above before they are stored in the 5739 history. (Unless you disable automatic simplification with \b{y}, that is.) 5740 In particular 5741 \bprog 5742 ? type(%1) 5743 %4 = "t_INT" 5744 @eprog 5745 5746 The library syntax is \fun{GEN}{simplify}{GEN x}. 5747 5748 \subsec{sizebyte$(x)$}\kbdsidx{sizebyte}\label{se:sizebyte} 5749 Outputs the total number of bytes occupied by the tree representing the 5750 PARI object $x$. 5751 5752 The library syntax is \fun{long}{gsizebyte}{GEN x}. 5753 Also available is \fun{long}{gsizeword}{GEN x} returning a 5754 number of \emph{words}. 5755 5756 \subsec{sizedigit$(x)$}\kbdsidx{sizedigit}\label{se:sizedigit} 5757 This function is DEPRECATED, essentially meaningless, and provided for 5758 backwards compatibility only. Don't use it! 5759 5760 outputs a quick upper bound for the number of decimal digits of (the 5761 components of) $x$, off by at most $1$. More precisely, for a positive 5762 integer $x$, it computes (approximately) the ceiling of 5763 $$\kbd{floor}(1 + \log_2 x) \log_{10}2,$$ 5764 5765 To count the number of decimal digits of a positive integer $x$, use 5766 \kbd{\#digits(x)}. To estimate (recursively) the size of $x$, use 5767 \kbd{normlp(x)}. 5768 5769 The library syntax is \fun{long}{sizedigit}{GEN x}. 5770 5771 \subsec{truncate$(x,\{\&e\})$}\kbdsidx{truncate}\label{se:truncate} 5772 Truncates $x$ and sets $e$ to the number of 5773 error bits. When $x$ is in $\R$, this means that the part after the decimal 5774 point is chopped away, $e$ is the binary exponent of the difference between 5775 the original and the truncated value (the ``fractional part''). If the 5776 exponent of $x$ is too large compared to its precision (i.e.~$e>0$), the 5777 result is undefined and an error occurs if $e$ was not given. The function 5778 applies componentwise on vector / matrices; $e$ is then the maximal number of 5779 error bits. If $x$ is a rational function, the result is the ``integer part'' 5780 (Euclidean quotient of numerator by denominator) and $e$ is not set. 5781 5782 Note a very special use of \kbd{truncate}: when applied to a power series, it 5783 transforms it into a polynomial or a rational function with denominator 5784 a power of $X$, by chopping away the $O(X^k)$. Similarly, when applied to 5785 a $p$-adic number, it transforms it into an integer or a rational number 5786 by chopping away the $O(p^k)$. 5787 5788 The library syntax is \fun{GEN}{trunc0}{GEN x, GEN *e = NULL}. 5789 The following functions are also available: \fun{GEN}{gtrunc}{GEN x} 5790 and \fun{GEN}{gcvtoi}{GEN x, long *e}. 5791 5792 \subsec{valuation$(x,p)$}\kbdsidx{valuation}\label{se:valuation} 5793 Computes the highest 5794 exponent of $p$ dividing $x$. If $p$ is of type integer, $x$ must be an 5795 integer, an intmod whose modulus is divisible by $p$, a fraction, a 5796 $q$-adic number with $q=p$, or a polynomial or power series in which case the 5797 valuation is the minimum of the valuation of the coefficients. 5798 5799 If $p$ is of type polynomial, $x$ must be of type polynomial or rational 5800 function, and also a power series if $x$ is a monomial. Finally, the 5801 valuation of a vector, complex or quadratic number is the minimum of the 5802 component valuations. 5803 5804 If $x=0$, the result is \kbd{+oo} if $x$ is an exact object. If $x$ is a 5805 $p$-adic numbers or power series, the result is the exponent of the zero. 5806 Any other type combinations gives an error. 5807 5808 The library syntax is \fun{GEN}{gpvaluation}{GEN x, GEN p}. 5809 Also available is 5810 \fun{long}{gvaluation}{GEN x, GEN p}, which returns \tet{LONG_MAX} if $x = 0$ 5811 and the valuation as a \kbd{long} integer. 5812 5813 \subsec{varhigher$(\var{name},\{v\})$}\kbdsidx{varhigher}\label{se:varhigher} 5814 Return a variable \emph{name} whose priority is higher 5815 than the priority of $v$ (of all existing variables if $v$ is omitted). 5816 This is a counterpart to \tet{varlower}. 5817 \bprog 5818 ? Pol([x,x], t) 5819 *** at top-level: Pol([x,x],t) 5820 *** ^------------ 5821 *** Pol: incorrect priority in gtopoly: variable x <= t 5822 ? t = varhigher("t", x); 5823 ? Pol([x,x], t) 5824 %3 = x*t + x 5825 @eprog\noindent This routine is useful since new GP variables directly 5826 created by the interpreter always have lower priority than existing 5827 GP variables. When some basic objects already exist in a variable 5828 that is incompatible with some function requirement, you can now 5829 create a new variable with a suitable priority instead of changing variables 5830 in existing objects: 5831 \bprog 5832 ? K = nfinit(x^2+1); 5833 ? rnfequation(K,y^2-2) 5834 *** at top-level: rnfequation(K,y^2-2) 5835 *** ^-------------------- 5836 *** rnfequation: incorrect priority in rnfequation: variable y >= x 5837 ? y = varhigher("y", x); 5838 ? rnfequation(K, y^2-2) 5839 %3 = y^4 - 2*y^2 + 9 5840 @eprog\noindent 5841 \misctitle{Caution 1} 5842 The \emph{name} is an arbitrary character string, only used for display 5843 purposes and need not be related to the GP variable holding the result, nor 5844 to be a valid variable name. In particular the \emph{name} can 5845 not be used to retrieve the variable, it is not even present in the parser's 5846 hash tables. 5847 \bprog 5848 ? x = varhigher("#"); 5849 ? x^2 5850 %2 = #^2 5851 @eprog 5852 \misctitle{Caution 2} There are a limited number of variables and if no 5853 existing variable with the given display name has the requested 5854 priority, the call to \kbd{varhigher} uses up one such slot. Do not create 5855 new variables in this way unless it's absolutely necessary, 5856 reuse existing names instead and choose sensible priority requirements: 5857 if you only need a variable with higher priority than $x$, state so 5858 rather than creating a new variable with highest priority. 5859 \bprog 5860 \\ quickly use up all variables 5861 ? n = 0; while(1,varhigher("tmp"); n++) 5862 *** at top-level: n=0;while(1,varhigher("tmp");n++) 5863 *** ^------------------- 5864 *** varhigher: no more variables available. 5865 *** Break loop: type 'break' to go back to GP prompt 5866 break> n 5867 65510 5868 \\ infinite loop: here we reuse the same 'tmp' 5869 ? n = 0; while(1,varhigher("tmp", x); n++) 5870 @eprog 5871 5872 The library syntax is \fun{GEN}{varhigher}{const char *name, long v = -1} where \kbd{v} is a variable number. 5873 5874 \subsec{variable$(\{x\})$}\kbdsidx{variable}\label{se:variable} 5875 Gives the main variable of the object $x$ (the variable with the highest 5876 priority used in $x$), and $p$ if $x$ is a $p$-adic number. Return $0$ if 5877 $x$ has no variable attached to it. 5878 \bprog 5879 ? variable(x^2 + y) 5880 %1 = x 5881 ? variable(1 + O(5^2)) 5882 %2 = 5 5883 ? variable([x,y,z,t]) 5884 %3 = x 5885 ? variable(1) 5886 %4 = 0 5887 @eprog\noindent The construction 5888 \bprog 5889 if (!variable(x),...) 5890 @eprog\noindent can be used to test whether a variable is attached to $x$. 5891 5892 If $x$ is omitted, returns the list of user variables known to the 5893 interpreter, by order of decreasing priority. (Highest priority is initially 5894 $x$, which come first until \tet{varhigher} is used.) If \kbd{varhigher} 5895 or \kbd{varlower} are used, it is quite possible to end up with different 5896 variables (with different priorities) printed in the same way: they 5897 will then appear multiple times in the output: 5898 \bprog 5899 ? varhigher("y"); 5900 ? varlower("y"); 5901 ? variable() 5902 %4 = [y, x, y] 5903 @eprog\noindent Using \kbd{v = variable()} then \kbd{v[1]}, \kbd{v[2]}, 5904 etc.~allows to recover and use existing variables. 5905 5906 The library syntax is \fun{GEN}{gpolvar}{GEN x = NULL}. 5907 However, in library mode, this function should not be used for $x$ 5908 non-\kbd{NULL}, since \tet{gvar} is more appropriate. Instead, for 5909 $x$ a $p$-adic (type \typ{PADIC}), $p$ is $gel(x,2)$; otherwise, use 5910 \fun{long}{gvar}{GEN x} which returns the variable number of $x$ if 5911 it exists, \kbd{NO\_VARIABLE} otherwise, which satisfies the property 5912 $\kbd{varncmp}(\kbd{NO\_VARIABLE}, v) > 0$ for all valid variable number 5913 $v$, i.e. it has lower priority than any variable. 5914 5915 \subsec{variables$(\{x\})$}\kbdsidx{variables}\label{se:variables} 5916 Returns the list of all variables occurring in object $x$ (all user 5917 variables known to the interpreter if $x$ is omitted), sorted by 5918 decreasing priority. 5919 \bprog 5920 ? variables([x^2 + y*z + O(t), a+x]) 5921 %1 = [x, y, z, t, a] 5922 @eprog\noindent The construction 5923 \bprog 5924 if (!variables(x),...) 5925 @eprog\noindent can be used to test whether a variable is attached to $x$. 5926 5927 If \kbd{varhigher} or \kbd{varlower} are used, it is quite possible to end up 5928 with different variables (with different priorities) printed in the same 5929 way: they will then appear multiple times in the output: 5930 \bprog 5931 ? y1 = varhigher("y"); 5932 ? y2 = varlower("y"); 5933 ? variables(y*y1*y2) 5934 %4 = [y, y, y] 5935 @eprog 5936 5937 The library syntax is \fun{GEN}{variables_vec}{GEN x = NULL}. 5938 5939 Also available is \fun{GEN}{variables_vecsmall}{GEN x} which returns 5940 the (sorted) variable numbers instead of the attached monomials of degree 1. 5941 5942 \subsec{varlower$(\var{name},\{v\})$}\kbdsidx{varlower}\label{se:varlower} 5943 Return a variable \emph{name} whose priority is lower 5944 than the priority of $v$ (of all existing variables if $v$ is omitted). 5945 This is a counterpart to \tet{varhigher}. 5946 5947 New GP variables directly created by the interpreter always 5948 have lower priority than existing GP variables, but it is not easy 5949 to check whether an identifier is currently unused, so that the 5950 corresponding variable has the expected priority when it's created! 5951 Thus, depending on the session history, the same command may fail or succeed: 5952 \bprog 5953 ? t; z; \\ now t > z 5954 ? rnfequation(t^2+1,z^2-t) 5955 *** at top-level: rnfequation(t^2+1,z^ 5956 *** ^-------------------- 5957 *** rnfequation: incorrect priority in rnfequation: variable t >= t 5958 @eprog\noindent Restart and retry: 5959 \bprog 5960 ? z; t; \\ now z > t 5961 ? rnfequation(t^2+1,z^2-t) 5962 %2 = z^4 + 1 5963 @eprog\noindent It is quite annoying for package authors, when trying to 5964 define a base ring, to notice that the package may fail for some users 5965 depending on their session history. The safe way to do this is as follows: 5966 \bprog 5967 ? z; t; \\ In new session: now z > t 5968 ... 5969 ? t = varlower("t", 'z); 5970 ? rnfequation(t^2+1,z^2-2) 5971 %2 = z^4 - 2*z^2 + 9 5972 ? variable() 5973 %3 = [x, y, z, t] 5974 @eprog 5975 \bprog 5976 ? t; z; \\ In new session: now t > z 5977 ... 5978 ? t = varlower("t", 'z); \\ create a new variable, still printed "t" 5979 ? rnfequation(t^2+1,z^2-2) 5980 %2 = z^4 - 2*z^2 + 9 5981 ? variable() 5982 %3 = [x, y, t, z, t] 5983 @eprog\noindent Now both constructions succeed. Note that in the 5984 first case, \kbd{varlower} is essentially a no-op, the existing variable $t$ 5985 has correct priority. While in the second case, two different variables are 5986 displayed as \kbd{t}, one with higher priority than $z$ (created in the first 5987 line) and another one with lower priority (created by \kbd{varlower}). 5988 5989 \misctitle{Caution 1} 5990 The \emph{name} is an arbitrary character string, only used for display 5991 purposes and need not be related to the GP variable holding the result, nor 5992 to be a valid variable name. In particular the \emph{name} can 5993 not be used to retrieve the variable, it is not even present in the parser's 5994 hash tables. 5995 \bprog 5996 ? x = varlower("#"); 5997 ? x^2 5998 %2 = #^2 5999 @eprog 6000 \misctitle{Caution 2} There are a limited number of variables and if no 6001 existing variable with the given display name has the requested 6002 priority, the call to \kbd{varlower} uses up one such slot. Do not create 6003 new variables in this way unless it's absolutely necessary, 6004 reuse existing names instead and choose sensible priority requirements: 6005 if you only need a variable with higher priority than $x$, state so 6006 rather than creating a new variable with highest priority. 6007 \bprog 6008 \\ quickly use up all variables 6009 ? n = 0; while(1,varlower("x"); n++) 6010 *** at top-level: n=0;while(1,varlower("x");n++) 6011 *** ^------------------- 6012 *** varlower: no more variables available. 6013 *** Break loop: type 'break' to go back to GP prompt 6014 break> n 6015 65510 6016 \\ infinite loop: here we reuse the same 'tmp' 6017 ? n = 0; while(1,varlower("tmp", x); n++) 6018 @eprog 6019 6020 The library syntax is \fun{GEN}{varlower}{const char *name, long v = -1} where \kbd{v} is a variable number. 6021 6022 \section{Combinatorics}\label{se:combinat} 6023 6024 Permutations are represented in gp as \typ{VECSMALL}s and can be input 6025 directly as \kbd{Vecsmall([1,3,2,4])} or obtained from the iterator 6026 \kbd{forperm}: 6027 \bprog 6028 ? forperm(3, p, print(p)) \\ iterate through S_3 6029 Vecsmall([1, 2, 3]) 6030 Vecsmall([1, 3, 2]) 6031 Vecsmall([2, 1, 3]) 6032 Vecsmall([2, 3, 1]) 6033 Vecsmall([3, 1, 2]) 6034 Vecsmall([3, 2, 1]) 6035 @eprog 6036 6037 Permutations can be multiplied via \kbd{*}, raised to some power using 6038 \kbd{\pow}, inverted using \kbd{\pow(-1)}, conjugated as 6039 \kbd{p * q * p\pow(-1)}. Their order and signature is available via 6040 \kbd{permorder} and \kbd{permsign}. 6041 6042 \subsec{bernfrac$(n)$}\kbdsidx{bernfrac}\label{se:bernfrac} 6043 Bernoulli number\sidx{Bernoulli numbers} $B_n$, 6044 where $B_0=1$, $B_1=-1/2$, $B_2=1/6$,\dots, expressed as a rational number. 6045 The argument $n$ should be a nonnegative integer. The function \tet{bervec} 6046 creates a cache of successive Bernoulli numbers which greatly speeds up 6047 later calls to \kbd{bernfrac}: 6048 \bprog 6049 ? bernfrac(20000); 6050 time = 107 ms. 6051 ? bernvec(10000); \\ cache B_0, B_2, ..., B_20000 6052 time = 35,957 ms. 6053 ? bernfrac(20000); \\ now instantaneous 6054 ? 6055 @eprog 6056 6057 The library syntax is \fun{GEN}{bernfrac}{long n}. 6058 6059 \subsec{bernpol$(n, \{v = 'x\})$}\kbdsidx{bernpol}\label{se:bernpol} 6060 \idx{Bernoulli polynomial} $B_n$ in variable $v$. 6061 \bprog 6062 ? bernpol(1) 6063 %1 = x - 1/2 6064 ? bernpol(3) 6065 %2 = x^3 - 3/2*x^2 + 1/2*x 6066 @eprog 6067 6068 The library syntax is \fun{GEN}{bernpol}{long n, long v = -1} where \kbd{v} is a variable number. 6069 6070 \subsec{bernreal$(n)$}\kbdsidx{bernreal}\label{se:bernreal} 6071 Bernoulli number\sidx{Bernoulli numbers} 6072 $B_n$, as \kbd{bernfrac}, but $B_n$ is returned as a real number 6073 (with the current precision). The argument $n$ should be a nonnegative 6074 integer. The function slows down as the precision increases: 6075 \bprog 6076 ? \p1000 6077 ? bernreal(200000); 6078 time = 5 ms. 6079 ? \p10000 6080 ? bernreal(200000); 6081 time = 18 ms. 6082 ? \p100000 6083 ? bernreal(200000); 6084 time = 84 ms. 6085 @eprog 6086 6087 The library syntax is \fun{GEN}{bernreal}{long n, long prec}. 6088 6089 \subsec{bernvec$(n)$}\kbdsidx{bernvec}\label{se:bernvec} 6090 Returns a vector containing, as rational numbers, 6091 the \idx{Bernoulli numbers} $B_0$, $B_2$,\dots, $B_{2n}$: 6092 \bprog 6093 ? bernvec(5) \\ B_0, B_2..., B_10 6094 %1 = [1, 1/6, -1/30, 1/42, -1/30, 5/66] 6095 ? bernfrac(10) 6096 %2 = 5/66 6097 @eprog\noindent This routine uses a lot of memory but is much faster than 6098 repeated calls to \kbd{bernfrac}: 6099 \bprog 6100 ? forstep(n = 2, 10000, 2, bernfrac(n)) 6101 time = 41,522 ms. 6102 ? bernvec(5000); 6103 time = 4,784 ms. 6104 @eprog\noindent The computed Bernoulli numbers are stored in an incremental 6105 cache which makes later calls to \kbd{bernfrac} and \kbd{bernreal} 6106 instantaneous in the cache range: re-running the same previous \kbd{bernfrac}s 6107 after the \kbd{bernvec} call gives: 6108 \bprog 6109 ? forstep(n = 2, 10000, 2, bernfrac(n)) 6110 time = 1 ms. 6111 @eprog\noindent The time and space complexity of this function are 6112 $\tilde{O}(n^2)$; in the feasible range $n \leq 10^5$ (requires about 2 hours), 6113 the practical time complexity is closer to $\tilde{O}(n^{\log_2 6})$. 6114 6115 The library syntax is \fun{GEN}{bernvec}{long n}. 6116 6117 \subsec{binomial$(x,\{k\})$}\kbdsidx{binomial}\label{se:binomial} 6118 \idx{binomial coefficient} $\binom{x}{k}$. 6119 Here $k$ must be an integer, but $x$ can be any PARI object. 6120 \bprog 6121 ? binomial(4,2) 6122 %1 = 6 6123 ? n = 4; vector(n+1, k, binomial(n,k-1)) 6124 %2 = [1, 4, 6, 4, 1] 6125 @eprog\noindent The argument $k$ may be omitted if $x = n$ is a 6126 nonnegative integer; in this case, return the vector with $n+1$ 6127 components whose $k+1$-th entry is \kbd{binomial}$(n,k)$ 6128 \bprog 6129 ? binomial(4) 6130 %3 = [1, 4, 6, 4, 1] 6131 @eprog 6132 6133 The library syntax is \fun{GEN}{binomial0}{GEN x, GEN k = NULL}. 6134 6135 \subsec{eulerfrac$(n)$}\kbdsidx{eulerfrac}\label{se:eulerfrac} 6136 Euler number\sidx{Euler numbers} $E_n$, 6137 where $E_0=1$, $E_1=0$, $E_2=-1$, \dots, are integers such that 6138 $$ \dfrac{1}{\cosh t} = \sum_{n\geq 0} \dfrac{E_n}{n!} t^n. $$ 6139 The argument $n$ should be a nonnegative integer. 6140 \bprog 6141 ? vector(10,i,eulerfrac(i)) 6142 %1 = [0, -1, 0, 5, 0, -61, 0, 1385, 0, -50521] 6143 ? eulerfrac(20000); 6144 ? sizedigit(%)) 6145 %3 = 73416 6146 @eprog 6147 6148 The library syntax is \fun{GEN}{eulerfrac}{long n}. 6149 6150 \subsec{eulerianpol$(n, \{v = 'x\})$}\kbdsidx{eulerianpol}\label{se:eulerianpol} 6151 \idx{Eulerian polynomial} $A_n$ in variable $v$. 6152 \bprog 6153 ? eulerianpol(2) 6154 %1 = x + 1 6155 ? eulerianpol(5, 't) 6156 %2 = t^4 + 26*t^3 + 66*t^2 + 26*t + 1 6157 6158 @eprog 6159 6160 The library syntax is \fun{GEN}{eulerianpol}{long n, long v = -1} where \kbd{v} is a variable number. 6161 6162 \subsec{eulerpol$(n, \{v = 'x\})$}\kbdsidx{eulerpol}\label{se:eulerpol} 6163 \idx{Euler polynomial} $E_n$ in variable $v$. 6164 \bprog 6165 ? eulerpol(1) 6166 %1 = x - 1/2 6167 ? eulerpol(3) 6168 %2 = x^3 - 3/2*x^2 + 1/4 6169 @eprog 6170 6171 The library syntax is \fun{GEN}{eulerpol}{long n, long v = -1} where \kbd{v} is a variable number. 6172 6173 \subsec{eulervec$(n)$}\kbdsidx{eulervec}\label{se:eulervec} 6174 Returns a vector containing, as rational numbers, 6175 the nonzero \idx{Euler numbers} $E_0$, $E_2$,\dots, $E_{2n}$: 6176 \bprog 6177 ? eulervec(5) \\ E_0, E_2..., E_10 6178 %1 = [1, -1, 5, -61, 1385, -50521] 6179 ? eulerfrac(10) 6180 %2 = -50521 6181 @eprog\noindent This routine uses more memory but is a little faster than 6182 repeated calls to \kbd{eulerfrac}: 6183 \bprog 6184 ? forstep(n = 2, 8000, 2, eulerfrac(n)) 6185 time = 46,851 ms. 6186 ? eulervec(4000); 6187 time = 30,588 ms. 6188 @eprog 6189 6190 The library syntax is \fun{GEN}{eulervec}{long n}. 6191 6192 \subsec{fibonacci$(x)$}\kbdsidx{fibonacci}\label{se:fibonacci} 6193 $x^{\text{th}}$ Fibonacci number. 6194 6195 The library syntax is \fun{GEN}{fibo}{long x}. 6196 6197 \subsec{hammingweight$(x)$}\kbdsidx{hammingweight}\label{se:hammingweight} 6198 If $x$ is a \typ{INT}, return the binary Hamming weight of $|x|$. Otherwise 6199 $x$ must be of type \typ{POL}, \typ{VEC}, \typ{COL}, \typ{VECSMALL}, or 6200 \typ{MAT} and the function returns the number of nonzero coefficients of 6201 $x$. 6202 \bprog 6203 ? hammingweight(15) 6204 %1 = 4 6205 ? hammingweight(x^100 + 2*x + 1) 6206 %2 = 3 6207 ? hammingweight([Mod(1,2), 2, Mod(0,3)]) 6208 %3 = 2 6209 ? hammingweight(matid(100)) 6210 %4 = 100 6211 @eprog 6212 6213 The library syntax is \fun{long}{hammingweight}{GEN x}. 6214 6215 \subsec{numbpart$(n)$}\kbdsidx{numbpart}\label{se:numbpart} 6216 Gives the number of unrestricted partitions of 6217 $n$, usually called $p(n)$ in the literature; in other words the number of 6218 nonnegative integer solutions to $a+2b+3c+\cdots=n$. $n$ must be of type 6219 integer and $n<10^{15}$ (with trivial values $p(n) = 0$ for $n < 0$ and 6220 $p(0) = 1$). The algorithm uses the Hardy-Ramanujan-Rademacher formula. 6221 To explicitly enumerate them, see \tet{partitions}. 6222 6223 The library syntax is \fun{GEN}{numbpart}{GEN n}. 6224 6225 \subsec{numtoperm$(n,k)$}\kbdsidx{numtoperm}\label{se:numtoperm} 6226 Generates the $k$-th permutation (as a row vector of length $n$) of the 6227 numbers $1$ to $n$. The number $k$ is taken modulo $n!\,$, i.e.~inverse 6228 function of \tet{permtonum}. The numbering used is the standard lexicographic 6229 ordering, starting at $0$. 6230 6231 The library syntax is \fun{GEN}{numtoperm}{long n, GEN k}. 6232 6233 \subsec{partitions$(k,\{a=k\},\{n=k\})$}\kbdsidx{partitions}\label{se:partitions} 6234 Returns the vector of partitions of the integer $k$ as a sum of positive 6235 integers (parts); for $k < 0$, it returns the empty set \kbd{[]}, and for $k 6236 = 0$ the trivial partition (no parts). A partition is given by a 6237 \typ{VECSMALL}, where parts are sorted in nondecreasing order: 6238 \bprog 6239 ? partitions(3) 6240 %1 = [Vecsmall([3]), Vecsmall([1, 2]), Vecsmall([1, 1, 1])] 6241 @eprog\noindent correspond to $3$, $1+2$ and $1+1+1$. The number 6242 of (unrestricted) partitions of $k$ is given 6243 by \tet{numbpart}: 6244 \bprog 6245 ? #partitions(