libPARI.dumb(3)
๐ libPARI.dumb(3) โ Functions and Operations Available in PARI and GP ๐
okay so this is libPARI.dumb(3) from the User Contributed Perl Documentation, and it is literally the glow-up guide to all the functions and operators hanging out in PARI and the GP/PARI calculator. They are numerous and ever-expanding, bestie. This page describes the ones available in version 2.3.5. It should be noted that many of these functions accept quite different types as arguments, but others are more restricted. The list of acceptable types will be given for each function or class of functions. Except when stated otherwise, it is understood that a function or operation which should make natural sense is legal. In this chapter, we will describe the functions according to a rough classification. The general entry looks something like:
foo(x, {flag = 0}): short description.
The library syntax is foo(x,flag).
This means that the GP function foo has one mandatory argument x, and an optional one, flag, whose default value is 0. (The {} should not be typed, it is just a convenient notation we will use throughout to denote optional arguments.) That is, you can type foo(x,2), or foo(x), which is then understood to mean foo(x,0). As well, a comma or closing parenthesis, where an optional argument should have been, signals to GP it should use the default. Thus, the syntax foo(x,) is also accepted as a synonym for our last expression. When a function has more than one optional argument, the argument list is filled with user supplied values, in order. When none are left, the defaults are used instead. Thus, assuming that foo's prototype had been
foo({x = 1},{y = 2},{z = 3}),
typing in foo(6,4) would give you foo(6,4,3). In the rare case when you want to set some far away argument, and leave the defaults in between as they stand, you can use the ``empty arg'' trick alluded to above: foo(6,,1) would yield foo(6,2,1). By the way, foo() by itself yields foo(1,2,3) as was to be expected.
In this rather special case of a function having no mandatory argument, you can even omit the (): a standalone foo would be enough (though we do not recommend it for your scripts, for the sake of clarity). In defining GP syntax, we strove to put optional arguments at the end of the argument list (of course, since they would not make sense otherwise), and in order of decreasing usefulness so that, most of the time, you will be able to ignore them.
Finally, an optional argument (between braces) followed by a star, like {x}*, means that any number of such arguments (possibly none) can be given. This is in particular used by the various print routines.
๐ฉ Flags, bestie. A flag is an argument which, rather than conveying actual information to the routine, instructs it to change its default behaviour, e.g. return more or less information. All such flags are optional, and will be called flag in the function descriptions to follow. There are two different kinds of flags:
- generic: all valid values for the flag are individually described (``If flag is equal to
1, then...''). - binary: use customary binary notation as a compact way to represent many toggles with just one integer. Let
(p_0,...,p_n)be a list of switches (i.e. of properties which take either the value0or1), the number2^3 + 2^5 = 40means thatp_3andp_5are set (that is, set to1), and none of the others are (that is, they are set to0). This is announced as ``The binary digits of flag mean 1:p_0, 2:p_1, 4:p_2'', and so on, using the available consecutive powers of2.
๐ Mnemonics for flags, iykyk. Numeric flags as mentioned above are obscure, error-prone, and quite rigid: should the authors want to adopt a new flag numbering scheme (for instance when noticing flags with the same meaning but different numeric values across a set of routines), it would break backward compatibility. The only advantage of explicit numeric values is that they are fast to type, so their use is only advised when using the calculator gp.
As an alternative, one can replace a numeric flag by a character string containing symbolic identifiers. For a generic flag, the mnemonic corresponding to the numeric identifier is given after it as in
fun(x, {flag = 0}):
If flag is equal to 1 = AGM, use an agm formula...
which means that one can use indifferently fun(x, 1) or fun(x, AGM).
For a binary flag, mnemonics corresponding to the various toggles are given after each of them. They can be negated by prepending no_ to the mnemonic, or by removing such a prefix. These toggles are grouped together using any punctuation character (such as , or ;). For instance (taken from description of ploth(X = a,b,"expr",{"flag" = 0},{n = 0}))
Binary digits of flags mean: 1 = Parametric,
2 = Recursive,...
so that, instead of 1, one could use the mnemonic Parametric; no_Recursive, or simply Parametric since Recursive is unset by default (default value of flag is 0, i.e. everything unset).
๐ซถ Pointers. If a parameter in the function prototype is prefixed with a & sign, as in
foo(x,&e)
it means that, besides the normal return value, the function may assign a value to e as a side effect. When passing the argument, the & sign has to be typed in explicitly. As of version 2.3.5, this pointer argument is optional for all documented functions, hence the & will always appear between brackets as in Z_issquare(x,{&e}).
๐
About library programming. The library function foo, as defined at the beginning of this section, is seen to have two mandatory arguments, x and flag: no PARI mathematical function has been implemented so as to accept a variable number of arguments, so all arguments are mandatory when programming with the library (often, variants are provided corresponding to the various flag values). When not mentioned otherwise, the result and arguments of a function are assumed implicitly to be of type GEN. Most other functions return an object of type long integer in C (see Chapter 4). The variable or parameter names prec and flag always denote long integers.
The entree type is used by the library to implement iterators (loops, sums, integrals, etc.) when a formal variable has to successively assume a number of values in a given set. When programming with the library, it is easier and much more efficient to code loops and the like directly. Hence this type is not documented, although it does appear in a few library function prototypes below. See Label se:sums for more details.
๐ Standard monadic or dyadic operators ๐
โจ + / - โจ
The expressions +x and -x refer to monadic operators (the first does nothing, the second negates x).
The library syntax is gneg(x) for -x.
๐ธ +, - ๐ธ
The expression x + y is the sum and x - y is the difference of x and y. Among the prominent impossibilities are addition/subtraction between a scalar type and a vector or a matrix, between vector/matrices of incompatible sizes and between an intmod and a real number.
The library syntax is gadd(x,y) for x + y, gsub(x,y) for x - y.
๐ฆ * ๐ฆ
The expression x * y is the product of x and y. Among the prominent impossibilities are multiplication between vector/matrices of incompatible sizes, between an intmod and a real number. Note that because of vector and matrix operations, * is not necessarily commutative. Note also that since multiplication between two column or two row vectors is not allowed, to obtain the scalar product of two vectors of the same length, you must multiply a line vector by a column vector, if necessary by transposing one of the vectors (using the operator ~ or the function mattranspose, see Label se:linear_algebra).
If x and y are binary quadratic forms, compose them. See also qfbnucomp and qfbnupow.
The library syntax is gmul(x,y) for x * y. Also available is gsqr(x) for x * x (faster of course!).
๐ / ๐
The expression x / y is the quotient of x and y. In addition to the impossibilities for multiplication, note that if the divisor is a matrix, it must be an invertible square matrix, and in that case the result is x*y^{-1}. Furthermore note that the result is as exact as possible: in particular, division of two integers always gives a rational number (which may be an integer if the quotient is exact) and not the Euclidean quotient (see x \ y for that), and similarly the quotient of two polynomials is a rational function in general. To obtain the approximate real value of the quotient of two integers, add 0. to the result; to obtain the approximate p-adic value of the quotient of two integers, add O(p^k) to the result; finally, to obtain the Taylor series expansion of the quotient of two polynomials, add O(X^k) to the result or use the taylor function (see Label se:taylor).
The library syntax is gdiv(x,y) for x / y.
๐ \ ๐
The expression x \ y is the Euclidean quotient of x and y. If y is a real scalar, this is defined as floor(x/y) if y > 0, and ceil(x/y) if y < 0 and the division is not exact. Hence the remainder x - (x\y)*y is in [0, |y|[.
Note that when y is an integer and x a polynomial, y is first promoted to a polynomial of degree 0. When x is a vector or matrix, the operator is applied componentwise.
The library syntax is gdivent(x,y) for x \ y.
๐ \/ ๐
The expression x \/ y evaluates to the rounded Euclidean quotient of x and y. This is the same as x \ y except for scalar division: the quotient is such that the corresponding remainder is smallest in absolute value and in case of a tie the quotient closest to + oo is chosen (hence the remainder would belong to ]-|y|/2, |y|/2]).
When x is a vector or matrix, the operator is applied componentwise.
The library syntax is gdivround(x,y) for x \/ y.
๐ % ๐
The expression x % y evaluates to the modular Euclidean remainder of x and y, which we now define. If y is an integer, this is the smallest non-negative integer congruent to x modulo y. If y is a polynomial, this is the polynomial of smallest degree congruent to x modulo y. When y is a non-integral real number, x%y is defined as x - (x\y)*y. This coincides with the definition for y integer if and only if x is an integer, but still belongs to [0, |y|[. For instance:
? (1/2) % 3
%1 = 2
? 0.5 % 3
*** forbidden division t_REAL % t_INT.
? (1/2) % 3.0
%2 = 1/2
Note that when y is an integer and x a polynomial, y is first promoted to a polynomial of degree 0. When x is a vector or matrix, the operator is applied componentwise.
The library syntax is gmod(x,y) for x % y.
๐ divrem(x,y,{v}) โ quotient AND remainder, no double-divide era
Bestie, divrem(x,y,{v}) creates a column vector with two components: the first is the Euclidean quotient x \y, the second is the Euclidean remainder x - (x\y)*y, of the division of x by y. This avoids the need to do two divisions if you need both the quotient and the remainder. If v is present, and x, y are multivariate polynomials, divide with respect to the variable v.
โ ๏ธ Beware thatdivrem(x,y)[2]is in general not the same asx % y; there is no operator to obtain it in GP:
? divrem(1/2, 3)[2]
%1 = 1/2
? (1/2) % 3
%2 = 2
? divrem(Mod(2,9), 3)[2]
*** forbidden division t_INTMOD \ t_INT.
? Mod(2,9) % 6
%3 = Mod(2,3)
The library syntax is divrem(x,y,v), where v is a long. Also available as gdiventres(x,y) when v is not needed.
โก ^ โ powering, but make it exact
The expression x^n is powering. If the exponent is an integer, then exact operations are performed using binary (left-shift) powering techniques. In particular, in this case x cannot be a vector or matrix unless it is a square matrix (invertible if the exponent is negative). If x is a p-adic number, its precision will increase if v_p(n) > 0. Powering a binary quadratic form (types t_QFI and t_QFR) returns a reduced representative of the class, provided the input is reduced. In particular, x^1 is identical to x.
PARI is able to rewrite the multiplication x * x of two identical objects as x^2, or sqr(x). Here, identical means the operands are two different labels referencing the same chunk of memory; no equality test is performed. This is no longer true when more than two arguments are involved.
If the exponent is not of type integer, this is treated as a transcendental function (see Label se:trans), and in particular has the effect of componentwise powering on vector or matrices.
As an exception, if the exponent is a rational number p/q and x an integer modulo a prime or a p-adic number, return a solution y of y^q = x^p if it exists. Currently, q must not have large prime factors. Beware that
? Mod(7,19)^(1/2)
%1 = Mod(11, 19) /* is any square root */
? sqrt(Mod(7,19))
%2 = Mod(8, 19) /* is the smallest square root */
? Mod(7,19)^(3/5)
%3 = Mod(1, 19)
? %3^(5/3)
%4 = Mod(1, 19) /* Mod(7,19) is just another cubic root */
If the exponent is a negative integer, an inverse must be computed. For non-invertible t_INTMOD, this will fail and implicitly exhibit a non trivial factor of the modulus:
? Mod(4,6)^(-1)
*** impossible inverse modulo: Mod(2, 6).
(Here, a factor 2 is obtained directly. In general, take the gcd of the representative and the modulus.) This is most useful when performing complicated operations modulo an integer N whose factorization is unknown. Either the computation succeeds and all is well, or a factor d is discovered and the computation may be restarted modulo d or N/d.
For non-invertible t_POLMOD, this will fail without exhibiting a factor.
? Mod(x^2, x^3-x)^(-1)
*** non-invertible polynomial in RgXQ_inv.
? a = Mod(3,4)*y^3 + Mod(1,4); b = y^6+y^5+y^4+y^3+y^2+y+1;
? Mod(a, b)^(-1);
*** non-invertible polynomial in RgXQ_inv.
In fact the latter polynomial is invertible, but the algorithm used (subresultant) assumes the base ring is a domain. If it is not the case, as here for Z/4Z, a result will be correct but chances are an error will occur first. In this specific case, one should work with 2-adics. In general, one can try the following approach:
? inversemod(a, b) =
{ local(m);
m = polsylvestermatrix(polrecip(a), polrecip(b));
m = matinverseimage(m, matid(#m)[,1]);
Polrev( vecextract(m, Str("..", poldegree(b))), variable(b) )
}
? inversemod(a,b)
%2 = Mod(2,4)*y^5 + Mod(3,4)*y^3 + Mod(1,4)*y^2 + Mod(3,4)*y + Mod(2,4)
This is not guaranteed to work either since it must invert pivots. See Label se:linear_algebra.
The library syntax is gpow(x,n,prec) for x^n.
๐ bittest(x,n) โ little bit peek
bittest(x,n) outputs the n-th bit of x starting from the right (i.e. the coefficient of 2^n in the binary expansion of x). The result is 0 or 1. To extract several bits at once as a vector, pass a vector for n.
See Label se:bitand for the behaviour at negative arguments.
The library syntax is bittest(x,n), where n and the result are longs.
โ๏ธ shift(x,n) โ slide those bits
shift(x,n) or x << n (= x >> (-n)) shifts x componentwise left by n bits if n >= 0 and right by |n| bits if n < 0. A left shift by n corresponds to multiplication by 2^n. A right shift of an integer x by |n| corresponds to a Euclidean division of x by 2^{|n|} with a remainder of the same sign as x, hence is not the same (in general) as x \ 2^n.
The library syntax is gshift(x,n) where n is a long.
โ๏ธ shiftmul(x,n) โ multiply by 2^n, with a plot twist
shiftmul(x,n) multiplies x by 2^n. The difference with shift is that when n < 0, ordinary division takes place, hence for example if x is an integer the result may be a fraction, while for shifts Euclidean division takes place when n < 0 hence if x is an integer the result is still an integer.
The library syntax is gmul2n(x,n) where n is a long.
๐๏ธ Comparison and boolean operators
The six standard comparison operators <=, <, >=, >, ==, != are available in GP, and in library mode under the names gle, glt, gge, ggt, geq, gne respectively. The library syntax is co(x,y), where co is the comparison operator. The result is 1 (as a GEN) if the comparison is true, 0 (as a GEN) if it is false. For the purpose of comparison, t_STR objects are strictly larger than any other non-string type; two t_STR objects are compared using the standard lexicographic order.
The standard boolean functions || (inclusive or), && (and) and ! (not) are also available, and the library syntax is gor(x,y), gand(x,y) and gnot(x) respectively.
In library mode, it is in fact usually preferable to use the two basic functions which are gcmp(x,y) which gives the sign (1, 0, or -1) of x-y, where x and y must be in R, and gequal(x,y) which can be applied to any two PARI objects x and y and gives 1 (i.e. true) if they are equal (but not necessarily identical), 0 (i.e. false) otherwise. Comparisons to special constants are implemented and should be used instead of gequal: gcmp0(x) (x == 0 ?), gcmp1(x) (x == 1 ?), and gcmp_1(x) (x == -1 ?).
Note that gcmp0(x) tests whether x is equal to zero, even if x is not an exact object. To test whether x is an exact object which is equal to zero, one must use isexactzero(x).
Also note that the gcmp and gequal functions return a C-integer, and not a GEN like gle etc.
GP accepts the following synonyms for some of the above functions: since we thought it might easily lead to confusion, we don't use the customary C operators for bitwise "and" or bitwise "or" (use bitand or bitor), hence | and & are accepted as synonyms of || and && respectively. Also, <> is accepted as a synonym for !=. On the other hand, = is definitely not a synonym for == since it is the assignment statement. periodt.
๐ค lex(x,y) โ lexicographic compare, but make it fashion
lex(x,y) gives the result of a lexicographic comparison between x and y (as -1, 0 or 1). This is to be interpreted in quite a wide sense: It is admissible to compare objects of different types (scalars, vectors, matrices), provided the scalars can be compared, as well as vectors/matrices of different lengths. The comparison is recursive.
In case all components are equal up to the smallest length of the operands, the more complex is considered to be larger. More precisely, the longest is the largest; when lengths are equal, we have matrix > vector > scalar. For example:
? lex([1,3], [1,2,5])
%1 = 1
? lex([1,3], [1,3,-1])
%2 = -1
? lex([1], [[1]])
%3 = -1
? lex([1], [1]~)
%4 = 0
The library syntax is lexcmp(x,y).
โโ sign(x) โ the vibe check for numbers
sign(x) gives the sign (0, 1 or -1) of x, which must be of type integer, real or fraction.
The library syntax is gsigne(x). The result is a long.
๐ max(x,y) and min(x,y)
max(x,y) and min(x,y) create the maximum and minimum of x and y when they can be compared.
The library syntax is gmax(x,y) and gmin(x,y).
๐ vecmax(x) โ biggest element energy
If x is a vector or a matrix, returns the maximum of the elements of x, otherwise returns a copy of x. Error if x is empty.
The library syntax is vecmax(x).
๐ vecmin(x) โ smallest element energy
If x is a vector or a matrix, returns the minimum of the elements of x, otherwise returns a copy of x. Error if x is empty.
The library syntax is vecmin(x).
๐ง Conversions and similar elementary functions or commands
Many of the conversion functions are rounding or truncating operations. In this case, if the argument is a rational function, the result is the Euclidean quotient of the numerator by the denominator, and if the argument is a vector or a matrix, the operation is done componentwise. This will not be restated for every function.
๐งต Col({x = []}) โ turn it into a column vector
Col({x = []}) transforms the object x into a column vector. The vector will be with one component only, except when x is a vector or a quadratic form (in which case the resulting vector is simply the initial object considered as a column vector), a matrix (the column of row vectors comprising the matrix is returned), a character string (a column of individual characters is returned), but more importantly when x is a polynomial or a power series. In the case of a polynomial, the coefficients of the vector start with the leading coefficient of the polynomial, while for power series only the significant coefficients are taken into account, but this time by increasing order of degree.
The library syntax is gtocol(x).
๐ List({x = []}) โ vector to list, iconic behavior
List({x = []}) transforms a (row or column) vector x into a list. The only other way to create a t_LIST is to use the function listcreate.
This is useless in library mode.
๐งฎ Mat({x = []}) โ make it a matrix
Mat({x = []}) transforms the object x into a matrix. If x is already a matrix, a copy of x is created. If x is not a vector or a matrix, this creates a 1 x 1 matrix. If x is a row (resp. column) vector, this creates a 1-row (resp. 1-column) matrix, unless all elements are column (resp. row) vectors of the same length, in which case the vectors are concatenated sideways and the associated big matrix is returned. matrix main character moment ๐
okay so, the Mat examples keep rolling like this:
? Mat(x + 1)
%1 =
[x + 1]
? Vec( matid(3) )
%2 = [[1, 0, 0]~, [0, 1, 0]~, [0, 0, 1]~]
? Mat(%)
%3 =
[1 0 0]
[0 1 0]
[0 0 1]
? Col( [1,2; 3,4] )
%4 = [[1, 2], [3, 4]]~
? Mat(%)
%5 =
[1 2]
[3 4]
The library syntax is gtomat(x).
Mod
Mod(x,y,{flag = 0}) creates the PARI object (x mod y), i.e. an intmod or a polmod. y must be an integer or a polynomial. If y is an integer, x must be an integer, a rational number, or a p-adic number compatible with the modulus y. If y is a polynomial, x must be a scalar (which is not a polmod), a polynomial, a rational function, or a power series.
This function is not the same as x % y, the result of which is an integer or a polynomial. ๐
flag is obsolete and should not be used.
The library syntax is gmodulo(x,y).
Pol
Pol(x,{v = x}) transforms the object x into a polynomial with main variable v. If x is a scalar, this gives a constant polynomial. If x is a power series, the effect is identical to truncate (see there), i.e. it chops off the O(X^k). If x is a vector, this function creates the polynomial whose coefficients are given in x, with x[1] being the leading coefficient (which can be zero).
Warning: this is not a substitution function. It will not transform an object containing variables of higher priority than v. ๐ซถ
? Pol(x + y, y)
*** Pol: variable must have higher priority in gtopoly.
The library syntax is gtopoly(x,v), where v is a variable number.
Polrev
Polrev(x,{v = x}) transforms the object x into a polynomial with main variable v. If x is a scalar, this gives a constant polynomial. If x is a power series, the effect is identical to truncate (see there), i.e. it chops off the O(X^k). If x is a vector, this function creates the polynomial whose coefficients are given in x, with x[1] being the constant term. Note that this is the reverse of Pol if x is a vector, otherwise it is identical to Pol.
The library syntax is gtopolyrev(x,v), where v is a variable number.
Qfb
Qfb(a,b,c,{D = 0.}) creates the binary quadratic form ax^2+bxy+cy^2. If b^2-4ac > 0, initialize Shanks' distance function to D. Negative definite forms are not implemented, use their positive definite counterpart instead. ๐ญ
The library syntax is Qfb0(a,b,c,D,prec). Also available are \funs{qfi}{a,b,c} (when b^2-4ac < 0), and \funs{qfr}{a,b,c,d} (when b^2-4ac > 0).
Ser
Ser(x,{v = x}) transforms the object x into a power series with main variable v (x by default). If x is a scalar, this gives a constant power series with precision given by the default serieslength (corresponding to the C global variable precdl). If x is a polynomial, the precision is the greatest of precdl and the degree of the polynomial. If x is a vector, the precision is similarly given, and the coefficients of the vector are understood to be the coefficients of the power series starting from the constant term (i.e. the reverse of the function Pol).
The warning given for Pol also applies here: this is not a substitution function.
The library syntax is gtoser(x,v), where v is a variable number (i.e. a C integer).
Set
Set({x = []}) converts x into a set, i.e. into a row vector of character strings, with strictly increasing entries with respect to lexicographic ordering. The components of x are put in canonical form (type t_STR) so as to be easily sorted. To recover an ordinary GEN from such an element, you can apply eval to it.
The library syntax is gtoset(x).
Str
Str({x}*) converts its argument list into a single character string (type t_STR, the empty string if x is omitted). To recover an ordinary GEN from a string, apply eval to it. The arguments of Str are evaluated in string context, see Label se:strings.
? x2 = 0; i = 2; Str(x, i)
%1 = "x2"
? eval(%)
%2 = 0
This function is mostly useless in library mode. Use the pair strtoGEN/GENtostr to convert between GEN and char*. The latter returns a malloced string, which should be freed after usage.
Strchr
Strchr(x) converts x to a string, translating each integer into a character.
? Strchr(97)
%1 = "a"
? Vecsmall("hello world")
%2 = Vecsmall([104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100])
? Strchr(%)
%3 = "hello world"
Strexpand
Strexpand({x}*) converts its argument list into a single character string (type t_STR, the empty string if x is omitted). Then performs environment expansion, see Label se:envir. This feature can be used to read environment variable values.
? Strexpand("$HOME/doc")
%1 = "/home/pari/doc"
The individual arguments are read in string context, see Label se:strings.
Strtex
Strtex({x}*) translates its arguments to TeX format, and concatenates the results into a single character string (type t_STR, the empty string if x is omitted).
The individual arguments are read in string context, see Label se:strings.
Vec
Vec({x = []}) transforms the object x into a row vector. The vector will be with one component only, except when x is a vector or a quadratic form (in which case the resulting vector is simply the initial object considered as a row vector), a matrix (the vector of columns comprising the matrix is returned), a character string (a vector of individual characters is returned), but more importantly when x is a polynomial or a power series. In the case of a polynomial, the coefficients of the vector start with the leading coefficient of the polynomial, while for power series only the significant coefficients are taken into account, but this time by increasing order of degree.
The library syntax is gtovec(x).
Vecsmall
Vecsmall({x = []}) transforms the object x into a row vector of type t_VECSMALL. This acts as Vec, but only on a limited set of objects (the result must be representable as a vector of small integers). In particular, polynomials and power series are forbidden. If x is a character string, a vector of individual characters in ASCII encoding is returned (Strchr yields back the character string).
The library syntax is gtovecsmall(x).
binary
binary(x) outputs the vector of the binary digits of |x|. Here x can be an integer, a real number (in which case the result has two components, one for the integer part, one for the fractional part) or a vector/matrix.
The library syntax is binaire(x).
bitand
bitand(x,y) is the bitwise and of two integers x and y, that is the integer
sum"_i (x_i and y_i) 2^i"
Negative numbers behave 2-adically, i.e. the result is the 2-adic limit of bitand(x_n,y_n), where x_n and y_n are non-negative integers tending to x and y respectively. (The result is an ordinary integer, possibly negative.)
? bitand(5, 3)
%1 = 1
? bitand(-5, 3)
%2 = 3
? bitand(-5, -3)
%3 = -7
The library syntax is gbitand(x,y).
bitneg
bitneg(x,{n = -1}) is the bitwise negation of an integer x, truncated to n bits, that is the integer
sum"_{i = 0}^{n-1} not(x_i) 2^i"
The special case n = -1 means no truncation: an infinite sequence of leading 1 is then represented as a negative number.
See Label se:bitand for the behaviour for negative arguments.
The library syntax is gbitneg(x).
bitnegimply
bitnegimply(x,y) is the bitwise negated imply of two integers x and y (or not (x ==> y)), that is the integer
sum" (x_i and not(y_i)) 2^i"
See Label se:bitand for the behaviour for negative arguments.
The library syntax is gbitnegimply(x,y).
bitor
bitor(x,y) is the bitwise (inclusive) or of two integers x and y, that is the integer
sum" (x_i or y_i) 2^i"
See Label se:bitand for the behaviour for negative arguments.
The library syntax is gbitor(x,y).
bittest
bittest(x,n) outputs the n-th bit of |x| starting from the right (i.e. the coefficient of 2^n in the binary expansion of x). The result is 0 or 1. To extract several bits at once as a vector, pass a vector for n.
The library syntax is bittest(x,n), where n and the result are longs.
bitxor
bitxor(x,y) is the bitwise (exclusive) or of two integers x and y, that is the integer
sum" (x_i xor y_i) 2^i"
See Label se:bitand for the behaviour for negative arguments.
The library syntax is gbitxor(x,y).
ceil
ceil(x) is the ceiling of x. When x is in R, the result is the smallest integer greater than or equal to x. Applied to a rational function, ceil(x) returns the euclidian quotient of the numerator by the denominator.
The library syntax is gceil(x).
centerlift
centerlift(x,{v}) lifts an element x = a mod n of Z/nZ to a in Z, and similarly lifts a polmod to a polynomial. This is the same as lift except that in the particular case of elements of Z/nZ, the lift y is such that -n/2 < y <= n/2. If x is of type fraction, complex, quadratic, polynomial, power series, rational function, vector or matrix, the lift is done for each coefficient. Reals are forbidden. ๐
The library syntax is centerlift0(x,v), where v is a long and an omitted v is coded as -1. Also available is \funs{centerlift}{x} = centerlift0(x,-1).
changevar
changevar(x,y) creates a copy of the object x where its variables are modified according to the permutation specified by the vector y. For example, assume that the variables have been introduced in the order x, a, b, c. Then, if y is the vector [x,c,a,b], the variable a will be replaced by c, b by a, and c by b, x being unchanged. Note that the permutation must be completely specified, e.g. [c,a,b] would not work, since this would replace x by c, and leave a and b unchanged (as well as c which is the fourth variable of the initial list). In particular, the new variable names must be distinct.
The library syntax is changevar(x,y).
๐ components of a PARI object ๐
There are essentially three ways to extract the components from a PARI object.
okay so the first and most general way to grab a component is component(x,n) โ it pulls out the n-th component of x, bestie. think of it like this: every PARI type has one or two initial code words, and the components are counted starting at 1 after those code words. so if x is a vector, that's literally the n-th component of x; if x is a matrix, it's the n-th column; if x is a polynomial, it's the n-th coefficient (i.e. of degree n-1); and for power series, it's the n-th significant coefficient. using component means you know the structure of the different PARI types, which you can recall by typing \t under gp. the library syntax is compo(x,n), where n is a long.
the two other methods are more natural but more restricted. the function polcoeff(x,n) gives the coefficient of degree n of the polynomial or power series x, with respect to the main variable of x (to check variable ordering, or to change it, use reorder, see Label se:reorder). in particular, if n is less than the valuation of x or, in the case of a polynomial, greater than the degree, the result is zero (contrary to compo, which would send an error message ๐ญ). if x is a power series and n is greater than the largest significant degree, then an error message is issued. for greater flexibility, vector or matrix types are also accepted for x, and the meaning is then identical with that of compo. finally, note that a scalar type is considered by polcoeff as a polynomial of degree zero. the library syntax is truecoeff(x,n).
the third method is specific to vectors or matrices in GP. if x is a (row or column) vector, then x[n] represents the n-th component of x, i.e. compo(x,n). it's more natural and shorter to write, no cap. if x is a matrix, x[m,n] represents the coefficient of row m and column n of the matrix, x[m,] represents the m-th row of x, and x[,n] represents the n-th column of x. finally note that in library mode, the macros gcoeff and gmael are available as direct accessors to a GEN component. see Chapter 4 for details.
๐ conj(x)
conjugate of x. the meaning is clear, except that for real quadratic numbers it means conjugation in the real quadratic field. this function has no effect on integers, reals, intmods, fractions or p-adics. the only forbidden type is polmod (see conjvec for this). the library syntax is gconj(x).
๐ฆ conjvec(x)
conjugate vector representation of x. if x is a polmod equal to Mod(a,q), this gives a vector of length degree(q) containing the complex embeddings of the polmod if q has integral or rational coefficients, and the conjugates of the polmod if q has some intmod coefficients. the order is the same as that of the polroots functions. if x is an integer or a rational number, the result is x. if x is a (row or column) vector, the result is a matrix whose columns are the conjugate vectors of the individual elements of x. the library syntax is conjvec(x,prec).
๐ denominator(x)
denominator of x. the meaning is clear when x is a rational number or function. if x is an integer or a polynomial, it is treated as a rational number or function, respectively, and the result is equal to 1. for polynomials, you probably want to use
denominator( content(x) )
instead. as for modular objects, t_INTMOD and t_PADIC have denominator 1, and the denominator of a t_POLMOD is the denominator of its (minimal degree) polynomial representative.
if x is a recursive structure, for instance a vector or matrix, the lcm of the denominators of its components (a common denominator) is computed. this also applies for t_COMPLEXs and t_QUADs.
โ ๏ธ warning: multivariate objects are created according to variable priorities, with possibly surprising side effects (x/yis a polynomial, buty/xis a rational function). seeLabel se:priority.
the library syntax is denom(x).
โจ floor(x)
floor of x. when x is in R, the result is the largest integer smaller than or equal to x. applied to a rational function, floor(x) returns the euclidian quotient of the numerator by the denominator. the library syntax is gfloor(x).
๐ธ frac(x)
fractional part of x. identical to x-floor(x). if x is real, the result is in [0,1[. the library syntax is gfrac(x).
๐ imag(x)
imaginary part of x. when x is a quadratic number, this is the coefficient of omega in the โcanonicalโ integral basis (1,omega). the library syntax is gimag(x). this returns a copy of the imaginary part. the internal routine imag_i is faster, since it returns the pointer and skips the copy.
๐ง length(x)
number of non-code words in x really used (i.e. the effective length minus 2 for integers and polynomials). in particular, the degree of a polynomial is equal to its length minus 1. if x has type t_STR, output number of letters. the library syntax is glength(x) and the result is a C long.
๐ซถ lift(x,{v})
lifts an element x = a mod n of Z/nZ to a in Z, and similarly lifts a polmod to a polynomial if v is omitted. otherwise, lifts only polmods whose modulus has main variable v (if v does not occur in x, lifts only intmods). if x is of recursive (non modular) type, the lift is done coefficientwise. for p-adics, this routine acts as truncate. it is not allowed to have x of type t_REAL.
? lift(Mod(5,3))
%1 = 2
? lift(3 + O(3^9))
%2 = 3
? lift(Mod(x,x^2+1))
%3 = x
? lift(x * Mod(1,3) + Mod(2,3))
%4 = x + 2
? lift(x * Mod(y,y^2+1) + Mod(2,3))
%5 = y*x + Mod(2, 3) \\ do you understand this one ?
? lift(x * Mod(y,y^2+1) + Mod(2,3), x)
%6 = Mod(y, y^2+1) * x + Mod(2, y^2+1)
the library syntax is lift0(x,v), where v is a long and an omitted v is coded as -1. also available is lift(x) = lift0(x,-1).
๐ norm(x)
algebraic norm of x, i.e. the product of x with its conjugate (no square roots are taken), or conjugates for polmods. for vectors and matrices, the norm is taken componentwise and hence is not the L^2-norm (see norml2). note that the norm of an element of R is its square, so as to be compatible with the complex norm. the library syntax is gnorm(x).
โญ norml2(x)
square of the L^2-norm of x. more precisely, if x is a scalar, norml2(x) is defined to be x * conj(x). if x is a (row or column) vector or a matrix, norml2(x) is defined recursively as sum_i norml2(x_i), where (x_i) run through the components of x. in particular, this yields the usual sum |x_i|^2 (resp. sum |x_{i,j}|^2) if x is a vector (resp. matrix) with complex components.
? norml2( [ 1, 2, 3 ] ) \\ vector
%1 = 14
? norml2( [ 1, 2; 3, 4] ) \\ matrix
%1 = 30
? norml2( I + x )
%3 = x^2 + 1
? norml2( [ [1,2], [3,4], 5, 6 ] ) \\ recursively defined
%4 = 91
the library syntax is gnorml2(x).
๐ numerator(x)
numerator of x. the meaning is clear when x is a rational number or function. if x is an integer or a polynomial, it is treated as a rational number or function, respectively, and the result is x itself. for polynomials, you probably want to use
numerator( content(x) )
instead. in other cases, numerator(x) is defined to be denominator(x)*x. this is the case when x is a vector or a matrix, but also for t_COMPLEX or t_QUAD. in particular, since a t_PADIC or t_INTMOD has denominator 1, its numerator is itself.
โ ๏ธ warning: multivariate objects are created according to variable priorities, with possibly surprising side effects (x/yis a polynomial, buty/xis a rational function). seeLabel se:priority.
the library syntax is numer(x).
๐ numtoperm(n,k)
generates the k-th permutation (as a row vector of length n) of the numbers 1 to n. the number k is taken modulo n!, i.e. inverse function of permtonum. the library syntax is numtoperm(n,k), where n is a long.
๐ฅ padicprec(x,p)
absolute p-adic precision of the object x. this is the minimum precision of the components of x. the result is VERYBIGINT (2^{31}-1 for 32-bit machines or 2^{63}-1 for 64-bit machines) if x is an exact object. the library syntax is padicprec(x,p) and the result is a long integer.
๐ permtonum(x)
given a permutation x on n elements, gives the number k such that x = numtoperm(n,k), i.e. inverse function of numtoperm. the library syntax is permtonum(x).
๐ precision(x,{n})
gives the precision in decimal digits of the PARI object x. if x is an exact object, the largest single precision integer is returned. if n is not omitted, creates a new object equal to x with a new precision n. this is to be understood as follows:
- for exact types, no change. for
xa vector or a matrix, the operation is done componentwise. - for real
x,nis the number of desired significant decimal digits. ifnis smaller than the precision ofx,xis truncated, otherwisexis extended with zeros. - for
xap-adic or a power series,nis the desired number of significantp-adic orX-adic digits, whereXis the main variable ofx.
note that the function precision never changes the type of the result. in particular, it is not possible to use it to obtain a polynomial from a power series. for that, see truncate. the library syntax is precision0(x,n), where n is a long. also available are ggprecision(x) (result is a GEN) and gprec(x,n), where n is a long.
๐ random({N = 2^{31}})
returns a random integer between 0 and N-1. N is an integer, which can be arbitrary large. this is an internal PARI function and does not depend on the system's random number generator. the resulting integer is obtained by means of linear congruences and will not be well distributed in arithmetic progressions. the random seed may be obtained via getrand, and reset using setrand.
note that random(2^31) is not equivalent to random(), although both return an integer between 0 and 2^{31}-1. in fact, calling random with an argument generates a number of random words (32bit or 64bit depending on the architecture), rescaled to the desired interval. the default uses directly a 31-bit generator.
Important technical note: the implementation of this function is incorrect unless N is a power of 2 (integers less than the bound are not equally likely โ some may not even occur ๐ญ). It is kept for backward compatibility only, and has been rewritten from scratch in the 2.4.x unstable series. Use the following script for a correct version:
RANDOM(N) =
{ local(n, L);
L = 1; while (L < N, L <<= 1;);
/* L/2 < N <= L, L power of 2 */
until(n < N, n = random(L)); n
}
The library syntax is genrand(N). Also available are pari_rand() which returns a random unsigned long (32bit or 64bit depending on the architecture), and pari_rand31() which returns a 31bit long integer. ๐ซถ
๐ธ real(x) ๐ธ
Real part of x. In the case where x is a quadratic number, this is the coefficient of 1 in the โcanonicalโ integral basis (1,omega).
The library syntax is greal(x). This returns a copy of the real part. The internal routine real_i is faster, since it returns the pointer and skips the copy.
๐ round(x,{&e}) ๐
If x is in R, rounds x to the nearest integer and sets e to the number of error bits, that is the binary exponent of the difference between the original and the rounded value (the โfractional partโ). If the exponent of x is too large compared to its precision (i.e. e > 0), the result is undefined and an error occurs if e was not given.
โ ๏ธ Important remark: note that, contrary to the other truncation functions, this function operates on every coefficient at every level of a PARI object. For example
truncate((2.4*X^2-1.7)/(X)) = 2.4*X,
whereas
round((2.4*X^2-1.7)/(X)) = (2*X^2-2)/(X).
An important use of round is to get exact results after a long approximate computation, when theory tells you that the coefficients must be integers.
The library syntax is grndtoi(x,&e), where e is a long integer. Also available is ground(x).
โจ simplify(x) โจ
This function simplifies x as much as it can. Specifically, a complex or quadratic number whose imaginary part is an exact 0 (i.e. not an approximate one as a O(3) or 0.E-28) is converted to its real part, and a polynomial of degree 0 is converted to its constant term. Simplifications occur recursively.
This function is especially useful before using arithmetic functions, which expect integer arguments:
? x = 1 + y - y
%1 = 1
? divisors(x)
*** divisors: not an integer argument in an arithmetic function
? type(x)
%2 = "t_POL"
? type(simplify(x))
%3 = "t_INT"
Note that GP results are simplified as above before they are stored in the history. (Unless you disable automatic simplification with \y, that is.) In particular
? type(%1)
%4 = "t_INT"
The library syntax is simplify(x).
๐ฆ sizebyte(x) ๐ฆ
Outputs the total number of bytes occupied by the tree representing the PARI object x.
The library syntax is taille2(x) which returns a long; taille(x) returns the number of words instead.
๐ sizedigit(x) ๐
Outputs a quick bound for the number of decimal digits of (the components of) x, off by at most 1. If you want the exact value, you can use #Str(x), which is slower.
The library syntax is sizedigit(x) which returns a long.
๐
truncate(x,{&e}) ๐
Truncates x and sets e to the number of error bits. When x is in R, this means that the part after the decimal point is chopped away, e is the binary exponent of the difference between the original and the truncated value (the โfractional partโ). If the exponent of x is too large compared to its precision (i.e. e > 0), the result is undefined and an error occurs if e was not given. The function applies componentwise on vector / matrices; e is then the maximal number of error bits. If x is a rational function, the result is the โinteger partโ (Euclidean quotient of numerator by denominator) and e is not set.
Note a very special use of truncate: when applied to a power series, it transforms it into a polynomial or a rational function with denominator a power of X, by chopping away the O(X^k). Similarly, when applied to a p-adic number, it transforms it into an integer or a rational number by chopping away the O(p^k).
The library syntax is gcvtoi(x,&e), where e is a long integer. Also available is gtrunc(x).
๐ valuation(x,p) ๐
Computes the highest exponent of p dividing x. If p is of type integer, x must be an integer, an intmod whose modulus is divisible by p, a fraction, a q-adic number with q = p, or a polynomial or power series in which case the valuation is the minimum of the valuation of the coefficients.
If p is of type polynomial, x must be of type polynomial or rational function, and also a power series if x is a monomial. Finally, the valuation of a vector, complex or quadratic number is the minimum of the component valuations.
If x = 0, the result is VERYBIGINT (2^{31}-1 for 32-bit machines or 2^{63}-1 for 64-bit machines) if x is an exact object. If x is a p-adic number or power series, the result is the exponent of the zero. Any other type combinations gives an error.
The library syntax is ggval(x,p), and the result is a long.
๐ง variable(x) ๐ง
Gives the main variable of the object x, and p if x is a p-adic number. Gives an error if x has no variable associated to it. Note that this function is useful only in GP, since in library mode the function gvar is more appropriate.
The library syntax is gpolvar(x). However, in library mode, this function should not be used. Instead, test whether x is a p-adic (type t_PADIC), in which case p is in x[2], or call the function gvar(x) which returns the variable number of x if it exists, BIGINT otherwise.
๐ Transcendental functions ๐
As a general rule, which of course in some cases may have exceptions, transcendental functions operate in the following way:
- If the argument is either an integer, a real, a rational, a complex or a quadratic number, it is, if necessary, first converted to a real (or complex) number using the current precision held in the default
realprecision. Note that only exact arguments are converted, while inexact arguments such as reals are not.
In GP this is transparent to the user, but when programming in library mode, care must be taken to supply a meaningful parameter prec as the last argument of the function if the first argument is an exact object. This parameter is ignored if the argument is inexact.
Note that in library mode the precision argument prec is a word count including codewords, i.e. represents the length in words of a real number, while under gp the precision (which is changed by the metacommand \p or using default(realprecision,...)) is the number of significant decimal digits.
Note that some accuracies attainable on 32-bit machines cannot be attained on 64-bit machines for parity reasons. For example the default gp accuracy is 28 decimal digits on 32-bit machines, corresponding to prec having the value 5, but this cannot be attained on 64-bit machines.
After possible conversion, the function is computed. Note that even if the argument is real, the result may be complex (e.g. acos(2.0) or acosh(0.0)). Note also that the principal branch is always chosen.
- If the argument is an intmod or a
p-adic, at present only a few functions likesqrt(square root),sqr(square),log,exp, powering,teichmuller(Teichmรผller character) andagm(arithmetic-geometric mean) are implemented.
Note that in the case of a 2-adic number, sqr(x) may not be identical to x*x: for example if x = 1+O(2^5) and y = 1+O(2^5) then x*y = 1+O(2^5) while sqr(x) = 1+O(2^6). Here, x * x yields the same result as sqr(x) since the two operands are known to be identical. The same statement holds true for p-adics raised to the power n, where v_p(n) > 0.
Remark: note that if we wanted to be strictly consistent with the PARI philosophy, we should havex*y = (4 mod 8)andsqr(x) = (4 mod 32)when bothxandyare congruent to 2 modulo 4. However, since intmod is an exact object, PARI assumes that the modulus must not change, and the result is hence(0 mod 4)in both cases. On the other hand,p-adics are not exact objects, hence are treated differently.
- If the argument is a polynomial, power series or rational function, it is, if necessary, first converted to a power series using the current precision held in the variable
precdl. Undergpthis again is transparent to the user. When programming in library mode, however, the global variableprecdlmust be set before calling the function if the argument has an exact type (i.e. not a power series). Hereprecdlis not an argument of the function, but a global variable.
Then the Taylor series expansion of the function around X = 0 (where X is the main variable) is computed to a number of terms depending on the number of terms of the argument and the function being computed.
- If the argument is a vector or a matrix, the result is the componentwise evaluation of the function. In particular, transcendental functions on square matrices, which are not implemented in the present version 2.3.5, will have a different name if they are implemented some day.
โก ^ โก
If y is not of type integer, x^y has the same effect as exp(y*log(x)). It can be applied to p-adic numbers as well as to the more usual types.
The library syntax is gpow(x,y,prec).
๐ Euler ๐
Euler's constant gamma = 0.57721.... Note that Euler is one of the few special reserved names which cannot be used for variables (the others are I and Pi, as well as all function names).
The library syntax is mpeuler(prec) where prec must be given. Note that this creates gamma on the PARI stack, but a copy is also created on the heap for quicker computations next time the function is called.
๐ I ๐
The complex number sqrt {-1}.
The library syntax is the global variable gi (of type GEN).
๐ Pi ๐
The constant pi (3.14159...).
The library syntax is mppi(prec) where prec must be given. Note that this creates pi on the PARI stack, but a copy is also created on the heap for quicker computations next time the function is called.
๐ฅ abs(x) ๐ฅ
Absolute value of x (modulus if x is complex). Rational functions are not allowed. Contrary to most transcendental functions, an exact argument is not converted to a real number before applying abs and an exact result is returned if possible. ๐
๐ abs(x)
okay so abs(x) is just the absolute value, but she's got range โจ โ it works for all the number types and knows what she's doing.
? abs(-1)
%1 = 1
? abs(3/7 + 4/7*I)
%2 = 5/7
? abs(1 + I)
%3 = 1.414213562373095048801688724
Plot twist for polynomials: if x is a polynomial, it returns -x when the leading coefficient is real and negative โ otherwise it just hands you back x. And for a power series? It looks at the constant coefficient instead. iykyk ๐
The library syntax is gabs(x,prec).
๐ธ acos(x)
principal branch of cos^{-1}(x), meaning Re(acos(x)) \in [0, pi] โ she stays in her lane, bestie. If x \in R and |x| > 1, then acos(x) goes full complex on you ๐ญ
The library syntax is gacos(x,prec).
๐ฆ acosh(x)
principal branch of cosh^{-1}(x), i.e. Im(acosh(x)) \in [0, pi]. And if x \in R with x < 1? Yeah, acosh(x) becomes complex. no cap.
The library syntax is gach(x,prec).
๐ agm(x,y)
the arithmetic-geometric mean of x and y โ genuinely iconic โจ For complex or negative numbers, the principal square root is always the one chosen. p-adic or power series arguments are also allowed ๐ซถ
heads up: ap-adicagmonly exists ifx/yis congruent to 1 modulop(and modulo 16 whenp = 2). Also,xandycan't both be vectors or matrices. that's the vibe check.
The library syntax is agm(x,y,prec).
๐ arg(x)
the argument of the complex number x, such that -pi < arg(x) <= pi. living within bounds, as she should ๐
The library syntax is garg(x,prec).
โญ asin(x)
principal branch of sin^{-1}(x), so Re(asin(x)) \in [-pi/2, pi/2]. If x \in R and |x| > 1 then asin(x) is complex โ she's expanding her horizons ๐
The library syntax is gasin(x,prec).
๐ง asinh(x)
principal branch of sinh^{-1}(x), i.e. Im(asinh(x)) \in [-pi/2, pi/2]. clean, simple, slays.
The library syntax is gash(x,prec).
๐ atan(x)
principal branch of tan^{-1}(x), meaning Re(atan(x)) \in ]-pi/2, pi/2[. open interval behavior, we respect it ๐
The library syntax is gatan(x,prec).
๐ atanh(x)
principal branch of tanh^{-1}(x), i.e. Im(atanh(x)) \in ]-pi/2, pi/2]. And if x \in R with |x| > 1, then atanh(x) is complex. ๐ญ it's giving "thresholds".
The library syntax is gath(x,prec).
๐ bernfrac(x)
the Bernoulli number B_x, where B_0 = 1, B_1 = -1/2, B_2 = 1/6,..., expressed as a rational number. The argument x should be of type integer โ fr fr, give her an integer.
The library syntax is bernfrac(x).
๐ฅ bernreal(x)
same as bernfrac โ Bernoulli number B_x โ except B_x comes back as a real number (with the current precision). glow-up version ๐ซถ
The library syntax is bernreal(x,prec).
๐ bernvec(x)
creates a vector containing, as rational numbers, the Bernoulli numbers B_0, B_2,..., B_{2x}.
this routine is obsolete. Use bernfrac instead each time you need a Bernoulli number in exact form. not me warning you twice ๐
Note: this routine is implemented using repeated independent calls to bernfrac, which is faster than the standard recursion in exact arithmetic. It is only kept for backward compatibility: it is not faster than individual calls to bernfrac, its output uses a lot of memory space, and coping with the index shift is awkward. ๐ so like... use the other one.
The library syntax is bernvec(x).
๐ธ besselh1(\nu,x)
the H^1-Bessel function of index nu and argument x. fancy math with a fancy name, obsessed.
The library syntax is hbessel1(\nu,x,prec).
๐ธ besselh2(\nu,x)
the H^2-Bessel function of index nu and argument x. her sister. equally iconic ๐
The library syntax is hbessel2(\nu,x,prec).
๐ฆ besseli(\nu,x)
the I-Bessel function of index nu and argument x.
little detail that matters: if x converts to a power series, the initial factor (x/2)^\nu/Gamma(\nu+1) is omitted (since it cannot be represented in PARI when nu is not integral). no cap, that's just how it is.
The library syntax is ibessel(\nu,x,prec).
๐ฆ besselj(\nu,x)
the J-Bessel function of index nu and argument x. same deal as above: if x converts to a power series, that initial factor (x/2)^\nu/Gamma(\nu+1) gets omitted, because it can't be represented in PARI when nu isn't integral. ๐ซถ
The library syntax is jbessel(\nu,x,prec).
๐ besseljh(n,x)
the J-Bessel function of half integral index, bestie. More precisely, besseljh(n,x) computes J_{n+1/2}(x) where n must be of type integer, and x is any element of C.
accuracy warning: in the present version 2.3.5, this function is not very accurate when x is small. ๐ญ watch out.
The library syntax is jbesselh(n,x,prec).
โจ besselk(\nu,x,{flag = 0})
the K-Bessel function of index nu (which can be complex) and argument x.
Only real and positive arguments x are allowed in the present version 2.3.5. โ ๏ธ
If flag is equal to 1, it uses another implementation of this function which is faster when x >> 1. speed demon mode ๐ฅ
The library syntax is kbessel(\nu,x,prec) and kbessel2(\nu,x,prec) respectively.
๐ besseln(\nu,x)
the N-Bessel function of index nu and argument x. rounding out the Bessel squad ๐ซถ
The library syntax is nbessel(\nu,x,prec).
๐ cos(x)
cosine of x. that's it, that's the tweet ๐
The library syntax is gcos(x,prec).
๐ cosh(x)
hyperbolic cosine of x. cos but make it hyperbolic โจ
The library syntax is gch(x,prec).
๐ง cotan(x)
cotangent of x. the underrated one of the trig family, honestly.
The library syntax is gcotan(x,prec).
๐ dilog(x)
principal branch of the dilogarithm of x, i.e. the analytic continuation of the power series log_2(x) = sum_{n >= 1}x^n/n^2. she's analytic and continued, main character energy ๐
The library syntax is dilog(x,prec).
โญ eint1(x,{n})
the exponential integral int_x^\infty (e^{-t})/(t)dt (x \in R).
If n is present, it outputs the n-dimensional vector [eint1(x),...,eint1(nx)] (x >= 0). And it's faster than repeatedly calling eint1(i * x) โ efficiency slay ๐ฅ
The library syntax is veceint1(x,n,prec). Also available is eint1(x,prec).
๐ erfc(x)
the complementary error function (2/\sqrt pi) int_x^\infty e^{-t^2}dt (x \in R). yes it's a mouthful, no I will not be shortening it ๐
The library syntax is erfc(x,prec).
๐ธ eta(x,{flag = 0})
Dedekind's eta function, without the q^{1/24}. Let me break that down for you bestie: if x is a complex number with positive imaginary part, the result is prod_{n = 1}^\infty (1-q^n), where q = e^{2i\pi x}. If x is a power series (or can be converted to a power series) with positive valuation, the result is prod_{n = 1}^\infty (1-x^n). ๐ฆ
And if flag = 1 and x can be converted to a complex number (i.e. it's not a power series), it computes the true eta function, including the leading q^{1/24}. the full package ๐
The library syntax is eta(x,prec).
๐ฅ exp(x)
exponential of x. p-adic arguments with positive valuation are accepted โ she's flexible like that โจ
The library syntax is gexp(x,prec).
๐ง gammah(x)
the gamma function evaluated at the argument x+1/2. note the sneaky +1/2, don't sleep on it ๐
The library syntax is ggamd(x,prec).
๐ gamma(x)
the gamma function of x. the moment. the icon. the legend. ๐
The library syntax is ggamma(x,prec).
๐ฆ hyperu(a,b,x)
the U-confluent hypergeometric function with parameters a and b. The parameters a and b can be complex, but the present implementation requires x to be positive. ๐ซถ rules are rules.
The library syntax is hyperu(a,b,x,prec).
๐ incgam(s,x,{y})
the incomplete gamma function. The argument x and s are complex numbers (x must be a positive real number if s = 0). The result returned is int_x^\infty e^{-t}t^{s-1}dt.
When y is given, assume (of course without checking!) that y = Gamma(s). For small x, this will speed up the computation. โก
no, seriously, it doesn't check. you're on your own if y is wrong, bestie ๐
The library syntax is incgam(s,x,prec) and incgam0(s,x,y,prec), respectively (an omitted y is coded as NULL).
๐ incgamc(s,x)
the complementary incomplete gamma function. The arguments x and s are complex numbers such that s is not a pole of Gamma and |x|/(|s|+1) is not much larger than 1 (otherwise the convergence is very slow ๐ญ). The result returned is int_0^x e^{-t}t^{s-1}dt.
The library syntax is incgamc(s,x,prec).
โจ log(x)
principal branch of the natural logarithm of x, i.e. Im(log(x)) \in ]-pi, pi]. The result is complex (with imaginary part equal to pi) if x \in R and x < 0 ๐
In general, the algorithm uses the formula
log(x) ~ (pi)/(2agm(1, 4/s)) - m log 2,
if s = x 2^m is large enough. (The result is exact to B bits provided s > 2^{B/2}.) At low accuracies, the series expansion near 1 is used. ๐
p-adic arguments are also accepted for x, with the convention that log(p) = 0. Hence in particular exp(log(x))/x is not in general equal to 1 but to a (p-1)-th root of unity (or +-1 if p = 2) times a power of p. ๐ญ yeah that's a whole thing, don't @ me.
The library syntax is glog(x,prec).
๐ lngamma(x)
principal branch of the logarithm of the gamma function of x. This function is analytic on the complex plane with non-positive integers removed. She can have much larger arguments than gamma itself ๐ฅ iconic behavior.
Note: thep-adiclngammafunction is not implemented. ๐
The library syntax is glngamma(x,prec).
๐ polylog(m,x,{flag = 0})
one of the different polylogarithms, depending on flag. choose your fighter ๐
If flag = 0 or is omitted: the m-th polylogarithm of x, i.e. the analytic continuation of the power series Li_m(x) = sum_{n >= 1}x^n/n^m (x < 1). It uses the functional equation linking the values at x and 1/x to restrict to the case |x| <= 1, then the power series when |x|^2 <= 1/2, and the power series expansion in log(x) otherwise. ๐ฆ
Using flag, it computes a modified m-th polylogarithm of x. We use Zagier's notations; let Re_m denote Re or Im depending whether m is odd or even:
If flag = 1: compute ~D_m(x), defined for |x| <= 1 by
Re_m(sum_{k = 0}^{m-1} ((-log|x|)^k)/(k!)Li_{m-k}(x) + ((-log|x|)^{m-1})/(m!)log|1-x|).
If flag = 2: compute D_m(x), defined for |x| <= 1 by
Re_m(sum_{k = 0}^{m-1}((-log|x|)^k)/(k!)Li_{m-k}(x) -(1)/(2)((-log|x|)^m)/(m!)).
If flag = 3: compute P_m(x), defined for |x| <= 1 by
Re_m(sum_{k = 0}^{m-1}(2^kB_k)/(k!)(log|x|)^kLi_{m-k}(x) -(2^{m-1}B_m)/(m!)(log|x|)^m).
And these three functions satisfy the functional equation f_m(1/x) = (-1)^{m-1}f_m(x). cute, consistent, slaying โจ
The library syntax is polylog0(m,x,flag,prec).
๐ธ psi(x)
the psi-function of x, i.e. the logarithmic derivative Gamma'(x)/Gamma(x). yes she's a derivative girlie ๐
The library syntax is gpsi(x,prec).
๐ sin(x)
sine of x. the classic. the blueprint. ๐
The library syntax is gsin(x,prec).
๐ sinh(x)
hyperbolic sine of x. sin, but make it hyperbolic ๐
The library syntax is gsh(x,prec).
๐ฅ sqr(x)
the square of x. And okay, this one is not completely straightforward, i.e. it's not just identical to x * x, since it can usually be computed more efficiently (roughly one-half of the elementary multiplications can be saved). also, squaring a 2-adic number increases its precision โ glow up ๐ For example,
? (1 + O(2^4))^2
%1 = 1 + O(2^5)
? (1 + O(2^4)) * (1 + O(2^4))
%2 = 1 + O(2^4)
like look at that precision difference, she ate ๐
Not me being obsessed with the fact that this function also gets called whenever you multiply two objects that are known to be identical โ like, they're literally the value of the same variable, or you're computing a power. ๐
? x = (1 + O(2^4)); x * x
%3 = 1 + O(2^5)
? (1 + O(2^4))^4
%4 = 1 + O(2^6)
(and yes, bestie, note the difference between %2 and %3 above ๐).
The library syntax is gsqr(x).
sqrt(x) ๐ธ
Principal branch of the square root of x, i.e. the one such that Arg(sqrt(x))\in ]-\pi/2, \pi/2], or โ saying the exact same thing in a cuter way โ such that Re(sqrt(x)) > 0, or Re(sqrt(x)) = 0 and Im(sqrt(x)) >= 0. If x\in \R and x < 0, then the result is complex with positive imaginary part. ๐
Intmod a prime and p-adics are allowed as arguments. In that case, the square root (if it exists) which is returned is the one whose first p-adic digit (or its unique p-adic digit in the case of intmods) is in the interval [0,p/2]. When the argument is an intmod a non-prime (or a non-prime-adic), the result is undefined. โ ๏ธ like, undefined undefined, so don't come for me.
The library syntax is gsqrt(x,prec).
sqrtn(x,n,{&z}) ๐ฆ
Principal branch of the nth root of x, i.e. such that Arg(sqrt(x))\in ]-\pi/n, \pi/n]. Intmod a prime and p-adics are allowed as arguments.
If z is present, it is set to a suitable root of unity allowing to recover all the other roots. If it was not possible, z is set to zero. In the case this argument is present and no square root exist, 0 is returned instead or raising an error.
? sqrtn(Mod(2,7), 2)
%1 = Mod(4, 7)
? sqrtn(Mod(2,7), 2, &z); z
%2 = Mod(6, 7)
? sqrtn(Mod(2,7), 3)
*** sqrtn: nth-root does not exist in gsqrtn.
? sqrtn(Mod(2,7), 3, &z)
%2 = 0
? z
%3 = 0
The following script computes all roots in all possible cases โ periodt, it's giving utility icon:
sqrtnall(x,n)=
{
local(V,r,z,r2);
r = sqrtn(x,n, &z);
if (!z, error("Impossible case in sqrtn"));
if (type(x) == "t_INTMOD" || type(x)=="t_PADIC" ,
r2 = r*z; n = 1;
while (r2!=r, r2*=z;n++));
V = vector(n); V[1] = r;
for(i=2, n, V[i] = V[i-1]*z);
V
}
addhelp(sqrtnall,"sqrtnall(x,n):compute the vector of nth-roots of x");
The library syntax is gsqrtn(x,n,&z,prec).
tan(x) โญ
tangent of x. simple as that, no notes ๐
The library syntax is gtan(x,prec).
tanh(x) ๐
hyperbolic tangent of x. ok go off.
The library syntax is gth(x,prec).
teichmuller(x) ๐
Teichmรผller character of the p-adic number x, i.e. the unique (p-1)-th root of unity congruent to x / p^{v_p(x)} modulo p.
The library syntax is teich(x).
theta(q,z) ๐
Jacobi sine theta-function. that's it, that's the vibe.
The library syntax is theta(q,z,prec).
thetanullk(q,k) โจ
k-th derivative at z = 0 of theta(q,z).
The library syntax is thetanullk(q,k,prec), where k is a long. (yes bestie, a long, not whatever you were about to pass in ๐ญ)
weber(x,{flag = 0}) ๐
one of Weber's three f functions. If flag = 0, returns
f(x) = exp(-i\pi/24).\eta((x+1)/2)/\eta(x) such that j =
(f^{24}-16)^3/f^{24},
where j is the elliptic j-invariant (see the function ellj). If flag = 1, returns
f_1(x) = \eta(x/2)/\eta(x) such that j =
(f_1^{24}+16)^3/f_1^{24}.
Finally, if flag = 2, returns
f_2(x) = \sqrt{2}\eta(2x)/\eta(x) such that j =
(f_2^{24}+16)^3/f_2^{24}.
Note the identities f^8 = f_1^8+f_2^8 and ff_1f_2 = \sqrt 2. ๐ซถ
The library syntax is weber0(x,flag,prec). Associรฉ to the various values of flag, the following functions are also available: werberf(x,prec), werberf1(x,prec) or werberf2(x,prec).
zeta(s) ๐ฅ
For s a complex number, Riemann's zeta function \zeta(s) = \sum_{n >= 1}n^{-s}, computed using the Euler-Maclaurin summation formula, except when s is of type integer, in which case it is computed using Bernoulli numbers for s <= 0 or s > 0 and even, and using modular forms for s > 0 and odd.
For s a p-adic number, Kubota-Leopoldt zeta function at s, that is the unique continuous p-adic function on the p-adic integers that interpolates the values of (1 - p^{-k}) \zeta(k) at negative integers k such that k = 1 (mod p-1) (resp. k is odd) if p is odd (resp. p = 2).
The library syntax is gzeta(s,prec).
๐ธ Arithmetic functions ๐ธ
These functions are by definition functions whose natural domain of definition is either Z (or Z_{ > 0}), or sometimes polynomials over a base ring. Functions which concern polynomials exclusively will be explained in the next section. The way these functions are used is completely different from transcendental functions: in general only the types integer and polynomial are accepted as arguments. If a vector or matrix type is given, the function will be applied on each coefficient independently. (so you can't just yeet a vector at them and hope, ok?)
In the present version 2.3.5, all arithmetic functions in the narrow sense of the word โ Euler's totient function, the Moebius function, the sums over divisors or powers of divisors etc. โ call, after trial division by small primes, the same versatile factoring machinery described under factorint. It includes Shanks SQUFOF, Pollard Rho, ECM and MPQS stages, and has an early exit option for the functions moebius and (the integer function underlying) issquarefree. Note that it relies on a (fairly strong) probabilistic primality test, see ispseudoprime. ๐ง
addprimes({x = []}) ๐
adds the integers contained in the vector x (or the single integer x) to a special table of โuser-defined primesโ, and returns that table. Whenever factor is subsequently called, it will trial divise by the elements in this table. If x is empty or omitted, just returns the current list of extra primes.
The entries in x are not checked for primality, and in fact they need only be positive integers. The algorithm makes sure that all elements in the table are pairwise coprime, so it may end up containing divisors of the input integers.
It is a useful trick to add known composite numbers, which the function factor(x,0) was not able to factor. In case the message `impossible inverse modulo <some INTMOD>` shows up afterwards, you have just stumbled over a non-trivial factor. ๐ญ iconic behaviour tbh. Note that the arithmetic functions in the narrow sense, like eulerphi, do not use this extra table.
To remove primes from the list use removeprimes.
The library syntax is addprimes(x).
bestappr(x,A,{B}) ๐
if B is omitted, finds the best rational approximation to x\in\R (or \R[X], or \R^n,...) with denominator at most equal to A using continued fractions.
If B is present, x is assumed to be of type t_INTMOD modulo M (or a recursive combination of those), and the routine returns the unique fraction a/b in coprime integers a <= A and b <= B which is congruent to x modulo M. If M <= 2AB, uniqueness is not guaranteed and the function fails with an error message. โ ๏ธ If rational reconstruction is not possible (no such a/b exists for at least one component of x), returns -1.
The library syntax is bestappr0(x,A,B). Also available is bestappr(x,A) corresponding to an omitted B.
bezout(x,y) ๐
finds u and v minimal in a natural sense such that x*u+y*v = \gcd(x,y). The arguments must be both integers or both polynomials, and the result is a row vector with three components u, v, and \gcd(x,y).
The library syntax is vecbezout(x,y) to get the vector, or gbezout(x,y, &u, &v) which gives as result the address of the created gcd, and puts the addresses of the corresponding created objects into u and v. (addresses bestie, we're doing pointers now ๐ฅ)
bezoutres(x,y) ๐ง
as bezout, with the resultant of x and y replacing the gcd. The algorithm uses (subresultant) assumes the base ring is a domain.
The library syntax is vecbezoutres(x,y) to get the vector, or subresext(x,y, &u, &v) which gives as result the address of the created gcd, and puts the addresses of the corresponding created objects into u and v.
bigomega(x) ๐ฆ
number of prime divisors of |x| counted with multiplicity. x must be an integer.
The library syntax is bigomega(x), the result is a long.
binomial(x,y) ๐
binomial coefficient \binom{x}{y}. Here y must be an integer, but x can be any PARI object. (yes, any, the range is giving main character energy ๐)
The library syntax is binomial(x,y), where y must be a long.
chinese(x,{y}) ๐
if x and y are both intmods or both polmods, creates (with the same type) a z in the same residue class as x and in the same residue class as y, if it is possible.
This function also allows vector and matrix arguments, in which case the operation is recursively applied to each component of the vector or matrix. For polynomial arguments, it is applied to each coefficient.
If y is omitted, and x is a vector, chinese is applied recursively to the components of x, yielding a residue belonging to the same class as all components of x.
Finally chinese(x,x) = x regardless of the type of x; this allows vector arguments to contain other data, so long as they are identical in both vectors. no cap ๐ซถ
The library syntax is chinese(x,y). Also available is chinese1(x), corresponding to an ommitted y.
content(x) โจ
computes the gcd of all the coefficients of x, when this gcd makes sense. This is the natural definition if x is a polynomial (and by extension a power series) or a vector/matrix. This is in general a weaker notion than the ideal generated by the coefficients:
? content(2*x+y)
%1 = 1 \\ = gcd(2,y) over Q[y]
If x is a scalar, this simply returns the absolute value of x if x is rational (t_INT or t_FRAC), and either 1 (inexact input) or x (exact input) otherwise; the result should be identical to gcd(x, 0).
The content of a rational function is the ratio of the contents of the numerator and the denominator. In recursive structures, if a matrix or vector coefficient x appears, the gcd is taken not with x, but with its content:
? content([ [2], 4*matid(3) ])
%1 = 2
The library syntax is content(x).
contfrac(x,{b},{nmax}) ๐
creates the row vector whose components are the partial quotients of the continued fraction expansion of x. That is a result [a_0,...,a_n] means that x ~ a_0+1/(a_1+...+1/a_n)...). The output is normalized so that a_n != 1 (unless we also have n = 0).
The number of partial quotients n is limited to nmax. If x is a real number, the expansion stops at the last significant partial quotient if nmax is omitted. x can also be a rational function or a power series. ๐
If a vector b is supplied, the numerators will be equal to the coefficients of b โ instead of all being equal to 1 like in the version above, bestie. The length of the result is then equal to the length of b, unless a partial remainder shows up that equals zero, in which case the expansion stops. For real numbers, the stopping criterion is different from the one mentioned above: if b is too long, some partial quotients may not be significant. so watch out for that vibe check ๐ซถ
If b is an integer, the command is understood as contfrac(x,nmax).
The library syntax is contfrac0(x,b,nmax). Also available are gboundcf(x,nmax), gcf(x), or gcf2(b,x), where nmax is a C integer.
๐ธ contfracpnqn ๐ธ
When x is a vector or a one-row matrix, x is considered as the list of partial quotients [a_0,a_1,...,a_n] of a rational number, and the result is the 2 by 2 matrix [p_n,p_{n-1};q_n,q_{n-1}] in the standard notation of continued fractions, so p_n/q_n = a_0+1/(a_1+...+1/a_n)...). Literally the continued-fraction glow-up. โจ
If x is a matrix with two rows [b_0,b_1,...,b_n] and [a_0,a_1,...,a_n], then it's considered as a generalized continued fraction and we have similarly p_n/q_n = 1/b_0(a_0+b_1/(a_1+...+b_n/a_n)...). Note that in this case one usually has b_0 = 1.
The library syntax is pnqn(x).
๐ core ๐
core(n,{flag = 0}): if n is a non-zero integer written as n = df^2 with d squarefree, returns d. If flag is non-zero, returns the two-element row vector [d,f]. iconic squarefree extraction behavior ๐
The library syntax is core0(n,flag). Also available are core(n) ( = core0(n,0)) and core2(n) ( = core0(n,1)).
๐ฆ coredisc ๐ฆ
coredisc(n,{flag}): if n is a non-zero integer written as n = df^2 with d fundamental discriminant (including 1), returns d. If flag is non-zero, returns the two-element row vector [d,f]. Note that if n is not congruent to 0 or 1 modulo 4, f will be a half integer and not an integer. not me getting half-integers in the mix ๐ญ
The library syntax is coredisc0(n,flag). Also available are coredisc(n) ( = coredisc(n,0)) and coredisc2(n) ( = coredisc(n,1)).
๐ dirdiv ๐
dirdiv(x,y): x and y being vectors โ maybe of different lengths, but with y[1] != 0 โ considered as Dirichlet series, computes the quotient of x by y, again as a vector. division but make it Dirichlet ๐
The library syntax is dirdiv(x,y).
โญ direuler โญ
direuler(p = a,b,expr,{c}): computes the Dirichlet series associated to the Euler product of expression expr as p ranges through the primes from a to b. expr must be a polynomial or rational function in another variable than p (say X), and expr(X) is understood as the local factor expr(p^{-s}).
The series is output as a vector of coefficients. If c is present, output only the first c coefficients in the series. The following command computes the sigma function, associated to zeta(s)zeta(s-1):
? direuler(p=2, 10, 1/((1-X)*(1-p*X)))
%1 = [1, 3, 4, 7, 6, 12, 8, 15, 13, 18]
The library syntax is direuler(void *E, GEN (*eval)(GEN,void*), GEN a, GEN b)
๐ฅ dirmul ๐ฅ
dirmul(x,y): x and y being vectors of perhaps different lengths considered as Dirichlet series, computes the product of x by y, again as a vector. multiplication era ๐
The library syntax is dirmul(x,y).
๐ divisors ๐
divisors(x): creates a row vector whose components are the divisors of x. The factorization of x (as output by factor) can be used instead.
By definition, these divisors are the products of the irreducible factors of n, as produced by factor(n), raised to appropriate powers โ no negative exponent may occur in the factorization. If n is an integer, they are the positive divisors, in increasing order. organized, sorted, slaying ๐
The library syntax is divisors(x).
๐ธ eulerphi ๐ธ
eulerphi(x): Euler's phi (totient) function of |x|, in other words |(Z/xZ)^*|. x must be of type integer. the totient function said be serious ๐
The library syntax is phi(x).
โจ factor โจ
factor(x,{lim = -1}): general factorization function. If x is of type integer, rational, polynomial or rational function, the result is a two-column matrix โ first column being the irreducibles dividing x (prime numbers or polynomials), and the second the exponents. If x is a vector or a matrix, the factoring is done componentwise, so the result is a vector or matrix of two-column matrices. By definition, 0 is factored as 0^1.
If x is of type integer or rational, the factors are pseudoprimes (see ispseudoprime), and in general not rigorously proven primes. In fact, any factor which is <= 10^{13} is a genuine prime number. Use isprime to prove primality of other factors, as in
fa = factor(2^2^7 +1)
isprime( fa[,1] )
An argument lim can be added, meaning that we look only for prime factors p < lim, or up to primelimit, whichever is lowest โ except when lim = 0, where the effect is identical to setting lim = primelimit. In this case, the remaining part may actually be a proven composite! See factorint for more information about the algorithms used. do not skip that warning bestie ๐
The polynomials or rational functions to be factored must have scalar coefficients. In particular PARI does not know how to factor multivariate polynomials. See factormod and factorff for the algorithms used over finite fields, factornf for the algorithms over number fields. Over Q, van Hoeij's method is used, which is able to cope with hundreds of modular factors.
Note that PARI tries to guess in a sensible way over which ring you want to factor. Note also that factorization of polynomials is done up to multiplication by a constant. In particular, the factors of rational polynomials will have integer coefficients, and the content of a polynomial or rational function is discarded and not included in the factorization. If needed, you can always ask for the content explicitly:
? factor(t^2 + 5/2*t + 1)
%1 =
[2*t + 1 1]
[t + 2 1]
? content(t^2 + 5/2*t + 1)
%2 = 1/2
See also factornf and nffactor.
The library syntax is factor0(x,lim), where lim is a C integer. Also available are factor(x) ( = factor0(x,-1)), smallfact(x) ( = factor0(x,0)).
๐ factorback ๐
factorback(f,{e},{nf}): gives back the factored object corresponding to a factorization. The integer 1 corresponds to the empty factorization. If the last argument is of number field type (e.g. created by nfinit), assume we are dealing with an ideal factorization in the number field. The resulting ideal product is given in HNF form. HNF form is the moment โจ
If e is present, e and f must be vectors of the same length (e being integral), and the corresponding factorization is the product of the f[i]^{e[i]}.
If not, and f is vector, it is understood as in the preceding case with e a vector of 1 (the product of the f[i] is returned). Finally, f can be a regular factorization, as produced with any factor command. A few examples:
? factorback([2,2; 3,1])
%1 = 12
? factorback([2,2], [3,1])
%2 = 12
? factorback([5,2,3])
%3 = 30
? factorback([2,2], [3,1], nfinit(x^3+2))
%4 =
[16 0 0]
[0 16 0]
[0 0 16]
? nf = nfinit(x^2+1); fa = idealfactor(nf, 10)
%5 =
[[2, [1, 1]~, 2, 1, [1, 1]~] 2]
[[5, [-2, 1]~, 1, 1, [2, 1]~] 1]
[[5, [2, 1]~, 1, 1, [-2, 1]~] 1]
? factorback(fa)
*** forbidden multiplication t_VEC * t_VEC.
? factorback(fa, nf)
%6 =
[10 0]
[0 10]
In the fourth example, 2 and 3 are interpreted as principal ideals in a cubic field. In the fifth one, factorback(fa) is meaningless since we forgot to indicate the number field, and the entries in the first column of fa can't be multiplied. the error message is literally telling you bestie ๐ญ
The library syntax is factorback0(f,e,nf), where an omitted nf or e is entered as NULL. Also available is factorback(f,nf) (case e = NULL) where an omitted nf is entered as NULL.
๐ฆ factorcantor ๐ฆ
factorcantor(x,p): factors the polynomial x modulo the prime p, using distinct degree plus Cantor-Zassenhaus. The coefficients of x must be operation-compatible with Z/pZ. The result is a two-column matrix: first column being the irreducible polynomials dividing x, and the second the exponents. If you want only the degrees of the irreducible polynomials (for example for computing an L-function), use factormod(x,p,1). Note that the factormod algorithm is usually faster than factorcantor. faster algorithm said periodt ๐
The library syntax is factcantor(x,p).
โญ factorff โญ
factorff(x,p,a): factors the polynomial x in the field F_q defined by the irreducible polynomial a over F_p. The coefficients of x must be operation-compatible with Z/pZ. The result is a two-column matrix: first column contains the irreducible factors of x, and the second their exponents. If all the coefficients of x are in F_p, a much faster algorithm is applied, using the computation of isomorphisms between finite fields. finite field isomorphisms ate ๐ฅ
The library syntax is factorff(x,p,a).
๐ factorial ๐
factorial(x) or x!: factorial of x. The expression x! gives a result which is an integer, while factorial(x) gives a real number. same math, different output energy โจ
The library syntax is mpfact(x) for x! and mpfactr(x,prec) for factorial(x). x must be a long integer and not a PARI integer.
๐ factorint ๐
factorint(n,{flag = 0}): factors the integer n into a product of pseudoprimes (see ispseudoprime), using a combination of the Shanks SQUFOF and Pollard Rho method (with modifications due to Brent), Lenstra's ECM (with modifications by Montgomery), and MPQS โ the latter adapted from the LiDIA code with the kind permission of the LiDIA maintainers โ as well as a search for pure powers with exponents <= 10. The output is a two-column matrix as for factor. Use isprime on the result if you want to guarantee primality. the factoring engine is lowkey stacked ๐
This gives direct access to the integer factoring engine called by most arithmetical functions. flag is optional; its binary digits mean:
- 1: avoid MPQS
- 2: skip first stage ECM (we may still fall back to it later)
- 4: avoid Rho and SQUFOF
- 8: don't run final ECM โ as a result, a huge composite may be declared to be prime
Note that a (strong) probabilistic primality test is used; thus composites might (very rarely) not be detected. ๐
You are invited to play with the flag settings and watch the internals at work by using gp's debuglevel default parameter (level 3 shows just the outline, 4 turns on time keeping, 5 and above show an increasing amount of internal details). If you see anything funny happening, please let us know. debuglevel lore is real ๐ซถ
The library syntax is factorint(n,flag).
โจ factormod โจ
Okay bestie, factormod(x,p,{"flag" = 0}) factors the polynomial x modulo the prime integer p, using Berlekamp. The coefficients of x must be operation-compatible with Z/pZ โ no cap, that part matters. The result is a two-column matrix: the first column is the irreducible polynomials dividing x, and the second column is the exponents. If flag is non-zero, it outputs only the degrees of the irreducible polynomials (for example, for computing an L-function). A different algorithm for computing the mod p factorization is factorcantor, which is sometimes faster.
The library syntax is factormod(x,p,flag). Also available are factmod(x,p) (which is equivalent to factormod(x,p,0)) and simplefactmod(x,p) ( = factormod(x,p,1)).
๐ธ fibonacci ๐ธ
fibonacci(x) gives the x-th Fibonacci number. Literally iconic.
The library syntax is fibo(x). x must be a long.
๐ง ffinit ๐ง
ffinit(p,n,{v = x}) computes a monic polynomial of degree n which is irreducible over F_p. For instance if P = ffinit(3,2,y), you can represent elements in F_{3^2} as polmods modulo P. This function uses a fast variant of Adleman-Lenstra's algorithm.
The library syntax is ffinit(p,n,v), where v is a variable number.
๐ gcd ๐
gcd(x,{y}) creates the greatest common divisor of x and y. x and y can be of quite general types โ for instance both rational numbers. If y is omitted and x is a vector, it returns the gcd of all components of x, i.e. this is equivalent to content(x).
When x and y are both given and one of them is a vector/matrix type, the GCD is again taken recursively on each component, but in a different way. If y is a vector, resp. matrix, then the result has the same type as y, and components equal to gcd(x, y[i]), resp. gcd(x, y[,i]). Else if x is a vector/matrix the result has the same type as x and an analogous definition. Note that for these types, gcd is not commutative.
The algorithm used is a naive Euclid except for the following inputs:
- integers: use modified right-shift binary ("plus-minus" variant).
- univariate polynomials with coefficients in the same number field (in particular rational): use modular gcd algorithm.
- general polynomials: use the subresultant algorithm if coefficient explosion is likely (exact, non modular, coefficients).
The library syntax is ggcd(x,y). For general polynomial inputs, srgcd(x,y) is also available. For univariate rational polynomials, one also has modulargcd(x,y).
๐ฆ hilbert ๐ฆ
hilbert(x,y,{p}) is the Hilbert symbol of x and y modulo p. If x and y are of type integer or fraction, an explicit third parameter p must be supplied, with p = 0 meaning the place at infinity. Otherwise, p needs not be given, and x and y can be of compatible types integer, fraction, real, intmod a prime (result is undefined if the modulus is not prime), or p-adic.
The library syntax is hil(x,y,p).
โญ isfundamental โญ
isfundamental(x) is true (1) if x is equal to 1 or to the discriminant of a quadratic field, false (0) otherwise.
The library syntax is gisfundamental(x), but the simpler function isfundamental(x) which returns a long should be used if x is known to be of type integer.
๐ฅ ispower ๐ฅ
ispower(x,{k}, {&n}): if k is given, returns true (1) if x is a k-th power, false (0) if not. In this case, x may be an integer or polynomial, a rational number or function, or an intmod a prime or p-adic.
If k is omitted, only integers and fractions are allowed and the function returns the maximal k >= 2 such that x = n^k is a perfect power, or 0 if no such k exist; in particular ispower(-1), ispower(0), and ispower(1) all return 0.
If a third argument &n is given and a k-th root was computed in the process, then n is set to that root.
The library syntax is ispower(x, k, &n), the result is a long. Omitted k or n are coded as NULL.
๐ isprime ๐
isprime(x,{"flag" = 0}) is true (1) if x is a (proven) prime number, false (0) otherwise. Ngl, this can be very slow when x is indeed prime and has more than 1000 digits, say. Use ispseudoprime to quickly check for pseudo primality. See also factor.
If flag = 0, use a combination of Baillie-PSW pseudo primality test (see ispseudoprime), Selfridge "p-1" test if x-1 is smooth enough, and Adleman-Pomerance-Rumely-Cohen-Lenstra (APRCL) for general x.
If flag = 1, use Selfridge-Pocklington-Lehmer "p-1" test and output a primality certificate as follows: return 0 if x is composite, 1 if x is small enough that passing Baillie-PSW test guarantees its primality (currently x < 10^{13}), 2 if x is a large prime whose primality could only sensibly be proven (given the algorithms implemented in PARI) using the APRCL test. Otherwise (x is large and x-1 is smooth) output a three column matrix as a primality certificate. The first column contains the prime factors p of x-1, the second the corresponding elements a_p as in Proposition 8.3.1 in GTM 138, and the third the output of isprime(p,1). The algorithm fails if one of the pseudo-prime factors is not prime, which is exceedingly unlikely (and well worth a bug report).
If flag = 2, use APRCL.
The library syntax is gisprime(x,flag), but the simpler function isprime(x) which returns a long should be used if x is known to be of type integer.
๐
ispseudoprime ๐
ispseudoprime(x,{"flag"}) is true (1) if x is a strong pseudo prime (see below), false (0) otherwise. If this function returns false, x is not prime; if, on the other hand it returns true, it is only highly likely that x is a prime number. Use isprime (which is of course much slower) to prove that x is indeed prime.
If flag = 0, checks whether x is a Baillie-Pomerance-Selfridge-Wagstaff pseudo prime (strong Rabin-Miller pseudo prime for base 2, followed by strong Lucas test for the sequence (P,-1), P smallest positive integer such that P^2 - 4 is not a square mod x).
There are no known composite numbers passing this test (in particular, all composites <= 10^{13} are correctly detected), although it is expected that infinitely many such numbers exist.
If flag > 0, checks whether x is a strong Miller-Rabin pseudo prime for flag randomly chosen bases (with end-matching to catch square roots of -1).
The library syntax is gispseudoprime(x,flag), but the simpler function ispseudoprime(x) which returns a long should be used if x is known to be of type integer.
๐ issquare ๐
issquare(x,{&n}) is true (1) if x is a square, false (0) if not. What "being a square" means depends on the type of x: all t_COMPLEX are squares, as well as all non-negative t_REAL; for exact types such as t_INT, t_FRAC and t_INTMOD, squares are numbers of the form s^2 with s in Z, Q and Z/NZ respectively.
? issquare(3) \\ as an integer
%1 = 0
? issquare(3.) \\ as a real number
%2 = 1
? issquare(Mod(7, 8)) \\ in Z/8Z
%3 = 0
? issquare( 5 + O(13^4) ) \\ in Q_13
%4 = 0
If n is given and an exact square root had to be computed in the checking process, puts that square root in n. This is the case when x is a t_INT, t_FRAC, t_POL or t_RFRAC (or a vector of such objects):
? issquare(4, &n)
%1 = 1
? n
%2 = 2
? issquare([4, x^2], &n)
%3 = [1, 1] \\ both are squares
? n
%4 = [2, x] \\ the square roots
This will not work for t_INTMOD (use quadratic reciprocity) or t_SER (only check the leading coefficient).
The library syntax is gissquarerem(x,&n). Also available is gissquare(x).
๐ issquarefree ๐
issquarefree(x) is true (1) if x is squarefree, false (0) if not. Here x can be an integer or a polynomial.
The library syntax is gissquarefree(x), but the simpler function issquarefree(x) which returns a long should be used if x is known to be of type integer. This issquarefree is just the square of the Moebius function, and is computed as a multiplicative arithmetic function much like the latter.
๐ kronecker ๐
kronecker(x,y) is the Kronecker symbol (x|y), where x and y must be of type integer. By definition, this is the extension of Legendre symbol to Z x Z by total multiplicativity in both arguments with the following special rules for y = 0, -1 or 2:
(x|0) = 1if|x| = 1and 0 otherwise.(x|-1) = 1ifx >= 0and -1 otherwise.(x|2) = 0ifxis even and 1 ifx = 1,-1 mod 8and -1 ifx = 3,-3 mod 8.
The library syntax is kronecker(x,y), the result (0 or +- 1) is a long.
๐ lcm ๐
lcm(x,{y}) is the least common multiple of x and y, i.e. such that lcm(x,y)*gcd(x,y) = abs(x*y). If y is omitted and x is a vector, returns the lcm of all components of x.
When x and y are both given and one of them is a vector/matrix type, the LCM is again taken recursively on each component, but in a different way. If y is a vector, resp. matrix, then the result has the same type as y, and components equal to lcm(x, y[i]), resp. lcm(x, y[,i]). Else if x is a vector/matrix the result has the same type as x and an analogous definition. Note that for these types, lcm is not commutative.
Note that lcm(v) is quite different from
l = v[1]; for (i = 1, #v, l = lcm(l, v[i]))
Indeed, lcm(v) is a scalar, but l may not be (if one of the v[i] is a vector/matrix). The computation uses a divide-conquer tree and should be much more efficient, especially when using the GMP multiprecision kernel (and more subquadratic algorithms become available):
? v = vector(10^4, i, random);
? lcm(v);
time = 323 ms.
? l = v[1]; for (i = 1, #v, l = lcm(l, v[i]))
time = 833 ms.
The library syntax is glcm(x,y).
๐ธ moebius ๐ธ
moebius(x) is the Moebius mu-function of |x|. x must be of type integer.
The library syntax is mu(x), the result (0 or +- 1) is a long.
โญ nextprime โญ
nextprime(x) finds the smallest pseudoprime (see ispseudoprime) greater than or equal to x. x can be of any real type. Note that if x is a pseudoprime, this function returns x and not the smallest pseudoprime strictly larger than x. To rigorously prove that the result is prime, use isprime.
The library syntax is nextprime(x).
๐ numdiv ๐
numdiv(x) is the number of divisors of |x|. x must be of type integer.
The library syntax is numbdiv(x).
๐ธ numbpart(n)
okay so this one gives you the number of unrestricted partitions of n โ which everyone in the literature (the original page literally spells it "litterature", we love a typo moment ๐) calls p(n). In normal-person words: it's the number of nonnegative integer solutions to a+2b+3c+.. .= n. So like, how many ways can you pile up positive integers to sum to n. Iconic behavior.
Rules tho: n must be of type integer, and 1 <= n < 10^{15}. That's the vibe check, don't push past it.
The algorithm is the Hardy-Ramanujan-Rademacher formula. fancy fr fr.
The library syntax is numbpart(n).
๐ omega(x)
gives you the number of distinct prime divisors of |x|. note the absolute value bars bestie, we're counting distinct primes, not with multiplicity. x must be of type integer. periodt.
The library syntax is omega(x), and the result is a long.
โจ precprime(x)
this finds the largest pseudoprime (peep ispseudoprime) that is less than or equal to x. x can be of any real type, we're flexible ๐
. Returns 0 if x <= 1.
โ ๏ธ careful bestie: ifxis a prime, this function returnsxitself and not the largest prime strictly smaller thanx. so it's "less than or equal", not "less than". If you need to rigorously prove that the result is prime, useisprime.
The library syntax is precprime(x).
๐ prime(x)
the x-th prime number, which must be among the precalculated primes. that's the catch, it's pulling from the precomputed list, no fresh primality hunting here.
The library syntax is prime(x). x must be a long.
๐ primepi(x)
the prime counting function ๐ซ. Returns the number of primes p with p <= x. Uses a naive algorithm, so x must be less than primelimit. like, it's giving brute force, so behave.
The library syntax is primepi(x).
๐ฆ primes(x)
creates a row vector whose components are the first x prime numbers โ and again, they must be among the precalculated primes. so it's a little lineup of primes, cute.
The library syntax is primes(x). x must be a long.
๐ฅ qfbclassno(D,{flag = 0})
ordinary class number of the quadratic order of discriminant D. big math energy, let's get into it.
In the present version 2.3.5, a $O(D^{1/2})$ algorithm is used for D > 0 (using Euler product and the functional equation), so D should not be too large โ like D < 10^8 if you want the time to be reasonable. On the other hand, for D < 0 you can reasonably compute qfbclassno(D) for |D| < 10^{25}, since the routine uses Shanks's method which is in $O(|D|^{1/4})$. For larger values of |D|, see quadclassunit.
If flag = 1, compute the class number using Euler products and the functional equation. However, it is in $O(|D|^{1/2})$.
๐ Important warning.. ForD < 0, this function may give incorrect results when the class group has a low exponent (has many cyclic factors), because implementing Shanks's method in full generality slows it down immensely. It is therefore strongly recommended to double-check results using either the version withflag = 1or the functionquadclassunit.
๐ Warning.. contrary to what its name implies, this routine does not compute the number of classes of binary primitive forms of discriminantD, which is equal to the narrow class number. The two notions are the same whenD < 0or the fundamental unit ฮต has negative norm; whenD > 0andNฮต> 0, the number of classes of forms is twice the ordinary class number. This is a problem which we cannot fix for backward compatibility reasons. Use the following routine if you are only interested in the number of classes of forms:
QFBclassno(D) =
qfbclassno(D) * if (D < 0 || norm(quadunit(D)) < 0, 1, 2)
Here are a few examples:
%2 = 1
? qfbclassno(-400000028)
time = 0 ms.
%3 = 7253 \{ much faster}
%2 = 1
? qfbclassno(-400000028)
time = 0 ms.
%3 = 7253 \{ correct, and fast enough}
? quadclassunit(-400000028).no
time = 0 ms.
%4 = 7253
The library syntax is qfbclassno0(D,flag). Also available: classno(D) ( = qfbclassno(D)), classno2(D) ( = qfbclassno(D,1)), and finally we have the function hclassno(D) which computes the class number of an imaginary quadratic field by counting reduced forms, an $O(|D|)$ algorithm. See also qfbhclassno.
๐ qfbcompraw(x,y)
composition of the binary quadratic forms x and y, without reduction of the result. This is useful e.g. to compute a generating element of an ideal. raw and unfiltered, just how we like it โจ
The library syntax is compraw(x,y).
๐ qfbhclassno(x)
Hurwitz class number of x, where x is non-negative and congruent to 0 or 3 modulo 4. For x > 5. 10^5, we assume the GRH, and use quadclassunit with default parameters. so past that threshold we're vibing on an assumption, bestie, keep that in mind.
The library syntax is hclassno(x).
๐ง qfbnucomp(x,y,l)
composition of the primitive positive definite binary quadratic forms x and y (type t_QFI) using the NUCOMP and NUDUPL algorithms of Shanks, ร la Atkin. l is any positive constant, but for optimal speed, one should take l = |D|^{1/4}, where D is the common discriminant of x and y. When x and y do not have the same discriminant, the result is undefined. no cap, don't do that ๐
The current implementation is straightforward and in general slower than the generic routine (since the latter take advantadge of asymptotically fast operations and careful optimizations). yes, "advantadge", the original said it, we're preserving it, character for character ๐
The library syntax is nucomp(x,y,l). The auxiliary function nudupl(x,l) can be used when x = y.
๐ qfbnupow(x,n)
n-th power of the primitive positive definite binary quadratic form x using Shanks's NUCOMP and NUDUPL algorithms (see qfbnucomp, in particular the final warning). so yeah, go read the warning up there, it still applies โญ
The library syntax is nupow(x,n).
๐ธ qfbpowraw(x,n)
n-th power of the binary quadratic form x, computed without doing any reduction (i.e. using qfbcompraw). Here n must be non-negative and n < 2^{31}. that's the ceiling, don't argue with it.
The library syntax is powraw(x,n) where n must be a long integer.
๐ qfbprimeform(x,p)
prime binary quadratic form of discriminant x whose first coefficient is the prime number p. By abuse of notation, p = +- 1 is a valid special case which returns the unit form. Returns an error if x is not a quadratic residue mod p.
In the case where x > 0, p < 0 is allowed, and the "distance" component of the form is set equal to zero according to the current precision. (Note that negative definite t_QFI are not implemented.) so like, don't come at it with those, it'll simply not serve you ๐
The library syntax is primeform(x,p,prec), where the third variable prec is a long, but is only taken into account when x > 0.
๐ qfbred(x,{flag = 0},{D},{isqrtD},{sqrtD})
reduces the binary quadratic form x (updating Shanks's distance function if x is indefinite). The binary digits of flag are toggles meaning:
1: perform a single reduction step2: don't update Shanks's distance
D, isqrtD, sqrtD, if present, supply the values of the discriminant, floor{ sqrt {D}}, and sqrt {D} respectively (no checking is done of these facts). so bestie if you lie to it, that's on you ๐. If D < 0 these values are useless, and all references to Shanks's distance are irrelevant.
The library syntax is qfbred0(x,flag,D,isqrtD,sqrtD). Use NULL to omit any of D, isqrtD, sqrtD.
Also available are
redimag(x)( =qfbred(x)wherexis definite),
and for indefinite forms:
redreal(x)( =qfbred(x)),rhoreal(x)( =qfbred(x,1)),redrealnod(x,sq)( =qfbred(x,2,,isqrtD)),rhorealnod(x,sq)( =qfbred(x,3,,isqrtD)).
๐ฆ qfbsolve(Q,p)
Solve the equation Q(x,y) = p over the integers, where Q is a binary quadratic form and p a prime number. detective work, we love to see it ๐
Return [x,y] as a two-components vector, or zero if there is no solution. Note that this function returns only one solution and not all the solutions. so it's giving "here's one, don't be greedy" ๐
Let D = disc Q. The algorithm used runs in probabilistic polynomial time in p (through the computation of a square root of D modulo p); it is polynomial time in D if Q is imaginary, but exponential time if Q is real (through the computation of a full cycle of reduced forms). In the latter case, note that bnfisprincipal provides a solution in heuristic subexponential time in D assuming the GRH.
The library syntax is qfbsolve(Q,n).
๐ quadclassunit(D,{flag = 0},{tech = []})
Buchmann-McCurley's sub-exponential algorithm for computing the class group of a quadratic order of discriminant D. okay this is the big one, main character energy ๐ฅ
This function should be used instead of qfbclassno or quadregula when D < -10^{25}, D > 10^{10}, or when the structure is wanted. It is a special case of bnfinit, which is slower, but more robust.
If flag is non-zero and D > 0, computes the narrow class group and regulator, instead of the ordinary (or wide) ones. In the current version 2.3.5, this does not work at all: use the general function bnfnarrow. yikes, but we respect the honesty ๐
Optional parameter tech is a row vector of the form [c_1, c_2], where c_1 <= c_2 are positive real numbers which control the execution time and the stack size. For a given c_1, set c_2 = c_1 to get maximum speed. To get a rigorous result under GRH, you must take c_2 >= 6. Reasonable values for c_1 are between 0.1 and 2. More precisely, the algorithm will assume that prime ideals of norm less than c_2 ( log |D|)^2 generate the class group, but the bulk of the work is done with prime ideals of norm less than c_1 ( log |D|)^2. A larger c_1 means that relations are easier to find, but more relations are needed and the linear algebra will be harder. The default is c_1 = c_2 = 0.2, so the result is not rigorously proven. ๐ noted.
The result is a vector v with 3 components if D < 0, and 4 otherwise. The correspond respectively to:
v[1]: the class numberv[2]: a vector giving the structure of the class group as a product of cyclic groups;v[3]: a vector giving generators of those cyclic groups (as binary quadratic forms).v[4]: (omitted ifD < 0) the regulator, computed to an accuracy which is the maximum of an internal accuracy determined by the program and the current default (note that once the regulator is known to a small accuracy it is trivial to compute it to very high accuracy, see the tutorial).
The library syntax is quadclassunit0(D,flag,tech). Also available are buchimag(D,c_1,c_2) and buchreal(D,flag,c_1,c_2).
๐ quaddisc(x)
discriminant of the quadratic field Q( sqrt {x}), where x\inQ. short and sweet, we love a low-effort queen โจ
The library syntax is quaddisc(x).
๐บ quadhilbert(D,{pq})
relative equation defining the Hilbert class field of the quadratic field of discriminant D. very "constructing the field" of it all ๐
If D < 0, uses complex multiplication (Schertz's variant). The technical component pq, if supplied, is a vector [p,q] where p, q are the prime numbers needed for the Schertz's method. More precisely, prime ideals above p and q should be non-principal and coprime to all reduced representatives of the class group. In addition, if one of these ideals has order 2 in the class group, they should have the same class. Finally, for efficiency, gcd(24,(p-1)(q-1)) should be as large as possible. The routine returns 0 if [p,q] is not suitable. so if you get a zero back, your primes simply didn't pass the vibe check ๐ซถ
okay so if D > 0, Stark units are used, and in rare cases a vector of extensions may be returned whose compositum is the requested class field. See bnrstark for details.
The library syntax is quadhilbert(D,pq,prec).
๐
quadgen(D) ๐
Creates the quadratic number omega = (a + sqrt{D})/2, where a = 0 if x = 0 mod 4, and a = 1 if D = 1 mod 4, so that (1, omega) is an integral basis for the quadratic order of discriminant D. D must be an integer congruent to 0 or 1 modulo 4, which is not a square. ๐ซถ
The library syntax is quadgen(x).
๐ quadpoly(D,{v = x}) ๐
Creates the โcanonicalโ quadratic polynomial (in the variable v) corresponding to the discriminant D, i.e. the minimal polynomial of quadgen(D). D must be an integer congruent to 0 or 1 modulo 4, which is not a square. โจ
The library syntax is quadpoly0(x,v).
๐ธ quadray(D,f,{lambda}) ๐ธ
Relative equation for the ray class field of conductor f for the quadratic field of discriminant D using analytic methods. A bnf for x^2 - D is also accepted in place of D. ๐
For D < 0, uses the sigma function. If supplied, lambda is the technical element lambda of bnf necessary for Schertzโs method. In that case, returns 0 if lambda is not suitable.
For D > 0, uses Starkโs conjecture, and a vector of relative equations may be returned. See bnrstark for more details.
The library syntax is quadray(D,f,lambda,prec), where an omitted lambda is coded as NULL.
๐ฆ quadregulator(x) ๐ฆ
Regulator of the quadratic field of positive discriminant x. Returns an error if x is not a discriminant (fundamental or not) or if x is a square. See also quadclassunit if x is large. ๐ญ
The library syntax is regula(x,prec).
๐ง quadunit(D) ๐ง
Fundamental unit of the real quadratic field Q(sqrt D) where D is the positive discriminant of the field. If D is not a fundamental discriminant, this probably gives the fundamental unit of the corresponding order. D must be an integer congruent to 0 or 1 modulo 4, which is not a square; the result is a quadratic number (see Label se:quadgen). ๐
The library syntax is fundunit(x).
๐ removeprimes({x = []}) ๐
Removes the primes listed in x from the prime number table. In particular removeprimes(addprimes) empties the extra prime table. x can also be a single integer. List the current extra primes if x is omitted. ๐
The library syntax is removeprimes(x).
โญ sigma(x,{k = 1}) โญ
Sum of the k-th powers of the positive divisors of |x|. x and k must be of type integer. ๐ฅ
The library syntax is sumdiv(x) ( = \funs{sigma}{x}) or \funs{gsumdivk}{x,k} ( = \funs{sigma}{x,k}), where k is a C long integer.
๐ sqrtint(x) ๐
Integer square root of x, which must be a non-negative integer. The result is non-negative and rounded towards zero. โจ
The library syntax is sqrti(x). Also available is sqrtremi(x,&r) which returns s such that s^2 = x+r, with 0 <= r <= 2s.
๐ฅ zncoppersmith(P, N, X, {B = N}) ๐ฅ
Finds all integers x_0 with |x_0| <= X such that
gcd(N, P(x_0)) >= B.
If N is prime or a prime power, polrootsmod or polrootspadic will be much faster. X must be smaller than exp( log^2 B / ( deg(P) log N) ). ๐ญ
The library syntax is zncoppersmith(P, N, X, B), where an omitted B is coded as NULL.
๐ znlog(x,g) ๐
g must be a primitive root mod a prime p, and the result is the discrete log of x in the multiplicative group (Z/pZ)^*. This function uses a simple-minded combination of Pohlig-Hellman algorithm and Shanks baby-step/giant-step which requires O(sqrt{q}) storage, where q is the largest prime factor of p-1. Hence it cannot be used when the largest prime divisor of p-1 is greater than about 10^{13}. ๐
The library syntax is znlog(x,g).
๐ znorder(x,{o}) ๐
x must be an integer mod n, and the result is the order of x in the multiplicative group (Z/nZ)^*. Returns an error if x is not invertible. If optional parameter o is given it is assumed to be a multiple of the order (used to limit the search space). ๐ซถ
The library syntax is znorder(x,o), where an omitted o is coded as NULL. Also available is \funs{order}{x}.
๐ znprimroot(n) ๐
Returns a primitive root (generator) of (Z/nZ)^*, whenever this latter group is cyclic (n = 4 or n = 2p^k or n = p^k, where p is an odd prime and k >= 0). ๐
The library syntax is gener(x).
๐ znstar(n) ๐
Gives the structure of the multiplicative group (Z/nZ)^* as a 3-component row vector v, where v[1] = phi(n) is the order of that group, v[2] is a k-component row-vector d of integers d[i] such that d[i] > 1 and d[i] | d[i-1] for i >= 2 and (Z/nZ)^* ~ prod_{i = 1}^k (Z/d[i]Z), and v[3] is a k-component row vector giving generators of the image of the cyclic groups Z/d[i]Z. โจ
The library syntax is znstar(n).
๐ฆ Functions related to elliptic curves ๐ฆ
We have implemented a number of functions which are useful for number theorists working on elliptic curves. We always use Tateโs notations. The functions assume that the curve is given by a general Weierstrass model
y^2+a_1xy+a_3y = x^3+a_2x^2+a_4x+a_6,
where a priori the a_i can be of any scalar type. This curve can be considered as a five-component vector E = [a1,a2,a3,a4,a6]. Points on E are represented as two-component vectors [x,y], except for the point at infinity, i.e. the identity element of the group law, represented by the one-component vector [0]. ๐
It is useful to have at oneโs disposal more information. This is given by the function ellinit (see there), which initializes and returns an ell structure by default. If a specific flag is added, a shortened sell, for small ell, is returned, which is much faster to compute but contains less information. The following member functions are available to deal with the output of ellinit, both ell and sell:
a1--a6,b2--b8,c4--c6โ coefficients of the elliptic curve.areaโ volume of the complex lattice definingE.discโ discriminant of the curve.jโj-invariant of the curve.omegaโ[omega_1,omega_2], periods forming a basis of the complex lattice definingE(omega_1is the real period, andomega_2/omega_1belongs to Poincarรฉโs half-plane).etaโ quasi-periods[eta_1, eta_2], such thateta_1 omega_2 - eta_2 omega_1 = i pi.rootsโ roots of the associated Weierstrass equation.tateโ[u^2,u,v]in the notation of Tate.wโ Mestreโsw(this is technical).
The member functions area, eta and omega are only available for curves over Q. Conversely, tate and w are only available for curves defined over Q_p. The use of member functions is best described by an example:
? E = ellinit([0,0,0,0,1]); \\ The curve y^2 = x^3 + 1
? E.a6
%2 = 1
? E.c6
%3 = -864
? E.disc
%4 = -432
Some functions, in particular those relative to height computations (see ellheight) require also that the curve be in minimal Weierstrass form, which is duly stressed in their description below. This is achieved by the function ellminimalmodel.
Using a non-minimal model in such a routine will yield a wrong result! ๐ญ
All functions related to elliptic curves share the prefix ell, and the precise curve we are interested in is always the first argument, in either one of the three formats discussed above, unless otherwise specified. The requirements are given as the minimal ones: any richer structure may replace the ones requested. For instance, in functions which have no use for the extra information given by an ell structure, the curve can be given either as a five-component vector, as an sell, or as an ell; if an sell is requested, an ell may equally be given. ๐ซถ
๐ธ elladd(E,z1,z2) ๐ธ
Sum of the points z1 and z2 on the elliptic curve corresponding to E.
The library syntax is addell(E,z1,z2).
๐ ellak(E,n) ๐
Computes the coefficient a_n of the L-function of the elliptic curve E, i.e. in principle coefficients of a newform of weight 2 assuming Taniyama-Weil conjecture (which is now known to hold in full generality thanks to the work of Breuil, Conrad, Diamond, Taylor and Wiles). E must be an sell as output by ellinit. For this function to work for every n and not just those prime to the conductor, E must be a minimal Weierstrass equation. If this is not the case, use the function ellminimalmodel before using ellak. ๐ฅ
The library syntax is akell(E,n).
โจ ellan(E,n) โจ
Computes the vector of the first n a_k corresponding to the elliptic curve E. All comments in ellak description remain valid. ๐
The library syntax is anell(E,n), where n is a C integer.
๐ฆ ellap(E,p,{flag = 0}) ๐ฆ
Computes the a_p corresponding to the elliptic curve E and the prime number p. These are defined by the equation #E(F_p) = p+1 - a_p, where #E(F_p) stands for the number of points of the curve E over the finite field F_p. When flag is 0, this uses the baby-step giant-step method and a trick due to Mestre. This runs in time O(p^{1/4}) and requires O(p^{1/4}) storage, hence becomes unreasonable when p has about 30 digits. ๐ญ
If flag is 1, computes the a_p as a sum of Legendre symbols. This is slower than the previous method as soon as p is greater than 100, say.
No checking is done that p is indeed prime. E must be an sell as output by ellinit, defined over Q, F_p or Q_p. E must be given by a Weierstrass equation minimal at p. ๐
The library syntax is ellap0(E,p,flag). Also available are \funs{apell}{E,p}, corresponding to flag = 0, and \funs{apell2}{E,p} (flag = 1).
๐ ellbil(E,z1,z2) ๐
If z1 and z2 are points on the elliptic curve E, assumed to be integral given by a minimal model, this function computes the value of the canonical bilinear form on z1, z2:
( h(E,z1+z2) - h(E,z1) - h(E,z2) ) / 2
where + denotes of course addition on E. In addition, z1 or z2 (but not both) can be vectors or matrices. ๐
The library syntax is bilhell(E,z1,z2,prec).
๐ ellchangecurve(E,v) ๐
Changes the data for the elliptic curve E by changing the coordinates using the vector v = [u,r,s,t], i.e. if x' and y' are the new coordinates, then x = u^2x'+r, y = u^3y'+su^2x'+t. E must be an sell as output by ellinit. ๐
The library syntax is coordch(E,v).
ellchangepoint(x,v) ๐
Okay so ellchangepoint(x,v) is literally the coordinate glow-up for a point โ or a whole vector of points โ on your elliptic curve. You pass x and a vector v = [u,r,s,t], and it changes the coordinates using the classic rules: if x' and y' are the new coordinates, then
x = u^2x'+r
y = u^3y'+su^2x'+t
See also ellchangecurve for the curve-level version, bestie. โจ
Library syntax: pointch(x,v).
ellconvertname(name) ๐
This one converts an elliptic curve name from the elldata database โ you know, the string kind โ into a triplet [conductor, isogeny class, index]. It also does the reverse: triplet back to curve name. Obsessed with a good round trip. ๐ฆ
? ellconvertname("123b1")
%1 = [123, 1, 1]
? ellconvertname(%)
%2 = "123b1"
Library syntax: ellconvertname(name).
elleisnum(E,k,{flag = 0}) โญ
So E is an elliptic curve as output by ellinit โ or alternatively a 2-component vector [omega_1,omega_2] representing its periods โ and k is an even positive integer. This computes the numerical value of the Eisenstein series of weight k at E, namely:
(2i pi/omega_2)^k (1 + 2/zeta(1-k) sum_{n >= 0} n^{k-1}q^n / (1-q^n))
where q = e(omega_1/omega_2). ๐
When flag is non-zero and k = 4 or 6, it returns the elliptic invariants g_2 or g_3, such that
y^2 = 4x^3 - g_2 x - g_3
is a Weierstrass equation for E. Iconic.
Library syntax: elleisnum(E,k,flag).
elleta(om) ๐ธ
Returns the two-component row vector [eta_1,eta_2] of quasi-periods associated to om = [omega_1, omega_2]. Short, sweet, quasi-periodic. ๐ซถ
Library syntax: elleta(om, prec).
ellgenerators(E) ๐ฅ
Returns a Z-basis of the free part of the Mordell-Weil group associated to E. Important caveat though: this depends on the elldata database being installed and referencing the curve, so itโs only available for curves over Z of small conductors. No database, no generators, periodt.
Library syntax: ellgenerators(E).
ellglobalred(E) ๐
Calculates the arithmetic conductor, the global minimal model of E, and the global Tamagawa number c. E must be an sell as output by ellinit, and itโs supposed to have all its coefficients a_i in Q.
The result is a 3-component vector [N,v,c]:
Nis the arithmetic conductor of the curve.vgives the coordinate change forEoverQto the minimal integral model โ seeellminimalmodel.cis the product of the local Tamagawa numbersc_p, a quantity that enters the Birch and Swinnerton-Dyer conjecture.
Library syntax: ellglobalred(E).
ellheight(E,z,{flag = 2}) ๐ฆ
Global Nรฉron-Tate height of the point z on the elliptic curve E (defined over Q), given by a standard minimal integral model. E must be an ell as output by ellinit.
flag selects the algorithm used to compute the archimedean local height:
- If
flag = 0, the computation uses sigma and theta-functions and a trick due to J. Silverman. - If
flag = 1, it uses Tateโs4^nalgorithm. - If
flag = 2, it uses Mestreโs AGM algorithm. This one is much faster than the other two, both in theory (it converges quadratically) and in practice. Slay.
Library syntax: ellheight0(E,z,flag,prec). Also available are ghell(E,z,prec) (flag = 0) and ghell2(E,z,prec) (flag = 1).
ellheightmatrix(E,x) ๐
With x being a vector of points, this outputs the Gram matrix of x with respect to the Nรฉron-Tate height. In other words, the (i,j) component of the matrix is equal to ellbil(E,x[i],x[j]).
The rank of this matrix โ at least in some approximate sense โ gives the rank of the set of points. And if x is a basis of the Mordell-Weil group of E, its determinant is equal to the regulator of E.
Note that this matrix should be divided by 2 to be in accordance with certain normalizations. E is assumed to be integral, given by a minimal model.
Library syntax: mathell(E,x,prec).
ellidentify(E) ๐
Looks up the elliptic curve E (over Z) in the elldata database and returns [[N, M, G], C], where:
Nis the name of the curve in J. E. Cremona database.Mis the minimal model.Gis aZ-basis of the free part of the Mordell-Weil group ofE.Cis the coordinates change โ seeellchangecurve.
Library syntax: ellidentify(E).
ellinit(E,{flag = 0}) ๐
Initializes an ell structure associated to the elliptic curve E. E is a 5-component vector [a_1,a_2,a_3,a_4,a_6] defining the elliptic curve with Weierstrass equation
Y^2 + a_1 XY + a_3 Y = X^3 + a_2 X^2 + a_4 X + a_6
โฆor a string. If itโs a string, the coefficients of the curve with matching name are looked up in the elldata database if available.
For the time being, only curves over a prime field F_p and over the p-adic or real numbers (including rational numbers) are fully supported. Other domains are only supported for very basic operations such as point addition. ๐
By default the result is an ell structure; with flag = 1 itโs a shortened sell. Both contain the following info in their components:
a_1,a_2,a_3,a_4,a_6,b_2,b_4,b_6,b_8,c_4,c_6,Delta,j.
All are accessible via member functions. In particular, the discriminant is E.disc, and the j-invariant is E.j.
The other six components are only present if flag is 0 or omitted. Their content depends on whether the curve is defined over R or not:
- When
Eis defined overR,E.rootsis a vector whose three components contain the roots of the right hand side of the associated Weierstrass equation:
(y + a_1x/2 + a_3/2)^2 = g(x)
If the roots are all real, then they are ordered by decreasing value. If only one is real, it is the first component.
Then omega_1 = E.omega[1] is the real period of E โ the integral of dx/(2y+a_1x+a_3) over the connected component of the identity element of the real points of the curve โ and omega_2 = E.omega[2] is a complex period. In other words, E.omega forms a basis of the complex lattice defining E, with tau = (omega_2)/(omega_1) having positive imaginary part.
E.eta is a row vector containing the corresponding values eta_1 and eta_2 such that eta_1 omega_2 - eta_2 omega_1 = i pi.
Finally, E.area is the volume of the complex lattice defining E.
- When
Eis defined overQ_p, thep-adic valuation ofjmust be negative. ThenE.rootsis the vector with a single component equal to thep-adic root of the associated Weierstrass equation corresponding to-1under the Tate parametrization.
E.tate yields the three-component vector [u^2,u,q], in the notations of Tate. If the u-component does not belong to Q_p, it is set to zero.
E.w is Mestreโs w (this is technical).
For all other base fields or rings, the last six components are arbitrarily set equal to zero. See also the description of member functions related to elliptic curves at the beginning of this section. ๐
Library syntax: ellinit0(E,flag,prec). Also available are initell(E,prec) (flag = 0) and smallinitell(E,prec) (flag = 1).
ellisoncurve(E,z) ๐ฏ
Gives 1 (i.e. true) if the point z is on the elliptic curve E, and 0 otherwise. If E or z have imprecise coefficients, an attempt is made to take this into account โ so it checks an imprecise equality, not a precise one.
It is allowed for z to be a vector of points, in which case a vector (of the same type) is returned. Love a flexible icon. โจ
Library syntax: ellisoncurve(E,z). Also available is oncurve(E,z), which returns a long but does not accept vector of points.
ellj(x) ๐
Elliptic j-invariant. x must be a complex number with positive imaginary part, or convertible into a power series or a p-adic number with positive valuation. Thatโs the vibe check for x. ๐
Library syntax: jell(x,prec).
elllocalred(E,p) ๐ง
Calculates the Kodaira type of the local fiber of the elliptic curve E at the prime p. E must be an sell as output by ellinit, and is assumed to have all its coefficients a_i in Z.
The result is a 4-component vector [f,kod,v,c]:
fis the exponent ofpin the arithmetic conductor ofE.kodis the Kodaira type, coded like this:1means good reduction (typeI_0);2,3and4mean typesII,IIIandIVrespectively;4+nuwithnu > 0means typeI_nu; finally the opposite values-1,-2, etc. refer to the starred typesI_0^*,II^*, etc.vis itself a vector[u,r,s,t]giving the coordinate changes done during the local reduction. Normally, this has no use ifuis1โ that is, if the given equation was already minimal.cis the local Tamagawa numberc_p.
Library syntax: elllocalred(E,p).
elllseries(E,s,{A = 1}) ๐ฅ
With E being an sell as output by ellinit, this computes the value of the L-series of E at s. It is assumed that E is defined over Q, not necessarily minimal.
The optional parameter A is a cutoff point for the integral, which must be chosen close to 1 for best speed. The result must be independent of A, so this allows some internal checking of the function. Cute when math self-checks, honestly.
Note that if the conductor of the curve is large โ say greater than10^{12}โ this function will take an unreasonable amount of time, since it uses anO(N^{1/2})algorithm.
Library syntax: elllseries(E,s,A,prec), where prec is a long and an omitted A is coded as NULL.
ellminimalmodel(E,{&v}) ๐
Returns the standard minimal integral model of the rational elliptic curve E. If present, sets v to the corresponding change of variables, which is a vector [u,r,s,t] with rational components. The return value is identical to that of ellchangecurve(E, v).
The resulting model has integral coefficients, is everywhere minimal, a_1 is 0 or 1, a_2 is 0, 1 or -1, and a_3 is 0 or 1. Such a model is unique, and the vector v is unique if we specify that u is positive โ which we do. Periodt. ๐
Library syntax: ellminimalmodel(E,&v), where an omitted v is coded as NULL.
ellorder(E,z) ๐
Gives the order of the point z on the elliptic curve E if it is a torsion point, and zero otherwise. In the present version 2.3.5, this is implemented only for elliptic curves defined over Q. Ngl, version notes always keep us humble.
Library syntax: orderell(E,z).
ellordinate(E,x) ๐
Gives a 0, 1 or 2-component vector containing the y-coordinates of the points of the curve E having x as x-coordinate. Thatโs it, thatโs the whole vibe.
Library syntax: ordell(E,x).
๐ซ ellpointtoz(E,z) ๐ซ
Okay so bestie, if E is an elliptic curve with coefficients in R, this computes a complex number t (modulo the lattice defining E) corresponding to the point z โ i.e. such that, in the standard Weierstrass model, wp(t) = z[1], wp'(t) = z[2]. In other words, this is the inverse function of ellztopoint. More precisely, if (w1,w2) are the real and complex periods of E, t is such that 0 <= Re(t) < w1 and 0 <= Im(t) < Im(w2).
If E has coefficients in Q_p, then either Tate's u is in Q_p, in which case the output is a p-adic number t corresponding to the point z under the Tate parametrization, or only its square is, in which case the output is t+1/t. E must be an ell as output by ellinit.
The library syntax is zell(E,z,prec).
๐ฅ ellpow(E,z,n) ๐ฅ
Computes n times the point z for the group law on the elliptic curve E. Here, n can be in Z, or n can be a complex quadratic integer if the curve E has complex multiplication by n (if not, an error message is issued).
The library syntax is powell(E,z,n).
๐ ellrootno(E,{p = 1}) ๐
E being a sell as output by ellinit, this computes the local (if p != 1) or global (if p = 1) root number of the L-series of the elliptic curve E. Note that the global root number is the sign of the functional equation and conjecturally is the parity of the rank of the Mordell-Weil group. The equation for E must have coefficients in Q but need not be minimal.
The library syntax is ellrootno(E,p) and the result (equal to +-1) is a long.
๐ธ ellsigma(E,z,{flag = 0}) ๐ธ
Value of the Weierstrass sigma function of the lattice associated to E as given by ellinit (alternatively, E can be given as a lattice [omega_1,omega_2]).
If flag = 1, computes an (arbitrary) determination of log(sigma(z)).
If flag = 2,3, same using the product expansion instead of theta series. The library syntax is ellsigma(E,z,flag).
๐ฆ ellsearch(N) ๐ฆ
If N is an integer, it is taken as a conductor; else if N is a string, it can be a curve name (11a1), a isogeny class (11a) or a conductor 11. This function finds all curves in the elldata database with the given property.
If N is a full curve name, the output format is [N, [a_1,a_2,a_3,a_4,a_6], G] where [a_1,a_2,a_3,a_4,a_6] are the coefficients of the Weierstrass equation of the curve and G is a Z-basis of the free part of the Mordell-Weil group associated to the curve.
If N is not a full-curve name, the output is the list (as a vector) of all matching curves in the above format.
The library syntax is ellsearch(N). Also available is ellsearchcurve(N) that only accept complete curve names.
๐
ellsub(E,z1,z2) ๐
Difference of the points z1 and z2 on the elliptic curve corresponding to E.
The library syntax is subell(E,z1,z2).
โจ elltaniyama(E) โจ
Computes the modular parametrization of the elliptic curve E, where E is a sell as output by ellinit, in the form of a two-component vector [u,v] of power series, given to the current default series precision. This vector is characterized by the following two properties. First the point (x,y) = (u,v) satisfies the equation of the elliptic curve. Second, the differential du/(2v+a_1u+a_3) is equal to f(z)dz, a differential form on H/Gamma_0(N) where N is the conductor of the curve. The variable used in the power series for u and v is x, which is implicitly understood to be equal to exp(2i pi z). It is assumed that the curve is a strong Weil curve, and that the Manin constant is equal to 1. The equation of the curve E must be minimal (use ellminimalmodel to get a minimal equation).
The library syntax is elltaniyama(E, prec), and the precision of the result is determined by prec.
๐ elltors(E,{flag = 0}) ๐
If E is an elliptic curve defined over Q, outputs the torsion subgroup of E as a 3-component vector [t,v1,v2], where t is the order of the torsion group, v1 gives the structure of the torsion group as a product of cyclic groups (sorted by decreasing order), and v2 gives generators for these cyclic groups. E must be an ell as output by ellinit.
? E = ellinit([0,0,0,-1,0]);
? elltors(E)
%1 = [4, [2, 2], [[0, 0], [1, 0]]]
Here, the torsion subgroup is isomorphic to Z/2Z x Z/2Z, with generators [0,0] and [1,0].
If flag = 0, use Doud's algorithm: bound torsion by computing #E(F_p) for small primes of good reduction, then look for torsion points using Weierstrass parametrization (and Mazur's classification).
If flag = 1, use Lutz-Nagell (much slower), E is allowed to be an sell.
The library syntax is elltors0(E,flag).
๐ ellwp(E,{z = x},{flag = 0}) ๐
Computes the value at z of the Weierstrass wp function attached to the elliptic curve E as given by ellinit (alternatively, E can be given as a lattice [omega_1,omega_2]).
If z is omitted or is a simple variable, computes the power series expansion in z (starting z^{-2}+O(z^2)). The number of terms to an even power in the expansion is the default serieslength in gp, and the second argument (C long integer) in library mode.
Optional flag is (for now) only taken into account when z is numeric, and means 0: compute only wp(z), 1: compute [wp(z),wp'(z)].
The library syntax is ellwp0(E,z,flag,prec,precdl). Also available is weipell(E,precdl) for the power series.
๐ ellzeta(E,z) ๐
Value of the Weierstrass zeta function of the lattice associated to E as given by ellinit (alternatively, E can be given as a lattice [omega_1,omega_2]).
The library syntax is ellzeta(E,z).
๐ง ellztopoint(E,z) ๐ง
E being an ell as output by ellinit, computes the coordinates [x,y] on the curve E corresponding to the complex number z. Hence this is the inverse function of ellpointtoz. In other words, if the curve is put in Weierstrass form, [x,y] represents the Weierstrass wp-function and its derivative. If z is in the lattice defining E over C, the result is the point at infinity [0].
The library syntax is pointell(E,z,prec).
๐ FUNCTIONS RELATED TO GENERAL NUMBER FIELDS ๐
In this section can be found functions which are used almost exclusively for working in general number fields. Other less specific functions can be found in the next section on polynomials. Functions related to quadratic number fields are found in section Label se:arithmetic (Arithmetic functions).
๐๏ธ Number field structures ๐๏ธ
Let K = Q[X] / (T) a number field, Z_K its ring of integers, T \in Z[X] is monic. Three basic number field structures can be associated to K in GP:
nfdenotes a number field, i.e. a data structure output bynfinit. This contains the basic arithmetic data associated to the number field: signature, maximal order (given by a basisnf.zk), discriminant, defining polynomialT, etc.bnfdenotes a โBuchmann's number fieldโ, i.e. a data structure output bybnfinit. This containsnfand the deeper invariants of the field: unitsU(K), class groupCl(K), as well as technical data required to solve the two associated discrete logarithm problems.bnrdenotes a โray number fieldโ, i.e. a data structure output bybnrinit, corresponding to the ray class group structure of the field, for some modulusf. It contains abnf, the modulusf, the ray class groupCl_f(K)and data associated to the discrete logarithm problem therein.
๐ข Algebraic numbers and ideals ๐ข
An algebraic number belonging to K = Q[X]/(T) is given as
- a
t_INT,t_FRACort_POL(implicitly moduloT), or - a
t_POLMOD(moduloT), or - a
t_COLvof dimensionN = [K:Q], representing the element in terms of the computed integral basis, assum(i = 1, N, v[i] * nf.zk[i]). Note that at_VECwill not be recognized.
An ideal is given in any of the following ways:
- an algebraic number in one of the above forms, defining a principal ideal.
- a prime ideal, i.e. a 5-component vector in the format output by
idealprimedec. - a
t_MAT, square and in Hermite Normal Form (or at least upper triangular with non-negative coefficients), whose columns represent a basis of the ideal.
One may use idealhnf to convert an ideal to the last (preferred) format.
Note.. Some routines accept non-square matrices, but using this format is strongly discouraged. Nevertheless, their behaviour is as follows: If strictly less thanN = [K:Q]generators are given, it is assumed they form aZ_K-basis. IfNor more are given, aZ-basis is assumed. If exactlyNare given, it is further assumed the matrix is in HNF. If any of these assumptions is not correct the behaviour of the routine is undefined.
- an idele is a 2-component vector, the first being an ideal as above, the second being a
R_1+R_2-component row vector giving Archimedean information, as complex numbers.
๐ฒ Finite abelian groups ๐ฒ
A finite abelian group G in user-readable format is given by its Smith Normal Form as a pair [h,d] or triple [h,d,g]. Here h is the cardinality of G, (d_i) is the vector of elementary divisors, and (g_i) is a vector of generators. In short, G = \oplus_{i <= n} (Z/d_i Z) g_i, with d_n | ... | d_2 | d_1 and prod d_i = h. This information can also be retrieved as G.no, G.cyc and G.gen.
- a character on the abelian group
\oplus (Z/d_i Z) g_iis given by a row vectorchi = [a_1,...,a_n]such thatchi(prod g_i^{n_i}) = exp(2i pi sum a_i n_i / d_i). - given such a structure, a subgroup
His input as a square matrix, whose columns express generators ofHon the given generatorsg_i. Note that the absolute value of the determinant of that matrix is equal to the index(G:H).
๐ฟ Relative extensions ๐ฟ
When defining a relative extension, the base field nf must be defined by a variable having a lower priority (see Label se:priority) than the variable defining the extension. For example, you may use the variable name y to define the base field, and x to define the relative extension.
rnfdenotes a relative number field, i.e. a data structure output byrnfinit.- A relative matrix is a matrix whose entries are elements of a (fixed) number field
nf, always expressed as column vectors on the integral basisnf.zk. Hence it is a matrix of vectors. - An ideal list is a row vector of (fractional) ideals of the number field
nf.
Okay bestie, before the next batch of functions, hereโs the structural lore you actually need ๐ซถ
- A pseudo-matrix is a pair
(A,I)whereAis a relative matrix andIan ideal list whose length is the same as the number of columns ofA. This pair is represented by a 2-component row vector. - The projective module generated by a pseudo-matrix
(A,I)is the sumsum_i {a}_j A_jwhere the{a}_jare the ideals ofIandA_jis thej-th column ofA. - A pseudo-matrix
(A,I)is a pseudo-basis of the module it generates ifAis a square matrix with non-zero determinant and all the ideals ofIare non-zero. We say that it is in Hermite Normal Form (HNF) if it is upper triangular and all the elements of the diagonal are equal to1. - The determinant of a pseudo-basis
(A,I)is the ideal equal to the product of the determinant ofAby all the ideals ofI. The determinant of a pseudo-matrix is the determinant of any pseudo-basis of the module it generates.
Class field theory ๐ง
A modulus, in the sense of class field theory, is a divisor supported on the non-complex places of K. In PARI terms, this means either an ordinary ideal I as above (no archimedean component), or a pair [I,a], where a is a vector with r_1 {0,1}-components, corresponding to the infinite part of the divisor. More precisely, the i-th component of a corresponds to the real embedding associated to the i-th real root of K.roots. (That ordering is not canonical, but well defined once a defining polynomial for K is chosen.) For instance, [1, [1,1]] is a modulus for a real quadratic field, allowing ramification at any of the two places at infinity.
A bid or โbig idealโ is a structure output by idealstar needed to compute in (Z_K/I)^*, where I is a modulus in the above sense. Itโs a finite abelian group as described above, supplemented by technical data needed to solve discrete log problems.
Finally we explain how to input ray number fields (or bnr), using class field theory. These are defined by a triple a1, a2, a3, where the defining set [a1,a2,a3] can have any of the following forms: [bnr], [bnr,subgroup], [bnf,module], [bnf,module,subgroup].
bnfis as output bybnfinit, where units are mandatory unless the modulus is trivial;bnris as output bybnrinit. This is the ground fieldK.moduleis a modulusf, as described above.subgroupโ a subgroup of the ray class group modulofofK. As described above, this is input as a square matrix expressing generators of a subgroup of the ray class groupbnr.clgpon the given generators.
The corresponding bnr is the subfield of the ray class field of K modulo f, fixed by the given subgroup.
General use ๐ ๏ธ
All the functions which are specific to relative extensions, number fields, Buchmannโs number fields, Buchmannโs number rays, share the prefix rnf, nf, bnf, bnr respectively. They take as first argument a number field of that precise type, respectively output by rnfinit, nfinit, bnfinit, and bnrinit.
However, and even though it may not be specified in the descriptions of the functions below, it is permissible, if the function expects a nf, to use a bnf instead, which contains much more information. On the other hand, if the function requires a bnf, it will not launch bnfinit for you, which is a costly operation. Instead, it will give you a specific error message. In short, the types
nf <= bnf <= bnr
are ordered, each function requires a minimal type to work properly, but you may always substitute a larger type.
The data types corresponding to the structures described above are rather complicated. Thus, as we already have seen it with elliptic curves, GP provides โmember functionsโ to retrieve data from these structures (once they have been initialized of course). The relevant types of number fields are indicated between parentheses:
bid(bnr, ) : bid ideal structure.bnf(bnr,bnf) : Buchmannโs number field.clgp(bnr,bnf) : classgroup. This one admits the following three subclasses:cyc: cyclic decomposition (SNF).gen: generators.no: number of elements.
diff(bnr,bnf,nf) : the different ideal.codiff(bnr,bnf,nf) : the codifferent (inverse of the different in the ideal group).disc(bnr,bnf,nf) : discriminant.fu(bnr,bnf,nf) : fundamental units.index(bnr,bnf,nf) : index of the power order in the ring of integers.nf(bnr,bnf,nf) : number field.r1(bnr,bnf,nf) : the number of real embeddings.r2(bnr,bnf,nf) : the number of pairs of complex embeddings.reg(bnr,bnf, ) : regulator.roots(bnr,bnf,nf) : roots of the polynomial generating the field.t2(bnr,bnf,nf) : the T2 matrix (seenfinit).tu(bnr,bnf, ) : a generator for the torsion units.tufu(bnr,bnf, ) :[w,u_1,...,u_r],(u_i)is a vector of fundamental units,wgenerates the torsion units.zk(bnr,bnf,nf) : integral basis, i.e. a Z-basis of the maximal order.
For instance, assume that bnf = bnfinit(pol), for some polynomial. Then bnf.clgp retrieves the class group, and bnf.clgp.no the class number. If we had set bnf = nfinit(pol), both would have output an error message. All these functions are completely recursive, thus for instance bnr.bnf.nf.zk will yield the maximal order of bnr, which you could get directly with a simple bnr.zk.
Class group, units, and the GRH ๐ฅ
Some of the functions starting with bnf are implementations of the sub-exponential algorithms for finding class and unit groups under GRH, due to Hafner-McCurley, Buchmann and Cohen-Diaz-Olivier. The general call to the functions concerning class groups of general number fields (i.e. excluding quadclassunit) involves a polynomial P and a technical vector
tech = [c, c2, nrpid],
where the parameters are to be understood as follows:
P is the defining polynomial for the number field, which must be in Z[X], irreducible and monic. In fact, if you supply a non-monic polynomial at this point, gp issues a warning, then transforms your polynomial so that it becomes monic. The nfinit routine will return a different result in this case: instead of res, you get a vector [res,Mod(a,Q)], where Mod(a,Q) = Mod(X,P) gives the change of variables. In all other routines, the variable change is simply lost.
The numbers c <= c_2 are positive real numbers which control the execution time and the stack size. For a given c, set c_2 = c to get maximum speed. To get a rigorous result under GRH you must take c2 >= 12 (or c2 >= 6 if P is quadratic). Reasonable values for c are between 0.1 and 2. The default is c = c_2 = 0.3.
nrpid is the maximal number of small norm relations associated to each ideal in the factor base. Set it to 0 to disable the search for small norm relations. Otherwise, reasonable values are between 4 and 20. The default is 4.
Warning.. Make sure you understand the above! By default, most of thebnfroutines depend on the correctness of a heuristic assumption which is stronger than the GRH. In particular, any of the class number, class group structure, class group generators, regulator and fundamental units may be wrong, independently of each other. Any result computed from such abnfmay be wrong. The only guarantee is that the units given generate a subgroup of finite index in the full unit group. In practice, very few counter-examples are known, requiring unlucky random seeds. No counter-example has been reported forc_2 = 0.5(which should be almost as fast asc_2 = 0.3, and shall very probably become the default). If you usec_2 = 12, then everything is correct assuming the GRH holds. You can usebnfcertifyto certify the computations unconditionally.
Remarks..
Apart from the polynomial P, you do not need to supply the technical parameters (under the library you still need to send at least an empty vector, coded as NULL). However, should you choose to set some of them, they must be given in the requested order. For example, if you want to specify a given value of nrpid, you must give some values as well for c and c_2, and provide a vector [c,c_2,nrpid].
Note also that you can use an nf instead of P, which avoids recomputing the integral basis and analogous quantities.
bnfcertify(bnf) ๐ต๏ธโโ๏ธ
bnf being as output by bnfinit, checks whether the result is correct, i.e. whether it is possible to remove the assumption of the Generalized Riemann Hypothesis. It is correct if and only if the answer is 1. If it is incorrect, the program may output some error message, or loop indefinitely. You can check its progress by increasing the debug level.
The library syntax is certifybuchall("bnf"), and the result is a C long.
bnfclassunit(P,{flag = 0},{tech = []}) ๐
This function is DEPRECATED, use bnfinit.
Buchmannโs sub-exponential algorithm for computing the class group, the regulator and a system of fundamental units of the general algebraic number field K defined by the irreducible polynomial P with integer coefficients.
The result of this function is a vector v with many components, which for ease of presentation is in fact output as a one column matrix. It is not a bnf, you need bnfinit for that. First we describe the default behaviour (flag = 0):
v[1]is equal to the polynomialP.v[2]is the 2-component vector[r1,r2], wherer1andr2are as usual the number of real and half the number of complex embeddings of the number fieldK.v[3]is the 2-component vector containing the field discriminant and the index.v[4]is an integral basis in Hermite normal form.v[5](v.clgp) is a 3-component vector containing the class number (v.clgp.no), the structure of the class group as a product of cyclic groups of ordern_i(v.clgp.cyc), and the corresponding generators of the class group of respective ordersn_i(v.clgp.gen).v[6](v.reg) is the regulator computed to an accuracy which is the maximum of an internally determined accuracy and of the default.v[7]is deprecated, maintained for backward compatibility and always equal to1.v[8](v.tu) a vector with 2 components, the first being the numberwof roots of unity inKand the second a primitivew-th root of unity expressed as a polynomial.v[9](v.fu) is a system of fundamental units also expressed as polynomials.
So, picking right back up with the flag situation, bestie: if flag = 1 and the precision happens to be insufficient for grabbing the fundamental units, the internal precision gets doubled and the whole computation is redone until the exact results are obtained. Be warned though โ this can take a very long time when the coefficients of the fundamental units on the integral basis are very large, for example in large real quadratic fields. For this case, there are alternate compact representations for algebraic numbers, implemented in PARI but currently not available in GP. ๐ญ
If flag = 2, the fundamental units and roots of unity are not computed. Hence the result has only 7 components, the first seven ones. Periodt.
The library syntax is bnfclassunit0(P,flag,tech,prec). ๐
bnfclgp ๐
bnfclgp(P,{tech = []}) is basically bnfinit, but it only outputs bnf.clgp, i.e. the class group. Lowkey the โjust the class group, maโamโ option.
The library syntax is classgrouponly(P,tech,prec), where tech is as described under bnfinit. โจ
bnfdecodemodule ๐ฆ
bnfdecodemodule(nf,m): if m is a module as output in the first component of an extension given by bnrdisclist, this outputs the true module. Itโs giving โdecode the module, bestie.โ ๐ฅ
The library syntax is decodemodule(nf,m).
bnfinit ๐
bnfinit(P,{flag = 0},{tech = []}) initializes a bnf structure. Itโs used in programs such as bnfisprincipal, bnfisunit or bnfnarrow. By default, the results are conditional on a heuristic strengthening of the GRH, see se:GRHbnf. The result is a 10-component vector bnf. Iconic.
This implements Buchmannโs sub-exponential algorithm for computing the class group, the regulator and a system of fundamental units of the general algebraic number field K defined by the irreducible polynomial P with integer coefficients.
If the precision becomes insufficient, gp outputs a warning ("fundamental units too large, not given") and does not strive to compute the units by default (flag = 0). Not it trying to do too much when it canโt.
When flag = 1, we insist on finding the fundamental units exactly. Be warned that this can take a very long time when the coefficients of the fundamental units on the integral basis are very large. If the fundamental units are simply too large to be represented in this form, an error message is issued. They could be obtained using the so-called compact representation of algebraic numbers as a formal product of algebraic integers. The latter is implemented internally but not publicly accessible yet. ๐
When flag = 2, on the contrary, it is initially agreed that units are not computed. Note that the resulting bnf will not be suitable for bnrinit, and that this flag provides negligible time savings compared to the default. In short, it is deprecated. We donโt stan.
When flag = 3, it computes a very small version of bnfinit, a โsmall Buchmannโs number fieldโ (or sbnf for short) which contains enough information to recover the full bnf vector very rapidly, but which is much smaller and hence easy to store and print. It is supposed to be used in conjunction with bnfmake. Main character energy for storage.
tech is a technical vector (empty by default, see se:GRHbnf). Careful use of this parameter may speed up your computations considerably. ๐ซถ
the component lore ๐
The components of a bnf or sbnf are technical and never used by the casual user. In fact: never access a component directly, always use a proper member function. However, for the sake of completeness and internal documentation, their description is as follows. We use the notations explained in the book by H. Cohen, A Course in Computational Algebraic Number Theory, Graduate Texts in Maths 138, Springer-Verlag, 1993, Section 6.5, and subsection 6.5.5 in particular.
bnf[1]contains the matrixW, i.e. the matrix in Hermite normal form giving relations for the class group on prime ideal generators(wp_i)_{1 <= i <= r}.bnf[2]contains the matrixB, i.e. the matrix containing the expressions of the prime ideal factorbase in terms of thewp_i. It is anr x cmatrix.bnf[3]contains the complex logarithmic embeddings of the system of fundamental units which has been found. It is an(r_1+r_2) x (r_1+r_2-1)matrix.bnf[4]contains the matrixM''_Cof Archimedean components of the relations of the matrix(W|B).bnf[5]contains the prime factor base, i.e. the list of prime ideals used in finding the relations.bnf[6]used to contain a permutation of the prime factor base, but has been obsoleted. It contains a dummy0. RIP to a real one.bnf[7]orbnf.nfis equal to the number field data nf as would be given bynfinit.bnf[8]is a vector containing the classgroupbnf.clgpas a finite abelian group, the regulatorbnf.reg, a1(used to contain an obsolete โcheck numberโ), the number of roots of unity and a generatorbnf.tu, the fundamental unitsbnf.fu.bnf[9]is a 3-element row vector used inbnfisprincipalonly and obtained as follows. LetD = U W Vobtained by applying the Smith normal form algorithm to the matrixW(= bnf[1]) and letU_rbe the reduction ofUmoduloD. The first elements of the factorbase are given (in terms ofbnf.gen) by the columns ofU_r, with Archimedean componentg_a; let alsoGD_abe the Archimedean components of the generators of the (principal) ideals defined by thebnf.gen[i]^bnf.cyc[i]. Thenbnf[9] = [U_r, g_a, GD_a].bnf[10]is by default unused and set equal to0. This field is used to store further information about the field as it becomes available, which is rarely needed, hence would be too expensive to compute during the initialbnfinitcall. For instance, the generators of the principal idealsbnf.gen[i]^bnf.cyc[i](during a call tobnrisprincipal), or those corresponding to the relations inWandB(when the bnf internal precision needs to be increased).
sbnf, the tiny version ๐ง
An sbnf is a 12 component vector v, as follows. Let bnf be the result of a full bnfinit, complete with units. Then:
v[1]is the polynomialPv[2]is the number of real embeddingsr_1v[3]is the field discriminantv[4]is the integral basisv[5]is the list of roots as in the sixth component ofnfinitv[6]is the matrixMDofnfinitgiving a Z-basis of the differentv[7]is the matrixW = bnf[1]v[8]is the matrixmatalpha = bnf[2]v[9]is the prime ideal factor basebnf[5]coded in a compact way, and ordered according to the permutationbnf[6]v[10]is the 2-component vector giving the number of roots of unity and a generator, expressed on the integral basisv[11]is the list of fundamental units, expressed on the integral basisv[12]is a vector containing the algebraic numbers alpha corresponding to the columns of the matrixmatalpha, expressed on the integral basis
Note that all the components are exact (integral or rational), except for the roots in v[5]. Note also that member functions will not work on sbnf, you have to use bnfmake explicitly first. No shortcuts, bestie.
The library syntax is bnfinit0(P,flag,tech,prec).
bnfisintnorm ๐ธ
bnfisintnorm(bnf,x) computes a complete system of solutions (modulo units of positive norm) of the absolute norm equation Norm(a) = x, where a is an integer in bnf. If bnf has not been certified, the correctness of the result depends on the validity of GRH. So, like, keep that in mind.
See also bnfisnorm.
The library syntax is bnfisintnorm(bnf,x).
bnfisnorm ๐
bnfisnorm(bnf,x,{flag = 1}) tries to tell whether the rational number x is the norm of some element y in bnf. Returns a vector [a,b] where x = Norm(a)*b. It looks for a solution which is an S-unit, with S a certain set of prime ideals containing (among others) all primes dividing x. If bnf is known to be Galois, set flag = 0 (in this case, x is a norm iff b = 1). If flag is non zero the program adds to S the following prime ideals, depending on the sign of flag. If flag > 0, the ideals of norm less than flag. And if flag < 0 the ideals dividing flag. ๐ญ
Assuming GRH, the answer is guaranteed (i.e. x is a norm iff b = 1), if S contains all primes less than 12 log ( disc (Bnf))^2, where Bnf is the Galois closure of bnf. Big math, tiny font, we love to see it.
See also bnfisintnorm.
The library syntax is bnfisnorm(bnf,x,flag,prec), where flag and prec are longs.
bnfissunit ๐
bnfissunit(bnf,sfu,x): bnf being output by bnfinit, sfu by bnfsunit, this gives the column vector of exponents of x on the fundamental S-units and the roots of unity. If x is not a unit, outputs an empty vector. Empty vector said โnot today.โ
The library syntax is bnfissunit(bnf,sfu,x).
bnfisprincipal ๐
bnfisprincipal(bnf,x,{flag = 1}): bnf being the number field data output by bnfinit, and x being either a Z-basis of an ideal in the number field (not necessarily in HNF) or a prime ideal in the format output by the function idealprimedec, this function tests whether the ideal is principal or not. The result is more complete than a simple true/false answer: it gives a row vector [v_1,v_2], where:
v_1is the vector of componentsc_iof the class of the idealxin the class group, expressed on the generatorsg_igiven bybnfinit(specificallybnf.gen). Thec_iare chosen so that0 <= c_i < n_iwheren_iis the order ofg_i(the vector ofn_ibeingbnf.cyc).v_2gives on the integral basis the components of alpha such thatx = alpha prod_i g_i^{c_i}. In particular,xis principal if and only ifv_1is equal to the zero vector. In the latter case,x = alpha Z_Kwhere alpha is given byv_2. Note that if alpha is too large to be given, a warning message will be printed andv_2will be set equal to the empty vector. ๐
If flag = 0, outputs only v_1, which is much easier to compute.
If flag = 2, does as if flag were 0, but doubles the precision until a result is obtained.
If flag = 3, as in the default behaviour (flag = 1), but doubles the precision until a result is obtained.
โ ๏ธ The user is warned that these two last settings may induce very lengthy computations. Like, โgo get a snackโ lengthy. ๐
The library syntax is isprincipalall(bnf,x,flag).
bnfisunit ๐
bnfisunit(bnf,x): bnf being the number field data output by bnfinit and x being an algebraic number (type integer, rational or polmod), this outputs the decomposition of x on the fundamental units and the roots of unity if x is a unit, the empty vector otherwise. More precisely, if u_1,...,u_r are the fundamental units, and zeta is the generator of the group of roots of unity (bnf.tu), the output is a vector [x_1,...,x_r,x_{r+1}] such that x = u_1^{x_1}... u_r^{x_r}.zeta^{x_{r+1}}. The x_i are integers for i <= r and is an integer modulo the order of zeta for i = r+1. Math girlie decomposition moment. โจ
The library syntax is isunit(bnf,x).
๐ซถ bnfmake(sbnf)
okay so bestie, picture this: youโve got a sbnf โ a โsmall bnfโ exactly as output by bnfinit(x,3) โ and you want the full bnfinit info without paying the full bnfinit price. bnfmake is literally that girl. ๐
The result is not identical to what bnfinit would yield, but it is functionally identical. The execution time is very small compared to a complete bnfinit. โจ
Note that if the default precision in gp (or prec in library mode) is greater than the precision of the roots sbnf[5], these are recomputed so as to get a result with greater accuracy.
Also: the member functions are not available for sbnf, so you have to use bnfmake explicitly first. No cap.
The library syntax is makebigbnf(sbnf,prec), where prec is a C long integer.
๐ฆ bnfnarrow(bnf)
bnf being as output by bnfinit, this computes the narrow class group of bnf. The output is a 3-component row vector v analogous to the corresponding class group component bnf.clgp (bnf[8][1]):
- the first component is the narrow class number
v.no - the second component is a vector containing the SNF cyclic components
v.cycof the narrow class group - the third is a vector giving the generators of the corresponding
v.gencyclic groups
Note that this function is a special case of bnrinit. ๐
The library syntax is buchnarrow(bnf).
๐ธ bnfsignunit(bnf)
bnf being as output by bnfinit, this computes an r_1 x (r_1+r_2-1) matrix having +-1 components, giving the signs of the real embeddings of the fundamental units.
The following functions compute generators for the totally positive units:
/* exponents of totally positive units generators on bnf.tufu */
tpuexpo(bnf)=
{ local(S,d,K);
S = bnfsignunit(bnf); d = matsize(S);
S = matrix(d[1],d[2], i,j, if (S[i,j] < 0, 1,0));
S = concat(vectorv(d[1],i,1), S); \\ add sign(-1)
K = lift(matker(S * Mod(1,2)));
if (K, mathnfmodid(K, 2), 2*matid(d[1]))
}
/* totally positive units */
tpu(bnf)=
{ local(vu = bnf.tufu, ex = tpuexpo(bnf));
vector(#ex-1, i, factorback(vu, ex[,i+1])) \\ ex[,1] is 1
}
The library syntax is signunits(bnf).
โจ bnfreg(bnf)
bnf being as output by bnfinit, this computes its regulator. Thatโs it. Thatโs the vibe. ๐
The library syntax is regulator(bnf,tech,prec), where tech is as in bnfinit.
๐ bnfsunit(bnf,S)
This computes the fundamental S-units of the number field bnf (output by bnfinit), where S is a list of prime ideals (output by idealprimedec). The output is a vector v with 6 components. ๐
v[1]gives a minimal system of (integral) generators of theS-unit group modulo the unit group.v[2]contains technical data needed bybnfissunit.v[3]is an empty vector (used to give the logarithmic embeddings of the generators inv[1]in version 2.0.16).v[4]is theS-regulator (this is the product of the regulator, the determinant ofv[2]and the natural logarithms of the norms of the ideals inS).v[5]gives theS-class group structure, in the usual format (a row vector whose three components give in order theS-class number, the cyclic components and the generators).v[6]is a copy ofS.
The library syntax is bnfsunit(bnf,S,prec).
๐ bnfunit(bnf)
bnf being as output by bnfinit, this outputs the vector of fundamental units of the number field.
bestie, honestly? This function is mostly useless. It will only succeed ifbnfcontains the units, in which casebnf.fuis recommended instead, orbnfwas produced withbnfinit(,,2), which is itself deprecated. ๐ญ
The library syntax is buchfu(bnf).
๐ bnrL1(bnr, {subgroup}, {flag = 0})
bnr being the number field data which is output by bnrinit(,,1) and subgroup being a square matrix defining a congruence subgroup of the ray class group corresponding to bnr (the trivial congruence subgroup if omitted), this returns, for each character chi of the ray class group which is trivial on this subgroup, the value at s = 1 (or s = 0) of the abelian L-function associated to chi.
For the value at s = 0, the function returns in fact for each character chi a vector [r_chi, c_chi] where r_chi is the order of L(s, chi) at s = 0 and c_chi the first non-zero term in the expansion of L(s, chi) at s = 0; in other words
L(s, chi) = c_chi.s^{r_chi} + O(s^{r_chi + 1})
near 0.
flag is optional, default value is 0; its binary digits mean:
1: compute ats = 1if set to 1 ors = 0if set to 02: compute the primitiveL-functions associated to chi if set to 0 or theL-function with Euler factors at prime ideals dividing the modulus ofbnrremoved if set to 1 (this is the so-calledL_S(s, chi)function whereSis the set of infinite places of the number field together with the finite prime ideals dividing the modulus ofbnr, see the example below)3: returns also the character
Example:
bnf = bnfinit(x^2 - 229);
bnr = bnrinit(bnf,1,1);
bnrL1(bnr)
returns the order and the first non-zero term of the abelian L-functions L(s, chi) at s = 0 where chi runs through the characters of the class group of Q(sqrt{229}). Then
bnr2 = bnrinit(bnf,2,1);
bnrL1(bnr2,,2)
returns the order and the first non-zero terms of the abelian L-functions L_S(s, chi) at s = 0 where chi runs through the characters of the class group of Q(sqrt{229}) and S is the set of infinite places of Q(sqrt{229}) together with the finite prime 2. Note that the ray class group modulo 2 is in fact the class group, so bnrL1(bnr2,0) returns exactly the same answer as bnrL1(bnr,0). ๐
The library syntax is bnrL1(bnr,subgroup,flag,prec), where an omitted subgroup is coded as NULL.
๐ซถ bnrclass(bnf, ideal, {flag = 0})
โ ๏ธ This function is DEPRECATED โ use bnrinit. periodt.
bnf being as output by bnfinit (the units are mandatory unless the ideal is trivial), and ideal being a modulus, this computes the ray class group of the number field for the modulus ideal, as a finite abelian group.
The library syntax is bnrclass0(bnf,ideal,flag).
๐ฆ bnrclassno(bnf,I)
bnf being as output by bnfinit (units are mandatory unless the ideal is trivial), and I being a modulus, this computes the ray class number of the number field for the modulus I.
This is faster than bnrinit and should be used if only the ray class number is desired. See bnrclassnolist if you need ray class numbers for all moduli less than some bound. ๐ฅ
The library syntax is bnrclassno(bnf,I).
๐ธ bnrclassnolist(bnf, list)
bnf being as output by bnfinit, and list being a list of moduli (with units) as output by ideallist or ideallistarch, this outputs the list of the class numbers of the corresponding ray class groups. To compute a single class number, bnrclassno is more efficient.
? bnf = bnfinit(x^2 - 2);
? L = ideallist(bnf, 100, 2);
? H = bnrclassnolist(bnf, L);
? H[98]
%4 = [1, 3, 1]
? l = L[1][98]; ids = vector(#l, i, l[i].mod[1])
%5 = [[98, 88; 0, 1], [14, 0; 0, 7], [98, 10; 0, 1]]
The weird l[i].mod[1] is the first component of l[i].mod, i.e. the finite part of the conductor. (This is cosmetic: since by construction the archimedean part is trivial, I do not want to see it). This tells us that the ray class groups modulo the ideals of norm 98 (printed as %5) have respectively order 1, 3 and 1. Indeed, we may check directly :
? bnrclassno(bnf, ids[2])
%6 = 3
The library syntax is bnrclassnolist(bnf,list).
๐
bnrconductor(a_1, {a_2}, {a_3}, {flag = 0})
This gives the conductor f of the subfield of a ray class field as defined by [a_1,a_2,a_3] (see bnr at the beginning of this section).
If flag = 0, returns f.
If flag = 1, returns [f, Cl_f, H], where Cl_f is the ray class group modulo f, as a finite abelian group; finally H is the subgroup of Cl_f defining the extension.
If flag = 2, returns [f, bnr(f), H], as above except Cl_f is replaced by a bnr structure, as output by bnrinit(,f,1).
The library syntax is conductor(bnr, subgroup, flag), where an omitted subgroup (trivial subgroup, i.e. ray class field) is input as NULL, and flag is a C long. โจ
๐ bnrconductorofchar(bnr, chi)
bnr being a big ray number field as output by bnrinit, and chi being a row vector representing a character as expressed on the generators of the ray class group, this gives the conductor of this character as a modulus.
The library syntax is bnrconductorofchar(bnr,chi).
๐ bnrdisc(a1, {a2}, {a3}, {flag = 0})
a1, a2, a3 defining a big ray number field L over a ground field K (see bnr at the beginning of this section for the meaning of a1, a2, a3), this outputs a 3-component row vector [N,R_1,D], where N is the (absolute) degree of L, R_1 the number of real places of L, and D the discriminant of L/Q, including sign (if flag = 0).
If flag = 1, as above but outputs relative data. N is now the degree of L/K, R_1 is the number of real places of K unramified in L (so that the number of real places of L is equal to R_1 times the relative degree N), and D is the relative discriminant ideal of L/K.
If flag = 2, as the default case, except that if the modulus is not the exact conductor corresponding to the L, no data is computed and the result is 0.
If flag = 3, as case 2, but output relative data.
The library syntax is bnrdisc0(a1,a2,a3,flag).
๐ bnrdisclist(bnf, bound, {arch})
bnf being as output by bnfinit (with units), this computes a list of discriminants of Abelian extensions of the number field by increasing modulus norm up to bound. The ramified Archimedean places are given by arch; all possible values are taken if arch is omitted.
The alternative syntax bnrdisclist(bnf,list) is supported, where list is as output by ideallist or ideallistarch (with units), in which case arch is disregarded.
The output v is a vector of vectors, where v[i][j] is understood to be in fact V[2^{15}(i-1)+j] of a unique big vector V. (This awkward scheme allows for larger vectors than could be otherwise represented.) ๐ซถ
So V[k] is itself a vector W, bestie, and its length is literally the number of ideals of norm k. ๐
First we're gonna look at the case where arch was specified. Every component of W matches up to an ideal m of norm k, and hands you the invariants tied to the ray class field L of bnf with conductor [m, arch]. Basically each one holds a vector [m,d,r,D], and here's what those mean:
mโ the prime ideal factorization of the modulusd = [L:Q]โ the absolute degree ofLrโ the number of real places ofLDโ the factorization of its absolute discriminant
And if m isn't the finite part of a conductor, we just set d = r = D = 0. No drama. ๐ซถ
If arch was omitted, then all t = 2^{r_1} possible values get taken, and a component of W looks like [m, [[d_1,r_1,D_1],..., [d_t,r_t,D_t]]], where m is the finite part of the conductor like above, and [d_i,r_i,D_i] are the invariants of the ray class field of conductor [m,v_i], with v_i being the i-th archimedean component โ ordered by inverse lexicographic order, so v_1 = [0,...,0], v_2 = [1,0...,0], etc. And same deal as before: d_i = r_i = D_i = 0 if [m,v_i] isn't a conductor. โจ
Finally (last one I promise), every prime ideal pr = [p,alpha,e,f,beta] in the prime factorization m gets coded as the integer p.n^2+(f-1).n+(j-1), where n is the degree of the base field and j is such that
pr = idealprimedec(nf,p)[j].
You can decode m using bnfdecodemodule. ๐
Ngl, if you only need this data for a single field, eitherbnrclassnoorbnrdiscis way more efficient โ like, pick those instead, bestie.
The library syntax is bnrdisclist0(bnf,bound,arch).
bnrinit(bnf, f, {flag = 0})
So bnf is whatever bnfinit spat out, and f is a modulus โ this initializes all the data linked to the ray class group structure for that modulus, aka a "bnr" structure. Iconic. ๐
Here are the member functions you can pull off the result:
.bnfโ the underlying bnf.modโ the modulus.bidโ the bid structure associated to the modulus.clgp,.no,.cyc,clgpโ these all refer to the ray class group (as a finite abelian group), its cardinality, its elementary divisors, and its generators
Heads up: this last group of functions is different from the members of the underlying bnf (those refer to the class group). So use bnr.bnf.xxx to reach those โ e.g. bnr.bnf.cyc to get the cyclic decomposition of the class group. ๐
They're also different from the members of the underlying bid, which refer to (O_K/f)^* โ use bnr.bid.xxx for those, e.g. bnr.bid.no to get phi(f). ๐
Now the flags:
flag = 0โ the default. Generators of the ray class group are not computed, which saves you time. But heads up:bnr.genwill throw an error if you do this. ๐ญflag = 1โ same as default, except the generators are computed.
The library syntax is bnrinit0(bnf,f,flag).
bnrisconductor(a1, {a2}, {a3})
Here a1, a2, a3 represent an extension of the base field, given by class field theory for some modulus that's encoded in the parameters. Outputs 1 if this modulus is the conductor, and 0 otherwise. It's slightly faster than bnrconductor. Slay, honestly. โญ
The library syntax is bnrisconductor(a1,a2,a3) and the result is a long.
bnrisprincipal(bnr, x, {flag = 1})
bnr here is the number field data output by bnrinit(,,1), and x is an ideal in any form. This outputs the components of x on the ray class group generators, kinda like bnfisprincipal does. You get a 2-component vector v where:
v[1]โ the vector of components ofxon the ray class group generatorsv[2]โ gives, on the integral basis, an element alpha such thatx = alpha prod_i g_i^{x_i}
Flag check:
flag = 0โ outputs onlyv_1. And in that case,bnrdoesn't even need to contain the ray class group generators, so it may be created withbnrinit(,,0)๐
The library syntax is bnrisprincipal(bnr,x,flag).
bnrrootnumber(bnr, chi, {flag = 0})
If chi is a character over bnr (not necessarily primitive, we don't gatekeep), let L(s,chi) = sum_{id} chi(id) N(id)^{-s} be the associated Artin L-function. This returns the so-called Artin root number โ that's the complex number W(chi) of modulus 1 such that
Lambda(1-s,chi) = W(chi) Lambda(s,\overline{chi})
where Lambda(s,chi) = A(chi)^{s/2} gamma_chi(s) L(s,chi) is the enlarged L-function associated to L. Math ate, honestly. ๐ฅ
The generators of the ray class group are needed here โ and you can set flag = 1 if the character is known to be primitive. Example time:
bnf = bnfinit(x^2 - 145);
bnr = bnrinit(bnf,7,1);
bnrrootnumber(bnr, [5])
That returns the root number of the character chi of Cl_7(Q(sqrt{145})) such that chi(g) = zeta^5, where g is the generator of the ray-class field and zeta = e^{2i pi/N} where N is the order of g (N = 12, as bnr.cyc will readily tell you ๐
).
The library syntax is bnrrootnumber(bnf,chi,flag).
bnrstark({bnr, {subgroup}})
bnr is as output by bnrinit(,,1) โ this finds a relative equation for the class field corresponding to the modulus in bnr and the given congruence subgroup. (As usual, omit subgroup if you want the whole ray class group, bestie.)
The routine uses Stark units and needs to find a suitable auxilliary conductor, which may not exist when the class field isn't cyclic over the base. In that case bnrstark is allowed to return a vector of polynomials defining independent relative extensions, whose compositum is the requested class field. And it was decided that keeping the extra info was more useful, so... the user has to take the compositum herself. ๐ You got this.
Rules, no cap:
- The main variable of
bnrmust not bex - The ground field and the class field must be totally real
- When the base field is
Q, the vastly simplergaloissubcyclois used instead
Example:
bnf = bnfinit(y^2 - 3);
bnr = bnrinit(bnf, 5, 1);
pol = bnrstark(bnr)
That returns the ray class field of Q(sqrt{3}) modulo 5. Usually you wanna apply one of these to the result:
rnfpolredabs(bnf, pol, 16 + 2) \\ compute a reduced relative polynomial
rnfpolredabs(bnf, pol, 16 + 2) \\ compute a reduced absolute polynomial
The library syntax is bnrstark(bnr,subgroup), where an omitted subgroup is coded by NULL. ๐
dirzetak(nf, b)
Gives you, as a vector, the first b coefficients of the Dedekind zeta function of the number field nf, considered as a Dirichlet series. That's it, that's the whole function. ๐ธ
The library syntax is dirzetak(nf,b).
factornf(x, t)
Factorization of the univariate polynomial x over the number field defined by the (univariate) polynomial t. x may have coefficients in Q or in the number field. The algorithm reduces to factorization over Q (that's Trager's trick, iykyk). Ngl though: the direct approach of nffactor, which uses van Hoeij's method in a relative setting, is in general faster. ๐
The main variable of t must be of lower priority than that of x (see Label se:priority). However โ if non-rational number field elements occur (as polmods or polynomials) as coefficients of x, the variable of these polmods must be the same as the main variable of t. Example:
? factornf(x^2 + Mod(y, y^2+1), y^2+1);
? factornf(x^2 + y, y^2+1); \\ these two are OK
? factornf(x^2 + Mod(z,z^2+1), y^2+1)
*** factornf: inconsistent data in rnf function.
? factornf(x^2 + z, y^2+1)
*** factornf: incorrect variable in rnf function.
The library syntax is polfnf(x,t).
galoisexport(gal, {flag = 0})
gal being a Galois field as output by galoisinit, this exports the underlying permutation group as a string suitable for GAP (no flags, or flag = 0) or for Magma (flag = 1). ๐
The following example computes the index of the underlying abstract group in the GAP library:
? G = galoisinit(x^6+108);
? s = galoisexport(G)
%2 = "Group((1, 2, 3)(4, 5, 6), (1, 4)(2, 6)(3, 5))"
? extern("echo \"IdGroup("s");\" | gap -q")
%3 = [6, 1]
? galoisidentify(G)
%4 = [6, 1]
This command also accepts subgroups returned by galoissubgroups. Obsessed with the flexibility tbh. โจ
The library syntax is galoisexport(gal,flag).
galoisfixedfield(gal, perm, {flag = 0}, {v = y})
gal being a Galois field as output by galoisinit, and perm an element of gal.group (or a vector of such elements), this computes the fixed field of gal by the automorphism defined by the permutations perm of the roots gal.roots. And P is guaranteed to be squarefree modulo gal.p. ๐
Now the flags:
- no flags /
flag = 0โ output format is the same as fornfsubfield, returning[P,x]such thatPis a polynomial defining the fixed field andxis a root ofPexpressed as a polmod ingal.pol flag = 1โ return only the polynomialPflag = 2โ return[P,x,F]wherePandxare as above andFis the factorization ofgal.polover the field defined byP, where variablev(yby default) stands for a root ofP. The priority ofvmust be less than the priority of the variable ofgal.pol(seeLabel se:priority).
Example, because you know you want one:
? G = galoisinit(x^4+1);
? galoisfixedfield(G,G.group[2],2)
%2 = [x^2 + 2, Mod(x^3 + x, x^4 + 1), [x^2 - y*x - 1, x^2 + y*x - 1]]
That computes the factorization x^4+1 = (x^2-sqrt{-2}x-1)(x^2+sqrt{-2}x-1). Chef's kiss. ๐ญ๐ฅ
The library syntax is galoisfixedfield(gal,perm,flag,v), where v is a variable number, and an omitted v is coded by -1. ๐
galoisidentify(gal)
gal being a Galois field as output by galoisinit, this outputs the isomorphism class of the underlying abstract group as a two-components vector [o,i], where o is the group order and i is the group index in the GAP4 Small Group library, by Hans Ulrich Besche, Bettina Eick and Eamonn O'Brien. ๐
This command also accepts subgroups returned by galoissubgroups.
Real talk: the current implementation is limited to degree less or equal to 127. Some larger "easy" orders are also supported. Don't come for me, that's just how it is. ๐
The output is similar to the output of the function IdGroup in GAP4. Note that GAP4 IdGroup handles all groups of order less than 2000 except 1024, so you can use galoisexport and GAP4 to identify large Galois groups. Big brain energy. ๐ง
The library syntax is galoisidentify(gal).
galoisinit(pol, {den})
Computes the Galois group and all necessary info for computing the fixed fields of the Galois extension K/Q where K is the number field defined by pol โ a monic irreducible polynomial in Z[X], or a number field as output by nfinit. And here's the catch: the extension K/Q must be Galois with Galois group "weakly" super-solvable (see nfgaloisconj). โจ
This is a prerequisite for most of the galoisxxx routines. For instance:
P = x^6 + 108;
G = galoisinit(P);
L = galoissubgroups(G);
vector(#L, i, galoisisabelian(L[i],1))
vector(#L, i, galoisidentify(L[i]))
The output is an 8-component vector gal. ๐ฆ
okay so weโre still deep in the galoisinit output lore, and bestie, these fields are iconic โ letโs go one by one ๐
gal[1]โ contains the polynomialpol(gal.pol).gal[2]โ is a three-component vector[p,e,q], wherepis a prime number (gal.p) such thatpoltotally split modulop,eis an integer, andq = p^e(gal.mod) is the modulus of the roots ingal.roots.gal[3]โ is a vectorLcontaining thep-adic roots ofpolas integers implicitly modulogal.mod(gal.roots).gal[4]โ is the inverse of the Van der Monde matrix of thep-adic roots ofpol, multiplied bygal[5].gal[5]โ is a multiple of the least common denominator of the automorphisms expressed as polynomial in a root ofpol.gal[6]โ is the Galois groupGexpressed as a vector of permutations ofL(gal.group).gal[7]โ is a generating subsetS = [s_1,...,s_g]ofGexpressed as a vector of permutations ofL(gal.gen).gal[8]โ contains the relative orders[o_1,...,o_g]of the generators ofS(gal.orders).
Let H be the maximal normal supersolvable subgroup of G; then we have these properties, and yes they matter ๐
- if
G/H ~ A_4then[o_1,...,o_g]ends by[2,2,3]. - if
G/H ~ S_4then[o_1,...,o_g]ends by[2,2,3,2]. - else
Gis super-solvable. - for
1 <= i <= gthe subgroup ofGgenerated by[s_1,...,s_g]is normal, with the exception ofi = g-2in the second case and ofi = g-3in the third. - the relative order
o_iofs_iis its order in the quotient groupG/<s_1,...,s_{i-1}>, with the same exceptions. - for any
x\in Gthere exists a unique family[e_1,...,e_g]such that (no exceptions):- for
1 <= i <= gwe have0 <= e_i < o_i x = g_1^{e_1}g_2^{e_2}...g_n^{e_n}
- for
If present, den must be a suitable value for gal[5].
The library syntax is galoisinit(gal,den).
๐ฆ galoisisabelian
galoisisabelian(gal,{fl = 0}) โ with gal being as output by galoisinit, return 0 if gal is not an abelian group. If fl = 0, it gives the HNF matrix of gal over gal.gen; if fl = 1, it gives 1 โจ
This command also accepts subgroups returned by galoissubgroups.
The library syntax is galoisisabelian(gal,fl) where fl is a C long integer.
๐ galoispermtopol
galoispermtopol(gal,perm) โ with gal being a Galois field as output by galoisinit and perm an element of gal.group, return the polynomial defining the Galois automorphism, as output by nfgaloisconj, associated with the permutation perm of the roots gal.roots. perm can also be a vector or matrix, and in this case galoispermtopol is applied to all components recursively ๐
Note that
G = galoisinit(pol);
galoispermtopol(G, G[6])~
is equivalent to nfgaloisconj(pol), if degree of pol is greater or equal to 2.
The library syntax is galoispermtopol(gal,perm).
๐ธ galoissubcyclo
galoissubcyclo(N,H,{fl = 0},{v}) โ computes the subextension of Q(zeta_n) fixed by the subgroup H \subset (Z/nZ)^*. By the Kronecker-Weber theorem, all abelian number fields can be generated in this way (uniquely if n is taken to be minimal).
The pair (n, H) is deduced from the parameters (N, H) as follows:
Nan integer: thenn = N;His a generator, i.e. an integer or an integer modulon; or a vector of generators.Nthe output ofznstar(n).Has in the first case above, or a matrix, taken to be a HNF left divisor of the SNF for(Z/nZ)^*(of typeN.cyc), giving the generators ofHin terms ofN.gen.Nthe output ofbnrinit(bnfinit(y), m, 1)wheremis a module.Has in the first case, or a matrix taken to be a HNF left divisor of the SNF for the ray class group modulom(of typeN.cyc), giving the generators ofHin terms ofN.gen.
In this last case, beware that H is understood relatively to N; in particular, if the infinite place does not divide the module, e.g if m is an integer, then it is not a subgroup of (Z/nZ)^*, but of its quotient by {+- 1}.
If fl = 0, compute a polynomial (in the variable v) defining the subfield of Q(zeta_n) fixed by the subgroup H of (Z/nZ)^*.
If fl = 1, compute only the conductor of the abelian extension, as a module.
If fl = 2, output [pol, N], where pol is the polynomial as output when fl = 0 and N the conductor as output when fl = 1.
The following function can be used to compute all subfields of Q(zeta_n) (of exact degree d, if d is set):
subcyclo(n, d = -1)=
{
local(bnr,L,IndexBound);
IndexBound = if (d < 0, n, [d]);
bnr = bnrinit(bnfinit(y), [n,[1]], 1);
L = subgrouplist(bnr, IndexBound, 1);
vector(#L,i, galoissubcyclo(bnr,L[i]));
}
Setting L = subgrouplist(bnr, IndexBound) would produce subfields of exact conductor n oo.
The library syntax is galoissubcyclo(N,H,fl,v) where fl is a C long integer, and v a variable number.
๐ง galoissubfields
galoissubfields(G,{fl = 0},{v}) โ output all the subfields of the Galois group G, as a vector. This works by applying galoisfixedfield to all subgroups. The meaning of the flag fl is the same as for galoisfixedfield.
The library syntax is galoissubfields(G,fl,v), where fl is a long and v a variable number.
๐ galoissubgroups
galoissubgroups(gal) โ output all the subgroups of the Galois group gal. A subgroup is a vector [gen, orders], with the same meaning as for gal.gen and gal.orders. Hence gen is a vector of permutations generating the subgroup, and orders is the relatives orders of the generators. The cardinal of a subgroup is the product of the relative orders. Such subgroup can be used instead of a Galois group in the following command: galoisisabelian, galoissubgroups, galoisexport and galoisidentify.
To get the subfield fixed by a subgroup sub of gal, use
galoisfixedfield(gal,sub[1])
The library syntax is galoissubgroups(gal).
๐ idealadd
idealadd(nf,x,y) โ sum of the two ideals x and y in the number field nf. When x and y are given by Z-bases, this does not depend on nf and can be used to compute the sum of any two Z-modules. The result is given in HNF.
The library syntax is idealadd(nf,x,y).
๐ idealaddtoone
idealaddtoone(nf,x,{y}) โ x and y being two co-prime integral ideals (given in any form), this gives a two-component row vector [a,b] such that a\in x, b\in y and a+b = 1.
The alternative syntax idealaddtoone(nf,v) is supported, where v is a k-component vector of ideals (given in any form) which sum to Z_K. This outputs a k-component vector e such that e[i]\in x[i] for 1 <= i <= k and sum_{1 <= i <= k}e[i] = 1.
The library syntax is idealaddtoone0(nf,x,y), where an omitted y is coded as NULL.
๐ฆ idealappr
idealappr(nf,x,{flag = 0}) โ if x is a fractional ideal (given in any form), gives an element alpha in nf such that for all prime ideals wp such that the valuation of x at wp is non-zero, we have v_{wp}(alpha) = v_{wp}(x), and v_{wp}(alpha) >= 0 for all other wp.
If flag is non-zero, x must be given as a prime ideal factorization, as output by idealfactor, but possibly with zero or negative exponents. This yields an element alpha such that for all prime ideals wp occurring in x, v_{wp}(alpha) is equal to the exponent of wp in x, and for all other prime ideals, v_{wp}(alpha) >= 0. This generalizes idealappr(nf,x,0) since zero exponents are allowed. Note that the algorithm used is slightly different, so that idealappr(nf,idealfactor(nf,x)) may not be the same as idealappr(nf,x,1).
The library syntax is idealappr0(nf,x,flag).
๐ idealchinese
idealchinese(nf,x,y) โ x being a prime ideal factorization (i.e. a 2 by 2 matrix whose first column contain prime ideals, and the second column integral exponents), y a vector of elements in nf indexed by the ideals in x, computes an element b such that
v_wp(b - y_wp) >= v_wp(x) for all prime ideals in x and v_wp(b) >= 0 for all other wp.
The library syntax is idealchinese(nf,x,y).
๐ฅ idealcoprime
idealcoprime(nf,x,y) โ given two integral ideals x and y in the number field nf, finds a beta in the field, expressed on the integral basis nf[7], such that beta.x is an integral ideal coprime to y.
The library syntax is idealcoprime(nf,x,y).
๐ idealdiv
idealdiv(nf,x,y,{flag = 0}) โ quotient x.y^{-1} of the two ideals x and y in the number field nf. The result is given in HNF.
If flag is non-zero, the quotient x.y^{-1} is assumed to be an integral ideal. This can be much faster when the norm of the quotient is small even though the norms of x and y are large.
The library syntax is idealdiv0(nf,x,y,flag). Also available are idealdiv(nf,x,y) (flag = 0) and idealdivexact(nf,x,y) (flag = 1).
๐ idealfactor
idealfactor(nf,x) โ factors into prime ideal powers the ideal x in the number field nf. The output format is similar to the factor function, and the prime ideals are represented in the form output by the idealprimedec function, i.e. as 5-element vectors.
The library syntax is idealfactor(nf,x).
๐ฆ idealhnf
idealhnf(nf,a,{b}) โ gives the Hermite normal form matrix of the ideal a. The ideal can be given in any form whatsoever (typically by an algebraic number if it is principal, by a Z_K-system of generators, as a prime ideal as given by idealprimedec, or by a Z-basis).
If b is not omitted, assume the ideal given was aZ_K+bZ_K, where a and b are elements of K given either as vectors on the integral basis nf[7] or as algebraic numbers.
The library syntax is idealhnf0(nf,a,b) where an omitted b is coded as NULL. Also available is idealhermite(nf,a) (b omitted).
๐ธ idealintersect
idealintersect(nf,A,B) โ intersection of the two ideals A and B in the number field nf. The result is given in HNF.
? nf = nfinit(x^2+1);
? idealintersect(nf, 2, x+1)
%2 =
[2 0]
[0 2]
This function does not apply to general Z-modules, e.g. orders, since its arguments are replaced by the ideals they generate. The following script intersects Z-modules A and B given by matrices of compatible dimensions with integer coefficients:
ZM_intersect(A,B) =
{ local( Ker = matkerint(concat(A,B)) );
mathnf(A * vecextract(Ker, Str("..", #A), ".."))
}
The library syntax is idealintersect(nf,A,B).
๐ง idealinv
idealinv(nf,x) โ inverse of the ideal x in the number field nf. The result is the Hermite normal form of the inverse of the ideal, together with the opposite of the Archimedean information if it is given.
The library syntax is idealinv(nf,x).
โจ ideallist โ all the ideals, bestie โจ
ideallist(nf,bound,{flag = 4}) computes the list of all ideals of norm less or equal to bound in the number field nf. The result is a row vector with exactly bound components. Each component is itself a row vector containing the information about ideals of a given norm, in no specific order, depending on the value of flag.
The possible values of flag are:
0โ give thebidassociated to the ideals, without generators.1โ as0, but include the generators in thebid.2โ in this case,nfmust be abnfwith units. Each component is of the form[bid,U], wherebidis as case0andUis a vector of discrete logarithms of the units. More precisely, it gives theideallogs with respect tobidofbnf.tufu. This structure is technical, and only meant to be used in conjunction withbnrclassnolistorbnrdisclist.3โ as2, but include the generators in thebid.4โ give only the HNF of the ideal.
? #L[65]
%4 = 4 \\ A single ideal of norm 1
? #L[65]
%4 = 4 \\ There are 4 ideals of norm 4 in B<Z>[i]
If one wants more information, one could do instead:
? nf = nfinit(x^2+1);
? L = ideallist(nf, 100, 0);
? l = L[25]; vector(#l, i, l[i].clgp)
%3 = [[20, [20]], [16, [4, 4]], [20, [20]]]
? l[1].mod
%4 = [[25, 18; 0, 1], []]
? l[2].mod
%5 = [[5, 0; 0, 5], []]
? l[3].mod
%6 = [[25, 7; 0, 1], []]
where we ask for the structures of (Z[i]/I)^* for all three ideals of norm 25. In fact, for all moduli with finite part of norm 25 and trivial archimedean part, as the last 3 commands show. See ideallistarch to treat general moduli.
The library syntax is ideallist0(nf,bound,flag), where bound must be a C long integer. Also available is ideallist(nf,bound), corresponding to the case flag = 4.
๐ธ ideallistarch โ archimedean glow-up ๐ธ
ideallistarch(nf,list,arch): here list is a vector of vectors of bid's, as output by ideallist with flag 0 to 3. It returns a vector of vectors with the same number of components as the original list. The leaves give information about moduli whose finite part is as in the original list, in the same order, and whose archimedean part is now arch (it was originally trivial). The information contained is of the same kind as was present in the input; see ideallist, in particular the meaning of flag.
? L = ideallist(bnf, 100, 0);
? l = L[98]; vector(#l, i, l[i].clgp)
%4 = [[42, [42]], [36, [6, 6]], [42, [42]]]
? La = ideallistarch(bnf, L, [1,1]); \\ two places at infinity
? L = ideallist(bnf, 100, 0);
? l = L[98]; vector(#l, i, l[i].clgp)
%4 = [[42, [42]], [36, [6, 6]], [42, [42]]]
? La = ideallistarch(bnf, L, [1,1]); \\ add them to the modulus
? l = La[98]; vector(#l, i, l[i].clgp)
%6 = [[168, [42, 2, 2]], [144, [6, 6, 2, 2]], [168, [42, 2, 2]]]
Of course, the results above are obvious: adding t places at infinity will add t copies of Z/2Z to the ray class group. The following application is more typical:
? L = ideallist(bnf, 100, 2); \\ units are required now
? La = ideallistarch(bnf, L, [1,1]);
? H = bnrclassnolist(bnf, La);
? H[98];
%6 = [2, 12, 2]
The library syntax is ideallistarch(nf,list,arch).
๐ฆ ideallog โ discrete logs but make it fashion ๐ฆ
ideallog(nf,x,bid): nf is a number field, bid a โbig idealโ as output by idealstar, and x a non-necessarily integral element of nf which must have valuation equal to 0 at all prime ideals dividing I = bid[1]. This function computes the โdiscrete logarithmโ of x on the generators given in bid[2]. In other words, if g_i are these generators, of orders d_i respectively, the result is a column vector of integers (x_i) such that 0 <= x_i < d_i and
x = prod_i g_i^{x_i} (mod ^*I) .
Note that when I is a module, this implies also sign conditions on the embeddings.
The library syntax is zideallog(nf,x,bid).
๐
idealmin โ find that minimum ๐
idealmin(nf,x,{vdir}) computes a minimum of the ideal x in the direction vdir in the number field nf.
The library syntax is minideal(nf,x,vdir,prec), where an omitted vdir is coded as NULL.
๐ฅ idealmul โ multiply those ideals ๐ฅ
idealmul(nf,x,y,{flag = 0}) does ideal multiplication of the ideals x and y in the number field nf. The result is a generating set for the ideal product with at most n elements, and is in Hermite normal form if either x or y is in HNF or is a prime ideal as output by idealprimedec, and this is given together with the sum of the Archimedean information in x and y if both are given.
If flag is non-zero, reduce the result using idealred.
The library syntax is idealmul(nf,x,y) (flag = 0) or idealmulred(nf,x,y,prec) (flag != 0), where as usual, prec is a C long integer representing the precision.
๐ idealnorm โ norm o'clock ๐
idealnorm(nf,x) computes the norm of the ideal x in the number field nf.
The library syntax is idealnorm(nf, x).
โญ idealpow โ power, but NOT reduced โญ
idealpow(nf,x,k,{flag = 0}) computes the k-th power of the ideal x in the number field nf. k can be positive, negative or zero. The result is NOT reduced, it is really the k-th ideal power, and is given in HNF.
If flag is non-zero, reduce the result using idealred. Note however that this is NOT the same as idealpow(nf,x,k) followed by reduction, since the reduction is performed throughout the powering process.
The library syntax corresponding to flag = 0 is idealpow(nf,x,k). If k is a long, you can use idealpows(nf,x,k). Corresponding to flag = 1 is idealpowred(nf,vp,k,prec), where prec is a long.
๐ idealprimedec โ prime ideal decomposition, no cap ๐
idealprimedec(nf,p) computes the prime ideal decomposition of the prime number p in the number field nf. p must be a (positive) prime number. Note that the fact that p is prime is not checked, so if a non-prime p is given the result is undefined.
The result is a vector of pr structures, each representing one of the prime ideals above p in the number field nf. The representation P = [p,a,e,f,b] of a prime ideal means the following. The prime ideal is equal to pZ_K + alphaZ_K where Z_K is the ring of integers of the field and alpha = sum_i a_i omega_i where the omega_i form the integral basis nf.zk, e is the ramification index, f is the residual index, and b represents a beta in Z_K such that P^{-1} = Z_K + beta/p Z_K which will be useful for computing valuations, but which the user can ignore. The number alpha is guaranteed to have a valuation equal to 1 at the prime ideal (this is automatic if e > 1).
The components of P should be accessed by member functions: P.p, P.e, P.f, and P.gen (returns the vector [p,a]).
The library syntax is primedec(nf,p).
๐ idealprincipal โ one-column principal realness ๐
idealprincipal(nf,x) creates the principal ideal generated by the algebraic number x (which must be of type integer, rational or polmod) in the number field nf. The result is a one-column matrix.
The library syntax is principalideal(nf,x).
๐ง idealred โ LLL reduction fairy ๐ง
idealred(nf,I,{vdir = 0}) is the LLL reduction of the ideal I in the number field nf, along the direction vdir. If vdir is present, it must be an r1+r2-component vector (r1 and r2 number of real and complex places of nf as usual).
This function finds a โsmallโ a in I (it is an LLL pseudo-minimum along direction vdir). The result is the Hermite normal form of the LLL-reduced ideal r I/a, where r is a rational number such that the resulting ideal is integral and primitive. This is often, but not always, a reduced ideal in the sense of Buchmann. If I is an idele, the logarithmic embeddings of a are subtracted to the Archimedean part.
More often than not, a principal ideal will yield the identity matrix. This is a quick and dirty way to check if ideals are principal without computing a full bnf structure, but it's not a necessary condition; hence, a non-trivial result doesn't prove the ideal is non-trivial in the class group.
Note that this is not the same as the LLL reduction of the lattice I since ideal operations are involved.
The library syntax is ideallllred(nf,x,vdir,prec), where an omitted vdir is coded as NULL.
๐ idealstar โ bid structure royalty ๐
idealstar(nf,I,{flag = 1}) outputs a bid structure, necessary for computing in the finite abelian group G = (Z_K/I)^*. Here, nf is a number field and I is a modulus: either an ideal in any form, or a row vector whose first component is an ideal and whose second component is a row vector of r_1 0 or 1.
This bid is used in ideallog to compute discrete logarithms. It also contains useful information which can be conveniently retrieved as bid.mod (the modulus), bid.clgp (G as a finite abelian group), bid.no (the cardinality of G), bid.cyc (elementary divisors) and bid.gen (generators).
- If
flag = 1(default), the result is abidstructure without generators. - If
flag = 2, asflag = 1, but including generators, which wastes some time. - If
flag = 0, deprecated. Only outputs(Z_K/I)^*as an abelian group, i.e as a 3-component vector[h,d,g]:his the order,dis the vector of SNF cyclic components andgthe corresponding generators. This flag is deprecated: it is in fact slightly faster to compute a truebidstructure, which contains much more information.
The library syntax is idealstar0(nf,I,flag).
๐ idealtwoelt โ two-element representation ๐
idealtwoelt(nf,x,{a}) computes a two-element representation of the ideal x in the number field nf, using a straightforward (exponential time) search. x can be an ideal in any form, (including perhaps an Archimedean part, which is ignored) and the result is a row vector [a,alpha] with two components such that x = aZ_K + alphaZ_K and a in Z, where a is the one passed as argument if any. If x is given by at least two generators, a is chosen to be the positive generator of x cap Z.
Note that when an explicit a is given, we use an asymptotically faster method, however in practice it is usually slower.
The library syntax is ideal_two_elt0(nf,x,a), where an omitted a is entered as NULL.
๐ idealval โ valuation vibes ๐
idealval(nf,x,vp) gives the valuation of the ideal x at the prime ideal vp in the number field nf, where vp must be a 5-component vector as given by idealprimedec.
The library syntax is idealval(nf,x,vp), and the result is a long integer.
๐ ideleprincipal(nf,x) โ principal idele energy
Okay so this one creates the principal idele generated by the algebraic number x โ and bestie, x must be of type integer, rational or polmod โ in the number field nf. The result is a two-component vector: the first component is a one-column matrix representing the corresponding principal ideal, and the second is the vector with r_1+r_2 components giving the complex logarithmic embedding of x. โจ
The library syntax is principalidele(nf,x).
๐ matalgtobasis(nf,x) โ matrix glow-up onto the integral basis
nf is a number field in nfinit format, and x is a matrix whose coefficients are expressed as polmods in nf. This transforms that matrix into a matrix whose coefficients are expressed on the integral basis of nf. Itโs the same as applying nfalgtobasis to each entry, but no cap, it would be dangerous to use the same name. ๐ซถ
The library syntax is matalgtobasis(nf,x).
๐ฆ matbasistoalg(nf,x) โ back to algebraic-number matrix realness
nf is a number field in nfinit format, and x is a matrix whose coefficients are expressed as column vectors on the integral basis of nf. This transforms that matrix into a matrix whose coefficients are algebraic numbers expressed as polmods. Itโs the same as applying nfbasistoalg to each entry, but bestie, it would be dangerous to use the same name. ๐
The library syntax is matbasistoalg(nf,x).
๐ modreverse(a) โ the reverse polmod reveal
a is a polmod A(X) modulo T(X). This finds the โreverse polmodโ B(X) modulo Q(X), where Q is the minimal polynomial of a, which must be equal to the degree of T, and such that if theta is a root of T then theta = B(alpha) for a certain root alpha of Q. Itโs very useful when one changes the generating element in algebraic extensions. ๐ง
The library syntax is polmodrecip(x).
๐ฅ newtonpoly(x,p) โ slopes, but make it fashion
Gives the vector of the slopes of the Newton polygon of the polynomial x with respect to the prime number p. The n components of the vector are in decreasing order, where n is equal to the degree of x. Vertical slopes occur iff the constant coefficient of x is zero and are denoted by VERYBIGINT, the biggest single precision integer representable on the machine (2^{31}-1 (resp. 2^{63}-1) on 32-bit (resp. 64-bit) machines), see Label se:valuation. ๐
The library syntax is newtonpoly(x,p).
๐ธ nfalgtobasis(nf,x) โ inverse of nfbasistoalg
This is the inverse function of nfbasistoalg. Given an object x whose entries are expressed as algebraic numbers in the number field nf, it transforms it so that the entries are expressed as a column vector on the integral basis nf.zk. ๐
The library syntax is algtobasis(nf,x).
๐ nfbasis(x,{flag = 0},{fa}) โ integral basis central
Integral basis of the number field defined by the irreducible, preferably monic, polynomial x, using a modified version of the round 4 algorithm by default, due to David Ford, Sebastian Pauli and Xavier Roblot. The binary digits of flag have the following meaning:
1โ assume that no square of a prime greater than the defaultprimelimitdivides the discriminant ofx, i.e. that the index ofxhas only small prime divisors.2โ use the round 2 algorithm. For small degrees and coefficient size, this is sometimes a little faster. (This program is the translation into C of a program written by David Ford in Algeb.)
Thus for instance, if flag = 3, this uses the round 2 algorithm and outputs an order which will be maximal at all the small primes. โจ
If fa is present, we assume (without checking!) that it is the two-column matrix of the factorization of the discriminant of the polynomial x. Note that it does not have to be a complete factorization. This is especially useful if only a local integral basis for some small set of places is desired: only factors with exponents greater or equal to 2 will be considered. ๐ซถ
The library syntax is nfbasis0(x,flag,fa). An extended version is nfbasis(x,&d,flag,fa), where d receives the discriminant of the number field (not of the polynomial x), and an omitted fa is input as NULL. Also available are base(x,&d) (flag = 0), base2(x,&d) (flag = 2) and factoredbase(x,fa,&d).
๐ง nfbasistoalg(nf,x) โ back to algebraic numbers
This is the inverse function of nfalgtobasis. Given an object x whose entries are expressed on the integral basis nf.zk, it transforms it into an object whose entries are algebraic numbers (i.e. polmods). ๐
The library syntax is basistoalg(nf,x).
๐
nfdetint(nf,x) โ determinant ideal, but not the determinant itself
Given a pseudo-matrix x, this computes a non-zero ideal contained in (i.e. multiple of) the determinant of x. This is particularly useful in conjunction with nfhnfmod. ๐ฅ
The library syntax is nfdetint(nf,x).
๐ธ nfdisc(x,{flag = 0},{fa}) โ field discriminant
Field discriminant of the number field defined by the integral, preferably monic, irreducible polynomial x. flag and fa are exactly as in nfbasis. That is, fa provides the matrix of a partial factorization of the discriminant of x, and the binary digits of flag are as follows:
1โ assume that no square of a prime greater thanprimelimitdivides the discriminant.2โ use the round 2 algorithm, instead of the default round 4. This should be slower except maybe for polynomials of small degree and coefficients.
The library syntax is nfdiscf0(x,flag,fa) where an omitted fa is input as NULL. You can also use discf(x) (flag = 0). ๐
๐ฆ nfeltdiv(nf,x,y) โ divide era
Given two elements x and y in nf, computes their quotient x/y in the number field nf. ๐
The library syntax is element_div(nf,x,y).
โญ nfeltdiveuc(nf,x,y) โ quotient with small components
Given two elements x and y in nf, computes an algebraic integer q in the number field nf such that the components of x-qy are reasonably small. In fact, this is functionally identical to round(nfeltdiv(nf,x,y)). โจ
The library syntax is nfdiveuc(nf,x,y).
๐ nfeltdivmodpr(nf,x,y,pr) โ quotient modulo a prime ideal
Given two elements x and y in nf and pr a prime ideal in modpr format (see nfmodprinit), computes their quotient x / y modulo the prime ideal pr. ๐
The library syntax is element_divmodpr(nf,x,y,pr).
๐ nfeltdivrem(nf,x,y) โ quotient and remainder, bestie
Given two elements x and y in nf, gives a two-element row vector [q,r] such that x = qy+r, q is an algebraic integer in nf, and the components of r are reasonably small. ๐ซถ
The library syntax is nfdivrem(nf,x,y).
๐ฅ nfeltmod(nf,x,y) โ modulo in the number field
Given two elements x and y in nf, computes an element r of nf of the form r = x-qy with q an algebraic integer, and such that r is small. This is functionally identical to
x - nfeltmul(nf,round(nfeltdiv(nf,x,y)),y).
The library syntax is nfmod(nf,x,y). ๐
๐ง nfeltmul(nf,x,y) โ multiply
Given two elements x and y in nf, computes their product x*y in the number field nf. ๐ธ
The library syntax is element_mul(nf,x,y).
๐ nfeltmulmodpr(nf,x,y,pr) โ product modulo a prime ideal
Given two elements x and y in nf and pr a prime ideal in modpr format (see nfmodprinit), computes their product x*y modulo the prime ideal pr. โจ
The library syntax is element_mulmodpr(nf,x,y,pr).
๐ nfeltpow(nf,x,k) โ power moves
Given an element x in nf, and a positive or negative integer k, computes x^k in the number field nf. ๐ฅ
The library syntax is element_pow(nf,x,k).
๐ nfeltpowmodpr(nf,x,k,pr) โ power modulo a prime ideal
Given an element x in nf, an integer k and a prime ideal pr in modpr format (see nfmodprinit), computes x^k modulo the prime ideal pr. ๐ซ
The library syntax is element_powmodpr(nf,x,k,pr).
๐ฆ nfeltreduce(nf,x,ideal) โ reduce, but make it small
Given an ideal in Hermite normal form and an element x of the number field nf, finds an element r in nf such that x-r belongs to the ideal and r is small. ๐
The library syntax is element_reduce(nf,x,ideal).
๐ธ nfeltreducemodpr(nf,x,pr) โ canonical rep mod pr
Given an element x of the number field nf and a prime ideal pr in modpr format, compute a canonical representative for the class of x modulo pr. ๐ซถ
The library syntax is nfreducemodpr(nf,x,pr).
๐ฅ nfeltval(nf,x,pr) โ valuation at a prime ideal
Given an element x in nf and a prime ideal pr in the format output by idealprimedec, computes the valuation at pr of the element x. The same result could be obtained using idealval(nf,x,pr) (since x would then be converted to a principal ideal), but it would be less efficient. ๐
The library syntax is element_val(nf,x,pr), and the result is a long.
๐ nffactor(nf,x) โ factor over the number field
Factorization of the univariate polynomial x over the number field nf given by nfinit. x has coefficients in nf (i.e. either scalar, polmod, polynomial or column vector). The main variable of nf must be of lower priority than that of x (see Label se:priority). However if the polynomial defining the number field occurs explicitly in the coefficients of x (as modulus of a t_POLMOD), its main variable must be the same as the main variable of x. For example,
? nffactor(nf, x^2 + Mod(z, z^2+1)); \\ OK
? nffactor(nf, x^2 + Mod(z, z^2+1)); \\ OK
? nffactor(nf, x^2 + Mod(z, z^2+1)); \\ WRONG
The library syntax is nffactor(nf,x). โจ
๐ nffactormod(nf,x,pr) โ factor mod a prime ideal
Factorization of the univariate polynomial x modulo the prime ideal pr in the number field nf. x can have coefficients in the number field (scalar, polmod, polynomial, column vector) or modulo the prime ideal (intmod modulo the rational prime under pr, polmod or polynomial with intmod coefficients, column vector of intmod). The prime ideal pr must be in the format output by idealprimedec. The main variable of nf must be of lower priority than that of x (see Label se:priority). However if the coefficients of the number field occur explicitly (as polmods) as coefficients of x, the variable of these polmods must be the same as the main variable of t (see nffactor). ๐
The library syntax is nffactormod(nf,x,pr).
๐ nfgaloisapply(nf,aut,x) โ Galois automorphism action
nf being a number field as output by nfinit, and aut being a Galois automorphism of nf expressed either as a polynomial or a polmod (such automorphisms being found using for example one of the variants of nfgaloisconj), computes the action of the automorphism aut on the object x in the number field. x can be an element (scalar, polmod, polynomial or column vector) of the number field, an ideal (either given by Z_K-generators or by a Z-basis), a prime ideal (given as a 5-element row vector) or an idele (given as a 2-element row vector). Because of possible confusion with elements and ideals, other vector or matrix arguments are forbidden. ๐ซถ
The library syntax is galoisapply(nf,aut,x).
๐ธ nfgaloisconj โจ (nf, {flag = 0}, {d})
okay so bestie, nf here is a number field exactly like nfinit spits out, and what this does is compute the conjugates of a root r of the non-constant polynomial x = nf[1], expressed as polynomials in r. And the cute part? You can use this even when your number field nf is not Galois, because some conjugates may straight-up live inside the field. ๐ซถ
Also nf can just be a plain polynomial if flag != 1. Easy.
Now the flags, and yes there are several, keep up ๐ :
- no flags, or
flag = 0โ ifnfis a number field, it uses a combo of flag 4 and flag 1, and the result is always complete. Ifnfisn't a number field, it uses a combo of flag 4 and flag 2, and the result is subject to the restriction offlag = 2โ but heads up, a warning gets issued when it's not proven complete. โ ๏ธ flag = 1โ usesnfroots(this one requires a number field).flag = 2โ uses complex approximations to the roots plus an integral LLL. But ngl, the result is not guaranteed to be complete: some conjugates may be missing and no warning gets issued ๐ญ โ especially if the corresponding polynomial has a huge index. In that case, bumping up the default precision may help.flag = 4โ uses Allombert's algorithm and permutation testing. If the field is Galois with a "weakly" super solvable Galois group, you get the complete list of automorphisms back; otherwise you only get the identity element. And ifdis present, it's assumed to be a multiple of the least common denominator of the conjugates expressed as polynomial in a root ofpol.
So real talk, a group G is "weakly" super solvable (WKSS) if it contains a super solvable normal subgroup H such that G = H, or G/H ~ A_4, or G/H ~ S_4. Abelian and nilpotent groups are WKSS. In practice, like, almost all groups of small order are WKSS โ the exceptions have order 36 (1 exception), 48 (2), 56 (1), 60 (1), 72 (5), 75 (1), 80 (1), 96 (10) and >= 108. ๐
Which means flag = 4 lets you quickly check whether a polynomial of order strictly less than 36 is Galois or not. This method is much faster than nfroots and can be applied to polynomials of degree larger than 50. iconic behavior honestly ๐
One lil limitation: this routine can only compute Q-automorphisms, but bestie you can use it to get K-automorphisms for any base field K like this:
rnfgaloisconj(nfK, R) = \\ K-automorphisms of L = K[X] / (R)
{ local(polabs, N, H);
R *= Mod(1, nfK.pol); \\ convert coeffs to polmod elts of K
polabs = rnfequation(nfK, R);
N = nfgaloisconj(polabs) % R; \\ Q-automorphisms of L
H = [];
for(i=1, #N, \\ select the ones that fix K
if (subst(R, variable(R), Mod(N[i],R)) == 0,
H = concat(H,N[i])
)
); H
}
K = nfinit(y^2 + 7);
polL = x^4 - y*x^3 - 3*x^2 + y*x + 1;
rnfgaloisconj(K, polL) \\ K-automorphisms of L
The library syntax is galoisconj0(nf,flag,d,prec). Also available are galoisconj(nf) for flag = 0, galoisconj2(nf,n,prec) for flag = 2 where n is a bound on the number of conjugates, and galoisconj4(nf,d) corresponding to flag = 4.
๐ฆ nfhilbert (nf,a,b,{pr})
If pr is omitted, you compute the global Hilbert symbol (a,b) in nf โ that's 1 if x^2 - a y^2 - b z^2 has a non-trivial solution (x,y,z) in nf, and -1 otherwise. Otherwise it computes the local symbol modulo the prime ideal pr (as output by idealprimedec). โจ
The library syntax is nfhilbert(nf,a,b,pr), where an omitted pr is coded as NULL.
๐ nfhnf (nf,x)
Given a pseudo-matrix (A,I), this finds a pseudo-basis in Hermite normal form of the module it generates. Slay. ๐
The library syntax is nfhermite(nf,x).
๐ nfhnfmod (nf,x,detx)
Given a pseudo-matrix (A,I) and an ideal detx which is contained in (read: an integral multiple of) the determinant of (A,I), this finds a pseudo-basis in Hermite normal form of the module generated by (A,I). The whole point? It avoids coefficient explosion ๐ฅ โ and you can compute detx using the function nfdetint.
The library syntax is nfhermitemod(nf,x,detx).
๐ nfinit (pol, {flag = 0})
okay this is the big one, main character energy fr fr. pol should be a non-constant, preferably monic, irreducible polynomial in Z[X], and this initializes a number field structure (nf) associated to the field K defined by pol. It's a technical object you pass as the first argument to most nf-something functions, but it also holds info that's directly useful. Access that info via member functions, though โ that's the preferred way, since the specific data organization described below may change in the future. โญ
Right now, nf is a row vector with 9 components:
nf[1]contains the polynomialpol(nf.pol).nf[2]contains[r1,r2](nf.sign,nf.r1,nf.r2), the number of real and complex places ofK.nf[3]contains the discriminant d(K) (nf.disc) ofK.nf[4]contains the index ofnf[1](nf.index), i.e.[Z_K : Z[theta]], where theta is any root ofnf[1].nf[5]is a vector containing 7 matricesM,G,T2,T,MD,TI,MDIthat are useful for certain computations in the number fieldK. The breakdown:Mis the(r1+r2) x nmatrix whose columns represent the numerical values of the conjugates of the elements of the integral basis.Gis such thatT2 = ^t G G, whereT2is the quadratic formT_2(x) = sum |sigma(x)|^2, with sigma running over the embeddings ofKinto C.- The
T2component is deprecated and currently unused. ๐ฉ (not me telling you to not rely on itโฆ) Tis then x nmatrix whose coefficients areTr(omega_i omega_j)where theomega_iare the elements of the integral basis. Note also that det(T)is equal to the discriminant of the fieldK.- The columns of
MD(nf.diff) express a Z-basis of the different ofKon the integral basis. TIis equal tod(K)T^{-1}, which has integral coefficients. Note that, understood as an ideal, the matrixT^{-1}generates the codifferent ideal.- Finally,
MDIis a two-element representation (for faster ideal product) of d(K) times the codifferent ideal (nf.disc*nf.codiff, which is an integral ideal).MDIis only used inidealinv.
nf[6]is the vector containing ther1+r2roots (nf.roots) ofnf[1]corresponding to ther1+r2embeddings of the number field into C (the firstr1components are real, the nextr2have positive imaginary part).nf[7]is an integral basis for Z_K(nf.zk) expressed on the powers of theta. Its first element is guaranteed to be1. This basis is LLL-reduced with respect toT_2(strictly speaking, it's a permutation of such a basis, due to the condition that the first element be1).nf[8]is then x nintegral matrix expressing the power basis in terms of the integral basis, and finallynf[9]is then x n^2matrix giving the multiplication table of the integral basis.
If you feed it a non-monic polynomial, nfinit will transform it into a monic one, then reduce it (see flag = 3). It's allowed โ though not very useful, given that nfnewprec exists โ to input a nf or a bnf instead of a polynomial. ๐
? nf = nfinit(x^3 - 12); \\ initialize number field Q[X] / (X^3 - 12)
? nf.pol \\ defining polynomial
%2 = x^3 - 12
? nf.disc \\ field discriminant
%3 = -972
? nf.index \\ index of power basis order in maximal order
%4 = 2
? nf.zk \\ integer basis, lifted to Q[X]
%5 = [1, x, 1/2*x^2]
? nf.sign \\ signature
%6 = [1, 1]
? factor(abs(nf.disc )) \\ determines ramified primes
%7 =
[2 2]
[3 5]
? idealfactor(nf, 2)
%8 =
[[2, [0, 0, -1]~, 3, 1, [0, 1, 0]~] 3] \\ B<P>_2^3
Now, if pol has a huge discriminant that's difficult to factor, there's a special input format [pol,B] that's also accepted, where pol is a polynomial as above and B is the integer basis, as would be computed by nfbasis. Super useful if the integer basis is known in advance, or was computed conditionally. ๐ง
? pol = polcompositum(x^5 - 101, polcyclo(7))[1];
? B = nfbasis(pol, 1); \\ faster than nfbasis(pol), but conditional
? nf = nfinit( [pol, B] );
? factor( abs(nf.disc) )
[5 18]
[7 25]
[101 24]
Heads up: B is conditional when its discriminant โ which is nf.disc โ can't be factored. In this example, the factorization above proves the correctness of the computation. โ
And the flags, bestie:
flag = 2โpolgets changed into another polynomialPdefining the same number field, one that's as simple as can easily be found using thepolredalgorithm, and all subsequent computations are done using this new polynomial. In particular, the first component of the result is the modified polynomial.flag = 3โ does apolredas in case 2, but outputs[nf,Mod(a,P)], wherenfis as before andMod(a,P) = Mod(x,pol)gives the change of variables. This is implicit whenpolis not monic: first a linear change of variables is performed to get a monic polynomial, then apolredreduction.flag = 4โ as 2, but uses a partialpolred.flag = 5โ as 3, using a partialpolred.
The library syntax is nfinit0(x,flag,prec).
๐ nfisideal (nf,x)
Returns 1 if x is an ideal in the number field nf, and 0 otherwise. Simple as that, no notes. โ๏ธ
The library syntax is isideal(x).
๐ธ nfisincl (x,y)
Tests whether the number field K defined by the polynomial x is conjugate to a subfield of the field L defined by y (where x and y must be in Q[X]). If they're not, the output is the number 0. If they are, the output is a vector of polynomials, each polynomial a representing an embedding of K into L โ like, being such that y | x o a. ๐ฆ
If y is a number field (nf), a much faster algorithm gets used (factoring x over y using nffactor). Before version 2.0.14 this wasn't guaranteed to return all the embeddings, which is why it used to be triggered by a special flag โ but that's no longer the case. ๐
The library syntax is nfisincl(x,y,flag).
๐ nfisisom (x,y)
Same energy as nfisincl, but it tests for isomorphism. And if either x or y is a number field, a much faster algorithm gets used. ๐
The library syntax is nfisisom(x,y,flag).
โญ nfnewprec (nf)
Transforms the number field nf into the corresponding data using the current (usually larger) precision. It works as expected if nf is in fact a bnf (that updates the bnf to current precision) โ but ngl it may be quite slow, because many generators of principal ideals have to be computed. ๐ฎโ๐จ
The library syntax is nfnewprec(nf,prec).
๐ง nfkermodpr (nf,a,pr)
Gives you the kernel of the matrix a in Z_K/pr, where pr is in modpr format โ see nfmodprinit. ๐ซถ
The library syntax is nfkermodpr(nf,a,pr).
๐ nfmodprinit (nf,pr)
Transforms the prime ideal pr into modpr format, which is the format you need for all operations modulo pr in the number field nf. Like a little glow-up for your prime ideal. โจ
The library syntax is nfmodprinit(nf,pr).
๐ธ nfsubfields โ bestie, let's find every subfield ๐ธ
nfsubfields(pol, {d = 0}) โ okay so this finds all the subfields of degree d inside the number field that pol defines (and yes, pol has to be monic and integral, no exceptions ๐
). If d is null or you just... don't pass it, you get all the subfields.
The result comes back as a vector of subfields, and each one is packaged as [g,h] โ where g is an absolute equation, and h expresses one of the roots of g in terms of the root x of the polynomial that defines nf.
Under the hood: this uses J. Klรผners's algorithm for the general case, and B. Allombert's galoissubfields when nf is Galois (with weakly supersolvable Galois group). Iconic collaboration honestly ๐ซถ
The library syntax is subfields(nf,d).
๐ฆ nfroots โ roots, but make it number-field โจ
nfroots({nf}, x) โ gives you the roots of the polynomial x in the number field nf (which you got from nfinit), without multiplicity. If you omit nf, you're just working in Q.
x has coefficients in the number field โ so like, scalar, polmod, polynomial, or column vector, all valid ๐
โ ๏ธ The main variable ofnfmust be of lower priority than that ofx(go peek atLabel se:priority). BUT โ if the coefficients of the number field show up explicitly (as polmods) in the coefficients ofx, then the variable of those polmods must be the same as the main variable oft(seenffactor). iykyk ๐
The library syntax is nfroots(nf,x).
๐ nfrootsof1 โ roots of unity, my beloved ๐
nfrootsof1(nf) โ computes the number of roots of unity w, plus a primitive w-th root of unity (expressed on the integral basis, obviously) that belongs to the number field nf.
Result is a two-component vector [w,z], where z is a column vector expressing a primitive w-th root of unity on the integral basis nf.zk. Slay ๐
The library syntax is rootsof1(nf).
๐ nfsnf โ Smith normal form, but make it modules ๐
nfsnf(nf, x) โ you hand it a torsion module x as a 3-component row vector [A,I,J], where:
Ais a square invertiblen x nmatrix,IandJare two ideal lists,
...and it outputs an ideal list d_1,...,d_n, which is the Smith normal form of x. In other words, x is isomorphic to Z_K/d_1\oplus...\oplusZ_K/d_n, and d_i divides d_{i-1} for i >= 2.
The link between x and [A,I,J] is literally this: if e_i is the canonical basis of K^n, I = [b_1,...,b_n] and J = [a_1,...,a_n], then x is isomorphic to
(b_1e_1\oplus...\oplus b_ne_n) / (a_1A_1\oplus...\oplus a_nA_n) ,
where the A_j are the columns of the matrix A.
Note that every finitely generated torsion module can be given this way โ and even with b_i = Z_K for all i. No cap, that's a whole vibe ๐
The library syntax is nfsmith(nf,x).
๐ฅ nfsolvemodpr โ solve it in the ring mod pr ๐ฅ
nfsolvemodpr(nf, a, b, pr) โ solution of a.x = b in Z_K/pr, where a is a matrix and b is a column vector, and where pr is in modpr format (see nfmodprinit).
The library syntax is nfsolvemodpr(nf,a,b,pr).
๐ polcompositum โ compositum era ๐
polcompositum(P, Q, {flag = 0}) โ with P and Q being squarefree polynomials in Z[X] in the same variable, this outputs the simple factors of the รฉtale Q-algebra A = Q(X, Y) / (P(X), Q(Y)).
The factors come as a list of polynomials R in Z[X], associated to the number field Q(X)/ (R), and they're sorted by increasing degree (with lexicographic ordering for factors of equal degree, bestie ๐
). Returns an error if one of the polynomials isn't squarefree โ so check your vibes first.
๐ก Note: it's more efficient to reduce to the case wherePandQare irreducible first. The routine won't do it for you (it can be expensive, and honestly the inputs are irreducible in most applications anyway). AssumingPis irreducible (of smaller degree thanQfor efficiency), it's generally much faster to proceed like this:
nf = nfinit(P); L = nffactor(nf, Q)[,1];
vector(#L, i, rnfequation(nf, L[i]))
...to get the same result. And if you only care about the degrees of the simple factors, you can swap the rnfequation instruction for a trivial poldegree(P) * poldegree(L[i]). Efficiency queen ๐
If flag = 1, it outputs a vector of 4-component vectors [R,a,b,k], where R ranges through the list of all possible compositums as above, and a (resp. b) expresses the root of P (resp. Q) as an element of Q(X)/(R). Finally, k is a small integer such that b + ka = X modulo R.
๐ซถ Real talk: a compositum is quite often defined by a complicated polynomial, and it's advisable to reduce it before further work. Here's a simple example involving the field Q(zeta_5, 5^{1/5}):
? pol = z[1]
%5 = x^20 + 25*x^10 + 5
? a = subst(a.pol, x, z[2]) \\ C<pol> defines the compositum
? pol = z[1]
%5 = x^20 + 25*x^10 + 5
? a = subst(a.pol, x, z[2]) \\ C<a> is a fifth root of 5
? pol = z[1]
%5 = x^20 + 25*x^10 + 5
? a = subst(a.pol, x, z[2]) \\ look for a simpler polynomial
? pol = z[1]
%5 = x^20 + 25*x^10 + 5
? a = subst(a.pol, x, z[2]) \\ C<a> in the new coordinates
%6 = Mod(-5/22*x^19 + 1/22*x^14 - 123/22*x^9 + 9/11*x^4, x^20 + 25*x^10 + 5)
The library syntax is polcompositum0(P,Q,flag).
โญ polgalois โ the Galois group, main character energy โญ
polgalois(x) โ Galois group of the non-constant polynomial x\inQ[X].
In the present version 2.3.5, x must be irreducible and the degree of x must be less than or equal to 7. On certain versions where the data file of Galois resolvents has been installed (available in the Unix distribution as a separate package), degrees 8, 9, 10 and 11 are also implemented. Fancy ๐
The output is a 4-component vector [n,s,k,name], and here's what each piece means:
nis the cardinality of the group,sis its signature (s = 1if the group is a subgroup of the alternating groupA_n,s = -1otherwise),nameis a character string containing the name of the transitive group according to the GAP 4 transitive groups library by Alexander Hulpke.
Now, k is more arbitrary ๐ญ and honestly the choice made up to version 2.2.3 of PARI is rather unfortunate: for n > 7, k is the numbering of the group among all transitive subgroups of S_n, as given in ``The transitive groups of degree up to eleven'', G. Butler and J. McKay, Communications in Algebra, vol. 11, 1983, pp. 863--911 (group k is denoted T_k there). And for n <= 7, it was ad hoc, so as to ensure that a given triple would designate a unique group.
Specifically, for polynomials of degree <= 7, the groups are coded as follows, using standard notations ๐
In degree 1: S_1 = [1,1,1].
In degree 2: S_2 = [2,-1,1].
In degree 3: A_3 = C_3 = [3,1,1], S_3 = [6,-1,1].
In degree 4: C_4 = [4,-1,1], V_4 = [4,1,1], D_4 = [8,-1,1], A_4 = [12,1,1], S_4 = [24,-1,1].
In degree 5: C_5 = [5,1,1], D_5 = [10,1,1], M_{20} = [20,-1,1], A_5 = [60,1,1], S_5 = [120,-1,1].
In degree 6: C_6 = [6,-1,1], S_3 = [6,-1,2], D_6 = [12,-1,1], A_4 = [12,1,1], G_{18} = [18,-1,1], S_4^ -= [24,-1,1], A_4 x C_2 = [24,-1,2], S_4^ += [24,1,1], G_{36}^ -= [36,-1,1], G_{36}^ += [36,1,1], S_4 x C_2 = [48,-1,1], A_5 = PSL_2(5) = [60,1,1], G_{72} = [72,-1,1], S_5 = PGL_2(5) = [120,-1,1], A_6 = [360,1,1], S_6 = [720,-1,1].
In degree 7: C_7 = [7,1,1], D_7 = [14,-1,1], M_{21} = [21,1,1], M_{42} = [42,-1,1], PSL_2(7) = PSL_3(2) = [168,1,1], A_7 = [2520,1,1], S_7 = [5040,-1,1].
๐ This is deprecated and obsolete, but for reasons of backward compatibility, we cannot change this behaviour yet. So you can use the defaultnew_galois_formatto switch to a consistent naming scheme, namelykis always the standard numbering of the group among all transitive subgroups ofS_n. If this default is in effect, the above groups will be coded as:
In degree 1: S_1 = [1,1,1].
In degree 2: S_2 = [2,-1,1].
In degree 3: A_3 = C_3 = [3,1,1], S_3 = [6,-1,2].
In degree 4: C_4 = [4,-1,1], V_4 = [4,1,2], D_4 = [8,-1,3], A_4 = [12,1,4], S_4 = [24,-1,5].
In degree 5: C_5 = [5,1,1], D_5 = [10,1,2], M_{20} = [20,-1,3], A_5 = [60,1,4], S_5 = [120,-1,5].
In degree 6: C_6 = [6,-1,1], S_3 = [6,-1,2], D_6 = [12,-1,3], A_4 = [12,1,4], G_{18} = [18,-1,5], A_4 x C_2 = [24,-1,6], S_4^ += [24,1,7], S_4^ -= [24,-1,8], G_{36}^ -= [36,-1,9], G_{36}^ += [36,1,10], S_4 x C_2 = [48,-1,11], A_5 = PSL_2(5) = [60,1,12], G_{72} = [72,-1,13], S_5 = PGL_2(5) = [120,-1,14], A_6 = [360,1,15], S_6 = [720,-1,16].
In degree 7: C_7 = [7,1,1], D_7 = [14,-1,2], M_{21} = [21,1,3], M_{42} = [42,-1,4], PSL_2(7) = PSL_3(2) = [168,1,5], A_7 = [2520,1,6], S_7 = [5040,-1,7].
โ ๏ธ Warning: the method used is that of resolvent polynomials and is sensitive to the current precision. The precision is updated internally, but in very rare cases, a wrong result may be returned if the initial precision was not sufficient. So like... be careful with your precision bestie, fr fr ๐ญ
The library syntax is polgalois(x,prec). To enable the new format in library mode, set the global variable new_galois_format to 1.
๐ธ polred โ cute little polynomials with small coefficients ๐ธ
polred(x, {flag = 0}, {fa}) โ finds polynomials with reasonably small coefficients defining subfields of the number field defined by x.
One of the polynomials always defines Q (hence is equal to x-1), and another always defines the same number field as x if x is irreducible. All x accepted by nfinit are also allowed here (e.g. non-monic polynomials, nf, bnf, [x,Z_K_basis]). Periodt ๐
The following binary digits of flag are significant:
- 1 โ possibly use a suborder of the maximal order. The primes dividing the index of the order chosen are larger than
primelimitor divide integers stored in theaddprimestable. - 2 โ gives also elements. The result is a two-column matrix, the first column giving the elements defining these subfields, the second giving the corresponding minimal polynomials.
If fa is given, it's assumed to be the two-column matrix of the factorization of the discriminant of the polynomial x.
The library syntax is polred0(x,flag,fa), where an omitted fa is coded by NULL. Also available are polred(x) and factoredpolred(x,fa), both corresponding to flag = 0.
๐ง polredabs โ minimal T_2-norm, absolute icon ๐ง
polredabs(x, {flag = 0}) โ finds one of the polynomials defining the same number field as the one defined by x, and such that the sum of the squares of the modulus of the roots (i.e. the T_2-norm) is minimal. All x accepted by nfinit are also allowed here (e.g. non-monic polynomials, nf, bnf, [x,Z_K_basis]).
๐ Warning: this routine uses an exponential-time algorithm to enumerate all potential generators, and may be exceedingly slow when the number field has many subfields (hence a lot of elements of smallT_2-norm). E.g. do not try it on the compositum of many quadratic fields โ usepolredinstead. Please, bestie, I'm begging you ๐
The binary digits of flag mean:
- 1 โ outputs a two-component row vector
[P,a], wherePis the default output andais an element expressed on a root of the polynomialP, whose minimal polynomial is equal tox. - 4 โ gives all polynomials of minimal
T_2norm (of the two polynomials P(x) and P(-x), only one is given).
16: possibly use a suborder of the maximal order. The primes dividing the index of the order chosen are larger thanprimelimitor divide integers stored in theaddprimestable. In that case it may happen that the output polynomial does not have minimalT_2norm.
The library syntax is polredabs0(x,flag).
๐ธ polredord(x)
Finds polynomials with reasonably small coefficients and of the same degree as that of x defining suborders of the order defined by x. One of the polynomials always defines Q (hence is equal to (x-1)^n, where n is the degree), and another always defines the same order as x if x is irreducible.
The library syntax is ordred(x).
๐ฆ poltschirnhaus(x)
Applies a random Tschirnhausen transformation to the polynomial x, which is assumed to be non-constant and separable, so as to obtain a new equation for the รฉtale algebra defined by x. This is for instance useful when computing resolvents, hence is used by the polgalois function.
The library syntax is tschirnhaus(x).
๐ rnfalgtobasis(rnf,x)
Expresses x on the relative integral basis. Here, rnf is a relative number field extension L/K as output by rnfinit, and x an element of L in absolute form, i.e. expressed as a polynomial or polmod with polmod coefficients, not on the relative integral basis.
The library syntax is rnfalgtobasis(rnf,x).
โจ rnfbasis(bnf, M)
Let K be the field represented by bnf, as output by bnfinit. M is a projective Z_K-module given by a pseudo-basis, as output by rnfhnfbasis. The routine returns either a true Z_K-basis of M if it exists, or an n+1-element generating set of M if not, where n is the rank of M over K. (Note that n is the size of the pseudo-basis.)
It is allowed to use a polynomial P with coefficients in K instead of M, in which case M is defined as the ring of integers of K[X]/(P) (P is assumed irreducible over K), viewed as a Z_K-module.
The library syntax is rnfbasis(bnf,x).
๐ rnfbasistoalg(rnf,x)
Computes the representation of x as a polmod with polmods coefficients. Here, rnf is a relative number field extension L/K as output by rnfinit, and x an element of L expressed on the relative integral basis.
The library syntax is rnfbasistoalg(rnf,x).
๐ฅ rnfcharpoly(nf,T,a,{v = x})
Characteristic polynomial of a over nf, where a belongs to the algebra defined by T over nf, i.e. nf[X]/(T). Returns a polynomial in variable v (x by default).
The library syntax is rnfcharpoly(nf,T,a,v), where v is a variable number.
๐ rnfconductor(bnf,pol,{flag = 0})
Given bnf as output by bnfinit, and pol a relative polynomial defining an Abelian extension, computes the class field theory conductor of this Abelian extension. The result is a 3-component vector [conductor, rayclgp, subgroup], where conductor is the conductor of the extension given as a 2-component row vector [f_0,f_ oo ], rayclgp is the full ray class group corresponding to the conductor given as a 3-component vector [h,cyc,gen] as usual for a group, and subgroup is a matrix in HNF defining the subgroup of the ray class group on the given generators gen. If flag is non-zero, check that pol indeed defines an Abelian extension, return 0 if it does not.
The library syntax is rnfconductor(rnf,pol,flag).
๐ rnfdedekind(nf,pol,pr)
Given a number field nf as output by nfinit and a polynomial pol with coefficients in nf defining a relative extension L of nf, evaluates the relative Dedekind criterion over the order defined by a root of pol for the prime ideal pr and outputs a 3-component vector as the result. The first component is a flag equal to 1 if the enlarged order could be proven to be pr-maximal and to 0 otherwise (it may be maximal in the latter case if pr is ramified in L), the second component is a pseudo-basis of the enlarged order and the third component is the valuation at pr of the order discriminant.
The library syntax is rnfdedekind(nf,pol,pr).
๐ซถ rnfdet(nf,M)
Given a pseudo-matrix M over the maximal order of nf, computes its determinant.
The library syntax is rnfdet(nf,M).
๐ rnfdisc(nf,pol)
Given a number field nf as output by nfinit and a polynomial pol with coefficients in nf defining a relative extension L of nf, computes the relative discriminant of L. This is a two-element row vector [D,d], where D is the relative ideal discriminant and d is the relative discriminant considered as an element of nf^*/{nf^*}^2. The main variable of nf must be of lower priority than that of pol, see Label se:priority.
The library syntax is rnfdiscf(bnf,pol).
๐ฆ rnfeltabstorel(rnf,x)
rnf being a relative number field extension L/K as output by rnfinit and x being an element of L expressed as a polynomial modulo the absolute equation rnf.pol, computes x as an element of the relative extension L/K as a polmod with polmod coefficients.
The library syntax is rnfelementabstorel(rnf,x).
๐ rnfeltdown(rnf,x)
rnf being a relative number field extension L/K as output by rnfinit and x being an element of L expressed as a polynomial or polmod with polmod coefficients, computes x as an element of K as a polmod, assuming x is in K (otherwise an error will occur). If x is given on the relative integral basis, apply rnfbasistoalg first, otherwise PARI will believe you are dealing with a vector.
The library syntax is rnfelementdown(rnf,x).
๐ rnfeltreltoabs(rnf,x)
rnf being a relative number field extension L/K as output by rnfinit and x being an element of L expressed as a polynomial or polmod with polmod coefficients, computes x as an element of the absolute extension L/Q as a polynomial modulo the absolute equation rnf.pol. If x is given on the relative integral basis, apply rnfbasistoalg first, otherwise PARI will believe you are dealing with a vector.
The library syntax is rnfelementreltoabs(rnf,x).
๐ง rnfeltup(rnf,x)
rnf being a relative number field extension L/K as output by rnfinit and x being an element of K expressed as a polynomial or polmod, computes x as an element of the absolute extension L/Q as a polynomial modulo the absolute equation rnf.pol. If x is given on the integral basis of K, apply nfbasistoalg first, otherwise PARI will believe you are dealing with a vector.
The library syntax is rnfelementup(rnf,x).
๐ฆ rnfequation(nf,pol,{flag = 0})
Given a number field nf as output by nfinit (or simply a polynomial) and a polynomial pol with coefficients in nf defining a relative extension L of nf, computes the absolute equation of L over Q.
If flag is non-zero, outputs a 3-component row vector [z,a,k], where z is the absolute equation of L over Q, as in the default behaviour, a expresses as an element of L a root alpha of the polynomial defining the base field nf, and k is a small integer such that theta = beta + k alpha where theta is a root of z and beta a root of pol.
The main variable of nf must be of lower priority than that of pol (see Label se:priority). Note that for efficiency, this does not check whether the relative equation is irreducible over nf, but only if it is squarefree. If it is reducible but squarefree, the result will be the absolute equation of the รฉtale algebra defined by pol. If pol is not squarefree, an error message will be issued.
The library syntax is rnfequation0(nf,pol,flag).
๐ธ rnfhnfbasis(bnf,x)
Given bnf as output by bnfinit, and either a polynomial x with coefficients in bnf defining a relative extension L of bnf, or a pseudo-basis x of such an extension, gives either a true bnf-basis of L in upper triangular Hermite normal form, if it exists, and returns 0 otherwise.
The library syntax is rnfhnfbasis(nf,x).
๐
rnfidealabstorel(rnf,x)
Let rnf be a relative number field extension L/K as output by rnfinit, and x an ideal of the absolute extension L/Q given by a Z-basis of elements of L. Returns the relative pseudo-matrix in HNF giving the ideal x considered as an ideal of the relative extension L/K.
If x is an ideal in HNF form, associated to an nf structure, for instance as output by idealhnf(nf,...), use rnfidealabstorel(rnf, nf.zk * x) to convert it to a relative ideal.
The library syntax is rnfidealabstorel(rnf,x).
๐ rnfidealdown(rnf,x)
Let rnf be a relative number field extension L/K as output by rnfinit, and x an ideal of L, given either in relative form or by a Z-basis of elements of L (see Label se:rnfidealabstorel), returns the ideal of K below x, i.e. the intersection of x with K.
The library syntax is rnfidealdown(rnf,x).
โจ rnfidealhnf(rnf,x)
rnf being a relative number field extension L/K as output by rnfinit and x being a relative ideal (which can be, as in the absolute case, of many different types, including of course elements), computes the HNF pseudo-matrix associated to x, viewed as a Z_K-module.
The library syntax is rnfidealhermite(rnf,x).
๐ฅ rnfidealmul(rnf,x,y)
rnf being a relative number field extension L/K as output by rnfinit and x and y being ideals of the relative extension L/K given by pseudo-matrices, outputs the ideal product, again as a relative ideal.
The library syntax is rnfidealmul(rnf,x,y).
๐ rnfidealnormabs(rnf,x)
rnf being a relative number field extension L/K as output by rnfinit and x being a relative ideal (which can be, as in the absolute case, of many different types, including of course elements), computes the norm of the ideal x considered as an ideal of the absolute extension L/Q. This is identical to idealnorm(rnfidealnormrel(rnf,x)), but faster.
The library syntax is rnfidealnormabs(rnf,x).
๐ rnfidealnormrel(rnf,x)
rnf being a relative number field extension L/K as output by rnfinit and x being a relative ideal (which can be, as in the absolute case, of many different types, including of course elements), computes the relative norm of x as an ideal of K in HNF.
The library syntax is rnfidealnormrel(rnf,x).
rnfidealreltoabs(rnf,x)
Okay so picture this: rnf is a relative number field extension L/K โ the kind of thing rnfinit hands you โ and x is a relative ideal. This function gives you back the ideal xZ_L as an absolute ideal of L/Q, in the form of a Z-basis, delivered as a vector of polynomials (modulo rnf.pol). ๐
The following routine might be useful, and honestly it's giving "handy little helper":
\\ return y = rnfidealreltoabs(rnf,...) as an ideal in HNF form
\\ associated to nf = nfinit( rnf.pol );
idealgentoHNF(nf, y) = mathnf( Mat( nfalgtobasis(nf, y) ) );
The library syntax is rnfidealreltoabs(rnf,x).
rnfidealtwoelt(rnf,x)
Same setup, bestie: rnf is a relative number field extension L/K as output by rnfinit, and x is an ideal of the relative extension L/K โ except this time it's given by a pseudo-matrix. The result? A vector of two generators of x over Z_L, expressed as polmods with polmod coefficients. Two for the price of one, lowkey iconic. โจ
The library syntax is rnfidealtwoelement(rnf,x).
rnfidealup(rnf,x)
Here rnf is again a relative number field extension L/K as output by rnfinit, and x is an ideal of K this time. This gives the ideal xZ_L as an absolute ideal of L/Q, in the form of a Z-basis, given by a vector of polynomials (modulo rnf.pol). ๐
Another routine that might be useful โ yes, it's the sibling of the one above:
\\ return y = rnfidealup(rnf,...) as an ideal in HNF form
\\ associated to nf = nfinit( rnf.pol );
idealgentoHNF(nf, y) = mathnf( Mat( nfalgtobasis(nf, y) ) );
The library syntax is rnfidealup(rnf,x).
rnfinit(nf,pol)
Buckle up boo, this one's the main character. ๐
nf is a number field in nfinit format, being used as the base field, and pol is a polynomial defining a relative extension over nf. This computes all the necessary data you need to actually work in that relative extension. Two rules though, no cap:
- The main variable of
polmust be of higher priority (seeLabel se:priority) than that ofnf. - The coefficients of
polmust lie innf.
The result is a row vector, and its components are, and I quote, technical. Let's set up the notation so nothing gets confusing: let K be the base field defined by nf, m the degree of the base field, n the relative degree, L the large field (of relative degree n or absolute degree nm), and r_1 and r_2 the number of real and complex places of K. ๐ฆ
Here's the full rundown of every slot:
rnf[1]contains the relative polynomialpol.rnf[2]is currently unused. (empty slot energy, we respect it)rnf[3]is a two-component row vector[d(L/K),s]whered(L/K)is the relative ideal discriminant ofL/Kandsis the discriminant ofL/Kviewed as an element ofK^*/(K^*)^2โ in other words it is the output ofrnfdisc.rnf[4]is the ideal index f, i.e. such thatd(pol)Z_K =f^2d(L/K).rnf[5]is currently unused.rnf[6]is currently unused.rnf[7]is a two-component row vector, where the first component is the relative integral pseudo basis expressed as polynomials (in the variable ofpol) with polmod coefficients innf, and the second component is the ideal list of the pseudobasis in HNF.rnf[8]is the inverse matrix of the integral basis matrix, with coefficients polmods innf.rnf[9]is currently unused.rnf[10]isnf.rnf[11]is the output ofrnfequation(nf, pol, 1). Namely, a vectorvabswith 3 entries describing the absolute extensionL/Q.vabs[1]is an absolute equation, more conveniently obtained asrnf.pol.vabs[2]expresses the generator alpha of the number fieldnfas a polynomial modulo the absolute equationvabs[1].vabs[3]is a small integerksuch that, if beta is an abstract root ofpoland alpha the generator ofnf, the generator whose root isvabswill be beta+ kalpha.rnf[12]is by default unused and set equal to 0. This field stores further information about the field as it becomes available (which is rarely needed, hence would be too expensive to compute during the initialrnfinitcall).
๐จ warning bestie, listen up: you must be very careful ifk != 0when dealing simultaneously with absolute and relative quantities, since the generator chosen for the absolute extension is not the same as for the relative one. If this happens, you can of course go on working, but we strongly advise changing the relative polynomial so that its root will be beta+ kalpha. Typically, the GP instruction would be
pol = subst(pol, x, x - k*Mod(y,nf.pol))
The library syntax is rnfinitalg(nf,pol,prec).
rnfisfree(bnf,x)
You hand in bnf as output by bnfinit, plus either a polynomial x with coefficients in bnf defining a relative extension L of bnf, or a pseudo-basis x of such an extension. This returns true (1) if L/bnf is free, false (0) if not. Simple as that, and we love a clean yes/no. ๐ธ
The library syntax is rnfisfree(bnf,x), and the result is a long.
rnfisnorm(T,a,{flag = 0})
Basically bnfisnorm but make it relative. ๐ซ T is as output by rnfisnorminit applied to the extension L/K. This tries to decide whether the element a in K is the norm of some x in the extension L/K.
The output is a vector [x,q], where a = Norm (x)*q. The algorithm looks for a solution x which is an S-integer, with S a list of places of K containing at least the ramified primes, the generators of the class group of L, as well as those primes dividing a.
If L/K is Galois, then that's enough. Otherwise, flag is used to add more primes to S: all the places above the primes p <= flag (resp. p|flag) if flag > 0 (resp. flag < 0).
The answer is guaranteed (i.e. a is a norm iff q = 1) if the field is Galois, or, under GRH, if S contains all primes less than 12 log^2|disc(M)|, where M is the normal closure of L/K.
If rnfisnorminit has determined (or was told) that L/K is Galois, and flag != 0, a Warning is issued (so that you can set flag = 1 to check whether L/K is known to be Galois, according to T). Example, because examples ate:
bnf = bnfinit(y^3 + y^2 - 2*y - 1);
p = x^2 + Mod(y^2 + 2*y + 1, bnf.pol);
T = rnfisnorminit(bnf, p);
rnfisnorm(T, 17)
This checks whether 17 is a norm in the Galois extension Q(beta) / Q(alpha), where alpha^3 + alpha^2 - 2alpha - 1 = 0 and beta^2 + alpha^2 + 2alpha + 1 = 0 โ and yes, it is. ๐ซถ
The library syntax is rnfisnorm(T,x,flag).
rnfisnorminit(pol,polrel,{flag = 2})
Let K be defined by a root of pol, and L/K the extension defined by the polynomial polrel. As usual, pol can in fact be an nf, or bnf, etc โ and if pol has degree 1 (so the base field is Q), then polrel is also allowed to be an nf, etc. This computes the technical data needed by rnfisnorm to solve norm equations Nx = a, for x in L, and a in K. ๐ง
The flag values, because there are exactly three and they matter:
- If flag
= 0, do not care whetherL/Kis Galois or not. - If flag
= 1,L/Kis assumed to be Galois (unchecked), which speeds uprnfisnorm. - If flag
= 2, let the routine determine whetherL/Kis Galois.
The library syntax is rnfisnorminit(pol,polrel,flag).
rnfkummer(bnr,{subgroup},{deg = 0})
bnr is as output by bnrinit. This finds a relative equation for the class field corresponding to the module in bnr and the given congruence subgroup (the full ray class field if subgroup is omitted). If deg is positive, it outputs the list of all relative equations of degree deg contained in the ray class field defined by bnr, with the same conductor as (bnr, subgroup). โญ
๐ Warning: this routine only works for subgroups of prime index. It uses Kummer theory, adjoining necessary roots of unity (it needs to compute a tough bnfinit here, so like, brace yourself), and finds a generator via Hecke's characterization of ramification in Kummer extensions of prime degree. If your extension does not have prime degree, for the time being, you have to split it by hand as a tower / compositum of such extensions. ๐
The library syntax is rnfkummer(bnr,subgroup,deg,prec), where deg is a long and an omitted subgroup is coded as NULL.
rnflllgram(nf,pol,order)
You give a polynomial pol with coefficients in nf defining a relative extension L, plus a suborder order of L (of maximal rank), as output by rnfpseudobasis(nf,pol) or something similar. The output is [[neworder],U], where neworder is a reduced order and U is the unimodular transformation matrix. โจ
The library syntax is rnflllgram(nf,pol,order,prec).
rnfnormgroup(bnr,pol)
bnr is a big ray class field as output by bnrinit, and pol is a relative polynomial defining an Abelian extension. This computes the norm group (alias Artin or Takagi group) corresponding to the Abelian extension of bnf = bnr[1] defined by pol, where the module corresponding to bnr is assumed to be a multiple of the conductor (i.e. pol defines a subextension of bnr). ๐
The result is the HNF defining the norm group on the given generators of bnr[5][3].
๐ heads up: neither the fact that pol defines an Abelian extension nor the fact that the module is a multiple of the conductor is checked. The result is undefined if the assumption is not correct. Like, it will not warn you, it'll just be wrong. You've been told. ๐
The library syntax is rnfnormgroup(bnr,pol).
rnfpolred(nf,pol)
Relative version of polred, periodt. Given a monic polynomial pol with coefficients in nf, it finds a list of relative polynomials defining some subfields โ hopefully simpler and containing the original field. ๐ฆ
Quick reality check: in the present version 2.3.5, this is slower and less efficient than rnfpolredabs. Not me being shady, that's just what the page says.
The library syntax is rnfpolred(nf,pol,prec).
rnfpolredabs(nf,pol,{flag = 0})
Relative version of polredabs. Given a monic polynomial pol with coefficients in nf, it finds a simpler relative polynomial defining the same field. The binary digits of flag mean:
1: returns[P,a]wherePis the default output andais an element expressed on a root ofPwhose characteristic polynomial ispol.2: returns an absolute polynomial (same asrnfequation(nf,rnfpolredabs(nf,pol))but faster).16: possibly use a suborder of the maximal order. This is slower than the default when the relative discriminant is smooth, and much faster otherwise. SeeLabel se:polredabs.
Remark. In the present implementation, this is both faster and much more efficient than rnfpolred โ and the difference is more dramatic than in the absolute case. Why? Because the implementation of rnfpolred is based on (a partial implementation of) an incomplete reduction theory of lattices over number fields, the function rnflllgram, which deserves to be improved. It's giving "we know, we know". ๐ญ
The library syntax is rnfpolredabs(nf,pol,flag,prec).
rnfpseudobasis (nf, pol) ๐
okay so bestie, you hand this one a number field nf (as output by nfinit) and a polynomial pol with coefficients in nf that defines a relative extension L of nf. It computes a pseudo-basis (A,I) for the maximal order Z_L viewed as a Z_K-module, plus the relative discriminant of L. The glow-up output is a four-element row vector [A,I,D,d], where D is the relative ideal discriminant and d is the relative discriminant considered as an element of nf^*/{nf^*}^2. The library syntax is rnfpseudobasis(nf,pol).
rnfsteinitz (nf, x) โจ
Given a number field nf as output by nfinit and either a polynomial x with coefficients in nf defining a relative extension L of nf, or a pseudo-basis x of such an extension as output for example by rnfpseudobasis, this computes another pseudo-basis (A,I) (not in HNF in general) such that all the ideals of I except perhaps the last one are equal to the ring of integers of nf, and outputs the four-component row vector [A,I,D,d] as in rnfpseudobasis. The name of this function comes from the fact that the ideal class of the last ideal of I, which is well defined, is the Steinitz class of the Z_K-module Z_L (its image in SK_0(Z_K)). The library syntax is rnfsteinitz(nf,x).
subgrouplist (bnr, {bound}, {flag = 0}) ๐
Here bnr is as output by bnrinit or a list of cyclic components of a finite Abelian group G, and this outputs the list of subgroups of G. Subgroups are given as HNF left divisors of the SNF matrix corresponding to G.
โ ๏ธ Warning: the present implementation cannot treat a groupGwhere any cyclic factor has more than2^{31}, resp.2^{63}elements on a 32-bit, resp. 64-bit architecture.forsubgroupis a bit more general and can handleGif allp-Sylow subgroups ofGsatisfy the condition above.
If flag = 0 (default) and bnr is as output by bnrinit, it gives only the subgroups whose modulus is the conductor. Otherwise, the modulus is not taken into account.
If bound is present, and is a positive integer, restrict the output to subgroups of index less than bound. If bound is a vector containing a single positive integer B, then only subgroups of index exactly equal to B are computed. For instance
%2 = [[2, 1; 0, 1], [1, 0; 0, 2], [2, 0; 0, 1], [3, 0; 0, 1], [1, 0; 0, 1]]
? subgrouplist([6,2],[3]) \\ index less than 3
%2 = [[2, 1; 0, 1], [1, 0; 0, 2], [2, 0; 0, 1], [3, 0; 0, 1], [1, 0; 0, 1]]
? subgrouplist([6,2],[3]) \\ index 3
%3 = [[3, 0; 0, 1]]
? bnr = bnrinit(bnfinit(x), [120,[1]], 1);
? L = subgrouplist(bnr, [8]);
In the last example, L corresponds to the 24 subfields of Q(zeta_{120}), of degree 8 and conductor 120 oo (by setting flag, we see there are a total of 43 subgroups of degree 8).
? vector(#L, i, galoissubcyclo(bnr, L[i]))
will produce their equations. (For a general base field, you would have to rely on bnrstark, or rnfkummer.)
The library syntax is subgrouplist0(bnr,bound,flag), where flag is a long integer, and an omitted bound is coded by NULL.
zetak (znf, x, {flag = 0}) ๐ธ
znf being a number field initialized by zetakinit (not by nfinit), this computes the value of the Dedekind zeta function of the number field at the complex number x. If flag = 1, computes the Dedekind Lambda function instead (i.e. the product of the Dedekind zeta function by its gamma and exponential factors).
โ ๏ธ CAVEAT: this implementation is not satisfactory and must be rewritten. In particular:
- The accuracy of the result depends in an essential way on the accuracy of both the
zetakinitprogram and the current accuracy. Be wary in particular thatxof large imaginary part or, on the contrary, very close to an ordinary integer will suffer from precision loss, yielding fewer significant digits than expected. Computing with 28 eight digits of relative accuracy, we have
? zeta(3)
%1 = 1.202056903159594285399738161
? zeta(3-1e-20)
%2 = 1.202056903159594285401719424
? zetak(zetakinit(x), 3-1e-20)
%3 = 1.2020569031595952919 \\ 5 digits are wrong
? zetak(zetakinit(x), 3-1e-28)
%4 = -25.33411749 \\ junk
- As the precision increases, results become unexpectedly completely wrong:
? \p100
? zetak(zetakinit(x^2-5), -1) - 1/30
%1 = 7.26691813 E-108 \\ perfect
? \p150
? zetak(zetakinit(x^2-5), -1) - 1/30
%2 = -2.486113578 E-156 \\ perfect
? \p200
? zetak(zetakinit(x^2-5), -1) - 1/30
%3 = 4.47... E-75 \\ more than half of the digits are wrong
? \p250
? zetak(zetakinit(x^2-5), -1) - 1/30
%4 = 1.6 E43 \\ junk
The library syntax is glambdak(znf,x,prec) or gzetak(znf,x,prec).
zetakinit (x) ๐ง
Computes a number of initialization data concerning the number field defined by the polynomial x so as to be able to compute the Dedekind zeta and lambda functions (respectively zetak(x) and zetak(x,1)). This function calls in particular the bnfinit program. The result is a 9-component vector v whose components are very technical and cannot really be used by the user except through the zetak function. The only component which can be used if it has not been computed already is v[1][4], which is the result of the bnfinit call.
This function is very inefficient and should be rewritten. It needs to compute millions of coefficients of the corresponding Dirichlet series if the precision is big. Unless the discriminant is small it will not be able to handle more than 9 digits of relative precision. For instance, zetakinit(x^8 - 2) needs 440MB of memory at default precision.
The library syntax is initzeta(x).
โจ Polynomials and power series โจ
We group here all functions which are specific to polynomials or power series. Many other functions which can be applied on these objects are described in the other sections. Also, some of the functions described here can be applied to other types. ๐
O (p^e) ๐
If p is an integer greater than 2, returns a p-adic 0 of precision e. In all other cases, returns a power series zero with precision given by e v, where v is the X-adic valuation of p with respect to its main variable.
The library syntax is zeropadic(p,e) for a p-adic and zeroser(v,e) for a power series zero in variable v, which is a long. The precision e is a long.
deriv (x, {v}) ๐ฆ
Derivative of x with respect to the main variable if v is omitted, and with respect to v otherwise. The derivative of a scalar type is zero, and the derivative of a vector or matrix is done componentwise. One can use x' as a shortcut if the derivative is with respect to the main variable of x.
By definition, the main variable of a t_POLMOD is the main variable among the coefficients from its two polynomial components (representative and modulus); in other words, assuming a polmod represents an element of R[X]/(T(X)), the variable X is a mute variable and the derivative is taken with respect to the main variable used in the base ring R.
The library syntax is deriv(x,v), where v is a long, and an omitted v is coded as -1. When x is a t_POL, derivpol(x) is a shortcut for deriv(x, -1).
eval (x) ๐
Replaces in x the formal variables by the values that have been assigned to them after the creation of x. This is mainly useful in GP, and not in library mode. Do not confuse this with substitution (see subst).
If x is a character string, eval(x) executes x as a GP command, as if directly input from the keyboard, and returns its output. For convenience, x is evaluated as if strictmatch was off. In particular, unused characters at the end of x do not prevent its evaluation:
? eval("1a")
% 1 = 1
The library syntax is geval(x). The more basic functions poleval(q,x), qfeval(q,x), and hqfeval(q,x) evaluate q at x, where q is respectively assumed to be a polynomial, a quadratic form (a symmetric matrix), or an Hermitian form (an Hermitian complex matrix).
factorpadic (pol, p, r, {flag = 0}) ๐
p-adic factorization of the polynomial pol to precision r, the result being a two-column matrix as in factor. The factors are normalized so that their leading coefficient is a power of p. r must be strictly larger than the p-adic valuation of the discriminant of pol for the result to make any sense. The method used is a modified version of the round 4 algorithm of Zassenhaus.
If flag = 1, use an algorithm due to Buchmann and Lenstra, which is usually less efficient.
The library syntax is factorpadic4(pol,p,r), where r is a long integer.
intformal (x, {v}) ๐
Formal integration of x with respect to the main variable if v is omitted, with respect to the variable v otherwise. Since PARI does not know about โabstractโ logarithms (they are immediately evaluated, if only to a power series), logarithmic terms in the result will yield an error. x can be of any type. When x is a rational function, it is assumed that the base ring is an integral domain of characteristic zero.
The library syntax is integ(x,v), where v is a long and an omitted v is coded as -1.
padicappr (pol, a) ๐
Vector of p-adic roots of the polynomial pol congruent to the p-adic number a modulo p, and with the same p-adic precision as a. The number a can be an ordinary p-adic number (type t_PADIC, i.e. an element of Z_p) or can be an integral element of a finite extension of Q_p, given as a t_POLMOD at least one of whose coefficients is a t_PADIC. In this case, the result is the vector of roots belonging to the same extension of Q_p as a.
The library syntax is padicappr(pol,a).
polcoeff (x, s, {v}) ๐
Coefficient of degree s of the polynomial x, with respect to the main variable if v is omitted, with respect to v otherwise. Also applies to power series, scalars (polynomial of degree 0), and to rational functions provided the denominator is a monomial.
The library syntax is polcoeff0(x,s,v), where v is a long and an omitted v is coded as -1. Also available is truecoeff(x,v).
poldegree (x, {v}) โญ
Degree of the polynomial x in the main variable if v is omitted, in the variable v otherwise.
The degree of 0 is a fixed negative number, whose exact value should not be used. The degree of a non-zero scalar is 0. Finally, when x is a non-zero polynomial or rational function, returns the ordinary degree of x. Raise an error otherwise.
Finishing poldegree real quick, bestie โ the library syntax is poldegree(x,v), where v and the result are longs (and an omitted v is coded as -1). Also available is degree(x), which is equivalent to poldegree(x,-1). ๐ซถ
polcyclo(n,{v = x}) โ cyclotomic queen ๐
Creates the n-th cyclotomic polynomial, in variable v (x by default). The integer n must be positive.
The library syntax is cyclo(n,v), where n and v are long integers (v is a variable number, usually obtained through varn).
poldisc(pol,{v}) โ discriminant drama ๐
Discriminant of the polynomial pol in the main variable if v is omitted, in v otherwise. The algorithm used is the subresultant algorithm.
The library syntax is poldisc0(x,v). Also available is discsr{x}, equivalent to poldisc0(x,-1).
poldiscreduced(f) โ reduced discriminant, reduced stress โจ
Reduced discriminant vector of the (integral, monic) polynomial f. This is the vector of elementary divisors of Z[alpha]/f'(alpha)Z[alpha], where alpha is a root of the polynomial f. The components of the result are all positive, and their product is equal to the absolute value of the discriminant of f.
The library syntax is reduceddiscsmith(x).
polhensellift(x, y, p, e) โ lift era ๐
Given a prime p, an integral polynomial x whose leading coefficient is a p-unit, a vector y of integral polynomials that are pairwise relatively prime modulo p, and whose product is congruent to x modulo p, lift the elements of y to polynomials whose product is congruent to x modulo p^e.
The library syntax is polhensellift(x,y,p,e) where e must be a long.
polinterpolate(xa,{ya},{v = x},{&e}) โ interpolate, donโt guess ๐ธ
Given the data vectors xa and ya of the same length n (xa containing the x-coordinates, and ya the corresponding y-coordinates), this function finds the interpolating polynomial passing through these points and evaluates it at v. If ya is omitted, return the polynomial interpolating the (i,xa[i]). If present, e will contain an error estimate on the returned value.
The library syntax is polint(xa,ya,v,&e), where e will contain an error estimate on the returned value.
polisirreducible(pol) โ is it irreducible? vibe check ๐ฅ
pol being a polynomial (univariate in the present version 2.3.5), returns 1 if pol is non-constant and irreducible, 0 otherwise. Irreducibility is checked over the smallest base field over which pol seems to be defined.
The library syntax is gisirreducible(pol).
pollead(x,{v}) โ leading coefficient, main character ๐ซ
Leading coefficient of the polynomial or power series x. This is computed with respect to the main variable of x if v is omitted, with respect to the variable v otherwise.
The library syntax is pollead(x,v), where v is a long and an omitted v is coded as -1. Also available is leading_term{x}.
pollegendre(n,{v = x}) โ Legendre polynomial, legendary ๐
Creates the n-th Legendre polynomial, in variable v.
The library syntax is legendre(n), where x is a long.
polrecip(pol) โ flip the coefficients ๐
Reciprocal polynomial of pol, i.e. the coefficients are in reverse order. pol must be a polynomial.
The library syntax is polrecip(x).
polresultant(x,y,{v},{flag = 0}) โ resultant realness ๐ฅ
Resultant of the two polynomials x and y with exact entries, with respect to the main variables of x and y if v is omitted, with respect to the variable v otherwise. The algorithm assumes the base ring is a domain.
flag = 0โ uses the subresultant algorithm.flag = 1โ uses the determinant of Sylvester's matrix instead (herexandymay have non-exact coefficients).flag = 2โ uses Ducos's modified subresultant algorithm. It should be much faster than the default if the coefficient ring is complicated (e.g multivariate polynomials or huge coefficients), and slightly slower otherwise.
The library syntax is polresultant0(x,y,v,flag), where v is a long and an omitted v is coded as -1. Also available are subres{x,y} (flag = 0) and resultant2{x,y} (flag = 1).
polroots(pol,{flag = 0}) โ roots, but make it complex ๐
Complex roots of the polynomial pol, given as a column vector where each root is repeated according to its multiplicity. The precision is given as for transcendental functions: in GP it is kept in the variable realprecision and is transparent to the user, but it must be explicitly given as a second argument in library mode.
The algorithm used is a modification of A. Schรถnhage's root-finding algorithm, due to and implemented by X. Gourdon. Barring bugs, it is guaranteed to converge and to give the roots to the required accuracy.
If flag = 1, use a variant of the Newton-Raphson method, which is not guaranteed to converge, but is rather fast. If you get the messages too many iterations in roots or INTERNAL ERROR: incorrect result in roots, use the default algorithm. This used to be the default root-finding function in PARI until version 1.39.06.
โ ๏ธflag = 1is not guaranteed to converge, bestie โ if you see those messages, go back to the default. This was the default until PARI version1.39.06.
The library syntax is roots(pol,prec) or rootsold{pol,prec}.
polrootsmod(pol,p,{flag = 0}) โ roots mod p, no cap ๐ง
Row vector of roots modulo p of the polynomial pol. The particular non-prime value p = 4 is accepted, mainly for 2-adic computations. Multiple roots are not repeated.
If p is very small, you may try setting flag = 1, which uses a naive search.
The library syntax is rootmod(pol,p) (flag = 0) or rootmod2{pol,p} (flag = 1).
polrootspadic(pol,p,r) โ p-adic roots, p-adic lore ๐
Row vector of p-adic roots of the polynomial pol, given to p-adic precision r. Multiple roots are not repeated. p is assumed to be a prime, and pol to be non-zero modulo p. Note that this is not the same as the roots in Z/p^rZ, rather it gives approximations in Z/p^rZ of the true roots living in Q_p.
If pol has inexact t_PADIC coefficients, this is not always well-defined; in this case, the equation is first made integral, then lifted to Z. Hence the roots given are approximations of the roots of a polynomial which is p-adically close to the input.
โ ๏ธ Inexactt_PADICcoefficients can make this not always well-defined โ the page says the equation is first made integral, then lifted toZ. So the roots you get are approximations for a polynomialp-adically close to your input.
The library syntax is rootpadic(pol,p,r), where r is a long.
polsturm(pol,{a},{b}) โ Sturmโs algorithm but make it interval ๐
Number of real roots of the real polynomial pol in the interval ]a,b], using Sturm's algorithm. a (resp. b) is taken to be -oo (resp. +oo) if omitted.
The library syntax is sturmpart(pol,a,b). Use NULL to omit an argument. sturm{pol} is equivalent to sturmpart{pol,NULL,NULL}. The result is a long.
polsubcyclo(n,d,{v = x}) โ sub-Abelian extensions, sub-iconic ๐ฆ
Gives polynomials (in variable v) defining the sub-Abelian extensions of degree d of the cyclotomic field Q(zeta_n), where d | phi(n).
If there is exactly one such extension the output is a polynomial, else it is a vector of polynomials, eventually empty.
To be sure to get a vector, you can use concat([],polsubcyclo(n,d))
The function galoissubcyclo allows to specify more closely which sub-Abelian extension should be computed.
The library syntax is polsubcyclo(n,d,v), where n, d and v are long and v is a variable number. When (Z/nZ)^* is cyclic, you can use subcyclo{n,d,v}, where n, d and v are long and v is a variable number.
polsylvestermatrix(x,y) โ Sylvester matrix slay ๐
Forms the Sylvester matrix corresponding to the two polynomials x and y, where the coefficients of the polynomials are put in the columns of the matrix (which is the natural direction for solving equations afterwards). The use of this matrix can be essential when dealing with polynomials with inexact entries, since polynomial Euclidean division doesn't make much sense in this case.
The library syntax is sylvestermatrix(x,y).
polsym(x,n) โ symmetric powers, Newtonโs formula energy โจ
Creates the vector of the symmetric powers of the roots of the polynomial x up to power n, using Newton's formula.
The library syntax is polsym(x).
poltchebi(n,{v = x}) โ Chebyshev, but the first kind ๐
Creates the n-th Chebyshev polynomial T_n of the first kind in variable v.
The library syntax is tchebi(n,v), where n and v are long integers (v is a variable number).
polzagier(n,m) โ Zagierโs polynomial, used by sumalt/sumpos ๐
Creates Zagier's polynomial P_n^{(m)} used in the functions sumalt and sumpos (with flag = 1). One must have m <= n. The exact definition can be found in โConvergence acceleration of alternating seriesโ, Cohen et al., Experiment. Math., vol. 9, 2000, pp. 3--12.
The library syntax is polzagreel(n,m,prec) if the result is only wanted as a polynomial with real coefficients to the precision prec, or polzag{n,m} if the result is wanted exactly, where n and m are longs.
serconvol(x,y) โ convolution, aka Hadamard product ๐
Convolution (or Hadamard product) of the two power series x and y; in other words if x = sum a_k*X^k and y = sum b_k*X^k then serconvol(x,y) = sum a_k*b_k*X^k.
The library syntax is convol(x,y).
serlaplace(x) โ Laplace transform vibe check ๐ธ
x must be a power series with non-negative exponents. If x = sum (a_k/k!)*X^k then the result is sum a_k*X^k.
The library syntax is laplace(x).
serreverse(x) โ reverse power series, not 1/x ๐
Reverse power series (i.e. x^{-1}, not 1/x) of x. x must be a power series whose valuation is exactly equal to one.
The library syntax is recip(x).
subst(x,y,z) โ substitute the simple variable ๐ซถ
Replace the simple variable y by the argument z in the โpolynomialโ expression x. Every type is allowed for x, but if it is not a genuine polynomial (or power series, or rational function), the substitution will be done as if the scalar components were polynomials of degree zero. In particular, beware that:
? subst(1, x, [1,2; 3,4])
%1 =
[1 0]
[0 1]
? subst(1, x, Mat([0,1]))
*** forbidden substitution by a non square matrix
If x is a power series, z must be either a polynomial, a power series, or a rational function.
The library syntax is gsubst(x,y,z), where y is the variable number.
substpol(x,y,z) โ substitute a whole polynomial, no cap ๐ฅ
Replace the โvariableโ y by the argument z in the โpolynomialโ expression x. Every type is allowed for x, but the same behaviour as subst above apply.
The difference with subst is that y is allowed to be any polynomial here. The substitution is done as per the following script:
subst_poly(pol, from, to) =
{ local(t = 'subst_poly_t, M = from - t);
subst(lift(Mod(pol,M), variable(M)), t, to)
}
For instance
? substpol(x^4 + x^2 + 1, x^2, y)
%1 = y^2 + y + 1
? substpol(x^4 + x^2 + 1, x^3, y)
%2 = x^2 + y*x + 1
? substpol(x^4 + x^2 + 1, (x+1)^2, y)
%3 = (-4*y - 6)*x + (y^2 + 3*y - 3)
The library syntax is gsubstpol(x,y,z).
โจ substvec โจ
substvec(x,v,w): okay so v is a vector of monomials (variables), and w is a vector of expressions of the same length. Youโre replacing in the expression x all occurrences of v_i by w_i. The substitutions are done simultaneously; more precisely, the v_i are first replaced by new variables in x, then these are replaced by the w_i:
? substvec([x,y], [x,y], [y,x])
%1 = [y, x]
? substvec([x,y], [x,y], [y,x+y])
%2 = [y, x + y] \\ not [y, 2*y]
The library syntax is gsubstvec(x,v,w).
๐ taylor ๐
taylor(x,y): Taylor expansion around 0 of x with respect to the simple variable y. x can be of any reasonable type, for example a rational function. The number of terms of the expansion is transparent to the user in GP, but must be given as a second argument in library mode.
The library syntax is tayl(x,y,n), where the long integer n is the desired number of terms in the expansion.
๐งฎ thue ๐งฎ
thue(tnf,a,{sol}): solves the equation P(x,y) = a in integers x and y, where tnf was created with thueinit(P). sol, if present, contains the solutions of Norm(x) = a modulo units of positive norm in the number field defined by P (as computed by bnfisintnorm). If the result is conditional (on the GRH or some heuristic strengthening), a Warning is printed. Otherwise, the result is unconditional, barring bugs. For instance, hereโs how to solve the Thue equation x^{13} - 5y^{13} = -4:
? tnf = thueinit(x^13 - 5);
? thue(tnf, -4)
%1 = [[1, 1]]
Hence, the only solution is x = 1, y = 1 and the result is unconditional. On the other hand:
? tnf = thueinit(x^3-2*x^2+3*x-17);
? thue(tnf, -15)
*** thue: Warning: Non trivial conditional class group.
*** May miss solutions of the norm equation.
%2 = [[1, 1]]
This time the result is conditional. All results computed using this tnf are likewise conditional, except for a right-hand side of +-1.
The library syntax is thue(tnf,a,sol), where an omitted sol is coded as NULL.
๐ฑ thueinit ๐ฑ
thueinit(P,{flag = 0}): initializes the tnf corresponding to P. It is meant to be used in conjunction with thue to solve Thue equations P(x,y) = a, where a is an integer. If flag is non-zero, certify the result unconditionally. Otherwise, assume GRH, this being much faster of course.
If the conditional computed class group is trivial or you are only interested in the case a = +-1, then results are unconditional anyway. So one should only use the flag if thue prints a Warning (see the example there).
The library syntax is thueinit(P,flag,prec).
๐ Vectors, matrices, linear algebra and sets ๐
Note that most linear algebra functions operating on subspaces defined by generating sets (such as mathnf, qflll, etc.) take matrices as arguments. As usual, the generating vectors are taken to be the columns of the given matrix.
Since PARI does not have a strong typing system, scalars live in unspecified commutative base rings. It is very difficult to write robust linear algebra routines in such a general setting. The developersโ choice has been to assume the base ring is a domain and work over its field of fractions. If the base ring is not a domain, one gets an error as soon as a non-zero pivot turns out to be non-invertible. Some functions, e.g. mathnf or mathnfmod, specifically assume the base ring is Z.
๐ algdep ๐
algdep(x,k,{flag = 0}): x being real/complex, or p-adic, finds a polynomial of degree at most k with integer coefficients having x as approximate root. Note that the polynomial which is obtained is not necessarily the โcorrectโ one. In fact it is not even guaranteed to be irreducible. One can check the closeness either by a polynomial evaluation (use subst), or by computing the roots of the polynomial given by algdep (use polroots).
Internally, lindep([1,x,...,x^k], flag) is used. If lindep is not able to find a relation and returns a lower bound for the sup norm of the smallest relation, algdep returns that bound instead. A suitable non-zero value of flag may improve on the default behaviour:
\\\\\\\\\ LLL
? \p200
? algdep(2^(1/6)+3^(1/5), 30); \\ wrong in 3.8s
? algdep(2^(1/6)+3^(1/5), 30, 100); \\ wrong in 1s
? algdep(2^(1/6)+3^(1/5), 30, 170); \\ right in 3.3s
? algdep(2^(1/6)+3^(1/5), 30, 200); \\ wrong in 2.9s
? \p250
? algdep(2^(1/6)+3^(1/5), 30); \\ right in 2.8s
? algdep(2^(1/6)+3^(1/5), 30, 200); \\ right in 3.4s
\\\\\\\\\ PSLQ
? \p200
? algdep(2^(1/6)+3^(1/5), 30, -3); \\ failure in 14s.
? \p250
? algdep(2^(1/6)+3^(1/5), 30, -3); \\ right in 18s
Proceeding by increments of 5 digits of accuracy, algdep with default flag produces its first correct result at 205 digits, and from then on a steady stream of correct results. Interestingly enough, our PSLQ also reliably succeeds from 205 digits on (and is 5 times slower at that accuracy).
The above example is the testcase studied in a 2000 paper by Borwein and Lisonek, Applications of integer relation algorithms, Discrete Math., 217, p. 65--82. The paper concludes in the superiority of the PSLQ algorithm, which either shows that PARIโs implementation of PSLQ is lacking, or that its LLL is extremely good. The version of PARI tested there was 1.39, which succeeded reliably from precision 265 on, in about 60 as much time as the current version.
The library syntax is algdep0(x,k,flag,prec), where k and flag are longs. Also available is algdep(x,k,prec) (flag = 0).
๐ charpoly ๐
charpoly(A,{v = x},{flag = 0}): characteristic polynomial of A with respect to the variable v, i.e. determinant of v*I-A if A is a square matrix. If A is not a square matrix, it returns the characteristic polynomial of the map โmultiplication by Aโ if A is a scalar, in particular a polmod. E.g. charpoly(I) = x^2+1.
The value of flag is only significant for matrices.
- If
flag = 0, the method used is essentially the same as for computing the adjoint matrix, i.e. computing the traces of the powers ofA. - If
flag = 1, uses Lagrange interpolation which is almost always slower. - If
flag = 2, uses the Hessenberg form. This is faster than the default when the coefficients are intmod a prime or real numbers, but is usually slower in other base rings.
The library syntax is charpoly0(A,v,flag), where v is the variable number. Also available are the functions caract(A,v) (flag = 1), carhess(A,v) (flag = 2), and caradj(A,v,pt) where, in this last case, pt is a GEN* which, if not equal to NULL, will receive the address of the adjoint matrix of A (see matadjoint), so both can be obtained at once.
๐งต concat ๐งต
concat(x,{y}): concatenation of x and y. If x or y is not a vector or matrix, it is considered as a one-dimensional vector. All types are allowed for x and y, but the sizes must be compatible. Note that matrices are concatenated horizontally, i.e. the number of rows stays the same. Using transpositions, it is easy to concatenate them vertically.
To concatenate vectors sideways (i.e. to obtain a two-row or two-column matrix), use Mat instead (see the example there). Concatenating a row vector to a matrix having the same number of columns will add the row to the matrix (top row if the vector is x, i.e. comes first, and bottom row otherwise).
The empty matrix [;] is considered to have a number of rows compatible with any operation, in particular concatenation. (Note that this is definitely not the case for empty vectors [ ] or [ ]~.)
If y is omitted, x has to be a row vector or a list, in which case its elements are concatenated, from left to right, using the above rules.
? concat([1,2], [3,4])
%1 = [1, 2, 3, 4]
? a = [[1,2]~, [3,4]~]; concat(a)
%2 =
[1 3]
[2 4]
? concat([1,2; 3,4], [5,6]~)
%3 =
[1 2 5]
[3 4 6]
? concat([%, [7,8]~, [1,2,3,4]])
%5 =
[1 2 5 7]
[3 4 6 8]
[1 2 3 4]
The library syntax is concat(x,y).
๐ง lindep ๐ง
lindep(x,{flag = 0}): x being a vector with p-adic or real/complex coefficients, finds a small integral linear combination among these coefficients.
If x is p-adic, flag is meaningless and the algorithm LLL-reduces a suitable (dual) lattice.
Otherwise, the value of flag determines the algorithm used; in the current version of PARI, we suggest to use non-negative values, since it is by far the fastest and most robust implementation. See the detailed example in Label se:algdep (algdep).
- If
flag >= 0, uses a floating point (variable precision) LLL algorithm. This is in general much faster than the other variants. Ifflag = 0the accuracy is chosen internally using a crude heuristic. Ifflag > 0the computation is done with an accuracy offlagdecimal digits. In that case, the parameterflagshould be between 0.6 and 0.9 times the number of correct decimal digits in the input. - If
flag = -1, uses a variant of the LLL algorithm due to Hastad, Lagarias and Schnorr (STACS 1986). If the precision is too low, the routine may enter an infinite loop. - If
flag = -2,xis allowed to be (and in any case interpreted as) a matrix. Returns a non trivial element of the kernel ofx, or 0 ifxhas trivial kernel. The element is defined over the field of coefficients ofx, and is in general not integral. - If
flag = -3, uses the PSLQ algorithm. This may return a real numberB, indicating that the input accuracy was exhausted and that no relation exist whose sup norm is less thanB. - If
flag = -4, uses an experimental 2-level PSLQ, which does not work at all. (Should be rewritten.)
The library syntax is lindep0(x,flag,prec). Also available is lindep(x,prec) (flag = 0).
๐ listcreate ๐
listcreate(n): creates an empty list of maximal length n.
This function is useless in library mode.
๐ listinsert ๐
listinsert(list,x,n): inserts the object x at position n in list (which must be of type t_LIST). All the remaining elements of list (from position n+1 onwards) are shifted to the right. This and listput are the only commands which enable you to increase a listโs effective length (as long as it remains under the maximal length specified at the time of the listcreate).
This function is useless in library mode.
๐ listkill ๐
listkill(list): kill list. This deletes all elements from list and sets its effective length to 0. The maximal length is not affected.
This function is useless in library mode.
๐งบ listput(list, x, {n})
ok so this one sets the n-th element of list (which must be of type t_LIST) equal to x. Slay. If n is omitted, or it's greater than the list's current effective length, it just appends x to the end, no drama.
And like, listput and listinsert are literally the only two commands that let you increase a list's effective length โ as long as it stays under the maximal length you specified back when you called listcreate. ๐ซถ
If you actually want to drop an element into an occupied cell (i.e. you do not want to change the effective length), just treat the list like a vector and use the usual list[n] = x construct. Easy.
ngl this function is useless in library mode. ๐
๐ listsort(list, {flag = 0})
sorts list (type t_LIST, bestie, keep up) in place. If flag is non-zero, it suppresses all repeated coefficients โ like, duplicates get yeeted. This is so much faster than the vecsort command because no copy has to be made. Main character efficiency honestly. โจ
Also useless in library mode. ๐
๐ matadjoint(x)
adjoint matrix of x โ that's the matrix y of cofactors of x, satisfying
x*y = det(x)*Id
x must be a (non-necessarily invertible) square matrix. She doesn't even need to be invertible, iconic.
The library syntax is adj(x).
๐ matcompanion(x)
the left companion matrix to the polynomial x. That's it, that's the whole vibe.
The library syntax is assmat(x).
๐ฅ matdet(x, {flag = 0})
determinant of x. x has to be a square matrix, no cap.
flag = 0โ uses Gauss-Bareiss.flag = 1โ uses classical Gaussian elimination, which is better when the entries of the matrix are reals or integers for example, but usually much worse for more complicated entries like multivariate polynomials. ๐
The library syntax is det(x) (flag = 0) and det2{x} (flag = 1).
๐งฎ matdetint(x)
ok so x being an m x n matrix with integer coefficients, this function computes a multiple of the determinant of the lattice generated by the columns of x if it is of rank m, and returns zero otherwise. Zero. Zilch. ๐ซฅ
This one's useful in conjunction with mathnfmod, which needs to know such a multiple. To obtain the exact determinant (assuming the rank is maximal), you can compute:
matdet(mathnfmod(x, matdetint(x)))
Heads up bestie: as soon as one of the dimensions gets large (mornis larger than 20, say), it will often be much faster to usemathnf(x, 1)ormathnf(x, 4)directly. Don't come for me.
The library syntax is detint(x).
๐ธ matdiagonal(x)
x being a vector, this creates the diagonal matrix whose diagonal entries are those of x. Cute, clean, diagonal. ๐
The library syntax is diagonal(x).
๐ฆ mateigen(x)
gives the eigenvectors of x as columns of a matrix. Obsessed.
The library syntax is eigen(x).
โญ matfrobenius(M, {flag = 0}, {v = x})
returns the Frobenius form of the square matrix M. Let's break down the flags:
flag = 1โ returns only the elementary divisors as a vector of polynomials in the variable v.flag = 2โ returns a two-components vector[F,B]whereFis the Frobenius form andBis the basis change so thatM = B^{-1}FB.
The library syntax is matfrobenius(M,flag,v), where v is the variable number.
๐ง mathess(x)
Hessenberg form of the square matrix x. Short and sweet. ๐
The library syntax is hess(x).
๐ mathilbert(x)
x being a long, creates the Hilbert matrix of order x โ i.e. the matrix whose coefficient (i,j) is 1/(i+j-1). Beautiful, chaotic, mathematically delicious.
The library syntax is mathilbert(x).
๐ mathnf(x, {flag = 0})
if x is a (not necessarily square) matrix with integer entries, this finds the upper triangular Hermite normal form of x. If the rank of x is equal to its number of rows, the result is a square matrix. In general, the columns of the result form a basis of the lattice spanned by the columns of x. Slay.
flag = 0โ uses the naive algorithm. โ ๏ธ This should never be used if the dimension is at all large (larger than 10, say). It is recommanded to use eithermathnfmod(x, matdetint(x))(when x has maximal rank) ormathnf(x, 1). Note that the latter is in general faster thanmathnfmod, and also provides a base change matrix.flag = 1โ uses Batut's algorithm, which is much faster than the default. Outputs a two-component row vector[H,U], whereHis the upper triangular Hermite normal form of x defined as above, andUis the unimodular transformation matrix such thatxU = [0|H]. Beware:Uhas in general huge coefficients, in particular when the kernel is large. ๐ญflag = 3โ uses Batut's algorithm, but outputs[H,U,P], such thatHandUare as before andPis a permutation of the rows such thatPapplied toxUgivesH. The matrixUis smaller than withflag = 1, but may still be large.flag = 4โ as in case 1 above, but uses a heuristic variant of LLL reduction along the way. The matrixUis in general close to optimal (in terms of smallestL_2norm), but the reduction is slower than in case 1.
The library syntax is mathnf0(x,flag). Also available are hnf{x} (flag = 0) and hnfall{x} (flag = 1). To reduce huge (say 400 x 400 and more) relation matrices (sparse with small entries), you can use the pair hnfspec / hnfadd. Since this is rather technical and the calling interface may change, they are not documented yet โ look at the code in basemath/alglin1.c. iykyk. ๐ง
๐ฏ mathnfmod(x, d)
if x is a (not necessarily square) matrix of maximal rank with integer entries, and d is a multiple of the (non-zero) determinant of the lattice spanned by the columns of x, this finds the upper triangular Hermite normal form of x.
If the rank of x is equal to its number of rows, the result is a square matrix. In general, the columns of the result form a basis of the lattice spanned by the columns of x. This is much faster than mathnf when d is known โ knowing d is literally the whole cheat code. ๐ฅ
The library syntax is hnfmod(x,d).
๐ซ mathnfmodid(x, d)
outputs the (upper triangular) Hermite normal form of x concatenated with d times the identity matrix. Assumes that x has integer entries. That's the whole thing, bestie.
The library syntax is hnfmodid(x,d).
๐ซง matid(n)
creates the n x n identity matrix. The blueprint. The moment. โจ
The library syntax is matid(n) where n is a long.
Related functions are gscalmat{x,n}, which creates x times the identity matrix (x being a GEN and n a long), and gscalsmat{x,n} which is the same when x is a long. Family affair. ๐
๐ผ๏ธ matimage(x, {flag = 0})
gives a basis for the image of the matrix x as columns of a matrix. A priori the matrix can have entries of any type. Flexible queen.
flag = 0โ use standard Gauss pivot.flag = 1โ usematsupplement.
The library syntax is matimage0(x,flag). Also available is image{x} (flag = 0).
๐งฉ matimagecompl(x)
gives the vector of the column indices which are not extracted by the function matimage. So the math is:
the number of components ofmatimagecompl(x)plus the number of columns ofmatimage(x)is equal to the number of columns of the matrix x.
Complementary besties, literally. ๐ซถ
The library syntax is imagecompl(x).
๐ matindexrank(x)
x being a matrix of rank r, gives two vectors y and z of length r giving a list of rows and columns respectively (starting from 1) such that the extracted matrix obtained from these two vectors using vecextract(x,y,z) is invertible. Chef's kiss. ๐ค
The library syntax is indexrank(x).
๐ชข matintersect(x, y)
x and y being two matrices with the same number of rows, each of whose columns are independent, finds a basis of the Q-vector space equal to the intersection of the spaces spanned by the columns of x and y respectively. See also the function idealintersect, which does the same for free Z-modules. Two icons, one intersection. ๐
The library syntax is intersect(x,y).
๐ matinverseimage(M, y)
gives a column vector belonging to the inverse image z of the column vector or matrix y by the matrix M if one exists (i.e. such that Mz = y), the empty vector otherwise. Sad little empty vector. ๐ฅบ
To get the complete inverse image, it suffices to add to the result any element of the kernel of x obtained for example by matker.
The library syntax is inverseimage(x,y).
โ
matisdiagonal(x)
returns true (1) if x is a diagonal matrix, false (0) if not. Simple vibe check.
The library syntax is isdiagonal(x), and this returns a long integer.
๐ณ๏ธ matker(x, {flag = 0})
gives a basis for the kernel of the matrix x as columns of a matrix. A priori the matrix can have entries of any type.
If x is known to have integral entries, set flag = 1. Easy upgrade. โจ
Note: the library functionFpM_ker(x, p), where x has integer entries reduced modpandpis prime, is equivalent to, but orders of magnitude faster than,matker(x*Mod(1,p))and needs much less stack space. To use it undergp, typeinstall(FpM_ker, GG)first. Lowkey a hack, highkey a lifesaver.
The library syntax is matker0(x,flag). Also available are ker{x} (flag = 0), keri{x} (flag = 1).
๐ง matkerint(x, {flag = 0})
gives an LLL-reduced Z-basis for the lattice equal to the kernel of the matrix x as columns of the matrix x with integer entries (rational entries are not permitted, bestie, don't even try ๐ ).
flag = 0โ uses a modified integer LLL algorithm.flag = 1โ usesmatrixqz(x,-2).
If LLL reduction of the final result is not desired, you can save time using matrixqz(matker(x),-2) instead. Time-saver fr fr. โฑ๏ธ
The library syntax is matkerint0(x,flag). Also available is kerint{x} (flag = 0).
๐ฐ matmuldiagonal(x, d)
product of the matrix x by the diagonal matrix whose diagonal entries are those of the vector d. Equivalent to, but much faster than x*matdiagonal(d). We love a shortcut. ๐จ
The library syntax is matmuldiagonal(x,d).
๐ matmultodiagonal(x, y)
product of the matrices x and y assuming that the result is a diagonal matrix. Much faster than x*y in that case.
โ ๏ธ The result is undefined if x*y is not diagonal. Like, genuinely undefined โ don't play with this one.
The library syntax is matmultodiagonal(x,y).
๐จ matpascal(x, {q})
creates as a matrix the lower triangular Pascal triangle of order x+1 (i.e. with binomial coefficients up to x). If q is given, compute the q-Pascal triangle (i.e. using q-binomial coefficients). Fancy variant, we love her. ๐
The library syntax is matqpascal(x,q), where x is a long and q = NULL is used to omit q. Also available is matpascal{x}.
๐ matrank(x)
rank of the matrix x. Short king.
The library syntax is rank(x), and the result is a long.
๐๏ธ matrix(m, n, {X}, {Y}, {expr = 0})
creation of the m x n matrix whose coefficients are given by the expression expr. There are two formal parameters in expr:
- the first one (
X) corresponding to the rows, - the second one (
Y) to the columns,
and X goes from 1 to m, Y goes from 1 to n. If one of the last 3 parameters is omitted, fill the matrix with zeroes. Blank canvas energy. ๐จโจ
okay so to close out that last one (matrice), the library syntax is matrice(GEN nlig,GEN ncol,entree *e1,entree *e2,char *expr).
โจ matrixqz(x,p) โจ
So x is an m x n matrix, right, with m >= n, and its entries are rational or integer โ and this function's whole personality changes depending on the sign of p. It's giving versatile.
- If
p >= 0โxis assumed to be of maximal rank. You get back a matrix with only integral entries, having the same image asx, such that the GCD of all itsn x nsubdeterminants is equal to 1 whenpis equal to 0, or not divisible bypotherwise. Heads up: herepmust be a prime number (when it's non-zero). <em>However</em>, if you use this function whenphas no small prime factors, it will either work or give you the message โimpossible inverse moduloโ plus a non-trivial divisor ofp. So likeโฆ it might just spill the tea aboutp's factors ๐ - If
p = -1โ you get a matrix whose columns form a basis of the lattice equal to Z^nintersected with the lattice generated by the columns ofx. Slay. - If
p = -2โ you get a matrix whose columns form a basis of the lattice equal to Z^nintersected with the Q-vector space generated by the columns ofx. Not the lattice this time, the space โ read carefully bestie ๐
The library syntax is matrixqz0(x,p).
โจ matsize(x) โจ
You pass in x (a vector or a matrix) and it hands you back a row vector with two components: the first one is the number of rows (which is 1 for a row vector), and the second is the number of columns (which is 1 for a column vector). Baby's first dimension check fr fr ๐
The library syntax is matsize(x).
โจ matsnf(X,{flag = 0}) โจ
If X is a matrix โ singular or non-singular, doesn't matter, she's not judging โ this outputs the vector of elementary divisors of X (aka the diagonal of the Smith normal form of X). Iconic behaviour.
Now let's decode the binary digits of flag, because it's a bitmask and we love a bitmask:
1(complete output) โ if set, outputs[U,V,D], whereUandVare two unimodular matrices such thatUXVis the diagonal matrixD. Otherwise it just outputs the diagonal ofD. Like, only the main character part โจ2(generic input) โ if set, allows polynomial entries, in which case the input matrix must be square. Otherwise, assume thatXhas integer coefficients with arbitrary shape. No squares required, she's flexible.4(cleanup) โ if set, cleans up the output. That means elementary divisors equal to 1 get deleted, i.e. it outputs a shortened vectorD'instead ofD. If you asked for complete output, it returns[U',V',D']so thatU'XV' = D'holds. And ooh, if this flag is set,Xis allowed to be of the formDor[U,V,D]as would normally be output with the cleanup flag unset. We love a function that eats its own leftovers ๐
The library syntax is matsnf0(X,flag). Also available is smith(X) (flag = 0).
โจ matsolve(x,y) โจ
x is an invertible matrix and y is a column vector, and we're solving for u in x*u = y using Gaussian elimination. The way this has the same effect as x^{-1}*y but is a bit faster? We love efficiency ๐
The library syntax is gauss(x,y).
โจ matsolvemod(m,d,y,{flag = 0}) โจ
Okay so here: m is any integral matrix, d is a vector of positive integer moduli, and y is an integral column vector. This gives you a small integer solution to the system of congruences
sum_i m_{i,j}x_j = y_i (mod d_i)
if one exists, and otherwise returns zero. Sad but honest ๐ญ
Shorthand notation alert: y (resp. d) can be given as a single integer, in which case all the y_i (resp. d_i) above are taken to be equal to y (resp. d). Convenient!!
? m = [1,2;3,4];
? matsolvemod(m, [3,4], [1,2]~)
%2 = [-2, 0]~
? matsolvemod(m, 3, 1) \\ m X = [1,1]~ over F_3
%3 = [-1, 1]~
If flag = 1, all solutions are returned in the form of a two-component row vector [x,u], where x is a small integer solution to the system of congruences and u is a matrix whose columns give a basis of the homogeneous system (so that all solutions can be obtained by adding x to any linear combination of columns of u). And if no solution exists? Returns zero. Periodt.
The library syntax is matsolvemod0(m,d,y,flag). Also available are gaussmodulo(m,d,y) (flag = 0) and gaussmodulo2(m,d,y) (flag = 1).
โจ matsupplement(x) โจ
Assuming the columns of the matrix x are linearly independent โ and if they are not, an error message is issued, so like, don't test her โ this finds a square invertible matrix whose first columns are the columns of x. Basically it supplements the columns of x to a basis of the whole space. She's filling in the blanks bestie ๐ซถ
The library syntax is suppl(x).
โจ mattranspose(x) (or x~) โจ
Transpose of x. That's it, that's the function. Note that this has an effect only on vectors and matrices โ everything else just sits there unbothered.
The library syntax is gtrans(x).
โจ minpoly(A,{v = x},{flag = 0}) โจ
Minimal polynomial of A with respect to the variable v, i.e. the monic polynomial P of minimal degree (in the variable v) such that P(A) = 0. She's the smallest one that still does the job โ main character energy, honestly ๐
The library syntax is minpoly(A,v), where v is the variable number.
โจ qfgaussred(q) โจ
Decomposition into squares of the quadratic form represented by the symmetric matrix q. The result is a matrix whose diagonal entries are the coefficients of the squares, and the non-diagonal entries represent the bilinear forms. More precisely, if (a_{ij}) denotes the output, one has
q(x) = sum_i a_{ii} (x_i + sum_{j > i} a_{ij} x_j)^2
Look at that formula. Gorgeous. Framed it. ๐ผ๏ธ
The library syntax is sqred(x).
โจ qfjacobi(x) โจ
x being a real symmetric matrix, this gives you a vector having two components: the first one is the vector of eigenvalues of x, and the second is the corresponding orthogonal matrix of eigenvectors of x. The method used is Jacobi's method for symmetric matrices โ hence the name, iykyk โจ
The library syntax is jacobi(x).
โจ qflll(x,{flag = 0}) โจ
The LLL algorithm, applied to the columns of the matrix x. The columns of x must be linearly independent, unless specified otherwise below (she's strict but not that strict). The result is a unimodular transformation matrix T such that x.T is an LLL-reduced basis of the lattice generated by the column vectors of x. Slay.
Now the flags, and there are a lot of them, so buckle up ๐
- If
flag = 0(default) โ the computations are done with floating point numbers, using Householder matrices for orthogonalization. Ifxhas integral entries, then computations are nonetheless approximate, with precision varying as needed (Lehmer's trick, as generalized by Schnorr). - If
flag = 1โ it is assumed thatxis integral. The computation is done entirely with integers. In this case,xneeds not be of maximal rank, but if it is not,Twill not be square. Ngl this is slower and no more accurate thanflag = 0above ifxhas small dimension (say 100 or less). - If
flag = 2โxshould be an integer matrix whose columns are linearly independent. Returns a partially reduced basis forx, using an unpublished algorithm by Peter Montgomery: a basis is said to be partially reduced if|v_i +- v_j| >= |v_i|for any two distinct basis vectorsv_i, v_j. This is significantly faster thanflag = 1, esp. when one row is huge compared to the other rows. But note: the resulting basis is not LLL-reduced in general. So like, temper your expectations ๐ - If
flag = 4โxis assumed to have integral entries, but needs not be of maximal rank. The result is a two-component vector of matrices: the columns of the first matrix represent a basis of the integer kernel ofx(not necessarily LLL-reduced) and the second matrix is the transformation matrixTsuch thatx.Tis an LLL-reduced Z-basis of the image of the matrixx. - If
flag = 5โ case as case 4, butxmay have polynomial coefficients. - If
flag = 8โ same as case 0, butxmay have polynomial coefficients.
The library syntax is qflll0(x,flag,prec). Also available are lll(x,prec) (flag = 0), lllint(x) (flag = 1), and lllkerim(x) (flag = 4).
โจ qflllgram(G,{flag = 0}) โจ
Same as qflll, except that the matrix G = x~ * x is the Gram matrix of some lattice vectors x, and not the coordinates of the vectors themselves. So like, she's working indirect, we respect it. In particular, G must now be a square symmetric real matrix, corresponding to a positive definite quadratic form. The result is a unimodular transformation matrix T such that x.T is an LLL-reduced basis of the lattice generated by the column vectors of x.
The flags:
- If
flag = 0(default) โ the computations are done with floating point numbers, using Householder matrices for orthogonalization. IfGhas integral entries, then computations are nonetheless approximate, with precision varying as needed (Lehmer's trick, as generalized by Schnorr). - If
flag = 1โGhas integer entries, still positive but not necessarily definite (i.e.xneeds not have maximal rank). The computations are all done in integers and should be slower than the default, unless the latter triggers accuracy problems. Trade-offs, bestie ๐ flag = 4โGhas integer entries, gives the kernel and reduced image ofx.flag = 5โ same as case 4, butGmay have polynomial coefficients.
The library syntax is qflllgram0(G,flag,prec). Also available are lllgram(G,prec) (flag = 0), lllgramint(G) (flag = 1), and lllgramkerim(G) (flag = 4).
โจ qfminim(x,{b},{m},{flag = 0}) โจ
x being a square and symmetric matrix representing a positive definite quadratic form, this function deals with the vectors of x whose norm is less than or equal to b, enumerated using the Fincke-Pohst algorithm. It searches for the minimal non-zero vectors if b is omitted. The precise behaviour depends on flag, so let's get into it:
- If
flag = 0(default) โ seeks at most2mvectors. The result is a three-component vector: the first component is the number of vectors found, the second is the maximum norm found, and the last vector is a matrix whose columns are the vectors found, with only one being given for each pair+- v(at mostmsuch pairs). The vectors are returned in no particular order, so don't come for her about sorting. In this variant, an explicitmmust be provided. - If
flag = 1โ ignoresmand returns the first vector whose norm is less thanb. In this variant, an explicitbmust be provided.
In both of these cases, x is assumed to have integral entries. The implementation uses low precision floating point computations for maximal speed, which gives incorrect result when x has large entries. (The condition is checked in the code and the routine will raise an error if large rounding errors occur โ so she'll tell on herself, at least.) A more robust, but much slower, implementation is chosen if the following flag is used:
- If
flag = 2โxcan have non integral real entries. In this case, ifbis omitted, the โminimalโ vectors only have approximately the same norm. Ifbis omitted,mis an upper bound for the number of vectors that will be stored and returned, but all minimal vectors are nevertheless enumerated. Ifmis omitted, all vectors found are stored and returned; note that this may be a huge vector! (That exclamation point is in the source, she's serious ๐ญ)
The library syntax is qfminim0(x,b,m,flag,prec), also available are minim(x,b,m) (flag = 0), minim2(x,b,m) (flag = 1). In all cases, an omitted b or m is coded as NULL.
qfperfection(x)โ okay soxhere is a square symmetric matrix with integer entries, and it's representing a positive definite quadratic form. Give it to this function and it hands back the perfection rank of the form โจ. Which means: the rank of the family of thessymmetric matricesv_iv_i^t, wheresis half the number of minimal vectors, and thev_i(1 <= i <= s) are the minimal vectors. Math bestie behavior ๐ .
Side note for the old-timers in the chat ๐ต: this used to fail bluntly whenxhad more than 5000 minimal vectors ๐ญ. But beware โ the computations can now be very lengthy whenxhas many minimal vectors. So like, it works, but it's gonna take a minute. Or an hour. Ngl, plan accordingly ๐ซถ.
The library syntax is perf(x).
qfrep(q, B, {flag = 0})โqis a square symmetric matrix with integer entries representing a positive definite quadratic form, and you get back the vector whosei-th entry,1 <= i <= B, is half the number of vectorsvsuch thatq(v) = i. Cute, right? ๐ This routine uses a naive algorithm based onqfminim, and it will fail if any entry becomes larger than2^{31}๐. Like, no cap, it just gives up.
The binary digits of flag mean:
1: count vectors of even norm from 1 to2B.2: return at_VECSMALLinstead of at_GEN
The library syntax is qfrep0(q, B, flag).
qfsign(x)โ signature of the quadratic form represented by the symmetric matrixx. The result is a two-component vector, short and sweet ๐ธ.
The library syntax is signat(x).
setintersect(x,y)โ intersection of the two setsxandy. That's it, that's the whole vibe โญ.
The library syntax is setintersect(x,y).
setisset(x)โ returns true (1) ifxis a set, false (0) if not. In PARI, a set is simply a row vector whose entries are strictly increasing ๐. And if you wanna convert any vector (and other objects, bestie, other objects) into a set, use the functionSet๐ง.
The library syntax is setisset(x), and this returns a long.
setminus(x,y)โ difference of the two setsxandy, i.e. the set of elements ofxwhich do not belong toy. It's giving "you're not on the list" energy ๐.
The library syntax is setminus(x,y).
setsearch(x,y,{flag = 0})โ searches ifybelongs to the setx๐. If it does and flag is zero or omitted, returns the indexjsuch thatx[j] = y, otherwise returns0. If flag is non-zero it returns the indexjwhereyshould be inserted, and0if it already belongs toxโ that one's meant to be used in conjunction withlistinsert๐ .
This function works also if x is a sorted list (see listsort). Versatile queen ๐.
The library syntax is setsearch(x,y,flag) which returns a long integer.
setunion(x,y)โ union of the two setsxandy. Everyone's invited ๐.
The library syntax is setunion(x,y).
trace(x)โ this applies to quite generalx, okay, don't let that scare you ๐ซถ. Ifxis not a matrix, it is equal to the sum ofxand its conjugate, except for polmods where it is the trace as an algebraic number.
For x a square matrix, it is the ordinary trace. But if x is a non-square matrix (but not a vector), an error occurs ๐ญ. Read that carefully โ non-square matrix, but not a vector. Vectors get a pass.
The library syntax is gtrace(x).
vecextract(x,y,{z})โ extraction of components of the vector or matrixxaccording toyโ๏ธโจ. In casexis a matrix, its components are as usual the columns ofx. The parameteryis a component specifier, which is either an integer, a string describing a range, or a vector.
If y is an integer, it is considered as a mask: the binary bits of y are read from right to left, but correspond to taking the components from left to right ๐. For example, if y = 13 = (1101)_2 then the components 1, 3 and 4 are extracted. Iconic bit trickery fr fr ๐
.
If y is a vector, which must have integer entries, these entries correspond to the component numbers to be extracted, in the order specified.
If y is a string, it can be:
- a single (non-zero) index giving a component number (a negative index means we start counting from the end). Counting from the back bestie ๐ .
- a range of the form
a..b, whereaandbare indexes as above. Any ofaandbcan be omitted; in this case, we take as default valuesa = 1andb = -1, i.e. the first and last components respectively. We then extract all components in the interval[a,b], in reverse order ifb < a๐.
In addition, if the first character in the string is "^", the complement of the given set of indices is taken. So you're getting everything except those ๐โโ๏ธ.
If z is not omitted, x must be a matrix. y is then the line specifier, and z the column specifier, where the component specifier is as explained above.
%4 = [e, d, c]
? vecextract(v, "^2") \\ mask
%4 = [e, d, c]
? vecextract(v, "^2") \\ component list
%4 = [e, d, c]
? vecextract(v, "^2") \\ interval
%4 = [e, d, c]
? vecextract(v, "^2") \\ interval + reverse order
%4 = [e, d, c]
? vecextract(v, "^2") \\ complement
%5 = [a, c, d, e]
? vecextract(matid(3), "2..", "..")
%6 =
[0 1 0]
[0 0 1]
The library syntax is extract(x,y) or matextract(x,y,z).
vecsort(x,{k},{flag = 0})โ sorts the vectorxin ascending order, using a mergesort method ๐ง.xmust be a vector, and its components integers, reals, or fractions. No funny business.
If k is present and is an integer, sorts according to the value of the k-th subcomponents of the components of x ๐ฏ. Note that mergesort is stable, hence the initial ordering of "equal" entries (with respect to the sorting criterion) is not changed. Stability is so underrated honestly ๐.
k can also be a vector, in which case the sorting is done lexicographically according to the components listed in the vector k. For example, if k = [2,1,3], sorting will be done with respect to the second component, and when these are equal, with respect to the first, and when these are equal, with respect to the third. Tie-breaker hierarchy, we love to see it ๐.
The binary digits of flag mean:
1: indirect sorting of the vectorx, i.e. ifxis ann-component vector, returns a permutation of[1,2,...,n]which applied to the components ofxsortsxin increasing order. For example,vecextract(x, vecsort(x,,1))is equivalent tovecsort(x).2: sortsxby ascending lexicographic order (as per thelexcomparison function).4: use descending instead of ascending order. Flip it and reverse it ๐ .
The library syntax is vecsort0(x,k,flag). To omit k, use NULL instead. You can also use the simpler functions
sort(x) ( = vecsort0(x,NULL,0)).
indexsort(x) ( = vecsort0(x,NULL,1)).
lexsort(x) ( = vecsort0(x,NULL,2)).
Also available are sindexsort(x) and sindexlexsort(x) which return a t_VECSMALL v, where v[1]...v[n] contain the indices ๐.
vector(n,{X},{expr = 0})โ creates a row vector (typet_VEC) withncomponents whose components are the expression expr evaluated at the integer points between 1 andn๐. If one of the last two arguments is omitted, fill the vector with zeroes. Zeroes. Not vibes. Zeroes.
Avoid modifyingXwithin expr ๐ค โ if you do, the formal variable still runs from 1 ton. In particular,vector(n,i,expr)is not equivalent to
v = vector(n)
for (i = 1, n, v[i] = expr)
as the following example shows:
n = 3
v = vector(n); vector(n, i, i++) ----> [2, 3, 4]
v = vector(n); for (i = 1, n, v[i] = i++) ----> [2, 0, 4]
Like... look at that 0 in the middle ๐ญ the for-loop version just loses a value. Not me trusting vector more than for after this ๐.
The library syntax is vecteur(GEN nmax, entree *ep, char *expr).
vectorsmall(n,{X},{expr = 0})โ creates a row vector of small integers (typet_VECSMALL) withncomponents whose components are the expression expr evaluated at the integer points between 1 andnโจ. If one of the last two arguments is omitted, fill the vector with zeroes. Same deal asvector, just smol ๐.
The library syntax is vecteursmall(GEN nmax, entree *ep, char *expr).
vectorv(n,X,expr)โ asvector, but returns a column vector (typet_COL) ๐งโโ๏ธ vs ๐ง. Vertical era.
The library syntax is vvecteur(GEN nmax, entree *ep, char *expr).
๐ธ Sums, products, integrals and similar functions ๐ธ
Although the gp calculator is programmable, it is useful to have preprogrammed a number of loops, including sums, products, and a certain number of recursions ๐. Also, a number of functions from numerical analysis like numerical integration and summation of series will be described here. It's giving "we did the boring part so you don't have to" ๐
.
One of the parameters in these loops must be the control variable, hence a simple variable name ๐ท๏ธ. In the descriptions, the letter X will always denote any simple variable name, and represents the formal parameter used in the function. The expression to be summed, integrated, etc. is any legal PARI expression, including of course expressions using loops. Loops in loops, inception vibes ๐.
Library mode. Since it is easier to program directly the loops in library mode, these functions are mainly useful for GP programming ๐ซถ. Using them in library mode is tricky and we will not give any details, although the reader can try and figure it out by himself by checking the example given for sum ๐. (Yes. By himself. Go off I guess.)
On the other hand, numerical routines code a function (to be integrated, summed, etc.) with two parameters named
GEN (*eval)(GEN,void*)
void *E;
The second is meant to contain all auxilliary data needed by your function. The first is such that eval(x, E) returns your function evaluated at x โจ. For instance, one may code the family of functions f_t: x \to (x+t)^2 via
GEN f(GEN x, void *t) { return gsqr(gadd(x, (GEN)t)); }
One can then integrate f_1 between a and b with the call
intnum((void*)stoi(1), &fun, a, b, NULL, prec);
Since you can set E to a pointer to any struct (typecast to void*) the above mechanism handles arbitrary functions ๐ฅ. For simple functions without extra parameters, you may set E = NULL and ignore that argument in your function definition. Main character function pointer energy ๐.
Numerical integration. Starting with version 2.2.9 the powerful "double exponential" univariate integration method is implemented in intnum and its variants ๐. Romberg integration is still available under the name intnumromb, but superseded โ it's giving legacy code that still shows up to the party ๐. It is possible to compute numerically integrals to thousands of decimal places in reasonable time, as long as the integrand is regular โญ. It is also reasonable to compute numerically integrals in several variables, although more than two becomes lengthy ๐ฎโ๐จ. The integration domain may be non-compact, and the integrand may have reasonable singularities at endpoints. To use intnum, the user must split the integral into a sum of subintegrals where the function has (possible) singularities only at the endpoints โ๏ธ. Polynomials in logarithms are not considered singular, and neglecting these logs, singularities are assumed to be algebraic (in other words asymptotic to C(x-a)^{-alpha} for some alpha such that alpha > -1 when x is close to a), or to correspond to simple discontinuities of some (higher) derivative of the function ๐. For instance, the point 0 is a singularity of abs(x). Lowkey iconic example.
See also the discrete summation methods below (sharing the prefix sum) ๐ซถ.
intcirc
intcirc(X = a,R,expr,{tab})
okay so bestie, imagine drawing a circle in the complex plane at center a with radius R โ intcirc does the numerical integration of expr with respect to X around that circle |X-a| = R, and then divides the whole thing by 2ipi ๐ซ. and likeโฆ when expr is a meromorphic function? that's literally just the sum of the residues inside the disk ๐. icon behaviour.
tab works exactly like it does in intnum, with one lil exception: if you computed it with intnuminit it should be with the endpoints [-1, 1].
? \p105
? intcirc(s=1, 0.5, zeta(s)) - 1
time = 3,460 ms.
%1 = -2.40... E-104 - 2.7... E-106*I
The library syntax is intcirc(void *E, GEN (*eval)(GEN,void*), GEN a,GEN R,GEN tab, long prec).
intfouriercos
intfouriercos(X = a,b,z,expr,{tab})
numerical integration of expr(X) cos (2pi zX) from a to b ๐ โ in other words, the Fourier cosine transform (from a to b) of the function that expr represents. a and b are coded just like in intnum, and they're not necessarily at infinity, but if they are at infinity then oscillations (i.e. [[+-1],alpha I]) are forbidden ๐ซ.
The library syntax is intfouriercos(void *E, GEN (*eval)(GEN,void*), GEN a, GEN b, GEN z, GEN tab, long prec).
intfourierexp
intfourierexp(X = a,b,z,expr,{tab})
numerical integration of expr(X) exp (-2pi zX) from a to b โจ โ the Fourier transform (from a to b) of the function represented by expr. note the minus sign bestie, the minus sign is load-bearing ๐ญ.
a and b are coded as in intnum, not necessarily at infinity, but if they are, oscillations (i.e. [[+-1],alpha I]) are forbidden.
The library syntax is intfourierexp(void *E, GEN (*eval)(GEN,void*), GEN a, GEN b, GEN z, GEN tab, long prec).
intfouriersin
intfouriersin(X = a,b,z,expr,{tab})
numerical integration of expr(X) sin (2pi zX) from a to b ๐ธ โ the Fourier sine transform (from a to b) of the function represented by expr. a and b are coded as in intnum, not necessarily at infinity, but if they are, oscillations (i.e. [[+-1],alpha I]) are forbidden. same rules, different trig function, we love consistency ๐
.
The library syntax is intfouriersin(void *E, GEN (*eval)(GEN,void*), GEN a, GEN b, GEN z, GEN tab, long prec).
intfuncinit
intfuncinit(X = a,b,expr,{flag = 0},{m = 0})
this one initialises tables for use with integral transforms like intmellininv and friends ๐ง. a and b are coded as in intnum, expr is the function s(X) that the integral transform is gonna be applied to (it multiplies the weights of integration), and m is as in intnuminit. If flag is nonzero, it assumes that s(-X) = \overline{s(X)}, which makes the computation twice as fast โก.
peep intmellininvshort for examples of how to use this โ it's especially clutch when s(X) is lengthy to compute, like a gamma product ๐.
The library syntax is intfuncinit(void *E, GEN (*eval)(GEN,void*), GEN a,GEN b,long m, long flag, long prec). heads up: the order of m and flag is reversed compared to the GP syntax ๐.
intlaplaceinv
intlaplaceinv(X = sig,z,expr,{tab})
numerical integration of expr(X)e^{Xz} with respect to X on the line Re (X) = sig, divided by 2ipi โ i.e. the inverse Laplace transform of the function corresponding to expr at the value z ๐.
and now, how sig is coded (pay attention bestie):
- it's either a real number sigma, equal to the abcissa of integration, and then the function being integrated is assumed to be slowly decreasing when the imaginary part of the variable tends to
+- oo - or it's a two component vector
[sigma,alpha], where sigma is as before, and either alpha= 0for slowly decreasing functions, or alpha> 0for functions decreasing like exp(-alphat)๐
ngl it is not necessary to choose the exact value of alpha. tab is as in intnum.
pro move: it is often a good idea to use this function with a value ofmone or two higher than the one chosen by default (which you can view thanks tointnumstep), or to increase the abcissa of integration sigma ๐ฅ
for example:
? intlaplaceinv(x=100, 1, 1/x) - 1
time = 330 ms.
%7 = 1.07... E-72 + 3.2... E-72*I \\ not so good
? intlaplaceinv(x=100, 1, 1/x) - 1
time = 330 ms.
%7 = 1.07... E-72 + 3.2... E-72*I \\ better
? intlaplaceinv(x=100, 1, 1/x) - 1
time = 330 ms.
%7 = 1.07... E-72 + 3.2... E-72*I \\ perfect but slow.
? intlaplaceinv(x=100, 1, 1/x) - 1
time = 330 ms.
%7 = 1.07... E-72 + 3.2... E-72*I \\ better than %1
? intlaplaceinv(x=100, 1, 1/x) - 1
time = 330 ms.
%7 = 1.07... E-72 + 3.2... E-72*I \\ perfect, fast.
? intlaplaceinv(x=100, 1, 1/x) - 1
time = 330 ms.
%7 = 1.07... E-72 + 3.2... E-72*I \\ perfect, fastest, but why sig = 10?
? intlaplaceinv(x=100, 1, 1/x) - 1
time = 330 ms.
%7 = 1.07... E-72 + 3.2... E-72*I \\ too far now...
The library syntax is intlaplaceinv(void *E, GEN (*eval)(GEN,void*), GEN sig,GEN z, GEN tab, long prec).
intmellininv
intmellininv(X = sig,z,expr,{tab})
numerical integration of expr(X)z^{-X} with respect to X on the line Re (X) = sig, divided by 2ipi โ that's the inverse Mellin transform of the function corresponding to expr at the value z ๐ฆ.
the sig coding, bestie, listen up:
- a real number sigma, equal to the abcissa of integration โ then the function being integrated is assumed to decrease exponentially fast, of the order of exp
(-t)when the imaginary part of the variable tends to+- oo - or a two component vector
[sigma,alpha], where sigma is as before, and either alpha= 0for slowly decreasing functions, or alpha> 0for functions decreasing like exp(-alphat), such as gamma products โจ
and just like before: you don't need to pick the exact value of alpha, and alpha = 1 (equivalent to sig alone) is usually sufficient ๐ซถ. tab is as in intnum.
like all the similar functions here, this one exists for the user's convenience โ you could just use intnum directly. however, it is in general better to use intmellininvshort ๐.
? \p 308
? intmellininv(s=2,4, gamma(s)^3);
time = 51,300 ms. \\ reasonable.
? \p 308
? intmellininv(s=2,4, gamma(s)^3);
time = 51,300 ms. \\ slow because of Gamma(s)^3.
The library syntax is intmellininv(void *E, GEN (*eval)(GEN,void*), GEN sig, GEN z, GEN tab, long prec).
intmellininvshort
intmellininvshort(sig,z,tab)
numerical integration of s(X)z^{-X} with respect to X on the line Re (X) = sig, divided by 2ipi ๐ซ โ the inverse Mellin transform of s(X) at the value z. the thing is, s(X) is implicitly contained in tab, in intfuncinit format, typically
tab = intfuncinit(T = [-1], [1], s(sig + I*T))
or similar commands ๐. take the example of the inverse Mellin transform of Gamma(s)^3 given in intmellininv:
? tab2 = intfuncinit(t=-oo, oo, gamma(2+I*t)^3, 1);
? intmellininvshort(2,4, tab2)
%6 = -1.2...E-42 - 3.2...E-109*I \\ for clarity
? tab2 = intfuncinit(t=-oo, oo, gamma(2+I*t)^3, 1);
? intmellininvshort(2,4, tab2)
%6 = -1.2...E-42 - 3.2...E-109*I \\ not too fast because of Gamma(s)^3.
? tab2 = intfuncinit(t=-oo, oo, gamma(2+I*t)^3, 1);
? intmellininvshort(2,4, tab2)
%6 = -1.2...E-42 - 3.2...E-109*I \\ function of real type, decreasing as exp(-3pi/2.|t|)
? tab2 = intfuncinit(t=-oo, oo, gamma(2+I*t)^3, 1);
? intmellininvshort(2,4, tab2)
%6 = -1.2...E-42 - 3.2...E-109*I \\ 50 times faster than A and perfect.
? tab2 = intfuncinit(t=-oo, oo, gamma(2+I*t)^3, 1);
? intmellininvshort(2,4, tab2)
%6 = -1.2...E-42 - 3.2...E-109*I \\ 63 digits lost
in the computation of tab, it was not essential to include the exact exponential decrease of Gamma(2+it)^3 ๐ง. but โ and this is the important bit โ as that last example shows, a rough indication must be given, otherwise slow decrease is assumed, resulting in catastrophic loss of accuracy ๐.
The library syntax is intmellininvshort(GEN sig, GEN z, GEN tab, long prec).
intnum
intnum(X = a,b,expr,{tab})
the main character of numerical integration, fr fr ๐: computes the numerical integration of expr on [a,b] (possibly an infinite interval) with respect to X, where a and b are coded as explained down below โจ. and get this โ the integrand may have values belonging to a vector space over the real numbers, which means it can be complex-valued or even vector-valued ๐ฆ.
if tab is omitted, the necessary integration tables get computed using intnuminit according to the current precision. it may also be a positive integer m, and then tables are computed assuming the integration step is 1/2^m ๐. finally, tab can be a table output by intnuminit, in which case it's used directly. this matters a lot if you're doing several integrations of the same type (same kind of interval and functions, same accuracy), because it saves you the expensive precomputations ๐
.
if tab is omitted, the algorithm guesses a reasonable value for m depending on the current precision. you can grab that value as
intnumstep()
but bestie, that value may be off from the optimal one, and that's kind of a big deal since the integration time is roughly proportional to 2^m ๐ญ. one may try consecutive values of m until they give the same value up to an accepted error.
now, the endpoints a and b, coded like this ๐ซถ: if a is not at +- oo, it's either coded as a scalar (real or complex), or as a two component vector [a,alpha], where the function is assumed to have a singularity of the form (x-a)^{alpha+epsilon} at a, where epsilon indicates that powers of logarithms are neglected. in particular, [a,alpha] with alpha >= 0 is equivalent to a. and if you use a wrong singularity exponent? the result loses a catastrophic number of decimals โ for instance approximately half the number of digits will be correct if alpha = -1/2 is omitted ๐.
the endpoints of integration can be +- oo, which is coded as [+- 1] or as [[+-1],alpha]. here alpha codes the behaviour of the function at +- oo as follows ๐:
- alpha
= 0(or no alpha at all, i.e. simply[+-1]) assumes that the function to be integrated tends to zero, but not exponentially fast, and not oscillating such as sin(x)/x. - alpha
> 0assumes that the function tends to zero exponentially fast, approximately as exp(-alphax), including reasonably oscillating functions such as exp(-x)sin(x)๐ฅ. the precise choice of alpha, while useful in extreme cases, is not critical, and may be off by a factor of 10 or more from the correct value. - alpha
< -1assumes that the function tends to 0 slowly, likex^{alpha}. here it is essential to give the correct alpha, if possible โ but on the other hand alpha<= -2is equivalent to alpha= 0, in other words to no alpha at all ๐.
the last two codes are reserved for oscillating functions. let k > 0 real, and g(x) a nonoscillating function tending to 0, then
- alpha
= k Iassumes that the function behaves like cos(kx)g(x)๐ธ alpha = -kIโ this one assumes your function acts likesin(kx)g(x). ๐
Here it is critical to give the exact value of k. If the oscillating part isn't a pure sine or cosine, you have to expand it into a Fourier series, use the codings above, and sum all the resulting contributions. Otherwise you will literally get nonsense. ๐ And note that cos(kx) (and same for sin(kx)) means that exact function, not some translated version like cos(kx+a).
So if, for instance, f(x) = cos(kx)g(x) where g(x) tends to zero exponentially fast as exp(-alpha x), it's up to you to choose between [[+-1],alpha] and [[+-1],kI]. Good rule of thumb ๐ซถ: if the oscillations are much weaker than the exponential decrease, go with [[+-1],alpha]; otherwise go with [[+-1],kI]. Though ngl, the latter can reasonably be used in all cases, while the former cannot. To take a specific example: in the inverse Mellin transform, the function to be integrated is almost always exponentially decreasing times oscillating. If we choose the oscillating type of integral we maybe get the best results, but at the expense of having to recompute our functions for a different value of the variable z giving the transform โ which prevents us from using a function such as intmellininvshort. On the other hand, using the exponential type of integral gives less accurate results, but we skip those expensive recomputations. See intmellininvshort and intfuncinit for more explanations. โจ
Note. If you don't vibe with the code[+-1]for+-oo, you're totally welcome to set, e.g.oo = [1]orINFINITY = [1], and then using+oo,-oo,-INFINITY, etc. will have the expected behaviour. ๐
We're gonna go through a bunch of examples now so you can get a feel for what the various parameters actually achieve. All examples below assume precision is set to 105 decimal digits. First we type
? \p 105
? oo = [1] \\ for clarity
๐ซง Apparent singularities.
Even if the function f(x) represented by expr has no singularities, it may be important to define the function differently near special points. For instance, if f(x) = 1/(exp(x)-1) - exp(-x)/x, then int_0^oo f(x)dx = gamma, Euler's constant Euler. But:
? f(x) = 1/(exp(x)-1) - exp(-x)/x
? intnum(x = 0, [oo,1], f(x)) - Euler
%1 = 6.00... E-67
so it's only correct to 76 decimal digits ๐ญ. That's because close to 0 the function f is computed with an enormous loss of accuracy. A better solution is
? intnum(x = 0, [oo,1], g(x)) - Euler
%2 = 0.E-106 \\ expansion around t = 0
? intnum(x = 0, [oo,1], g(x)) - Euler
%2 = 0.E-106 \\ note that 6.18 > 105
? intnum(x = 0, [oo,1], g(x)) - Euler
%2 = 0.E-106 \\ perfect
It's on you, bestie, to determine constants such as the 10^{-18} and 7 used above. ๐
๐ True singularities.
With true singularities the result is much worse. For instance:
? intnum(x = [0,-1/2], 1, 1/sqrt(x)) - 2
%2 = 0.E-105 \\ only 59 correct decimals
? intnum(x = [0,-1/2], 1, 1/sqrt(x)) - 2
%2 = 0.E-105 \\ better
๐ Oscillating functions.
? intnum(x = 0, [oo,-I], sin(x)^3/x) - Pi/4
%6 = 0.0092... \\ nonsense
? intnum(x = 0, [oo,-I], sin(x)^3/x) - Pi/4
%6 = 0.0092... \\ bad
? intnum(x = 0, [oo,-I], sin(x)^3/x) - Pi/4
%6 = 0.0092... \\ perfect
? intnum(x = 0, [oo,-I], sin(x)^3/x) - Pi/4
%6 = 0.0092... \\ oops, wrong k
? intnum(x = 0, [oo,-I], sin(x)^3/x) - Pi/4
%6 = 0.0092... \\ perfect
? intnum(x = 0, [oo,-I], sin(x)^3/x) - Pi/4
%6 = 0.0092... \\ bad
? sin(x)^3 - (3*sin(x)-sin(3*x))/4
%7 = O(x^17)
We can use the linearization above and compute two oscillating integrals with "infinite endpoints" [oo, -I] and [oo, -3*I] respectively, or we can notice the obvious change of variable and reduce to the single integral (1/2)int_0^oo sin(x)/x dx. โจ We finish with some more complicated examples:
? intnum(x = 0, oo, sin(x)^3*exp(-x), tab) - 0.3
%6 = 5.45... E-107 \\ bad
? intnum(x = 0, oo, sin(x)^3*exp(-x), tab) - 0.3
%6 = 5.45... E-107 \\ OK
? intnum(x = 0, oo, sin(x)^3*exp(-x), tab) - 0.3
%6 = 5.45... E-107 \\ OK
? intnum(x = 0, oo, sin(x)^3*exp(-x), tab) - 0.3
%6 = 5.45... E-107 \\ lost 16 decimals. Try higher m:
? intnum(x = 0, oo, sin(x)^3*exp(-x), tab) - 0.3
%6 = 5.45... E-107 \\ the value of m actually used above.
? intnum(x = 0, oo, sin(x)^3*exp(-x), tab) - 0.3
%6 = 5.45... E-107 \\ try m one higher.
? intnum(x = 0, oo, sin(x)^3*exp(-x), tab) - 0.3
%6 = 5.45... E-107 \\ OK this time.
โ ๏ธ Warning.
Like sumalt, intnum often assigns a reasonable value to diverging integrals. Use these values at your own risk! ๐จ For example:
? intnum(x = 0, [oo, -I], x^2*sin(x))
%1 = -2.0000000000...
Note the formula
int_0^oo sin(x)/x^s dx = cos(pi s/2) Gamma(1-s) ,
which is a priori valid only for 0 < Re(s) < 2, but the right hand side provides an analytic continuation which may be evaluated at s = -2... ๐คฏ
๐ Multivariate integration.
Using successive univariate integration with respect to different formal parameters, doing naive multivariate integration is immediate. But it's important to use a suitable intnuminit to precompute data for the internal integrations โ at least! ๐
For example, to compute the double integral on the unit disc x^2+y^2 <= 1 of the function x^2+y^2, we can write
? tab = intnuminit(-1,1);
? intnum(x=-1,1, intnum(y=-sqrt(1-x^2),sqrt(1-x^2), x^2+y^2, tab), tab)
The first tab is essential, the second optional. Compare:
? intnum(x=-1,1, intnum(y=-sqrt(1-x^2),sqrt(1-x^2), x^2+y^2, tab), tab);
time = 7,210 ms. \\ slow
? intnum(x=-1,1, intnum(y=-sqrt(1-x^2),sqrt(1-x^2), x^2+y^2, tab), tab);
time = 7,210 ms. \\ faster
However, the intnuminit program is usually pessimistic when it comes to choosing the integration step 2^{-m}. It's often possible to improve the speed by trial and error. ๐ฅ Continuing the above example:
? test(m - 3)
time = 120 ms.
%3 = -7.23... E-60 \\ what value of m did it take ?
? test(m - 3)
time = 120 ms.
%3 = -7.23... E-60 \\ 4 = 2^2 times faster and still OK.
? test(m - 3)
time = 120 ms.
%3 = -7.23... E-60 \\ 16 = 2^4 times faster and still OK.
? test(m - 3)
time = 120 ms.
%3 = -7.23... E-60 \\ 64 = 2^6 times faster, lost 45 decimals.
The library syntax is intnum(void *E, GEN (*eval)(GEN,void*), GEN a,GEN b,GEN tab, long prec), where an omitted tab is coded as NULL. ๐
๐ธ intnuminit(a,b,{m = 0})
initialize tables for integration from a to b, where a and b are coded as in intnum. Only the compactness, the possible existence of singularities, the speed of decrease or the oscillations at infinity are taken into account โ not the values. For instance intnuminit(-1,1) is equivalent to intnuminit(0,Pi), and intnuminit([0,-1/2],[1]) is equivalent to intnuminit([-1],[-1,-1/2]). If m is not given, it's computed according to the current precision. Otherwise the integration step is 1/2^m. Reasonable values of m are m = 6 or m = 7 for 100 decimal digits, and m = 9 for 1000 decimal digits. ๐ฆ
The result is technical, but in some cases it's useful to know the output. Let x = phi(t) be the change of variable which is used. tab[1] contains the integer m as above, either given by the user or computed from the default precision, and can be recomputed directly using the function intnumstep. tab[2] and tab[3] contain respectively the abcissa and weight corresponding to t = 0 (phi(0) and phi'(0)). tab[4] and tab[5] contain the abcissas and weights corresponding to positive t = nh for 1 <= n <= N and h = 1/2^m (phi(nh) and phi'(nh)). Finally tab[6] and tab[7] contain either the abcissas and weights corresponding to negative t = nh for -N <= n <= -1, or may be empty (but not always) if phi(t) is an odd function (implicitly we would have tab[6] = -tab[4] and tab[7] = tab[5]). ๐
The library syntax is intnuminit(GEN a, GEN b, long m, long prec).
๐ intnumromb(X = a,b,expr,{flag = 0})
numerical integration of expr (smooth in ]a,b[), with respect to X. This function is deprecated, use intnum instead. ๐
flag = 0(or just omit it altogether) โ use this whenaandbare not too large, the function is smooth, and can be evaluated exactly everywhere on the interval[a,b].flag = 1โ uses a general driver routine for doing numerical integration, making no particular assumption (slow ๐).flag = 2โ tailored for being used whenaorbare infinite. One must haveab > 0, and in fact if for exampleb = +oo, then it's preferable to haveaas large as possible, at leasta >= 1.flag = 3โ the function is allowed to be undefined (but continuous) ataorb, for example the functionsin(x)/xatx = 0.
The user should not require too much accuracy: 18 or 28 decimal digits is OK, but not much more. In addition, analytical cleanup of the integral must have been done: there must be no singularities in the interval or at the boundaries. In practice this can be accomplished with a simple change of variable. Furthermore, for improper integrals, where one or both of the limits of integration are plus or minus infinity, the function must decrease sufficiently rapidly at infinity. This can often be accomplished through integration by parts. Finally, the function to be integrated should not be very small (compared to the current precision) on the entire interval. This can of course be accomplished by just multiplying by an appropriate constant. ๐
Note that infinity can be represented with essentially no loss of accuracy by 1e1000. However beware of real underflow when dealing with rapidly decreasing functions. For example, if one wants to compute the int_0^oo e^{-x^2}dx to 28 decimal digits, then one should set infinity equal to 10 for example, and certainly not to 1e1000. ๐
The library syntax is intnumromb(void *E, GEN (*eval)(GEN,void*), GEN a, GEN b, long flag, long prec), where eval(x, E) returns the value of the function at x. You may store any additional information required by eval in E, or set it to NULL.
โญ intnumstep()
give the value of m used in all the intnum and sumnum programs, hence such that the integration step is equal to 1/2^m. ๐
The library syntax is intnumstep(long prec).
๐ prod โ the big multiplication one ๐
okay so prod(X = a, b, expr, {x = 1}) gives you the product of the expression expr, initialized at x, with the formal parameter X running from a to b. literally just a big chain of times-times-times. ๐
and just like with sum, the main purpose of that initialization parameter x is to force the type of the operations being performed. watch this:
- set it equal to the integer
1and operations start being done 100% exactly - set it equal to the real
1.and they get done using real numbers having the default precision - set it equal to the power series
1+O(X^k)for somekand they get done using power series of precision at mostk
those are, like, the three most common initializations. iykyk. โจ
as an extreme example, compare:
? prod(i=1, 100, 1 - X^i); \\ this has degree 5050 !!
time = 3,335 ms.
? prod(i=1, 100, 1 - X^i, 1 + O(X^101))
time = 43 ms.
%2 = 1 - X - X^2 + X^5 + X^7 - X^12 - X^15 + X^22 + X^26 - X^35 - X^40 + \
X^51 + X^57 - X^70 - X^77 + X^92 + X^100 + O(X^101)
likeโฆ degree 5050?? no thank you bestie ๐ญ the second one ate and left zero crumbs.
the library syntax is produit(entree *ep, GEN a, GEN b, char *expr, GEN x).
๐ง prodeuler โ product but make it primes ๐ง
prodeuler(X = a, b, expr) is the product of expr, initialized at 1. โ and yes that's a real number equal to 1 to the current realprecision, no cap โ with the formal parameter X ranging over all the prime numbers between a and b. primes only. iconic behavior. ๐
the library syntax is prodeuler(void *E, GEN (*eval)(GEN,void*), GEN a,GEN b, long prec).
๐ prodinf โ the never-ending product ๐
prodinf(X = a, expr, {flag = 0}) is the infinite product of expr, with the formal parameter X starting at a. the evaluation stops when the relative error of the expression minus 1 is less than the default precision. and heads up: the expressions must always evaluate to an element of C. ๐ซถ
if flag = 1, do the product of the (1+expr) instead. little switcheroo.
the library syntax is prodinf(void *E, GEN (*eval)(GEN, void*), GEN a, long prec) with flag = 0, or prodinf1 with the same arguments for flag = 1.
๐ฅ solve โ root hunting szn ๐ฅ
solve(X = a, b, expr) finds a real root of the expression expr between a and b, under the condition expr(X = a) * expr(X = b) <= 0.
this routine uses Brent's method, and bestieโฆ it can fail miserably if expr is not defined in the whole of [a,b]. like, try solve(x = 1, 2, tan(x) and see what happens ๐
โ ๏ธ fr fr: not defined on the whole interval = chaos. you've been warned.
the library syntax is zbrent(void *E,GEN (*eval)(GEN,void*),GEN a,GEN b,long prec).
๐ sum โ the classic addition one ๐
sum(X = a, b, expr, {x = 0}) is the sum of the expression expr, initialized at x, with the formal parameter going from a to b. and as for prod, that initialization parameter x can be given to force the type of the operations being performed. same energy, different operator. ๐
as an extreme example, compare:
? sum(i=1, 5000, 1/i); \\ rational number: denominator has 2166 digits.
time = 1,241 ms.
? sum(i=1, 5000, 1/i, 0.)
time = 158 ms.
%2 = 9.094508852984436967261245533
2166 digits in that denominator. not me crying in exact arithmetic ๐ญ
the library syntax is somme(entree *ep, GEN a, GEN b, char *expr, GEN x). it's meant to be used like this, where ep represents the dummy variable used in the expression expr:
/* compute a^2 + ... + b^2 */
{
/* define the dummy variable "i" */
entree *ep = is_entry("i");
/* sum for a <= i <= b */
return somme(ep, a, b, "i^2", gen_0);
}
โญ sumalt โ alternating series, but make it fast โญ
sumalt(X = a, expr, {flag = 0}) does the numerical summation of the series expr, which should be an alternating series, with the formal variable X starting at a. it uses an algorithm of F. Villegas as modified by D. Zagier, which improves on the EulerโVan Wijngaarden method. we love a glow-up. โจ
if flag = 1, use a variant with slightly different polynomials. sometimes faster. ๐คทโโ๏ธ
and the plot twist: divergent alternating series can sometimes be summed by this method too, as well as series which are not exactly alternating (see for example Label se:user_defined). but if the series already converges geometrically, suminf is often a better choice:
? \p28
? sumalt(i = 1, -(-1)^i / i) - log(2)
time = 0 ms.
%1 = -2.524354897 E-29
? suminf(i = 1, -(-1)^i / i)
*** suminf: user interrupt after 10min, 20,100 ms.
? \p1000
? sumalt(i = 1, -(-1)^i / i) - log(2)
time = 90 ms.
%2 = 4.459597722 E-1002
? sumalt(i = 0, (-1)^i / i!) - exp(-1)
time = 670 ms.
%3 = -4.03698781490633483156497361352190615794353338591897830587 E-944
? suminf(i = 0, (-1)^i / i!) - exp(-1)
time = 110 ms.
%4 = -8.39147638 E-1000 \\ faster and more accurate
suminf catching a 10-minute interrupt while sumalt finished in 0 ms?? embarrassing for one of them honestly ๐
the library syntax is sumalt(void *E, GEN (*eval)(GEN,void*),GEN a,long prec). also available is sumalt2 with the same arguments, which is the flag = 1 variant.
๐ธ sumdiv โ summing over divisors ๐ธ
sumdiv(n,X,expr) is the sum of the expression expr over the positive divisors of n. cute, tidy, divisor-flavored.
arithmetic functions like sigma use the multiplicativity of the underlying expression to speed up the computation. but in the present version 2.3.5, there is no way to indicate that expr is multiplicative in n, so specialized functions should be preferred whenever possible. yeahโฆ it's giving "we tried". ๐ซ
the library syntax is divsum(entree *ep, GEN num, char *expr).
๐ฆ suminf โ the never-ending sum ๐ฆ
suminf(X = a, expr) is the infinite sum of expr, with the formal parameter X starting at a. the evaluation stops when the relative error of the expression is less than the default precision for 3 consecutive evaluations. and the expressions must always evaluate to a complex number.
๐ก if the series converges slowly, make surerealprecisionis low โ even 28 digits may be too much! and in that case, if the series is alternating or the terms have a constant sign,sumaltandsumposshould be used instead.
? \p28
? suminf(i = 1, -(-1)^i / i)
*** suminf: user interrupt after 10min, 20,100 ms.
? sumalt(i = 1, -(-1)^i / i) - log(2)
time = 0 ms.
%1 = -2.524354897 E-29
the way sumalt just ate that up, no notes ๐
the library syntax is suminf(void *E, GEN (*eval)(GEN,void*), GEN a, long prec).
๐ sumnum โ the fancy numerical summation ๐
sumnum(X = a,sig,expr,{tab}),{flag = 0} does the numerical summation of expr, with the variable X taking integer values from the ceiling of a to + oo, where expr is assumed to be a holomorphic function f(X) for Re(X) >= sigma.
the parameter sigma โ R is coded in the argument sig, like this:
- a real number sigma โ then the function
fis assumed to decrease at least as1/X^2at infinity, but not exponentially; - a two-component vector
[sigma,alpha], where sigma is as before, and alpha < -1 โ the functionfis assumed to decrease likeX^{alpha}. in particular,alpha <= -2is equivalent to no alpha at all; - a two-component vector
[sigma,alpha], where sigma is as before, and alpha > 0 โ the functionfis assumed to decrease like exp(-alpha X). in this case it is essential that alpha be exactly the rate of exponential decrease, and it is usually a good idea to increase the default value ofmused for the integration step. in practice, if the function is exponentially decreasing,sumnumis slower and less accurate thansumposorsuminf, so should not be used. ๐
the function uses the intnum routines and integration on the line Re(s) = sigma. the optional argument tab is as in intnum, except it must be initialized with sumnuminit instead of intnuminit. don't mix those up bestie.
when tab is not precomputed, sumnum can be slower than sumpos, when the latter is applicable. it is in general faster for slowly decreasing functions. โญ
finally, if flag is nonzero, we assume that the function f to be summed is of real type, i.e. satisfies \overline{f(z)} = f(\overline{z}), which speeds up the computation.
? d - c
time = 0 ms.
%5 = 1.97... E-306 \\ slower but done once and for all.
? d - c
time = 0 ms.
%5 = 1.97... E-306 \\ 3 times as fast as C<sumpos>
? d - c
time = 0 ms.
%5 = 1.97... E-306 \\ perfect.
? d - c
time = 0 ms.
%5 = 1.97... E-306 \\ function of real type
? d - c
time = 0 ms.
%5 = 1.97... E-306 \\ twice as fast, no imaginary part.
? d - c
time = 0 ms.
%5 = 1.97... E-306 \\ fast
? d - c
time = 0 ms.
%5 = 1.97... E-306 \\ slow.
? d - c
time = 0 ms.
%5 = 1.97... E-306 \\ perfect.
for slowly decreasing functions, we must indicate singularities:
time = 12,210 ms.
? b - zeta(4/3)
%3 = 1.05... E-300 \\ slow because of the computation of n^{-4/3}.
time = 12,210 ms.
? b - zeta(4/3)
%3 = 1.05... E-300 \\ lost 200 decimals because of singularity at oo
time = 12,210 ms.
? b - zeta(4/3)
%3 = 1.05... E-300 \\ of real type
time = 12,210 ms.
? b - zeta(4/3)
%3 = 1.05... E-300 \\ better
lost 200 decimals. 200. ๐ญ
since the complex values of the function are used, beware of determination problems. for instance:
? sumnum(n=1,[2,-3/2], 1/n^(3/2), tab,1) - zeta(3/2)
time = 8,990 ms.
%3 = -1.19... E-305 \\ fast and correct
? sumnum(n=1,[2,-3/2], 1/n^(3/2), tab,1) - zeta(3/2)
time = 8,990 ms.
%3 = -1.19... E-305 \\ nonsense. However
? sumnum(n=1,[2,-3/2], 1/n^(3/2), tab,1) - zeta(3/2)
time = 8,990 ms.
%3 = -1.19... E-305 \\ perfect, as 1/(n* F<sqrt> {n}) above but much slower
for exponentially decreasing functions, sumnum is given for completeness, but one of suminf or sumpos should always be preferred. if you experiment with such functions and sumnum anyway, indicate the exact rate of decrease and increase m by 1 or 2:
? m = intnumstep()
%4 = 9
? sumnum(n=1,[2,log(2)], 2^(-n), m+1, 1) - 1
time = 11,770 ms.
%5 = -1.9... E-305 \\ fast and perfect
? m = intnumstep()
%4 = 9
? sumnum(n=1,[2,log(2)], 2^(-n), m+1, 1) - 1
time = 11,770 ms.
%5 = -1.9... E-305 \\ also fast and perfect
? m = intnumstep()
%4 = 9
? sumnum(n=1,[2,log(2)], 2^(-n), m+1, 1) - 1
time = 11,770 ms.
%5 = -1.9... E-305 \\ nonsense
? m = intnumstep()
%4 = 9
? sumnum(n=1,[2,log(2)], 2^(-n), m+1, 1) - 1
time = 11,770 ms.
%5 = -1.9... E-305 \\ of real type
? m = intnumstep()
%4 = 9
? sumnum(n=1,[2,log(2)], 2^(-n), m+1, 1) - 1
time = 11,770 ms.
%5 = -1.9... E-305 \\ slow and lost 70 decimals
? m = intnumstep()
%4 = 9
? sumnum(n=1,[2,log(2)], 2^(-n), m+1, 1) - 1
time = 11,770 ms.
%5 = -1.9... E-305 \\ now perfect, but slow.
"nonsense" โ "of real type" โ "slow and lost 70 decimals" โ "now perfect, but slow". a whole journey in four lines, honestly ๐ซถ
the library syntax is sumnum(void *E, GEN (*eval)(GEN,void*), GEN a,GEN sig,GEN tab,long flag, long prec).
๐ sumnumalt โ the one you should NOT use ๐
sumnumalt(X = a,sig,expr,{tab},{flag = 0}) does the numerical summation of (-1)^Xexpr(X), with the variable X taking integer values from the ceiling of a to + oo, where expr is assumed to be a holomorphic function for Re(X) >= sig (or sig[1]).
๐จ Warning!! this function uses theintnumroutines and is orders of magnitude slower thansumalt. it is only given for completeness and should not be used in practice. like, at all. don't do it. i'm begging ๐
it's giving "we included it so the docs look complete" energy, and honestly? respect for the honesty. ๐ญ
Warning2. The expression expr must not include the"(-1)^X"coefficient. Sosumalt(n = a,(-1)^nf(n))is (approximately) equal tosumnumalt(n = a,sig,f(n)).
The sig arg is coded exactly like in sumnum. But for slowly decreasing functions (where sig is coded as ["sigma","alpha"] with alpha" < -1"), it's honestly not that deep whether you indicate alpha or not ๐
. Like, same as with sumalt, the program will often give you meaningful results (usually analytic continuations, slay) even for divergent series. But the exponential decrease must be indicated, no skipping that part bestie.
tab works like in intnum, but if you use it, it has to be initialized with sumnuminit. If flag is nonzero, it assumes the function f you're summing is of real type, i.e. it satisfies "\overline{f(z)} = f(\overline{z})", and then it's twice as fast when tab is precomputed ๐ฅ.
? a - b
time = 0 ms.
%1 = -1.66... E-308 \\ abcissa F<sigma> = 2, alternating sums.
? a - b
time = 0 ms.
%1 = -1.66... E-308 \\ slow, but done once and for all.
? a - b
time = 0 ms.
%1 = -1.66... E-308 \\ similar speed to C<sumnum>
? a - b
time = 0 ms.
%1 = -1.66... E-308 \\ infinitely faster!
? a - b
time = 0 ms.
%1 = -1.66... E-308 \\ perfect
The library syntax is sumnumalt"(void *E, GEN (*eval)(GEN,void*), GEN a, GEN sig, GEN tab, long flag, long prec)".
๐ธ \subsecidx{sumnuminit}"(sig,{m = 0},{sgn = 1})" ๐ธ
This one initializes the tables for numerical summation using sumnum (with sgn" = 1") or sumnumalt (with sgn" = -1"). The sig is the abcissa of integration, coded as in sumnum, and m is as in intnuminit. Setup era โจ.
The library syntax is sumnuminit"(GEN sig, long m, long sgn, long prec)".
๐ \subsecidx{sumpos}"(X = a,"expr",{"flag" = 0})" ๐
Numerical summation of the series expr, which must be a series of terms all having the same sign, with the formal variable X starting at a. The algorithm is Van Wijngaarden's trick for converting such a series into an alternating one, and ngl it's quite slow ๐ญ. For regular functions, sumnum is in general much faster once the initializations have been made using sumnuminit.
If flag" = 1", it uses slightly different polynomials. Sometimes faster. Vibes.
The library syntax is sumpos"(void *E, GEN (*eval)(GEN,void*),GEN a,long prec)". Also available is sumpos2 with the same arguments (flag" = 1").
๐ PLOTTING FUNCTIONS ๐
Okay so plotting is not even a side purpose of PARI, but likeโฆ a number of plotting functions are provided anyway ๐. And a lot of people suggested ideas or submitted patches for this section of the code. Among these, special thanks go to Klaus-Peter Nischke who suggested the recursive plotting and the forking/resizing stuff under X11, and Ilya Zakharevich who undertook a complete rewrite of the graphic code, so that most of it is now platform-independent and should be easy to port or expand. Iconic behavior honestly ๐.
There are three types of graphic functions.
โจ High-level plotting functions โจ
(all the functions starting with "ploth") in which you, the user, have little to do but explain what type of plot you want, and whose syntax is similar to the one used in the preceding section. Low effort, high reward, we love to see it.
โจ Low-level plotting functions โจ
(called rectplot functions, sharing the prefix "plot"), where every drawing primitive (point, line, box, etc.) is specified by you. These low-level functions work as follows.
You have at your disposal 16 virtual windows which are filled independently, and can then be physically ORed on a single window at user-defined positions. These windows are numbered from 0 to 15, and must be initialized before being used by the function plotinit, which specifies the height and width of the virtual window (called a rectwindow in the sequel). At all times, a virtual cursor (initialized at "[0,0]") is associated to the window, and its current value can be obtained using the function plotcursor ๐ฆ.
A number of primitive graphic objects (called rect objects) can then be drawn in these windows, using a default color associated to that window (which can be changed under X11, using the plotcolor function, black otherwise) and only the part of the object which is inside the window will be drawn, with the exception of polygons and strings which are drawn entirely. The ones sharing the prefix "plotr" draw relatively to the current position of the virtual cursor, the others use absolute coordinates. Those having the prefix "plotrecth" put in the rectwindow a large batch of rect objects corresponding to the output of the related "ploth" function.
Finally, the actual physical drawing is done using the function plotdraw. The rectwindows are preserved so that further drawings using the same windows at different positions or different windows can be done without extra work. To erase a window (and free the corresponding memory), use the function plotkill. It is not possible to partially erase a window ๐ค. Erase it completely, initialize it again and then fill it with the graphic objects that you want to keep. Full reset energy.
In addition to initializing the window, you may use a scaled window to avoid unnecessary conversions. For this, use the function plotscale below. As long as this function is not called, the scaling is simply the number of pixels, the origin being at the upper left and the "y"-coordinates going downwards. Yes, downwards. Don't ask ๐.
Note that in the present version 2.3.5 all plotting functions (both low and high level) are written for the X11-window system (hence also for GUI's based on X11 such as Openwindows and Motif) only, though little code remains which is actually platform-dependent. It is also possible to compile "gp" with either of the Qt or FLTK graphical libraries. A Suntools/Sunview, Macintosh, and an Atari/Gem port were provided for previous versions, but are now obsolete. RIP to the fallen ๐ชฆ.
Under X11, the physical window (opened by plotdraw or any of the "ploth*" functions) is completely separated from "gp" (technically, a "fork" is done, and the non-graphical memory is immediately freed in the child process), which means you can go on working in the current "gp" session, without having to kill the window first ๐
. Under X11, this window can be closed, enlarged or reduced using the standard window manager functions. No zooming procedure is implemented though (yet). Manifesting zoom for a future release โจ.
๐ธ Functions for PostScript output: ๐ธ
in the same way that printtex allows you to have a TeX output corresponding to printed results, the functions starting with "ps" allow you to have "PostScript" output of the plots. This will not be absolutely identical with the screen output, but will be sufficiently close. Note that you can use PostScript output even if you do not have the plotting routines enabled ๐ซถ.
The PostScript output is written in a file whose name is derived from the "psfile" default ("./pari.ps" if you did not tamper with it). Each time a new PostScript output is asked for, the PostScript output is appended to that file. Hence you probably want to remove this file, or change the value of "psfile", in between plots. On the other hand, in this manner, as many plots as desired can be kept in a single file. Accidental infinite scroll of plots, but make it aesthetic ๐ญ.
๐ And library mode ? ๐
None of the graphic functions are available within the PARI library, you must be under "gp" to use them. The reason for that is that you really should not use PARI for heavy-duty graphical work, there are better specialized alternatives around. This whole set of routines was only meant as a convenient, but simple-minded, visual aid. If you really insist on using these in your program (we warned you), the source ("plot*.c") should be readable enough for you to achieve something. Don't say we didn't tell you ๐.
๐ \subsecidx{plot}"(X = a,b,"expr",{"Ymin"},{"Ymax"})" ๐
Crude ASCII plot of the function represented by expression expr from a to b, with Y ranging from Ymin to Ymax. If Ymin (resp. Ymax) is not given, the minima (resp. the maxima) of the computed values of the expression is used instead. ASCII art but make it math ๐.
๐ \subsecidx{plotbox}"(w,x2,y2)" ๐
Let "(x1,y1)" be the current position of the virtual cursor. Draw in the rectwindow w the outline of the rectangle which is such that the points "(x1,y1)" and "(x2,y2)" are opposite corners. Only the part of the rectangle which is in w is drawn. The virtual cursor does not move. Stay put bestie ๐
.
๐ \subsecidx{plotclip}"(w)" ๐
'clips' the content of rectwindow w, i.e remove all parts of the drawing that would not be visible on the screen. Together with plotcopy this function enables you to draw on a scratchpad before commiting the part you're interested in to the final picture. Draft then post, the content creator workflow โจ.
๐ \subsecidx{plotcolor}"(w,c)" ๐
Set default color to c in rectwindow w. In present version 2.3.5, this is only implemented for the X11 window system, and you only have the following palette to choose from:
1= black2= blue3= sienna4= red5= green6= grey7= gainsborough
Note that it should be fairly easy for you to hardwire some more colors by tweaking the files "rect.h" and "plotX.c". User-defined colormaps would be nice, and may be available in future versions. Seven colors is giving default Minecraft skin ngl ๐.
๐ \subsecidx{plotcopy}"(w1,w2,dx,dy)" ๐
Copy the contents of rectwindow w1 to rectwindow w2, with offset "(dx,dy)". Ctrl+C Ctrl+V but geometric ๐ฆ.
๐ \subsecidx{plotcursor}"(w)" ๐
Give as a 2-component vector the current (scaled) position of the virtual cursor corresponding to the rectwindow w. Where you at, cursor?
๐ \subsecidx{plotdraw}"(list)" ๐
Physically draw the rectwindows given in list which must be a vector whose number of components is divisible by 3. If list = [w1,x1,y1,w2,x2,y2,...], the windows w1, w2, etc. are physically placed with their upper left corner at physical position "(x1,y1)", "(x2,y2)",โฆ respectively, and are then drawn together. Overlapping regions will thus be drawn twice, and the windows are considered transparent. Then display the whole drawing in a special window on your screen. The big reveal ๐
๐ \subsecidx{ploth}"(X = a,b,"expr",{"flag" = 0},{n = 0})" ๐
High precision plot of the function "y = f(x)" represented by the expression expr, "x" going from a to b. This opens a specific window (which is killed whenever you click on it ๐), and returns a four-component vector giving the coordinates of the bounding box in the form "["xmin","xmax","ymin","ymax"]".
Important note. Since this may involve a lot of function calls, it is advised to keep the current precision to a minimum (e.g. 9) before calling this function. Trust, your machine will thank you ๐ญ.
"n" specifies the number of reference point on the graph (0 means use the hardwired default values, that is: 1000 for general plot, 1500 for parametric plot, and 15 for recursive plot).
If no flag is given, expr is either a scalar expression f(X), in which case the plane curve "y = f(X)" will be drawn, or a vector "[f_1(X),...,f_k(X)]", and then all the curves "y = f_i(X)" will be drawn in the same window. Multi-curve slay โจ.
The binary digits of flag mean:
okay so the flag bits for ploth keep going, and every single one is a little vibe check for your plot ๐
1 = Parametricโ parametric plot. Here expr must be a vector with an even number of components. Successive pairs are then understood as the parametric coordinates of a plane curve. Each of these are then drawn.
For instance:
ploth(X = 0,2*Pi,[sin(X),cos(X)],1)
will draw a circle.
ploth(X = 0,2*Pi,[sin(X),cos(X)])
will draw two entwined sinusoidal curves.
ploth(X = 0,2*Pi,[X,X,sin(X),cos(X)],1)
will draw a circle and the line y = x.
2 = Recursiveโ recursive plot. If this flag is set, only one curve can be drawn at a time, i.e. expr must be either a two-component vector (for a single parametric curve, and the parametric flag has to be set), or a scalar function. The idea is to choose pairs of successive reference points, and if their middle point is not too far away from the segment joining them, draw this as a local approximation to the curve. Otherwise, add the middle point to the reference points. This is fast, and usually more precise than usual plot. Compare the results of
ploth(X = -1,1,sin(1/X),2) and ploth(X = -1,1,sin(1/X))
for instance. But beware that if you are extremely unlucky, or choose too few reference points, you may draw some nice polygon bearing little resemblance to the original curve. For instance you should never plot recursively an odd function in a symmetric interval around 0. Try
ploth(x = -20, 20, sin(x), 2)
to see why. Hence, it's usually a good idea to try and plot the same curve with slightly different parameters.
The other values toggle various display options:
4 = no_Rescaleโ do not rescale plot according to the computed extrema. This is meant to be used when graphing multiple functions on a rectwindow (as aplotrecthcall), in conjunction withplotscale.8 = no_X_axisโ do not print thex-axis.16 = no_Y_axisโ do not print they-axis.32 = no_Frameโ do not print frame.64 = no_Linesโ only plot reference points, do not join them.128 = Points_tooโ plot both lines and points.256 = Splinesโ use splines to interpolate the points.512 = no_X_ticksโ plot nox-ticks.1024 = no_Y_ticksโ plot noy-ticks.2048 = Same_ticksโ plot all ticks with the same length.
๐ธ plothraw(listx,listy,{"flag" = 0})
given listx and listy two vectors of equal length, plots (in high precision) the points whose (x,y)-coordinates are given in listx and listy. Automatic positioning and scaling is done, but with the same scaling factor on x and y. If flag is 1, join points, other non-0 flags toggle display options and should be combinations of bits 2^k, k >= 3 as in ploth.
๐ plothsizes()
return data corresponding to the output window in the form of a 6-component vector: window width and height, sizes for ticks in horizontal and vertical directions (this is intended for the gnuplot interface and is currently not significant), width and height of characters.
๐ฆ plotinit(w,x,y,{"flag"})
initialize the rectwindow w, destroying any rect objects you may have already drawn in w. The virtual cursor is set to (0,0). The rectwindow size is set to width x and height y. If flag = 0, x and y represent pixel units. Otherwise, x and y are understood as fractions of the size of the current output device (hence must be between 0 and 1) and internally converted to pixels.
The plotting device imposes an upper bound for x and y, for instance the number of pixels for screen output. These bounds are available through the plothsizes function. The following sequence initializes in a portable way (i.e independent of the output device) a window of maximal size, accessed through coordinates in the [0,1000] x [0,1000] range:
s = plothsizes();
plotinit(0, s[1]-1, s[2]-1);
plotscale(0, 0,1000, 0,1000);
๐ plotkill(w)
erase rectwindow w and free the corresponding memory. Note that if you want to use the rectwindow w again, you have to use plotinit first to specify the new size. So it's better in this case to use plotinit directly as this throws away any previous work in the given rectwindow.
๐ plotlines(w,X,Y,{"flag" = 0})
draw on the rectwindow w the polygon such that the (x,y)-coordinates of the vertices are in the vectors of equal length X and Y. For simplicity, the whole polygon is drawn, not only the part of the polygon which is inside the rectwindow. If flag is non-zero, close the polygon. In any case, the virtual cursor does not move.
X and Y are allowed to be scalars (in this case, both have to). There, a single segment will be drawn, between the virtual cursor current position and the point (X,Y). And only the part thereof which actually lies within the boundary of w. Then move the virtual cursor to (X,Y), even if it is outside the window. If you want to draw a line from (x1,y1) to (x2,y2) where (x1,y1) is not necessarily the position of the virtual cursor, use plotmove(w,x1,y1) before using this function.
๐ plotlinetype(w,type)
change the type of lines subsequently plotted in rectwindow w. type -2 corresponds to frames, -1 to axes, larger values may correspond to something else. w = -1 changes highlevel plotting. This is only taken into account by the gnuplot interface.
๐ซถ plotmove(w,x,y)
move the virtual cursor of the rectwindow w to position (x,y).
โญ plotpoints(w,X,Y)
draw on the rectwindow w the points whose (x,y)-coordinates are in the vectors of equal length X and Y and which are inside w. The virtual cursor does not move. This is basically the same function as plothraw, but either with no scaling factor or with a scale chosen using the function plotscale.
As was the case with the plotlines function, X and Y are allowed to be (simultaneously) scalar. In this case, draw the single point (X,Y) on the rectwindow w (if it is actually inside w), and in any case move the virtual cursor to position (x,y).
๐ง plotpointsize(w,size)
changes the โsizeโ of following points in rectwindow w. If w = -1, change it in all rectwindows. This only works in the gnuplot interface.
๐ plotpointtype(w,type)
change the type of points subsequently plotted in rectwindow w. type = -1 corresponds to a dot, larger values may correspond to something else. w = -1 changes highlevel plotting. This is only taken into account by the gnuplot interface.
๐ plotrbox(w,dx,dy)
draw in the rectwindow w the outline of the rectangle which is such that the points (x1,y1) and (x1+dx,y1+dy) are opposite corners, where (x1,y1) is the current position of the cursor. Only the part of the rectangle which is in w is drawn. The virtual cursor does not move.
๐ฅ plotrecth(w,X = a,b,expr,{"flag" = 0},{n = 0})
writes to rectwindow w the curve output of ploth(w,X = a,b,expr,flag,n).
๐ plotrecthraw(w,data,{"flag" = 0})
plot graph(s) for data in rectwindow w. flag has the same significance here as in ploth, though recursive plot is no more significant.
data is a vector of vectors, each corresponding to a list a coordinates. If parametric plot is set, there must be an even number of vectors, each successive pair corresponding to a curve. Otherwise, the first one contains the x coordinates, and the other ones contain the y-coordinates of curves to plot.
๐ญ plotrline(w,dx,dy)
draw in the rectwindow w the part of the segment (x1,y1)-(x1+dx,y1+dy) which is inside w, where (x1,y1) is the current position of the virtual cursor, and move the virtual cursor to (x1+dx,y1+dy) (even if it is outside the window).
๐ plotrmove(w,dx,dy)
move the virtual cursor of the rectwindow w to position (x1+dx,y1+dy), where (x1,y1) is the initial position of the cursor (i.e. to position (dx,dy) relative to the initial cursor).
โจ plotrpoint(w,dx,dy)
draw the point (x1+dx,y1+dy) on the rectwindow w (if it is inside w), where (x1,y1) is the current position of the cursor, and in any case move the virtual cursor to position (x1+dx,y1+dy).
๐ plotscale(w,x1,x2,y1,y2)
scale the local coordinates of the rectwindow w so that x goes from x1 to x2 and y goes from y1 to y2 (x2 < x1 and y2 < y1 being allowed). Initially, after the initialization of the rectwindow w using the function plotinit, the default scaling is the graphic pixel count, and in particular the y axis is oriented downwards since the origin is at the upper left. The function plotscale allows to change all these defaults and should be used whenever functions are graphed.
๐ฆ plotstring(w,x,{"flag" = 0})
draw on the rectwindow w the String x (see Label se:strings), at the current position of the cursor.
flag is used for justification: bits 1 and 2 regulate horizontal alignment: left if 0, right if 2, center if 1. Bits 4 and 8 regulate vertical alignment: bottom if 0, top if 8, v-center if 4. Can insert additional small gap between point and string: horizontal if bit 16 is set, vertical if bit 32 is set (see the tutorial for an example).
๐ธ psdraw(list)
same as plotdraw, except that the output is a PostScript program appended to the psfile.
๐
psploth(X = a,b,expr)
same as ploth, except that the output is a PostScript program appended to the psfile.
๐ psplothraw(listx,listy)
same as plothraw, except that the output is a PostScript program appended to the psfile.
๐ฉโ๐ป Programming in GP ๐ฉโ๐ป
๐น๏ธ Control statements ๐น๏ธ
A number of control statements are available in GP. They're simpler and have a syntax slightly different from their C counterparts, but they're quite powerful enough to write any kind of program. Some of them are specific to GP, since they're made for number theorists. As usual, X will denote any simple variable name, and seq will always denote a sequence of expressions, including the empty sequence.
โ ๏ธ Caveat: in constructs like
for (X = a,b, seq)
the variable X is considered local to the loop, leading to possibly unexpected behaviour:
n = 5;
for (n = 1, 10,
if (something_nice(), break);
);
\\ at this point C<n> is 5 !
If the sequence seq modifies the loop index, then the loop is modified accordingly:
? for (n = 1, 10, n += 2; print(n))
3
6
9
12
break({n = 1})
okay so break is your "nope, I'm out" card ๐
it interrupts execution of the current seq, and immediately exits from the n innermost enclosing loops, within the current function call (or the top level loop). n must be bigger than 1. If n is greater than the number of enclosing loops, all enclosing loops are exited. so like, it just leaves everything. iconic escape behaviour fr fr.
for(X = a,b,seq)
evaluates seq, where the formal variable X goes from a to b. Nothing is done if a > b. a and b must be in R. that's it, that's the whole vibe ๐
fordiv(n,X,seq)
evaluates seq, where the formal variable X ranges through the divisors of n (see divisors, which is used as a subroutine). It is assumed that factor can handle n, without negative exponents. Instead of n, it is possible to input a factorization matrix, i.e. the output of factor(n).
This routine uses divisors as a subroutine, then loops over the divisors. In particular, if n is an integer, divisors are sorted by increasing size.
To avoid storing all divisors, possibly using a lot of memory, the following (much slower) routine loops over the divisors using essentially constant space:
FORDIV(N)=
{ local(P, E);
P = factor(N); E = P[,2]; P = P[,1];
forvec( v = vector(#E, i, [0,E[i]]),
X = factorback(P, v)
\\ ...
);
}
? for(i=1,10^5, FORDIV(i))
time = 3,445 ms.
? for(i=1,10^5, fordiv(i, d, ))
time = 490 ms.
like, look at that timing gap bestie ๐ญ memory vs speed, the eternal struggle. pick your fighter.
forell(E,a,b,seq)
evaluates seq, where the formal variable E ranges through all elliptic curves of conductors from a to b. The elldata database must be installed and contain data for the specified conductors. no database, no elliptic curves, no cap ๐ฆ
forprime(X = a,b,seq)
evaluates seq, where the formal variable X ranges over the prime numbers between a to b (including a and b if they are prime). More precisely, the value of X is incremented to the smallest prime strictly larger than X at the end of each iteration. Nothing is done if a > b. Note that a and b must be in R.
? { forprime(p = 2, 12,
print(p);
if (p == 3, p = 6);
)
}
2
3
7
11
ok so notice how you literally reassign p = 6 and it just... doesn't care? because the next value is the smallest prime strictly larger than X. the loop said "not me being told what to do" ๐ iykyk.
forstep(X = a,b,s,seq)
evaluates seq, where the formal variable X goes from a to b, in increments of s. Nothing is done if s > 0 and a > b or if s < 0 and a < b. s must be in R^* or a vector of steps [s_1,...,s_n]. In the latter case, the successive steps are used in the order they appear in s.
? forstep(x=5, 20, [2,4], print(x))
5
7
11
13
17
19
multi-step choreography โจ literally a little dance routine, 2 then 4 then 2 then 4. obsessed.
forsubgroup(H = G,{B},seq)
evaluates seq for each subgroup H of the abelian group G (given in SNF form or as a vector of elementary divisors), whose index is bounded by B. The subgroups are not ordered in any obvious way, unless G is a p-group in which case Birkhoff's algorithm produces them by decreasing index. A subgroup is given as a matrix whose columns give its generators on the implicit generators of G. For example, the following prints all subgroups of index less than 2 in G = Z/2Zg_1 xZ/2Z g_2:
? G = [2,2]; forsubgroup(H=G, 2, print(H))
[1; 1]
[1; 2]
[2; 1]
[1, 0; 1, 1]
The last one, for instance is generated by (g_1, g_1 + g_2). This routine is intended to treat huge groups, when subgrouplist is not an option due to the sheer size of the output.
For maximal speed the subgroups have been left as produced by the algorithm. To print them in canonical form (as left divisors of G in HNF form), one can for instance use
? G = matdiagonal([2,2]); forsubgroup(H=G, 2, print(mathnf(concat(G,H))))
[2, 1; 0, 1]
[1, 0; 0, 2]
[2, 0; 0, 1]
[1, 0; 0, 1]
Note that in this last representation, the index [G:H] is given by the determinant. See galoissubcyclo and galoisfixedfield for nfsubfields applications to Galois theory.
Warning: the present implementation cannot treat a groupG, if one of itsp-Sylow subgroups has a cyclic factor with more than2^{31}, resp.2^{63}elements on a 32-bit, resp. 64-bit architecture. ๐ซถ big groups, big problems, know your limits bestie.
forvec(X = v,seq,{flag = 0})
Let v be an n-component vector (where n is arbitrary) of two-component vectors [a_i,b_i] for 1 <= i <= n. This routine evaluates seq, where the formal variables X[1],..., X[n] go from a_1 to b_1,..., from a_n to b_n, i.e. X goes from [a_1,...,a_n] to [b_1,...,b_n] with respect to the lexicographic ordering. (The formal variable with the highest index moves the fastest.) If flag = 1, generate only nondecreasing vectors X, and if flag = 2, generate only strictly increasing vectors X. ๐ nested loop energy but make it a vector.
if(a,{seq1},{seq2})
evaluates the expression sequence seq1 if a is non-zero, otherwise the expression seq2. Of course, seq1 or seq2 may be empty:
if (a,seq) evaluates seq if a is not equal to zero (you don't have to write the second comma), and does nothing otherwise,
if (a,,seq) evaluates seq if a is equal to zero, and does nothing otherwise. You could get the same result using the ! (not) operator: if (!a,seq).
Note that the boolean operators && and || are evaluated according to operator precedence as explained in Label se:operators, but that, contrary to other operators, the evaluation of the arguments is stopped as soon as the final truth value has been determined. For instance
if (reallydoit && longcomplicatedfunction(), ...)%
is a perfectly safe statement. short-circuiting ate, no cap ๐ฅ it's giving "don't do the expensive thing if you already know the answer."
Recall that functions such as break and next operate on loops (such as forxxx, while, until). The if statement is not a loop (obviously!). bestie. it's an if. it's not a loop. ๐
next({n = 1})
interrupts execution of current seq, resume the next iteration of the innermost enclosing loop, within the current function call (or top level loop). If n is specified, resume at the n-th enclosing loop. If n is bigger than the number of enclosing loops, all enclosing loops are exited.
return({x = 0})
returns from current subroutine, with result x. If x is omitted, return the (void) value (return no result, like print). bye bye function, here's your parting gift ๐ or like, nothing. your choice.
until(a,seq)
evaluates seq until a is not equal to 0 (i.e. until a is true). If a is initially not equal to 0, seq is evaluated once (more generally, the condition on a is tested after execution of the seq, not before as in while). so it's the "do the thing, THEN check" girlie. main character energy, actions first ๐ธ
while(a,seq)
while a is non-zero, evaluates the expression sequence seq. The test is made before evaluating the seq, hence in particular if a is initially equal to zero the seq will not be evaluated at all. the cautious one. checks the vibe before committing. opposite of until, and honestly? valid. ๐
โจ Specific functions used in GP programming โจ
In addition to the general PARI functions, it is necessary to have some functions which will be of use specifically for gp, though a few of these can be accessed under library mode. Before we start describing these, we recall the difference between strings and keywords (see Label se:strings): the latter don't get expanded at all, and you can type them without any enclosing quotes. The former are dynamic objects, where everything outside quotes gets immediately expanded. strings = live wires ๐ฆ, keywords = frozen statues, remember that and you're golden.
addhelp(S,str)
changes the help message for the symbol S. The string str is expanded on the spot and stored as the online help for S. If S is a function you have defined, its definition will still be printed before the message str. It is recommended that you document global variables and user functions in this way. Of course gp will not protest if you skip this.
Nothing prevents you from modifying the help of built-in PARI functions. (But if you do, we would like to hear why you needed to do it!) like genuinely, tell us. we're nosy. ๐
alias(newkey,key)
defines the keyword newkey as an alias for keyword key. key must correspond to an existing function name. This is different from the general user macros in that alias expansion takes place immediately upon execution, without having to look up any function code, and is thus much faster. A sample alias file misc/gpalias is provided with the standard distribution. Alias commands are meant to be read upon startup from the .gprc file, to cope with function names you are dissatisfied with, and should be useless in interactive usage. it's a "startup config" thing, not a "type it at the prompt" thing, bestie. speed demon behaviour โญ
allocatemem({x = 0})
this is a very special operation which allows the user to change the stack size after initialization. x must be a non-negative integer. If x != 0, a new stack of size 16*ceil{x/16} bytes is allocated, all the PARI data on the old stack is moved to the new one, and the old stack is discarded. If x = 0, the size of the new stack is twice the size of the old one.
Although it is a function, allocatemem cannot be used in loop-like constructs, or as part of a larger expression, e.g 2 + allocatemem(). Such an attempt will raise an error. The technical reason is that this routine usually moves the stack, so objects from the current expression may not be correct anymore, e.g. loop indexes.
so like, it moves the whole stack. everything. mid-expression. yeah. don't nest it, don't get creative, just call it on its own line ๐ญ it's giving "do not pass go."
The library syntax is allocatemoremem(x), where x is an unsigned long, and the return type is void. gp uses a variant which makes sure it was not called within a loop. (and yes, allocatemoremem is really spelled like that in the library syntax. we don't make the rules ๐)
default({key},{val})
returns the default corresponding to keyword key. If val is present, sets the default to val first (which is subject to string expansion first). Typing default() (or \d) yields the complete default list as well as their current values. See Label se:defaults for a list of available defaults, and Label se:meta for some shortcut alternatives. Note that the shortcut are meant for interactive use and usually display more information than default.
The library syntax is gp_default(key, val), where key and val are char *. ๐
error({str}*)
outputs its argument list (each of them interpreted as a string), then interrupts the running gp program, returning to the input prompt. For instance
error("n = ", n, " is not squarefree !")
dramatic exit but make it informative ๐ throw the error, say why, go back to the prompt. periodt.
extern(str)
the string str is the name of an external command (i.e. one you would type from your UNIX shell prompt). This command is immediately run and its input fed into gp, just as if read from a file. shell powers, unlocked ๐โจ
The library syntax is extern0(str), where str is a char *.
getheap()
returns a two-component row vector giving the number of objects on the heap and the amount of memory they occupy in long words. Useful mainly for debugging purposes. peek behind the curtain energy ๐
The library syntax is getheap().
๐ฑ getrand()
Returns the current value of the random number seed ๐ โ mostly a debugging vibe check, ngl. No cap, that's its whole personality.
The library syntax is getrand(), returns a C long.
๐งต getstack()
Hands you back the current value of top-avma, i.e. literally the number of bytes used up to now on the stack. Bestie, it should be equal to 0 in between commands โ if it isn't, something's sus. Also mainly for debugging ๐.
The library syntax is getstack(), returns a C long.
โฑ๏ธ gettime()
Returns the time (in milliseconds) elapsed since either the last call to gettime, or to the beginning of the containing GP instruction (if inside gp), whichever came last. Whichever came last, periodt โจ.
The library syntax is gettime(), returns a C long.
๐ global(list of variables)
Declares the corresponding variables to be global. From now on you are forbidden to use them as formal parameters for function definitions or as loop indexes ๐ซ โ so iconic of global honestly.
This is especially useful when patching together various scripts, possibly written with different naming conventions. For instance the following situation is dangerous:
p = 3 \\ fix characteristic
...
forprime(p = 2, N, ...)
f(p) = ...
because within the loop or within the function's body (even worse: in the subroutines called in that scope), the true global value of p will be hidden ๐. If the statement global(p = 3) appears at the beginning of the script, then both expressions will trigger syntax errors. Slay, honestly.
Calling global without arguments prints the list of global variables in use. In particular, eval(global) will output the values of all global variables ๐
โจ๏ธ input()
Reads a string, interpreted as a GP expression, from the input file โ usually standard input (i.e. the keyboard) ๐. If a sequence of expressions is given, the result is the result of the last expression of the sequence.
When using this instruction, it is useful to prompt for the string by using the print1 function. Note that in the present version 2.19 of pari.el, when using gp under GNU Emacs (see Label se:emacs) one must prompt for the string, with a string which ends with the same prompt as any of the previous ones (a "? " will do for instance) โจ.
๐ง install(name, code, {gpname}, {lib})
Loads from dynamic library lib the function name. Assigns to it the name gpname in this gp session, with argument code code (see the Libpari Manual for an explanation of those ๐). If lib is omitted, uses libpari.so. If gpname is omitted, uses name.
This function is useful for adding custom functions to the gp interpreter, or picking useful functions from unrelated libraries ๐ฅ. For instance, it makes the function system obsolete:
? install(system, vs, sys, "libc.so")
? sys("ls gp*")
gp.c gp.h gp_rl.c
But it also gives you access to all (non static) functions defined in the PARI library ๐ซถ. For instance, the function GEN addii(GEN x, GEN y) adds two PARI integers, and is not directly accessible under gp (it's eventually called by the + operator of course):
? install("addii", "GG")
? addii(1, 2)
%1 = 3
Re-installing a function will print a Warning, and update the prototype code if needed, but will reload a symbol from the library, even it the latter has been recompiled ๐.
Caution: This function may not work on all systems, especially when gp has been compiled statically ๐. In that case, the first use of an installed function will provoke a Segmentation Fault, i.e. a major internal blunder (this should never happen with a dynamically linked executable). Hence, if you intend to use this function, please check first on some harmless example such as the ones above that it works properly on your machine. Fr fr, do the vibe check first ๐
๐ kill(s)
Kills the present value of the variable, alias or user-defined function s. The corresponding identifier can now be used to name any GP object (variable or function) ๐. This is the only way to replace a variable by a function having the same name (or the other way round), as in the following example:
? f = 1
%1 = 1
? f(x) = 0
*** unused characters: f(x)=0
^----
? kill(f)
? f(x) = 0
? f()
%2 = 0
When you kill a variable, all objects that used it become invalid ๐ญ. You can still display them, even though the killed variable will be printed in a funny way. For example:
? a^2 + 1
%1 = a^2 + 1
? kill(a)
? %1
%2 = #<1>^2 + 1
If you simply want to restore a variable to its "undefined" value (monomial of degree one), use the quote operator: a = 'a. Predefined symbols (x and GP function names) cannot be killed ๐ซ.
๐จ๏ธ print({str}*)
Outputs its (string) arguments in raw format, ending with a newline ๐ .
โ๏ธ print1({str}*)
Outputs its (string) arguments in raw format, without ending with a newline (note that you can still embed newlines within your strings, using the \n notation !) ๐
๐ธ printp({str}*)
Outputs its (string) arguments in prettyprint (beautified) format, ending with a newline โจ.
๐ฆ printp1({str}*)
Outputs its (string) arguments in prettyprint (beautified) format, without ending with a newline.
๐ printtex({str}*)
Outputs its (string) arguments in TeX format ๐. This output can then be used in a TeX manuscript. The printing is done on the standard output. If you want to print it to a file you should use writetex (see there).
Another possibility is to enable the log default (see Label se:defaults). You could for instance do:
default(logfile, "new.tex");
default(log, 1);
printtex(result);
๐ช quit()
Exits gp. That's it, that's the whole function. Bye bestie ๐๐
๐ read({filename})
Reads in the file filename (subject to string expansion) ๐. If filename is omitted, re-reads the last file that was fed into gp. The return value is the result of the last expression evaluated.
If a GP "binary file" is read using this command (see Label se:writebin), the file is loaded and the last object in the file is returned.
๐งบ readvec({str})
Reads in the file filename (subject to string expansion). If filename is omitted, re-reads the last file that was fed into gp. The return value is a vector whose components are the evaluation of all sequences of instructions contained in the file ๐. For instance, if file contains
1
2
3
then we will get:
? \r a
%1 = 1
%2 = 2
%3 = 3
? read(a)
%4 = 3
? readvec(a)
%5 = [1, 2, 3]
In general a sequence is just a single line, but as usual braces and \\ may be used to enter multiline sequences โจ.
๐ reorder({x = []})
x must be a vector. If x is the empty vector, this gives the vector whose components are the existing variables in increasing order (i.e. in decreasing importance) ๐. Killed variables (see kill) will be shown as 0. If x is non-empty, it must be a permutation of variable names, and this permutation gives a new order of importance of the variables, for output only ๐. For example, if the existing order is [x,y,z], then after reorder([z,x]) the order of importance of the variables, with respect to output, will be [z,y,x]. The internal representation is unaffected โ it's giving cosmetic only, no cap ๐
.
๐ฒ setrand(n)
Reseeds the random number generator to the value n. The initial seed is n = 1 ๐ฑ.
The library syntax is setrand(n), where n is a long. Returns n.
๐ฅ๏ธ system(str)
str is a string representing a system command. This command is executed, its output written to the standard output (this won't get into your logfile ๐), and control returns to the PARI system. This simply calls the C system command.
๐ธ๏ธ trap({e}, {rec}, {seq})
Tries to evaluate seq, trapping error e โ that is, effectively preventing it from aborting computations in the usual way ๐ค. The recovery sequence rec is executed if the error occurs and the evaluation of rec becomes the result of the command. If e is omitted, all exceptions are trapped. Note in particular that hitting ^C (Control-C) raises an exception โ ๏ธ. See Label se:errorrec for an introduction to error recovery under gp.
? \\ trap division by 0
? inv(x) = trap (gdiver, INFINITY, 1/x)
? inv(2)
%1 = 1/2
? inv(0)
%2 = INFINITY
If seq is omitted, defines rec as a default action when catching exception e, provided no other trap as above intercepts it first. The error message is printed, as well as the result of the evaluation of rec, and control is given back to the gp prompt ๐. In particular, current computation is then lost ๐ญ.
The following error handler prints the list of all user variables, then stores in a file their name and their values:
? { trap( ,
print(reorder);
writebin("crash")) }
If no recovery code is given (rec is omitted) a break loop will be started (see Label se:breakloop). In particular
? trap()
by itself installs a default error handler, that will start a break loop whenever an exception is raised ๐.
If rec is the empty string "" the default handler (for that error if e is present) is disabled ๐ซ.
Note: The interface is currently not adequate for trapping individual exceptions. In the current version 2.3.5, the following keywords are recognized, but the name list will be expanded and changed in the future (all library mode errors can be trapped: it's a matter of defining the keywords to gp, and there are currently far too many useless ones) ๐:
accurerโ accuracy problemarcherโ not available on this architecture or operating systemerrpileโ the PARI stack overflowsgdiverโ division by 0invmoderโ impossible inverse modulosiginterโSIGINTreceived (usually from Control-C)talkerโ miscellaneous errortypeerโ wrong typeuserโ user error (from theerrorfunction)
๐ท๏ธ type(x)
This is useful only under gp ๐. Returns the internal type name of the PARI object x as a string. Check out existing type names with the metacommand \t. For example type(1) will return "t_INT" โจ.
The library syntax is type0(x), though the macro typ is usually simpler to use since it return an integer that can easily be matched with the symbols t_*. The name type was avoided due to the fact that type is a reserved identifier for some C(++) compilers ๐.
๐ version()
Returns the current version number as a t_VEC with three integer components: major version number, minor version number and patchlevel ๐. To check against a particular version number, you can use:
and the if vibe check for version stuff is literally this, bestie:
if (lex(version(), [2,2,0]) >= 0,
\\ code to be executed if we are running 2.2.0 or more recent.
,
\\ compatibility code
);
๐ธ whatnow("key") ๐ธ
if key is the name of a function that was present in GP version 1.39.15 or lower, this outputs the new function name and syntax, if it changed at all โ and yes, 387 out of 560 did, no cap.
๐
write("filename",{"str"}*) ๐
writes (appends) to filename the remaining arguments, and appends a newline โ same output as print. Slay.
๐ write1("filename",{"str"}*) ๐
same but writes (appends) to filename the remaining arguments without a trailing newline โ same output as print1. Obsessed with the no-newline life.
๐ฆ writebin("filename",{x}) ๐ฆ
writes (appends) to filename the object x in binary format. Lowkey not human readable, but it contains the exact internal structure of x, and itโs much faster to save/load than a string expression like the one write would produce. The binary file format includes a magic number, so the file can be recognized and correctly input by the regular read or \r function. If saved objects refer to (polynomial) variables that are not defined in the new session, they will be displayed in a funny way (see Label se:kill). ๐
If x is omitted, it saves all user variables from the session, together with their names. Reading such a โnamed objectโ back in a gp session will set the corresponding user variable to the saved value. E.g. after
x = 1; writebin("log")
reading log into a clean session will set x to 1. The relative variables priorities (see Label se:priority) of new variables set in this way remain the same โ preset variables retain their former priority, but are set to the new value. In particular, reading such a session log into a clean session will restore all variables exactly as they were in the original one. โจ
User functions, installed functions and history objects can not be saved via this function. Just as a regular input file, a binary file can be compressed using gzip, provided the file name has the standard .gz extension.
โ ๏ธ in the present implementation, the binary files are architecture dependent and compatibility with future versions ofgpis not guaranteed. Hence binary files should not be used for long term storage (also, they are larger and harder to compress than text files). fr fr, donโt archive your whole personality in a.binand expect future-you to open it ๐
๐ writetex("filename",{"str"}*) ๐
as write, but in TeX format. Cute.
okay bestie, thatโs the end of libPARI.dumb(3) ๐ซถ this page was served to you by perl v5.42.2, dated 2025-11-19 โ now go forth and writebin("log") responsibly ๐
๐ฆ where this page comes from
- alpine 3.24: perl-math-pari-doc 2.030528-r1 ยท GPL-1.0-or-later OR Artistic-1.0-Perl OR GPL-2.0-only
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms