This is maxima.info, produced by makeinfo version 4.8 from maxima.texi.

   This is a Texinfo Maxima Manual

   Copyright 1994,2001 William F. Schelter

INFO-DIR-SECTION Math
START-INFO-DIR-ENTRY
* Maxima: (maxima).     A computer algebra system.
END-INFO-DIR-ENTRY


File: maxima.info,  Node: Introduction to Series,  Next: Functions and Variables for Series,  Prev: Functions and Variables for Sums and Products,  Up: Sums Products and Series

28.2 Introduction to Series
===========================

Maxima contains functions `taylor' and `powerseries' for finding the
series of differentiable functions.  It also has tools such as `nusum'
capable of finding the closed form of some series.  Operations such as
addition and multiplication work as usual on series.  This section
presents the global variables which control the expansion.


File: maxima.info,  Node: Functions and Variables for Series,  Next: Introduction to Fourier series,  Prev: Introduction to Series,  Up: Sums Products and Series

28.3 Functions and Variables for Series
=======================================

 -- Option variable: cauchysum
     Default value: `false'

     When multiplying together sums with `inf' as their upper limit, if
     `sumexpand' is `true' and `cauchysum' is `true' then the Cauchy
     product will be used rather than the usual product.  In the Cauchy
     product the index of the inner summation is a function of the
     index of the outer one rather than varying independently.

     Example:

          (%i1) sumexpand: false$
          (%i2) cauchysum: false$
          (%i3) s: sum (f(i), i, 0, inf) * sum (g(j), j, 0, inf);
                                inf         inf
                                ====        ====
                                \           \
          (%o3)                ( >    f(i))  >    g(j)
                                /           /
                                ====        ====
                                i = 0       j = 0
          (%i4) sumexpand: true$
          (%i5) cauchysum: true$
          (%i6) ''s;
                           inf     i1
                           ====   ====
                           \      \
          (%o6)             >      >     g(i1 - i2) f(i2)
                           /      /
                           ====   ====
                           i1 = 0 i2 = 0


 -- Function: deftaylor (<f_1>(<x_1>), <expr_1>, ..., <f_n>(<x_n>),
          <expr_n>)
     For each function <f_i> of one variable <x_i>, `deftaylor' defines
     <expr_i> as the Taylor series about zero.  <expr_i> is typically a
     polynomial in <x_i> or a summation; more general expressions are
     accepted by `deftaylor' without complaint.

     `powerseries (<f_i>(<x_i>), <x_i>, 0)' returns the series defined
     by `deftaylor'.

     `deftaylor' returns a list of the functions <f_1>, ..., <f_n>.
     `deftaylor' evaluates its arguments.

     Example:

          (%i1) deftaylor (f(x), x^2 + sum(x^i/(2^i*i!^2), i, 4, inf));
          (%o1)                          [f]
          (%i2) powerseries (f(x), x, 0);
                                inf
                                ====      i1
                                \        x         2
          (%o2)                  >     -------- + x
                                /       i1    2
                                ====   2   i1!
                                i1 = 4
          (%i3) taylor (exp (sqrt (f(x))), x, 0, 4);
                                2         3          4
                               x    3073 x    12817 x
          (%o3)/T/     1 + x + -- + ------- + -------- + . . .
                               2     18432     307200


 -- Option variable: maxtayorder
     Default value: `true'

     When `maxtayorder' is `true', then during algebraic manipulation
     of (truncated) Taylor series, `taylor' tries to retain as many
     terms as are known to be correct.


 -- Function: niceindices (<expr>)
     Renames the indices of sums and products in <expr>.  `niceindices'
     attempts to rename each index to the value of
     `niceindicespref[1]', unless that name appears in the summand or
     multiplicand, in which case `niceindices' tries the succeeding
     elements of `niceindicespref' in turn, until an unused variable is
     found.  If the entire list is exhausted, additional indices are
     constructed by appending integers to the value of
     `niceindicespref[1]', e.g., `i0', `i1', `i2', ...

     `niceindices' returns an expression.  `niceindices' evaluates its
     argument.

     Example:

          (%i1) niceindicespref;
          (%o1)                  [i, j, k, l, m, n]
          (%i2) product (sum (f (foo + i*j*bar), foo, 1, inf), bar, 1, inf);
                           inf    inf
                          /===\   ====
                           ! !    \
          (%o2)            ! !     >      f(bar i j + foo)
                           ! !    /
                          bar = 1 ====
                                  foo = 1
          (%i3) niceindices (%);
                               inf  inf
                              /===\ ====
                               ! !  \
          (%o3)                ! !   >    f(i j l + k)
                               ! !  /
                              l = 1 ====
                                    k = 1


 -- Option variable: niceindicespref
     Default value: `[i, j, k, l, m, n]'

     `niceindicespref' is the list from which `niceindices' takes the
     names of indices for sums and products.

     The elements of `niceindicespref' are typically names of variables,
     although that is not enforced by `niceindices'.

     Example:

          (%i1) niceindicespref: [p, q, r, s, t, u]$
          (%i2) product (sum (f (foo + i*j*bar), foo, 1, inf), bar, 1, inf);
                           inf    inf
                          /===\   ====
                           ! !    \
          (%o2)            ! !     >      f(bar i j + foo)
                           ! !    /
                          bar = 1 ====
                                  foo = 1
          (%i3) niceindices (%);
                               inf  inf
                              /===\ ====
                               ! !  \
          (%o3)                ! !   >    f(i j q + p)
                               ! !  /
                              q = 1 ====
                                    p = 1


 -- Function: nusum (<expr>, <x>, <i_0>, <i_1>)
     Carries out indefinite hypergeometric summation of <expr> with
     respect to <x> using a decision procedure due to R.W. Gosper.
     <expr> and the result must be expressible as products of integer
     powers, factorials, binomials, and rational functions.

     The terms "definite" and "indefinite summation" are used
     analogously to "definite" and "indefinite integration".  To sum
     indefinitely means to give a symbolic result for the sum over
     intervals of variable length, not just e.g. 0 to inf.  Thus, since
     there is no formula for the general partial sum of the binomial
     series, `nusum' can't do it.

     `nusum' and `unsum' know a little about sums and differences of
     finite products.  See also `unsum'.

     Examples:

          (%i1) nusum (n*n!, n, 0, n);

          Dependent equations eliminated:  (1)
          (%o1)                     (n + 1)! - 1
          (%i2) nusum (n^4*4^n/binomial(2*n,n), n, 0, n);
                               4        3       2              n
                2 (n + 1) (63 n  + 112 n  + 18 n  - 22 n + 3) 4      2
          (%o2) ------------------------------------------------ - ------
                              693 binomial(2 n, n)                 3 11 7
          (%i3) unsum (%, n);
                                        4  n
                                       n  4
          (%o3)                   ----------------
                                  binomial(2 n, n)
          (%i4) unsum (prod (i^2, i, 1, n), n);
                              n - 1
                              /===\
                               ! !   2
          (%o4)              ( ! !  i ) (n - 1) (n + 1)
                               ! !
                              i = 1
          (%i5) nusum (%, n, 1, n);

          Dependent equations eliminated:  (2 3)
                                      n
                                    /===\
                                     ! !   2
          (%o5)                      ! !  i  - 1
                                     ! !
                                    i = 1


 -- Function: pade (<taylor_series>, <numer_deg_bound>,
          <denom_deg_bound>)
     Returns a list of all rational functions which have the given
     Taylor series expansion where the sum of the degrees of the
     numerator and the denominator is less than or equal to the
     truncation level of the power series, i.e.  are "best"
     approximants, and which additionally satisfy the specified degree
     bounds.

     <taylor_series> is a univariate Taylor series.  <numer_deg_bound>
     and <denom_deg_bound> are positive integers specifying degree
     bounds on the numerator and denominator.

     <taylor_series> can also be a Laurent series, and the degree
     bounds can be `inf' which causes all rational functions whose total
     degree is less than or equal to the length of the power series to
     be returned.  Total degree is defined as `<numer_deg_bound> +
     <denom_deg_bound>'.  Length of a power series is defined as
     `"truncation level" + 1 - min(0, "order of series")'.

          (%i1) taylor (1 + x + x^2 + x^3, x, 0, 3);
                                        2    3
          (%o1)/T/             1 + x + x  + x  + . . .
          (%i2) pade (%, 1, 1);
                                           1
          (%o2)                       [- -----]
                                         x - 1
          (%i3) t: taylor(-(83787*x^10 - 45552*x^9 - 187296*x^8
                             + 387072*x^7 + 86016*x^6 - 1507328*x^5
                             + 1966080*x^4 + 4194304*x^3 - 25165824*x^2
                             + 67108864*x - 134217728)
                 /134217728, x, 0, 10);
                              2    3       4       5       6        7
                       x   3 x    x    15 x    23 x    21 x    189 x
          (%o3)/T/ 1 - - + ---- - -- - ----- + ----- - ----- - ------
                       2    16    32   1024    2048    32768   65536

                                            8         9          10
                                      5853 x    2847 x    83787 x
                                    + ------- + ------- - --------- + . . .
                                      4194304   8388608   134217728
          (%i4) pade (t, 4, 4);
          (%o4)                          []

     There is no rational function of degree 4 numerator/denominator,
     with this power series expansion.  You must in general have degree
     of the numerator and degree of the denominator adding up to at
     least the degree of the power series, in order to have enough
     unknown coefficients to solve.

          (%i5) pade (t, 5, 5);
                               5                4                 3
          (%o5) [- (520256329 x  - 96719020632 x  - 489651410240 x

                            2
           - 1619100813312 x  - 2176885157888 x - 2386516803584)

                         5                 4                  3
          /(47041365435 x  + 381702613848 x  + 1360678489152 x

                            2
           + 2856700692480 x  + 3370143559680 x + 2386516803584)]


 -- Function: powerseries (<expr>, <x>, <a>)
     Returns the general form of the power series expansion for <expr>
     in the variable <x> about the point <a> (which may be `inf' for
     infinity):
                     inf
                     ====
                     \               n
                      >    b  (x - a)
                     /      n
                     ====
                     n = 0

     If `powerseries' is unable to expand <expr>, `taylor' may give the
     first several terms of the series.

     When `verbose' is `true', `powerseries' prints progress messages.

          (%i1) verbose: true$
          (%i2) powerseries (log(sin(x)/x), x, 0);
          can't expand
                                           log(sin(x))
          so we'll try again after applying the rule:
                                                  d
                                                / -- (sin(x))
                                                [ dx
                                  log(sin(x)) = i ----------- dx
                                                ]   sin(x)
                                                /
          in the first simplification we have returned:
                                       /
                                       [
                                       i cot(x) dx - log(x)
                                       ]
                                       /
                              inf
                              ====        i1  2 i1             2 i1
                              \      (- 1)   2     bern(2 i1) x
                               >     ------------------------------
                              /                i1 (2 i1)!
                              ====
                              i1 = 1
          (%o2)                -------------------------------------
                                                2


 -- Option variable: psexpand
     Default value: `false'

     When `psexpand' is `true', an extended rational function
     expression is displayed fully expanded.  The switch `ratexpand'
     has the same effect.

     When `psexpand' is `false', a multivariate expression is displayed
     just as in the rational function package.

     When `psexpand' is  `multi', then terms with the same total degree
     in the variables are grouped together.


 -- Function: revert (<expr>, <x>)
 -- Function: revert2 (<expr>, <x>, <n>)
     These functions return the reversion of <expr>, a Taylor series
     about zero in the variable <x>.  `revert' returns a polynomial of
     degree equal to the highest power in <expr>.  `revert2' returns a
     polynomial of degree <n>, which may be greater than, equal to, or
     less than the degree of <expr>.

     `load ("revert")' loads these functions.

     Examples:

          (%i1) load ("revert")$
          (%i2) t: taylor (exp(x) - 1, x, 0, 6);
                             2    3    4    5     6
                            x    x    x    x     x
          (%o2)/T/      x + -- + -- + -- + --- + --- + . . .
                            2    6    24   120   720
          (%i3) revert (t, x);
                         6       5       4       3       2
                     10 x  - 12 x  + 15 x  - 20 x  + 30 x  - 60 x
          (%o3)/R/ - --------------------------------------------
                                          60
          (%i4) ratexpand (%);
                               6    5    4    3    2
                              x    x    x    x    x
          (%o4)             - -- + -- - -- + -- - -- + x
                              6    5    4    3    2
          (%i5) taylor (log(x+1), x, 0, 6);
                              2    3    4    5    6
                             x    x    x    x    x
          (%o5)/T/       x - -- + -- - -- + -- - -- + . . .
                             2    3    4    5    6
          (%i6) ratsimp (revert (t, x) - taylor (log(x+1), x, 0, 6));
          (%o6)                           0
          (%i7) revert2 (t, x, 4);
                                    4    3    2
                                   x    x    x
          (%o7)                  - -- + -- - -- + x
                                   4    3    2


 -- Function: taylor (<expr>, <x>, <a>, <n>)
 -- Function: taylor (<expr>, [<x_1>, <x_2>, ...], <a>, <n>)
 -- Function: taylor (<expr>, [<x>, <a>, <n>, 'asymp])
 -- Function: taylor (<expr>, [<x_1>, <x_2>, ...], [<a_1>, <a_2>, ...],
          [<n_1>, <n_2>, ...])
 -- Function: taylor (<expr>, [<x_1>, <a_1>, <n_1>], [<x_2>, <a_2>,
          <n_2>], ...)
     `taylor (<expr>, <x>, <a>, <n>)' expands the expression <expr> in
     a truncated Taylor or Laurent series in the variable <x> around
     the point <a>, containing terms through `(<x> - <a>)^<n>'.

     If <expr> is of the form `<f>(<x>)/<g>(<x>)' and `<g>(<x>)' has no
     terms up to degree <n> then `taylor' attempts to expand `<g>(<x>)'
     up to degree `2 <n>'.  If there are still no nonzero terms,
     `taylor' doubles the degree of the expansion of `<g>(<x>)' so long
     as the degree of the expansion is less than or equal to `<n>
     2^taylordepth'.

     `taylor (<expr>, [<x_1>, <x_2>, ...], <a>, <n>)' returns a
     truncated power series of degree <n> in all variables <x_1>,
     <x_2>, ...  about the point `(<a>, <a>, ...)'.

     `taylor (<expr>, [<x_1>, <a_1>, <n_1>], [<x_2>, <a_2>, <n_2>],
     ...)' returns a truncated power series in the variables <x_1>,
     <x_2>, ... about the point `(<a_1>, <a_2>, ...)', truncated at
     <n_1>, <n_2>, ...

     `taylor (<expr>, [<x_1>, <x_2>, ...], [<a_1>, <a_2>, ...], [<n_1>,
     <n_2>, ...])' returns a truncated power series in the variables
     <x_1>, <x_2>, ... about the point `(<a_1>, <a_2>, ...)', truncated
     at <n_1>, <n_2>, ...

     `taylor (<expr>, [<x>, <a>, <n>, 'asymp])' returns an expansion of
     <expr> in negative powers of `<x> - <a>'.  The highest order term
     is `(<x> - <a>)^<-n>'.

     When `maxtayorder' is `true', then during algebraic manipulation
     of (truncated) Taylor series, `taylor' tries to retain as many
     terms as are known to be correct.

     When `psexpand' is `true', an extended rational function
     expression is displayed fully expanded.  The switch `ratexpand'
     has the same effect.  When `psexpand' is `false', a multivariate
     expression is displayed just as in the rational function package.
     When `psexpand' is  `multi', then terms with the same total degree
     in the variables are grouped together.

     See also the `taylor_logexpand' switch for controlling expansion.

     Examples:

          (%i1) taylor (sqrt (sin(x) + a*x + 1), x, 0, 3);
                                     2             2
                       (a + 1) x   (a  + 2 a + 1) x
          (%o1)/T/ 1 + --------- - -----------------
                           2               8

                                             3      2             3
                                         (3 a  + 9 a  + 9 a - 1) x
                                       + -------------------------- + . . .
                                                     48
          (%i2) %^2;
                                              3
                                             x
          (%o2)/T/           1 + (a + 1) x - -- + . . .
                                             6
          (%i3) taylor (sqrt (x + 1), x, 0, 5);
                                 2    3      4      5
                            x   x    x    5 x    7 x
          (%o3)/T/      1 + - - -- + -- - ---- + ---- + . . .
                            2   8    16   128    256
          (%i4) %^2;
          (%o4)/T/                  1 + x + . . .
          (%i5) product ((1 + x^i)^2.5, i, 1, inf)/(1 + x^2);
                                   inf
                                  /===\
                                   ! !    i     2.5
                                   ! !  (x  + 1)
                                   ! !
                                  i = 1
          (%o5)                   -----------------
                                        2
                                       x  + 1
          (%i6) ev (taylor(%, x,  0, 3), keepfloat);
                                         2           3
          (%o6)/T/    1 + 2.5 x + 3.375 x  + 6.5625 x  + . . .
          (%i7) taylor (1/log (x + 1), x, 0, 3);
                                         2       3
                           1   1   x    x    19 x
          (%o7)/T/         - + - - -- + -- - ----- + . . .
                           x   2   12   24    720
          (%i8) taylor (cos(x) - sec(x), x, 0, 5);
                                          4
                                     2   x
          (%o8)/T/                - x  - -- + . . .
                                         6
          (%i9) taylor ((cos(x) - sec(x))^3, x, 0, 5);
          (%o9)/T/                    0 + . . .
          (%i10) taylor (1/(cos(x) - sec(x))^3, x, 0, 5);
                                                         2          4
                      1     1       11      347    6767 x    15377 x
          (%o10)/T/ - -- + ---- + ------ - ----- - ------- - --------
                       6      4        2   15120   604800    7983360
                      x    2 x    120 x

                                                                    + . . .
          (%i11) taylor (sqrt (1 - k^2*sin(x)^2), x, 0, 6);
                         2  2       4      2   4
                        k  x    (3 k  - 4 k ) x
          (%o11)/T/ 1 - ----- - ----------------
                          2            24

                                              6       4       2   6
                                         (45 k  - 60 k  + 16 k ) x
                                       - -------------------------- + . . .
                                                    720
          (%i12) taylor ((x + 1)^n, x, 0, 4);
                                2       2     3      2         3
                              (n  - n) x    (n  - 3 n  + 2 n) x
          (%o12)/T/ 1 + n x + ----------- + --------------------
                                   2                 6

                                         4      3       2         4
                                       (n  - 6 n  + 11 n  - 6 n) x
                                     + ---------------------------- + . . .
                                                    24
          (%i13) taylor (sin (y + x), x, 0, 3, y, 0, 3);
                         3                 2
                        y                 y
          (%o13)/T/ y - -- + . . . + (1 - -- + . . .) x
                        6                 2

                              3                       2
                         y   y            2      1   y            3
                    + (- - + -- + . . .) x  + (- - + -- + . . .) x  + . . .
                         2   12                  6   12
          (%i14) taylor (sin (y + x), [x, y], 0, 3);
                               3        2      2      3
                              x  + 3 y x  + 3 y  x + y
          (%o14)/T/   y + x - ------------------------- + . . .
                                          6
          (%i15) taylor (1/sin (y + x), x, 0, 3, y, 0, 3);
                    1   y              1    1               1            2
          (%o15)/T/ - + - + . . . + (- -- + - + . . .) x + (-- + . . .) x
                    y   6               2   6                3
                                       y                    y

                                                     1            3
                                                + (- -- + . . .) x  + . . .
                                                      4
                                                     y
          (%i16) taylor (1/sin (y + x), [x, y], 0, 3);
                                       3         2       2        3
                      1     x + y   7 x  + 21 y x  + 21 y  x + 7 y
          (%o16)/T/ ----- + ----- + ------------------------------- + . . .
                    x + y     6                   360


 -- Option variable: taylordepth
     Default value: 3

     If there are still no nonzero terms, `taylor' doubles the degree
     of the expansion of `<g>(<x>)' so long as the degree of the
     expansion is less than or equal to `<n> 2^taylordepth'.


 -- Function: taylorinfo (<expr>)
     Returns information about the Taylor series <expr>.  The return
     value is a list of lists.  Each list comprises the name of a
     variable, the point of expansion, and the degree of the expansion.

     `taylorinfo' returns `false' if <expr> is not a Taylor series.

     Example:

          (%i1) taylor ((1 - y^2)/(1 - x), x, 0, 3, [y, a, inf]);
                            2                       2
          (%o1)/T/ - (y - a)  - 2 a (y - a) + (1 - a )

                   2                        2
           + (1 - a  - 2 a (y - a) - (y - a) ) x

                   2                        2   2
           + (1 - a  - 2 a (y - a) - (y - a) ) x

                   2                        2   3
           + (1 - a  - 2 a (y - a) - (y - a) ) x  + . . .
          (%i2) taylorinfo(%);
          (%o2)               [[y, a, inf], [x, 0, 3]]


 -- Function: taylorp (<expr>)
     Returns `true' if <expr> is a Taylor series, and `false' otherwise.


 -- Option variable: taylor_logexpand
     Default value: `true'

     `taylor_logexpand' controls expansions of logarithms in `taylor'
     series.

     When `taylor_logexpand' is `true', all logarithms are expanded
     fully so that zero-recognition problems involving logarithmic
     identities do not disturb the expansion process.  However, this
     scheme is not always mathematically correct since it ignores
     branch information.

     When `taylor_logexpand' is set to `false', then the only expansion
     of logarithms that occur is that necessary to obtain a formal
     power series.


 -- Option variable: taylor_order_coefficients
     Default value: `true'

     `taylor_order_coefficients' controls the ordering of coefficients
     in a Taylor series.

     When `taylor_order_coefficients' is `true', coefficients of taylor
     series are ordered canonically.


 -- Function: taylor_simplifier (<expr>)
     Simplifies coefficients of the power series <expr>.  `taylor'
     calls this function.


 -- Option variable: taylor_truncate_polynomials
     Default value: `true'

     When `taylor_truncate_polynomials' is `true', polynomials are
     truncated based upon the input truncation levels.

     Otherwise, polynomials input to `taylor' are considered to have
     infinite precison.


 -- Function: taytorat (<expr>)
     Converts <expr> from `taylor' form to canonical rational expression
     (CRE) form.  The effect is the same as `rat (ratdisrep (<expr>))',
     but faster.


 -- Function: trunc (<expr>)
     Annotates the internal representation of the general expression
     <expr> so that it is displayed as if its sums were truncated
     Taylor series.  <expr> is not otherwise modified.

     Example:

          (%i1) expr: x^2 + x + 1;
                                      2
          (%o1)                      x  + x + 1
          (%i2) trunc (expr);
                                          2
          (%o2)                  1 + x + x  + . . .
          (%i3) is (expr = trunc (expr));
          (%o3)                         true


 -- Function: unsum (<f>, <n>)
     Returns the first backward difference `<f>(<n>) - <f>(<n> - 1)'.
     Thus `unsum' in a sense is the inverse of `sum'.

     See also `nusum'.

     Examples:

          (%i1) g(p) := p*4^n/binomial(2*n,n);
                                               n
                                            p 4
          (%o1)               g(p) := ----------------
                                      binomial(2 n, n)
          (%i2) g(n^4);
                                        4  n
                                       n  4
          (%o2)                   ----------------
                                  binomial(2 n, n)
          (%i3) nusum (%, n, 0, n);
                               4        3       2              n
                2 (n + 1) (63 n  + 112 n  + 18 n  - 22 n + 3) 4      2
          (%o3) ------------------------------------------------ - ------
                              693 binomial(2 n, n)                 3 11 7
          (%i4) unsum (%, n);
                                        4  n
                                       n  4
          (%o4)                   ----------------
                                  binomial(2 n, n)


 -- Option variable: verbose
     Default value: `false'

     When `verbose' is `true', `powerseries' prints progress messages.



File: maxima.info,  Node: Introduction to Fourier series,  Next: Functions and Variables for Fourier series,  Prev: Functions and Variables for Series,  Up: Sums Products and Series

28.4 Introduction to Fourier series
===================================

The `fourie' package comprises functions for the symbolic computation
of Fourier series.  There are functions in the `fourie' package to
calculate Fourier integral coefficients and some functions for
manipulation of expressions.


File: maxima.info,  Node: Functions and Variables for Fourier series,  Next: Functions and Variables for Poisson series,  Prev: Introduction to Fourier series,  Up: Sums Products and Series

28.5 Functions and Variables for Fourier series
===============================================

 -- Function: equalp (<x>, <y>)
     Returns `true' if `equal (<x>, <y>)' otherwise `false' (doesn't
     give an error message like `equal (x, y)' would do in this case).


 -- Function: remfun (<f>, <expr>)
 -- Function: remfun (<f>, <expr>, <x>)
     `remfun (<f>, <expr>)' replaces all occurrences of `<f> (<arg>)'
     by <arg> in <expr>.

     `remfun (<f>, <expr>, <x>)' replaces all occurrences of `<f>
     (<arg>)' by <arg> in <expr> only if <arg> contains the variable
     <x>.


 -- Function: funp (<f>, <expr>)
 -- Function: funp (<f>, <expr>, <x>)
     `funp (<f>, <expr>)' returns `true' if <expr> contains the
     function <f>.

     `funp (<f>, <expr>, <x>)' returns `true' if <expr> contains the
     function <f> and the variable <x> is somewhere in the argument of
     one of the instances of <f>.


 -- Function: absint (<f>, <x>, <halfplane>)
 -- Function: absint (<f>, <x>)
 -- Function: absint (<f>, <x>, <a>, <b>)
     `absint (<f>, <x>, <halfplane>)' returns the indefinite integral
     of <f> with respect to <x> in the given halfplane (`pos', `neg',
     or `both').  <f> may contain expressions of the form `abs (x)',
     `abs (sin (x))', `abs (a) * exp (-abs (b) * abs (x))'.

     `absint (<f>, <x>)' is equivalent to `absint (<f>, <x>, pos)'.

     `absint (<f>, <x>, <a>, <b>)' returns the definite integral of <f>
     with respect to <x> from <a> to <b>.  <f> may include absolute
     values.


 -- Function: fourier (<f>, <x>, <p>)
     Returns a list of the Fourier coefficients of `<f>(<x>)' defined
     on the interval `[-p, p]'.


 -- Function: foursimp (<l>)
     Simplifies `sin (n %pi)' to 0 if `sinnpiflag' is `true' and `cos
     (n %pi)' to `(-1)^n' if `cosnpiflag' is `true'.


 -- Option variable: sinnpiflag
     Default value: `true'

     See `foursimp'.


 -- Option variable: cosnpiflag
     Default value: `true'

     See `foursimp'.


 -- Function: fourexpand (<l>, <x>, <p>, <limit>)
     Constructs and returns the Fourier series from the list of Fourier
     coefficients <l> up through <limit> terms (<limit> may be `inf').
     <x> and <p> have same meaning as in `fourier'.


 -- Function: fourcos (<f>, <x>, <p>)
     Returns the Fourier cosine coefficients for `<f>(<x>)' defined on
     `[0, <p>]'.


 -- Function: foursin (<f>, <x>, <p>)
     Returns the Fourier sine coefficients for `<f>(<x>)' defined on
     `[0, <p>]'.


 -- Function: totalfourier (<f>, <x>, <p>)
     Returns `fourexpand (foursimp (fourier (<f>, <x>, <p>)), <x>, <p>,
     'inf)'.


 -- Function: fourint (<f>, <x>)
     Constructs and returns a list of the Fourier integral coefficients
     of `<f>(<x>)' defined on `[minf, inf]'.


 -- Function: fourintcos (<f>, <x>)
     Returns the Fourier cosine integral coefficients for `<f>(<x>)' on
     `[0, inf]'.


 -- Function: fourintsin (<f>, <x>)
     Returns the Fourier sine integral coefficients for `<f>(<x>)' on
     `[0, inf]'.



File: maxima.info,  Node: Functions and Variables for Poisson series,  Prev: Functions and Variables for Fourier series,  Up: Sums Products and Series

28.6 Functions and Variables for Poisson series
===============================================

 -- Function: intopois (<a>)
     Converts <a> into a Poisson encoding.


 -- Function: outofpois (<a>)
     Converts <a> from Poisson encoding to general representation.  If
     <a> is not in Poisson form, `outofpois' carries out the conversion,
     i.e., the return value is `outofpois (intopois (<a>))'.  This
     function is thus a canonical simplifier for sums of powers of sine
     and cosine terms of a particular type.


 -- Function: poisdiff (<a>, <b>)
     Differentiates <a> with respect to <b>. <b> must occur only in the
     trig arguments or only in the coefficients.


 -- Function: poisexpt (<a>, <b>)
     Functionally identical to `intopois (<a>^<b>)'.  <b> must be a
     positive integer.


 -- Function: poisint (<a>, <b>)
     Integrates in a similarly restricted sense (to `poisdiff').
     Non-periodic terms in <b> are dropped if <b> is in the trig
     arguments.


 -- Option variable: poislim
     Default value: 5

     `poislim' determines the domain of the coefficients in the
     arguments of the trig functions.  The initial value of 5
     corresponds to the interval [-2^(5-1)+1,2^(5-1)], or [-15,16], but
     it can be set to [-2^(n-1)+1, 2^(n-1)].


 -- Function: poismap (<series>, <sinfn>, <cosfn>)
     will map the functions <sinfn> on the sine terms and <cosfn> on the
     cosine terms of the Poisson series given.  <sinfn> and <cosfn> are
     functions of two arguments which are a coefficient and a
     trigonometric part of a term in series respectively.


 -- Function: poisplus (<a>, <b>)
     Is functionally identical to `intopois (a + b)'.


 -- Function: poissimp (<a>)
     Converts <a> into a Poisson series for <a> in general
     representation.


 -- Special symbol: poisson
     The symbol `/P/' follows the line label of Poisson series
     expressions.


 -- Function: poissubst (<a>, <b>, <c>)
     Substitutes <a> for <b> in <c>.  <c> is a Poisson series.

     (1) Where <B> is a variable <u>, <v>, <w>, <x>, <y>, or <z>, then
     <a> must be an expression linear in those variables (e.g., `6*u +
     4*v').

     (2) Where <b> is other than those variables, then <a> must also be
     free of those variables, and furthermore, free of sines or cosines.

     `poissubst (<a>, <b>, <c>, <d>, <n>)' is a special type of
     substitution which operates on <a> and <b> as in type (1) above,
     but where <d> is a Poisson series, expands `cos(<d>)' and
     `sin(<d>)' to order <n> so as to provide the result of substituting
     `<a> + <d>' for <b> in <c>.  The idea is that <d> is an expansion
     in terms of a small parameter.  For example, `poissubst (u, v,
     cos(v), %e, 3)' yields `cos(u)*(1 - %e^2/2) - sin(u)*(%e -
     %e^3/6)'.


 -- Function: poistimes (<a>, <b>)
     Is functionally identical to `intopois (<a>*<b>)'.


 -- Function: poistrim ()
     is a reserved function name which (if the user has defined it)
     gets applied during Poisson multiplication.  It is a predicate
     function of 6 arguments which are the coefficients of the <u>,
     <v>, ..., <z> in a term.  Terms for which `poistrim' is `true'
     (for the coefficients of that term) are eliminated during
     multiplication.


 -- Function: printpois (<a>)
     Prints a Poisson series in a readable format.  In common with
     `outofpois', it will convert <a> into a Poisson encoding first, if
     necessary.



File: maxima.info,  Node: Number Theory,  Next: Symmetries,  Prev: Sums Products and Series,  Up: Top

29 Number Theory
****************

* Menu:

* Functions and Variables for Number Theory::


File: maxima.info,  Node: Functions and Variables for Number Theory,  Prev: Number Theory,  Up: Number Theory

29.1 Functions and Variables for Number Theory
==============================================

 -- Function: bern (<n>)
     Returns the <n>'th Bernoulli number for integer <n>.  Bernoulli
     numbers equal to zero are suppressed if `zerobern' is `false'.

     See also `burn'.

          (%i1) zerobern: true$
          (%i2) map (bern, [0, 1, 2, 3, 4, 5, 6, 7, 8]);
                                1  1       1      1        1
          (%o2)           [1, - -, -, 0, - --, 0, --, 0, - --]
                                2  6       30     42       30
          (%i3) zerobern: false$
          (%i4) map (bern, [0, 1, 2, 3, 4, 5, 6, 7, 8]);
                                1  1    1   1     1   5     691   7
          (%o4)           [1, - -, -, - --, --, - --, --, - ----, -]
                                2  6    30  42    30  66    2730  6


 -- Function: bernpoly (<x>, <n>)
     Returns the <n>'th Bernoulli polynomial in the variable <x>.


 -- Function: bfzeta (<s>, <n>)
     Returns the Riemann zeta function for the argument <s>.  The
     return value is a big float (bfloat); <n> is the number of digits
     in the return value.


 -- Function: bfhzeta (<s>, <h>, <n>)
     Returns the Hurwitz zeta function for the arguments <s> and <h>.
     The return value is a big float (bfloat); <n> is the number of
     digits in the return value.

     The Hurwitz zeta function is defined as

                                  inf
                                  ====
                                  \        1
                   zeta (s,h)  =   >    --------
                                  /            s
                                  ====  (k + h)
                                  k = 0

     `load ("bffac")' loads this function.


 -- Function: burn (<n>)
     Returns a rational number, which is an approximation of the <n>'th
     Bernoulli number for integer <n>.  `burn' exploits the observation
     that (rational) Bernoulli numbers can be approximated by
     (transcendental) zetas with tolerable efficiency:

                             n - 1  1 - 2 n
                        (- 1)      2        zeta(2 n) (2 n)!
               B(2 n) = ------------------------------------
                                          2 n
                                       %pi

     `burn' may be more efficient than `bern' for large, isolated <n>
     as `bern' computes all the Bernoulli numbers up to index <n> before
     returning.  `burn' invokes the approximation for even integers <n>
     > 255.  For odd integers and <n> <= 255 the function `bern' is
     called.

     `load ("bffac")' loads this function.  See also `bern'.


 -- Function: chinese ([<r_1>, ..., <r_n>], [<m_1>, ..., <m_n>])
     Solves the system of congruences `x = r_1 mod m_1', ..., `x = r_n
     mod m_n'.  The remainders <r_n> may be arbitrary integers while
     the moduli <m_n> have to be positive and pairwise coprime integers.

          (%i1) mods : [1000, 1001, 1003, 1007];
          (%o1)                   [1000, 1001, 1003, 1007]
          (%i2) lreduce('gcd, mods);
          (%o2)                               1
          (%i3) x : random(apply("*", mods));
          (%o3)                         685124877004
          (%i4) rems : map(lambda([z], mod(x, z)), mods);
          (%o4)                       [4, 568, 54, 624]
          (%i5) chinese(rems, mods);
          (%o5)                         685124877004
          (%i6) chinese([1, 2], [3, n]);
          (%o6)                    chinese([1, 2], [3, n])
          (%i7) %, n = 4;
          (%o7)                              10


 -- Function: cf (<expr>)
     Computes a continued fraction approximation.  <expr> is an
     expression comprising continued fractions, square roots of
     integers, and literal real numbers (integers, rational numbers,
     ordinary floats, and bigfloats).  `cf' computes exact expansions
     for rational numbers, but expansions are truncated at `ratepsilon'
     for ordinary floats and `10^(-fpprec)' for bigfloats.

     Operands in the expression may be combined with arithmetic
     operators.  Maxima does not know about operations on continued
     fractions outside of `cf'.

     `cf' evaluates its arguments after binding `listarith' to `false'.
     `cf' returns a continued fraction, represented as a list.

     A continued fraction `a + 1/(b + 1/(c + ...))' is represented by
     the list `[a, b, c, ...]'.  The list elements `a', `b', `c', ...
     must evaluate to integers.  <expr> may also contain `sqrt (n)'
     where `n' is an integer.  In this case `cf' will give as many
     terms of the continued fraction as the value of the variable
     `cflength' times the period.

     A continued fraction can be evaluated to a number by evaluating
     the arithmetic representation returned by `cfdisrep'.  See also
     `cfexpand' for another way to evaluate a continued fraction.

     See also `cfdisrep', `cfexpand', and `cflength'.

     Examples:

        * <expr> is an expression comprising continued fractions and
          square roots of integers.

               (%i1) cf ([5, 3, 1]*[11, 9, 7] + [3, 7]/[4, 3, 2]);
               (%o1)               [59, 17, 2, 1, 1, 1, 27]
               (%i2) cf ((3/17)*[1, -2, 5]/sqrt(11) + (8/13));
               (%o2)        [0, 1, 1, 1, 3, 2, 1, 4, 1, 9, 1, 9, 2]

        * `cflength' controls how many periods of the continued fraction
          are computed for algebraic, irrational numbers.

               (%i1) cflength: 1$
               (%i2) cf ((1 + sqrt(5))/2);
               (%o2)                    [1, 1, 1, 1, 2]
               (%i3) cflength: 2$
               (%i4) cf ((1 + sqrt(5))/2);
               (%o4)               [1, 1, 1, 1, 1, 1, 1, 2]
               (%i5) cflength: 3$
               (%i6) cf ((1 + sqrt(5))/2);
               (%o6)           [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2]

        * A continued fraction can be evaluated by evaluating the
          arithmetic representation returned by `cfdisrep'.

               (%i1) cflength: 3$
               (%i2) cfdisrep (cf (sqrt (3)))$
               (%i3) ev (%, numer);
               (%o3)                   1.731707317073171

        * Maxima does not know about operations on continued fractions
          outside of `cf'.

               (%i1) cf ([1,1,1,1,1,2] * 3);
               (%o1)                     [4, 1, 5, 2]
               (%i2) cf ([1,1,1,1,1,2]) * 3;
               (%o2)                  [3, 3, 3, 3, 3, 6]



 -- Function: cfdisrep (<list>)
     Constructs and returns an ordinary arithmetic expression of the
     form `a + 1/(b + 1/(c + ...))' from the list representation of a
     continued fraction `[a, b, c, ...]'.

          (%i1) cf ([1, 2, -3] + [1, -2, 1]);
          (%o1)                     [1, 1, 1, 2]
          (%i2) cfdisrep (%);
                                            1
          (%o2)                     1 + ---------
                                              1
                                        1 + -----
                                                1
                                            1 + -
                                                2


 -- Function: cfexpand (<x>)
     Returns a matrix of the numerators and denominators of the last
     (column 1) and next-to-last (column 2) convergents of the
     continued fraction <x>.

          (%i1) cf (rat (ev (%pi, numer)));

          `rat' replaced 3.141592653589793 by 103993/33102 =3.141592653011902
          (%o1)                  [3, 7, 15, 1, 292]
          (%i2) cfexpand (%);
                                   [ 103993  355 ]
          (%o2)                    [             ]
                                   [ 33102   113 ]
          (%i3) %[1,1]/%[2,1], numer;
          (%o3)                   3.141592653011902


 -- Option variable: cflength
     Default value: 1

     `cflength' controls the number of terms of the continued fraction
     the function `cf' will give, as the value `cflength' times the
     period.  Thus the default is to give one period.

          (%i1) cflength: 1$
          (%i2) cf ((1 + sqrt(5))/2);
          (%o2)                    [1, 1, 1, 1, 2]
          (%i3) cflength: 2$
          (%i4) cf ((1 + sqrt(5))/2);
          (%o4)               [1, 1, 1, 1, 1, 1, 1, 2]
          (%i5) cflength: 3$
          (%i6) cf ((1 + sqrt(5))/2);
          (%o6)           [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2]


 -- Function: divsum (<n>, <k>)
 -- Function: divsum (<n>)
     `divsum (<n>, <k>)' returns the sum of the divisors of <n> raised
     to the <k>'th power.

     `divsum (<n>)' returns the sum of the divisors of <n>.

          (%i1) divsum (12);
          (%o1)                          28
          (%i2) 1 + 2 + 3 + 4 + 6 + 12;
          (%o2)                          28
          (%i3) divsum (12, 2);
          (%o3)                          210
          (%i4) 1^2 + 2^2 + 3^2 + 4^2 + 6^2 + 12^2;
          (%o4)                          210


 -- Function: euler (<n>)
     Returns the <n>'th Euler number for nonnegative integer <n>.
     Euler numbers equal to zero are suppressed if `zerobern' is
     `false'.

     For the Euler-Mascheroni constant, see `%gamma'.

          (%i1) zerobern: true$
          (%i2) map (euler, [0, 1, 2, 3, 4, 5, 6]);
          (%o2)               [1, 0, - 1, 0, 5, 0, - 61]
          (%i3) zerobern: false$
          (%i4) map (euler, [0, 1, 2, 3, 4, 5, 6]);
          (%o4)               [1, - 1, 5, - 61, 1385, - 50521, 2702765]


 -- Option variable: factors_only
     Default value: `false'

     Controls the value returned by `ifactors' . The default `false'
     causes `ifactors' to provide information about multiplicities of
     the computed prime factors. If `factors_only' is set to `true',
     `ifactors' returns nothing more than a list of prime factors.

     Example: See `ifactors' .


 -- Function: fib (<n>)
     Returns the <n>'th Fibonacci number.  `fib(0)' equal to 0 and
     `fib(1)' equal to 1, and `fib (-<n>)' equal to `(-1)^(<n> + 1) *
     fib(<n>)'.

     After calling `fib', `prevfib' is equal to `fib (<x> - 1)', the
     Fibonacci number preceding the last one computed.

          (%i1) map (fib, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
          (%o1)         [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]


 -- Function: fibtophi (<expr>)
     Expresses Fibonacci numbers in <expr> in terms of the constant
     `%phi', which is `(1 + sqrt(5))/2', approximately 1.61803399.

     Examples:

          (%i1) fibtophi (fib (n));
                                     n             n
                                 %phi  - (1 - %phi)
          (%o1)                  -------------------
                                     2 %phi - 1
          (%i2) fib (n-1) + fib (n) - fib (n+1);
          (%o2)          - fib(n + 1) + fib(n) + fib(n - 1)
          (%i3) fibtophi (%);
                      n + 1             n + 1       n             n
                  %phi      - (1 - %phi)        %phi  - (1 - %phi)
          (%o3) - --------------------------- + -------------------
                          2 %phi - 1                2 %phi - 1
                                                    n - 1             n - 1
                                                %phi      - (1 - %phi)
                                              + ---------------------------
                                                        2 %phi - 1
          (%i4) ratsimp (%);
          (%o4)                           0


 -- Function: ifactors (<n>)
     For a positive integer <n> returns the factorization of <n>.  If
     `n=p1^e1..pk^nk' is the decomposition of <n> into prime factors,
     ifactors returns `[[p1, e1], ... , [pk, ek]]'.

     Factorization methods used are trial divisions by primes up to
     9973, Pollard's rho and p-1 method and elliptic curves.

     The value returned by `ifactors' is controlled by the option
     variable `factors_only' .  The default `false' causes `ifactors'
     to provide information about the multiplicities of the computed
     prime factors. If `factors_only' is set to `true', `ifactors'
     simply returns the list of prime factors.

          (%i1) ifactors(51575319651600);
          (%o1)     [[2, 4], [3, 2], [5, 2], [1583, 1], [9050207, 1]]
          (%i2) apply("*", map(lambda([u], u[1]^u[2]), %));
          (%o2)                        51575319651600
          (%i3) ifactors(51575319651600), factors_only : true;
          (%o3)                   [2, 3, 5, 1583, 9050207]


 -- Function: igcdex (<n>, <k>)
     Returns a list `[<a>, <b>, <u>]' where <u> is the greatest common
     divisor of <n> and <k>, and <u> is equal to `<a> <n> + <b> <k>'.
     The arguments <n> and <k> must be integers.

     `igcdex' implements the Euclidean algorithm.  See also `gcdex'.

     The command `load(gcdex)' loads the function.

     Examples:

          (%i1) load(gcdex)$

          (%i2) igcdex(30,18);
          (%o2)                      [- 1, 2, 6]
          (%i3) igcdex(1526757668, 7835626735736);
          (%o3)            [845922341123, - 164826435, 4]
          (%i4) igcdex(fib(20), fib(21));
          (%o4)                   [4181, - 2584, 1]


 -- Function: inrt (<x>, <n>)
     Returns the integer <n>'th root of the absolute value of <x>.

          (%i1) l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]$
          (%i2) map (lambda ([a], inrt (10^a, 3)), l);
          (%o2) [2, 4, 10, 21, 46, 100, 215, 464, 1000, 2154, 4641, 10000]


 -- Function: inv_mod (<n>, <m>)
     Computes the inverse of <n> modulo <m>.  `inv_mod (n,m)' returns
     `false', if <n> is a zero divisor modulo <m>.

          (%i1) inv_mod(3, 41);
          (%o1)                           14
          (%i2) ratsimp(3^-1), modulus=41;
          (%o2)                           14
          (%i3) inv_mod(3, 42);
          (%o3)                          false


 -- Function: isqrt (<x>)
     Returns the "integer square root" of the absolute value of <x>,
     which is an integer.


 -- Function: jacobi (<p>, <q>)
     Returns the Jacobi symbol of <p> and <q>.

          (%i1) l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]$
          (%i2) map (lambda ([a], jacobi (a, 9)), l);
          (%o2)         [1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0]


 -- Function: lcm (<expr_1>, ..., <expr_n>)
     Returns the least common multiple of its arguments.  The arguments
     may be general expressions as well as integers.

     `load ("functs")' loads this function.


 -- Function: mod (<x>, <y>)
     If <x> and <y> are real numbers and <y> is nonzero, return `<x> -
     <y> * floor(<x> / <y>)'.  Further for all real <x>, we have `mod
     (<x>, 0) = <x>'.  For a discussion of the definition `mod (<x>, 0)
     = <x>', see Section 3.4, of "Concrete Mathematics," by Graham,
     Knuth, and Patashnik.  The function `mod (<x>, 1)' is a sawtooth
     function with period 1 with `mod (1, 1) = 0' and `mod (0, 1) = 0'.

     To find the principal argument (a number in the interval `(-%pi,
     %pi]') of a complex number, use the function `<x> |-> %pi - mod
     (%pi - <x>, 2*%pi)', where <x> is an argument.

     When <x> and <y> are constant expressions (`10 * %pi', for
     example), `mod' uses the same big float evaluation scheme that
     `floor' and `ceiling' uses.  Again, it's possible, although
     unlikely, that `mod' could return an erroneous value in such cases.

     For nonnumerical arguments <x> or <y>, `mod' knows several
     simplification rules:

          (%i1) mod (x, 0);
          (%o1)                           x
          (%i2) mod (a*x, a*y);
          (%o2)                      a mod(x, y)
          (%i3) mod (0, x);
          (%o3)                           0


 -- Function: next_prime (<n>)
     Returns the smallest prime bigger than <n>.

          (%i1) next_prime(27);
          (%o1)                       29


 -- Function: partfrac (<expr>, <var>)
     Expands the expression <expr> in partial fractions with respect to
     the main variable <var>.  `partfrac' does a complete partial
     fraction decomposition.  The algorithm employed is based on the
     fact that the denominators of the partial fraction expansion (the
     factors of the original denominator) are relatively prime.  The
     numerators can be written as linear combinations of denominators,
     and the expansion falls out.

          (%i1) 1/(1+x)^2 - 2/(1+x) + 2/(2+x);
                                2       2        1
          (%o1)               ----- - ----- + --------
                              x + 2   x + 1          2
                                              (x + 1)
          (%i2) ratsimp (%);
                                           x
          (%o2)                 - -------------------
                                   3      2
                                  x  + 4 x  + 5 x + 2
          (%i3) partfrac (%, x);
                                2       2        1
          (%o3)               ----- - ----- + --------
                              x + 2   x + 1          2
                                              (x + 1)

 -- Function: power_mod (<a>, <n>, <m>)
     Uses a modular algorithm to compute `a^n mod m' where <a> and <n>
     are integers and <m> is a positive integer.  If <n> is negative,
     `inv_mod' is used to find the modular inverse.

          (%i1) power_mod(3, 15, 5);
          (%o1)                          2
          (%i2) mod(3^15,5);
          (%o2)                          2
          (%i3) power_mod(2, -1, 5);
          (%o3)                          3
          (%i4) inv_mod(2,5);
          (%o4)                          3


 -- Function: primep (<n>)
     Primality test.  If `primep (<n>)' returns `false', <n> is a
     composite number and if it returns `true', <n> is a prime number
     with very high probability.

     For <n> less than 341550071728321 a deterministic version of
     Miller-Rabin's test is used.  If `primep (<n>)' returns `true',
     then <n> is a prime number.

     For <n> bigger than 341550071728321 `primep' uses
     `primep_number_of_tests' Miller-Rabin's pseudo-primality tests and
     one Lucas pseudo-primality test.  The probability that a non-prime
     <n> will pass one Miller-Rabin test is less than 1/4.  Using the
     default value 25 for `primep_number_of_tests', the probability of
     <n> beeing composite is much smaller that 10^-15.


 -- Option variable: primep_number_of_tests
     Default value: 25

     Number of Miller-Rabin's tests used in `primep'.


 -- Function: prev_prime (<n>)
     Returns the greatest prime smaller than <n>.

          (%i1) prev_prime(27);
          (%o1)                       23


 -- Function: qunit (<n>)
     Returns the principal unit of the real quadratic number field
     `sqrt (<n>)' where <n> is an integer, i.e., the element whose norm
     is unity.  This amounts to solving Pell's equation `a^2 - <n> b^2
     = 1'.

          (%i1) qunit (17);
          (%o1)                     sqrt(17) + 4
          (%i2) expand (% * (sqrt(17) - 4));
          (%o2)                           1


 -- Function: totient (<n>)
     Returns the number of integers less than or equal to <n> which are
     relatively prime to <n>.


 -- Option variable: zerobern
     Default value: `true'

     When `zerobern' is `false', `bern' excludes the Bernoulli numbers
     and `euler' excludes the Euler numbers which are equal to zero.
     See `bern' and `euler'.


 -- Function: zeta (<n>)
     Returns the Riemann zeta function.  If <n> is a negative integer,
     0, or a positive even integer, the Riemann zeta function
     simplifies to an exact value.  For a positive even integer the
     option variable `zeta%pi' has to be `true' in addition (See
     `zeta%pi').  For a floating point or bigfloat number the Riemann
     zeta function is evaluated numerically.  Maxima returns a noun
     form `zeta (<n>)' for all other arguments, including rational
     noninteger, and complex arguments, or for even integers, if
     `zeta%pi' has the value `false'.

     `zeta(1)' is undefined, but Maxima knows the limit `limit(zeta(x),
     x, 1)' from above and below.

     The Riemann zeta function distributes over lists, matrices, and
     equations.

     See also `bfzeta' and `zeta%pi'.

     Examples:

          (%i1) zeta([-2, -1, 0, 0.5, 2, 3, 1+%i]);
                                                       2
                      1     1                       %pi
          (%o1) [0, - --, - -, - 1.460354508809586, ----, zeta(3),
                      12    2                        6
                                                              zeta(%i + 1)]
          (%i2) limit(zeta(x),x,1,plus);
          (%o2)                          inf
          (%i3) limit(zeta(x),x,1,minus);
          (%o3)                         minf


 -- Option variable: zeta%pi
     Default value: `true'

     When `zeta%pi' is `true', `zeta' returns an expression
     proportional to `%pi^n' for even integer `n'.  Otherwise, `zeta'
     returns a noun form `zeta (n)' for even integer `n'.

     Examples:

          (%i1) zeta%pi: true$
          (%i2) zeta (4);
                                           4
                                        %pi
          (%o2)                         ----
                                         90
          (%i3) zeta%pi: false$
          (%i4) zeta (4);
          (%o4)                        zeta(4)


 -- Function: zn_log (<a>, <g>, <n>)
 -- Function: zn_log (<a>, <g>, <n>, [[<p1>, <e1>], ..., [<pk>, <ek>]])
     Computes the discrete logarithm. Let (Z/<n>Z)* be a cyclic group,
     <g> a primitive root modulo <n> and let <a> be a member of this
     group.  `zn_log (a, g, n)' then solves the congruence `g^x = a mod
     n'.

     The applied algorithm needs a prime factorization of `totient(n)'.
     This factorization might be time consuming as well and in some
     cases it can be useful to factor first and then to pass the list
     of factors to `zn_log' as the fourth argument.  The list must be
     of the same form as the list returned by `ifactors(totient(n))'
     using the default option `factors_only : false'.

     The algorithm uses a Pohlig-Hellman-reduction and Pollard's
     Rho-method for discrete logarithms. The run time of `zn_log'
     primarily depends on the bitlength of the totient's greatest prime
     factor.

     See also `zn_primroot' , `zn_order' , `ifactors' , `totient' .

     Examples:

     `zn_log (a, g, n)' solves the congruence `g^x = a mod n'.

          (%i1) n : 22$
          (%i2) g : zn_primroot(n);
          (%o2)                               7
          (%i3) ord_7 : zn_order(7, n);
          (%o3)                              10
          (%i4) powers_7 : makelist(power_mod(g, x, n), x, 0, ord_7 - 1);
          (%o4)              [1, 7, 5, 13, 3, 21, 15, 17, 9, 19]
          (%i5) zn_log(21, g, n);
          (%o5)                               5
          (%i6) map(lambda([x], zn_log(x, g, n)), powers_7);
          (%o6)                [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

     The optional fourth argument must be of the same form as the list
     returned by `ifactors(totient(n))'.  The run time primarily
     depends on the bitlength of the totient's greatest prime factor.

          (%i1) (p : 2^127-1, primep(p));
          (%o1)                             true
          (%i2) ifs : ifactors(p - 1)$
          (%i3) g : zn_primroot(p, ifs);
          (%o3)                              43
          (%i4) a : power_mod(g, 1234567890, p)$
          (%i5) zn_log(a, g, p, ifs);
          (%o5)                          1234567890
          (%i6) time(%o5);
          (%o6)                            [1.204]
          (%i7) f_max : last(ifs);
          (%o7)                       [77158673929, 1]
          (%i8) slength( printf(false, "~b", f_max[1]) );
          (%o8)                              37


 -- Function: zn_order (<x>, <n>)
 -- Function: zn_order (<x>, <n>, [[<p1>, <e1>], ..., [<pk>, <ek>]])
     Returns the order of <x> if it is a unit of the finite group
     (Z/<n>Z)* or returns `false'.  <x> is a unit modulo <n> if it is
     coprime to <n>.

     The applied algorithm needs a prime factorization of `totient(n)'.
     This factorization might be time consuming in some cases and it
     can be useful to factor first and then to pass the list of factors
     to `zn_log' as the third argument.  The list must be of the same
     form as the list returned by `ifactors(totient(n))' using the
     default option `factors_only : false'.

     See also `zn_primroot' , `ifactors' , `totient' .

     Examples:

     `zn_order' computes the order of the unit <x> in (Z/<n>Z)*.

          (%i1) n : 22$
          (%i2) g : zn_primroot(n);
          (%o2)                               7
          (%i3) units_22 : sublist(makelist(i,i,1,21), lambda([x], gcd(x, n) = 1));
          (%o3)              [1, 3, 5, 7, 9, 13, 15, 17, 19, 21]
          (%i4) (ord_7 : zn_order(7, n)) = totient(n);
          (%o4)                            10 = 10
          (%i5) powers_7 : makelist(power_mod(g,i,n), i,0,ord_7 - 1);
          (%o5)              [1, 7, 5, 13, 3, 21, 15, 17, 9, 19]
          (%i6) map(lambda([x], zn_order(x, n)), powers_7);
          (%o6)              [1, 10, 5, 10, 5, 2, 5, 10, 5, 10]
          (%i7) map(lambda([x], ord_7/gcd(x, ord_7)), makelist(i, i,0,ord_7 - 1));
          (%o7)              [1, 10, 5, 10, 5, 2, 5, 10, 5, 10]
          (%i8) totient(totient(n));
          (%o8)                               4

     The optional third argument must be of the same form as the list
     returned by `ifactors(totient(n))'.

          (%i1) (p : 2^142 + 217, primep(p));
          (%o1)                             true
          (%i2) ifs : ifactors( totient(p) )$
          (%i3) g : zn_primroot(p, ifs);
          (%o3)                               3
          (%i4) is( (ord_3 : zn_order(g, p, ifs)) = totient(p) );
          (%o4)                             true
          (%i5) map(lambda([x], ord_3/zn_order(x, p, ifs)), makelist(i,i,2,15));
          (%o5)        [22, 1, 44, 10, 5, 2, 22, 2, 8, 2, 1, 1, 20, 1]


 -- Function: zn_primroot (<n>)
 -- Function: zn_primroot (<n>, [[<p1>, <e1>], ..., [<pk>, <ek>]])
     If the multiplicative group (Z/<n>Z)* is cyclic, `zn_primroot'
     computes the smallest primitive root modulo <n>.  (Z/<n>Z)* is
     cyclic if <n> is equal to `2', `4', `p^k' or `2*p^k', where `p' is
     prime and greater than `2' and `k' is a natural number.
     `zn_primroot' performs an according pretest if the option variable
     `zn_primroot_pretest'

     (default: `false') is set to `true'.  In any case the computation
     is limited by the upper bound `zn_primroot_limit' .

     If (Z/<n>Z)* is not cyclic or if there is no primitive root up to
     `zn_primroot_limit', `zn_primroot' returns `false'.

     The applied algorithm needs a prime factorization of `totient(n)'.
     This factorization might be time consuming in some cases and it
     can be useful to factor first and then to pass the list of factors
     to `zn_log' as an additional argument.  The list must be of the
     same form as the list returned by `ifactors(totient(n))' using the
     default option `factors_only : false'.

     See also `zn_primroot_p' , `zn_order' , `ifactors' , `totient' .

     Examples:

     `zn_primroot' computes the smallest primitive root modulo <n> or
     returns `false'.

          (%i1) n : 14$
          (%i2) g : zn_primroot(n);
          (%o2)                               3
          (%i3) zn_order(g, n) = totient(n);
          (%o3)                             6 = 6
          (%i4) n : 15$
          (%i5) zn_primroot(n);
          (%o5)                             false

     The optional second argument must be of the same form as the list
     returned by `ifactors(totient(n))'.

          (%i1) (p : 2^142 + 217, primep(p));
          (%o1)                             true
          (%i2) ifs : ifactors( totient(p) )$
          (%i3) g : zn_primroot(p, ifs);
          (%o3)                               3
          (%i4) [time(%o2), time(%o3)];
          (%o4)                    [[15.556972], [0.004]]
          (%i5) is(zn_order(g, p, ifs) = p - 1);
          (%o5)                             true
          (%i6) n : 2^142 + 216$
          (%i7) ifs : ifactors(totient(n))$
          (%i8) zn_primroot(n, ifs),
                zn_primroot_limit : 200, zn_primroot_verbose : true;
          `zn_primroot' stopped at zn_primroot_limit = 200
          (%o8)                             false


 -- Option variable: zn_primroot_limit
     Default value: `1000'

     If `zn_primroot'  cannot find a primitve root, it stops at this
     upper bound.  If the option variable `zn_primroot_verbose'
     (default: `false') is set to `true', a message will be printed
     when `zn_primroot_limit' is reached.


 -- Function: zn_primroot_p (<x>, <n>)
 -- Function: zn_primroot_p (<x>, <n>, [[<p1>, <e1>], ..., [<pk>,
          <ek>]])
     Checks whether <x> is a primitive root in the multiplicative group
     (Z/<n>Z)*.

     The applied algorithm needs a prime factorization of `totient(n)'.
     This factorization might be time consuming and in case
     `zn_primroot_p' will be consecutively applied to a list of
     candidates it can be useful to factor first and then to pass the
     list of factors to `zn_log' as a third argument.  The list must be
     of the same form as the list returned by `ifactors(totient(n))'
     using the default option `factors_only : false'.

     See also `zn_primroot' , `zn_order' , `ifactors' , `totient' .

     Examples:

     `zn_primroot_p' as a predicate function.

          (%i1) n : 14$
          (%i2) units_14 : sublist(makelist(i,i,1,13), lambda([i], gcd(i, n) = 1));
          (%o2)                     [1, 3, 5, 9, 11, 13]
          (%i3) zn_primroot_p(13, n);
          (%o3)                            false
          (%i4) sublist(units_14, lambda([x], zn_primroot_p(x, n)));
          (%o4)                            [3, 5]
          (%i5) map(lambda([x], zn_order(x, n)), units_14);
          (%o5)                      [1, 6, 6, 3, 3, 2]

     The optional third argument must be of the same form as the list
     returned by `ifactors(totient(n))'.

          (%i1) (p : 2^142 + 217, primep(p));
          (%o1)                             true
          (%i2) ifs : ifactors( totient(p) )$
          (%i3) sublist(makelist(i,i,1,50), lambda([x], zn_primroot_p(x, p, ifs)));
          (%o3)      [3, 12, 13, 15, 21, 24, 26, 27, 29, 33, 38, 42, 48]
          (%i4) [time(%o2), time(%o3)];
          (%o4)                   [[7.748484], [0.036002]]


 -- Option variable: zn_primroot_pretest
     Default value: `false'

     The multiplicative group (Z/<n>Z)* is cyclic if <n> is equal to
     `2', `4', `p^k' or `2*p^k', where `p' is prime and greater than
     `2' and `k' is a natural number.

     `zn_primroot_pretest' controls whether `zn_primroot'  will check
     if one of these cases occur before it computes the smallest
     primitive root.  Only if `zn_primroot_pretest' is set to `true'
     this pretest will be performed.


 -- Option variable: zn_primroot_verbose
     Default value: `false'

     Controls whether `zn_primroot'  prints a message when reaching
     `zn_primroot_limit' .



File: maxima.info,  Node: Symmetries,  Next: Groups,  Prev: Number Theory,  Up: Top

30 Symmetries
*************

* Menu:

* Introduction to Symmetries::
* Functions and Variables for Symmetries::


File: maxima.info,  Node: Introduction to Symmetries,  Next: Functions and Variables for Symmetries,  Prev: Symmetries,  Up: Symmetries

30.1 Introduction to Symmetries
===============================

`sym' is a package for working with symmetric groups of polynomials.

   It was written for Macsyma-Symbolics by Annick Valibouze
(`http://www-calfor.lip6.fr/~avb/').  The algorithms are described in
the following papers:

  1. Fonctions syme'triques et changements de bases. Annick Valibouze.
     EUROCAL'87 (Leipzig, 1987), 323-332, Lecture Notes in Comput. Sci
     378.  Springer, Berlin, 1989.
     `http://www.stix.polytechnique.fr/publications/1984-1994.html'

  2. Re'solvantes et fonctions syme'triques. Annick Valibouze.
     Proceedings of the ACM-SIGSAM 1989 International Symposium on
     Symbolic and Algebraic Computation, ISSAC'89 (Portland, Oregon).
     ACM Press, 390-399, 1989.
     `http://www-calfor.lip6.fr/~avb/DonneesTelechargeables/MesArticles/issac89ACMValibouze.pdf'

  3. Symbolic computation with symmetric polynomials, an extension to
     Macsyma.  Annick Valibouze. Computers and Mathematics (MIT, USA,
     June 13-17, 1989), Springer-Verlag, New York Berlin, 308-320, 1989.
     `http://www.stix.polytechnique.fr/publications/1984-1994.html'

  4. The'orie de Galois Constructive. Annick Valibouze. Me'moire
     d'habilitation a` diriger les recherches (HDR), Universite' P. et
     M. Curie (Paris VI), 1994.


File: maxima.info,  Node: Functions and Variables for Symmetries,  Prev: Introduction to Symmetries,  Up: Symmetries

30.2 Functions and Variables for Symmetries
===========================================

30.2.1 Changing bases
---------------------

 -- Function: comp2pui (<n>, <L>)
     implements passing from the complete symmetric functions given in
     the list <L> to the elementary symmetric functions from 0 to <n>.
     If the list <L> contains fewer than <n+1> elements, it will be
     completed with formal values of the type <h1>, <h2>, etc. If the
     first element of the list <L> exists, it specifies the size of the
     alphabet, otherwise the size is set to <n>.

          (%i1) comp2pui (3, [4, g]);
                                  2                    2
          (%o1)    [4, g, 2 h2 - g , 3 h3 - g h2 + g (g  - 2 h2)]


 -- Function: ele2pui (<m>, <L>)
     goes from the elementary symmetric functions to the complete
     functions.  Similar to `comp2ele' and `comp2pui'.

     Other functions for changing bases: `comp2ele'.


 -- Function: ele2comp (<m>, <L>)
     Goes from the elementary symmetric functions to the compete
     functions.  Similar to `comp2ele' and `comp2pui'.

     Other functions for changing bases: `comp2ele'.


 -- Function: elem (<ele>, <sym>, <lvar>)
     decomposes the symmetric polynomial <sym>, in the variables
     contained in the list <lvar>, in terms of the elementary symmetric
     functions given in the list <ele>.  If the first element of <ele>
     is given, it will be the size of the alphabet, otherwise the size
     will be the degree of the polynomial <sym>.  If values are missing
     in the list <ele>, formal values of the type <e1>, <e2>, etc. will
     be added.  The polynomial <sym> may be given in three different
     forms: contracted (`elem' should then be 1, its default value),
     partitioned (`elem' should be 3), or extended (i.e. the entire
     polynomial, and `elem' should then be 2).  The function `pui' is
     used in the same way.

     On an alphabet of size 3 with <e1>, the first elementary symmetric
     function, with value 7, the symmetric polynomial in 3 variables
     whose contracted form (which here depends on only two of its
     variables) is <x^4-2*x*y> decomposes as follows in elementary
     symmetric functions:

          (%i1) elem ([3, 7], x^4 - 2*x*y, [x, y]);
          (%o1) 7 (e3 - 7 e2 + 7 (49 - e2)) + 21 e3

                                                   + (- 2 (49 - e2) - 2) e2
          (%i2) ratsimp (%);
                                        2
          (%o2)             28 e3 + 2 e2  - 198 e2 + 2401

     Other functions for changing bases: `comp2ele'.


 -- Function: mon2schur (<L>)
     The list <L> represents the Schur function S_L: we have L = [i_1,
     i_2, ..., i_q], with i_1 <= i_2 <= ... <= i_q.  The Schur function
     S_[i_1, i_2, ..., i_q] is the minor of the infinite matrix
     h_[i-j], i <= 1, j <= 1, consisting of the q first rows and the
     columns 1 + i_1, 2 + i_2, ..., q + i_q.

     This Schur function can be written in terms of monomials by using
     `treinat' and `kostka'.  The form returned is a symmetric
     polynomial in a contracted representation in the variables
     x_1,x_2,...

          (%i1) mon2schur ([1, 1, 1]);
          (%o1)                       x1 x2 x3
          (%i2) mon2schur ([3]);
                                            2        3
          (%o2)                x1 x2 x3 + x1  x2 + x1
          (%i3) mon2schur ([1, 2]);
                                                2
          (%o3)                  2 x1 x2 x3 + x1  x2

     which means that for 3 variables this gives:

             2 x1 x2 x3 + x1^2 x2 + x2^2 x1 + x1^2 x3 + x3^2 x1
              + x2^2 x3 + x3^2 x2
     Other functions for changing bases: `comp2ele'.


 -- Function: multi_elem (<l_elem>, <multi_pc>, <l_var>)
     decomposes a multi-symmetric polynomial in the multi-contracted
     form <multi_pc> in the groups of variables contained in the list
     of lists <l_var> in terms of the elementary symmetric functions
     contained in <l_elem>.

          (%i1) multi_elem ([[2, e1, e2], [2, f1, f2]], a*x + a^2 + x^3,
                [[x, y], [a, b]]);
                                                            3
          (%o1)         - 2 f2 + f1 (f1 + e1) - 3 e1 e2 + e1
          (%i2) ratsimp (%);
                                   2                       3
          (%o2)         - 2 f2 + f1  + e1 f1 - 3 e1 e2 + e1

     Other functions for changing bases: `comp2ele'.


 -- Function: multi_pui
     is to the function `pui' what the function `multi_elem' is to the
     function `elem'.

          (%i1) multi_pui ([[2, p1, p2], [2, t1, t2]], a*x + a^2 + x^3,
                [[x, y], [a, b]]);
                                                      3
                                          3 p1 p2   p1
          (%o1)              t2 + p1 t1 + ------- - ---
                                             2       2


 -- Function: pui (<L>, <sym>, <lvar>)
     decomposes the symmetric polynomial <sym>, in the variables in the
     list <lvar>, in terms of the power functions in the list <L>.  If
     the first element of <L> is given, it will be the size of the
     alphabet, otherwise the size will be the degree of the polynomial
     <sym>.  If values are missing in the list <L>, formal values of
     the type <p1>, <p2> , etc. will be added. The polynomial <sym> may
     be given in three different forms: contracted (`elem' should then
     be 1, its default value), partitioned (`elem' should be 3), or
     extended (i.e. the entire polynomial, and `elem' should then be
     2). The function `pui' is used in the same way.

          (%i1) pui;
          (%o1)                           1
          (%i2) pui ([3, a, b], u*x*y*z, [x, y, z]);
                                 2
                             a (a  - b) u   (a b - p3) u
          (%o2)              ------------ - ------------
                                  6              3
          (%i3) ratsimp (%);
                                                 3
                                (2 p3 - 3 a b + a ) u
          (%o3)                 ---------------------
                                          6
     Other functions for changing bases: `comp2ele'.


 -- Function: pui2comp (<n>, <lpui>)
     renders the list of the first <n> complete functions (with the
     length first) in terms of the power functions given in the list
     <lpui>. If the list <lpui> is empty, the cardinal is <n>,
     otherwise it is its first element (as in `comp2ele' and
     `comp2pui').

          (%i1) pui2comp (2, []);
                                                 2
                                          p2 + p1
          (%o1)                   [2, p1, --------]
                                             2
          (%i2) pui2comp (3, [2, a1]);
                                                      2
                                           a1 (p2 + a1 )
                                   2  p3 + ------------- + a1 p2
                            p2 + a1              2
          (%o2)     [2, a1, --------, --------------------------]
                               2                  3
          (%i3) ratsimp (%);
                                      2                     3
                               p2 + a1   2 p3 + 3 a1 p2 + a1
          (%o3)        [2, a1, --------, --------------------]
                                  2               6
     Other functions for changing bases: `comp2ele'.


 -- Function: pui2ele (<n>, <lpui>)
     effects the passage from power functions to the elementary
     symmetric functions.  If the flag `pui2ele' is `girard', it will
     return the list of elementary symmetric functions from 1 to <n>,
     and if the flag is `close', it will return the <n>-th elementary
     symmetric function.

     Other functions for changing bases: `comp2ele'.


 -- Function: puireduc (<n>, <lpui>)
     <lpui> is a list whose first element is an integer <m>.
     `puireduc' gives the first <n> power functions in terms of the
     first <m>.

          (%i1) puireduc (3, [2]);
                                                   2
                                             p1 (p1  - p2)
          (%o1)          [2, p1, p2, p1 p2 - -------------]
                                                   2
          (%i2) ratsimp (%);
                                                     3
                                         3 p1 p2 - p1
          (%o2)              [2, p1, p2, -------------]
                                               2


 -- Function: schur2comp (<P>, <l_var>)
     <P> is a polynomial in the variables of the list <l_var>.  Each of
     these variables represents a complete symmetric function.  In
     <l_var> the <i>-th complete symmetric function is represented by
     the concatenation of the letter `h' and the integer <i>: `h<i>'.
     This function expresses <P> in terms of Schur functions.

          (%i1) schur2comp (h1*h2 - h3, [h1, h2, h3]);
          (%o1)                         s
                                         1, 2
          (%i2) schur2comp (a*h3, [h3]);
          (%o2)                         s  a
                                         3


30.2.2 Changing representations
-------------------------------

 -- Function: cont2part (<pc>, <lvar>)
     returns the partitioned polynomial associated to the contracted
     form <pc> whose variables are in <lvar>.

          (%i1) pc: 2*a^3*b*x^4*y + x^5;
                                     3    4      5
          (%o1)                   2 a  b x  y + x
          (%i2) cont2part (pc, [x, y]);
                                             3
          (%o2)              [[1, 5, 0], [2 a  b, 4, 1]]


 -- Function: contract (<psym>, <lvar>)
     returns a contracted form (i.e. a monomial orbit under the action
     of the symmetric group) of the polynomial <psym> in the variables
     contained in the list <lvar>.  The function `explose' performs the
     inverse operation.  The function `tcontract' tests the symmetry of
     the polynomial.

          (%i1) psym: explose (2*a^3*b*x^4*y, [x, y, z]);
                   3      4      3      4      3    4        3    4
          (%o1) 2 a  b y z  + 2 a  b x z  + 2 a  b y  z + 2 a  b x  z

                                                     3      4      3    4
                                                + 2 a  b x y  + 2 a  b x  y
          (%i2) contract (psym, [x, y, z]);
                                        3    4
          (%o2)                      2 a  b x  y


 -- Function: explose (<pc>, <lvar>)
     returns the symmetric polynomial associated with the contracted
     form <pc>. The list <lvar> contains the variables.

          (%i1) explose (a*x + 1, [x, y, z]);
          (%o1)                  a z + a y + a x + 1


 -- Function: part2cont (<ppart>, <lvar>)
     goes from the partitioned form to the contracted form of a
     symmetric polynomial.  The contracted form is rendered with the
     variables in <lvar>.

          (%i1) part2cont ([[2*a^3*b, 4, 1]], [x, y]);
                                        3    4
          (%o1)                      2 a  b x  y


 -- Function: partpol (<psym>, <lvar>)
     <psym> is a symmetric polynomial in the variables of the list
     <lvar>. This function retturns its partitioned representation.

          (%i1) partpol (-a*(x + y) + 3*x*y, [x, y]);
          (%o1)               [[3, 1, 1], [- a, 1, 0]]


 -- Function: tcontract (<pol>, <lvar>)
     tests if the polynomial <pol> is symmetric in the variables of the
     list <lvar>.  If so, it returns a contracted representation like
     the function `contract'.


 -- Function: tpartpol (<pol>, <lvar>)
     tests if the polynomial <pol> is symmetric in the variables of the
     list <lvar>.  If so, it returns its partitioned representation like
     the function `partpol'.


30.2.3 Groups and orbits
------------------------

 -- Function: direct ([<p_1>, ..., <p_n>], <y>, <f>, [<lvar_1>, ...,
          <lvar_n>])
     calculates the direct image (see M. Giusti, D. Lazard et A.
     Valibouze, ISSAC 1988, Rome) associated to the function <f>, in
     the lists of variables <lvar_1>, ..., <lvar_n>, and in the
     polynomials <p_1>, ..., <p_n> in a variable <y>.  The arity of the
     function <f> is important for the calulation.  Thus, if the
     expression for <f> does not depend on some variable, it is useless
     to include this variable, and not including it will also
     considerably reduce the amount of computation.

          (%i1) direct ([z^2  - e1* z + e2, z^2  - f1* z + f2],
                        z, b*v + a*u, [[u, v], [a, b]]);
                 2
          (%o1) y  - e1 f1 y

                                           2            2             2   2
                            - 4 e2 f2 - (e1  - 2 e2) (f1  - 2 f2) + e1  f1
                          + -----------------------------------------------
                                                   2
          (%i2) ratsimp (%);
                        2                2                   2
          (%o2)        y  - e1 f1 y + (e1  - 4 e2) f2 + e2 f1
          (%i3) ratsimp (direct ([z^3-e1*z^2+e2*z-e3,z^2  - f1* z + f2],
                        z, b*v + a*u, [[u, v], [a, b]]));
                 6            5         2                        2    2   4
          (%o3) y  - 2 e1 f1 y  + ((2 e1  - 6 e2) f2 + (2 e2 + e1 ) f1 ) y

                                    3                               3   3
           + ((9 e3 + 5 e1 e2 - 2 e1 ) f1 f2 + (- 2 e3 - 2 e1 e2) f1 ) y

                   2       2        4    2
           + ((9 e2  - 6 e1  e2 + e1 ) f2

                              2       2       2                   2    4
           + (- 9 e1 e3 - 6 e2  + 3 e1  e2) f1  f2 + (2 e1 e3 + e2 ) f1 )

            2          2                      2     3          2
           y  + (((9 e1  - 27 e2) e3 + 3 e1 e2  - e1  e2) f1 f2

                           2            2    3                5
           + ((15 e2 - 2 e1 ) e3 - e1 e2 ) f1  f2 - 2 e2 e3 f1 ) y

                     2                   3           3     2   2    3
           + (- 27 e3  + (18 e1 e2 - 4 e1 ) e3 - 4 e2  + e1  e2 ) f2

                   2      3                   3    2   2
           + (27 e3  + (e1  - 9 e1 e2) e3 + e2 ) f1  f2

                             2    4        2   6
           + (e1 e2 e3 - 9 e3 ) f1  f2 + e3  f1

     Finding the polynomial whose roots are the sums a+u where a is a
     root of z^2 - e_1 z + e_2 and u is a root of z^2 - f_1 z + f_2.

          (%i1) ratsimp (direct ([z^2 - e1* z + e2, z^2 - f1* z + f2],
                                    z, a + u, [[u], [a]]));
                 4                    3             2
          (%o1) y  + (- 2 f1 - 2 e1) y  + (2 f2 + f1  + 3 e1 f1 + 2 e2

               2   2                              2               2
           + e1 ) y  + ((- 2 f1 - 2 e1) f2 - e1 f1  + (- 2 e2 - e1 ) f1

                            2                     2            2
           - 2 e1 e2) y + f2  + (e1 f1 - 2 e2 + e1 ) f2 + e2 f1  + e1 e2 f1

               2
           + e2

     `direct' accepts two flags: `elementaires' and `puissances'
     (default) which allow decomposing the symmetric polynomials
     appearing in the calculation into elementary symmetric functions,
     or power functions, respectively.

     Functions of `sym' used in this function:

     `multi_orbit' (so `orbit'), `pui_direct', `multi_elem' (so
     `elem'), `multi_pui' (so `pui'), `pui2ele', `ele2pui' (if the flag
     `direct' is in `puissances').


 -- Function: multi_orbit (<P>, [<lvar_1>, <lvar_2>,..., <lvar_p>])
     <P> is a polynomial in the set of variables contained in the lists
     <lvar_1>, <lvar_2>, ..., <lvar_p>. This function returns the orbit
     of the polynomial <P> under the action of the product of the
     symmetric groups of the sets of variables represented in these <p>
     lists.

          (%i1) multi_orbit (a*x + b*y, [[x, y], [a, b]]);
          (%o1)                [b y + a x, a y + b x]
          (%i2) multi_orbit (x + y + 2*a, [[x, y], [a, b, c]]);
          (%o2)        [y + x + 2 c, y + x + 2 b, y + x + 2 a]
     Also see: `orbit' for the action of a single symmetric group.


 -- Function: multsym (<ppart_1>, <ppart_2>, <n>)
     returns the product of the two symmetric polynomials in <n>
     variables by working only modulo the action of the symmetric group
     of order <n>. The polynomials are in their partitioned form.

     Given the 2 symmetric polynomials in <x>, <y>:  `3*(x + y) +
     2*x*y' and `5*(x^2 + y^2)' whose partitioned forms are `[[3, 1],
     [2, 1, 1]]' and `[[5, 2]]', their product will be

          (%i1) multsym ([[3, 1], [2, 1, 1]], [[5, 2]], 2);
          (%o1)         [[10, 3, 1], [15, 3, 0], [15, 2, 1]]
     that is `10*(x^3*y + y^3*x) + 15*(x^2*y + y^2*x) + 15*(x^3 +
     y^3)'.

     Functions for changing the representations of a symmetric
     polynomial:

     `contract', `cont2part', `explose', `part2cont', `partpol',
     `tcontract', `tpartpol'.


 -- Function: orbit (<P>, <lvar>)
     computes the orbit of the polynomial <P> in the variables in the
     list <lvar> under the action of the symmetric group of the set of
     variables in the list <lvar>.

          (%i1) orbit (a*x + b*y, [x, y]);
          (%o1)                [a y + b x, b y + a x]
          (%i2) orbit (2*x + x^2, [x, y]);
                                  2         2
          (%o2)                 [y  + 2 y, x  + 2 x]
     See also `multi_orbit' for the action of a product of
     symmetric groups on a polynomial.


 -- Function: pui_direct (<orbite>, [<lvar_1>, ..., <lvar_n>], [<d_1>,
          <d_2>, ..., <d_n>])
     Let <f> be a polynomial in <n> blocks of variables <lvar_1>, ...,
     <lvar_n>.  Let <c_i> be the number of variables in <lvar_i>, and
     <SC> be the product of <n> symmetric groups of degree <c_1>, ...,
     <c_n>. This group acts naturally on <f>.  The list <orbite> is the
     orbit, denoted `<SC>(<f>)', of the function <f> under the action
     of <SC>. (This list may be obtained by the function
     `multi_orbit'.)  The <di> are integers s.t.  c_1 <= d_1, c_2 <=
     d_2, ..., c_n <= d_n.

     Let <SD> be the product of the symmetric groups S_[d_1] x S_[d_2]
     x ... x S_[d_n].  The function `pui_direct' returns the first <n>
     power functions of `<SD>(<f>)' deduced from the power functions of
     `<SC>(<f>)', where <n> is the size of `<SD>(<f>)'.

     The result is in multi-contracted form w.r.t. <SD>, i.e. only one
     element is kept per orbit, under the action of <SD>.

          (%i1) l: [[x, y], [a, b]];
          (%o1)                   [[x, y], [a, b]]
          (%i2) pui_direct (multi_orbit (a*x + b*y, l), l, [2, 2]);
                                                 2  2
          (%o2)               [a x, 4 a b x y + a  x ]
          (%i3) pui_direct (multi_orbit (a*x + b*y, l), l, [3, 2]);
                                       2  2     2    2        3  3
          (%o3) [2 a x, 4 a b x y + 2 a  x , 3 a  b x  y + 2 a  x ,

              2  2  2  2      3    3        4  4
          12 a  b  x  y  + 4 a  b x  y + 2 a  x ,

              3  2  3  2      4    4        5  5
          10 a  b  x  y  + 5 a  b x  y + 2 a  x ,

              3  3  3  3       4  2  4  2      5    5        6  6
          40 a  b  x  y  + 15 a  b  x  y  + 6 a  b x  y + 2 a  x ]
          (%i4) pui_direct ([y + x + 2*c, y + x + 2*b, y + x + 2*a],
                [[x, y], [a, b, c]], [2, 3]);
                                       2              2
          (%o4) [3 x + 2 a, 6 x y + 3 x  + 4 a x + 4 a ,

                           2                   3        2       2        3
                        9 x  y + 12 a x y + 3 x  + 6 a x  + 12 a  x + 8 a ]


30.2.4 Partitions
-----------------

 -- Function: kostka (<part_1>, <part_2>)
     written by P. Esperet, calculates the Kostka number of the
     partition <part_1> and <part_2>.

          (%i1) kostka ([3, 3, 3], [2, 2, 2, 1, 1, 1]);
          (%o1)                           6


 -- Function: lgtreillis (<n>, <m>)
     returns the list of partitions of weight <n> and length <m>.

          (%i1) lgtreillis (4, 2);
          (%o1)                   [[3, 1], [2, 2]]
     Also see: `ltreillis', `treillis' and `treinat'.


 -- Function: ltreillis (<n>, <m>)
     returns the list of partitions of weight <n> and length less than
     or equal to <m>.

          (%i1) ltreillis (4, 2);
          (%o1)               [[4, 0], [3, 1], [2, 2]]
     Also see: `lgtreillis', `treillis' and `treinat'.


 -- Function: treillis (<n>)
     returns all partitions of weight <n>.

          (%i1) treillis (4);
          (%o1)    [[4], [3, 1], [2, 2], [2, 1, 1], [1, 1, 1, 1]]

     See also: `lgtreillis', `ltreillis' and `treinat'.


 -- Function: treinat (<part>)
     retruns the list of partitions inferior to the partition <part>
     w.r.t.  the natural order.

          (%i1) treinat ([5]);
          (%o1)                         [[5]]
          (%i2) treinat ([1, 1, 1, 1, 1]);
          (%o2) [[5], [4, 1], [3, 2], [3, 1, 1], [2, 2, 1], [2, 1, 1, 1],

                                                           [1, 1, 1, 1, 1]]
          (%i3) treinat ([3, 2]);
          (%o3)                 [[5], [4, 1], [3, 2]]

     See also: `lgtreillis', `ltreillis' and `treillis'.


30.2.5 Polynomials and their roots
----------------------------------

 -- Function: ele2polynome (<L>, <z>)
     returns the polynomial in <z> s.t. the elementary symmetric
     functions of its roots are in the list `<L> = [<n>, <e_1>, ...,
     <e_n>]', where <n> is the degree of the polynomial and <e_i> the
     <i>-th elementary symmetric function.

          (%i1) ele2polynome ([2, e1, e2], z);
                                    2
          (%o1)                    z  - e1 z + e2
          (%i2) polynome2ele (x^7 - 14*x^5 + 56*x^3  - 56*x + 22, x);
          (%o2)          [7, 0, - 14, 0, 56, 0, - 56, - 22]
          (%i3) ele2polynome ([7, 0, -14, 0, 56, 0, -56, -22], x);
                            7       5       3
          (%o3)            x  - 14 x  + 56 x  - 56 x + 22
     The inverse: `polynome2ele (<P>, <z>)'.

     Also see: `polynome2ele', `pui2polynome'.


 -- Function: polynome2ele (<P>, <x>)
     gives the list `<l> = [<n>, <e_1>, ..., <e_n>]' where <n> is the
     degree of the polynomial <P> in the variable <x> and <e_i> is the
     <i>-the elementary symmetric function of the roots of <P>.

          (%i1) polynome2ele (x^7 - 14*x^5 + 56*x^3 - 56*x + 22, x);
          (%o1)          [7, 0, - 14, 0, 56, 0, - 56, - 22]
          (%i2) ele2polynome ([7, 0, -14, 0, 56, 0, -56, -22], x);
                            7       5       3
          (%o2)            x  - 14 x  + 56 x  - 56 x + 22
     The inverse: `ele2polynome (<l>, <x>)'


 -- Function: prodrac (<L>, <k>)
     <L> is a list containing the elementary symmetric functions on a
     set <A>. `prodrac' returns the polynomial whose roots are the <k>
     by <k> products of the elements of <A>.

     Also see `somrac'.


 -- Function: pui2polynome (<x>, <lpui>)
     calculates the polynomial in <x> whose power functions of the roots
     are given in the list <lpui>.

          (%i1) pui;
          (%o1)                           1
          (%i2) kill(labels);
          (%o0)                         done
          (%i1) polynome2ele (x^3 - 4*x^2 + 5*x - 1, x);
          (%o1)                     [3, 4, 5, 1]
          (%i2) ele2pui (3, %);
          (%o2)                     [3, 4, 6, 7]
          (%i3) pui2polynome (x, %);
                                  3      2
          (%o3)                  x  - 4 x  + 5 x - 1
     See also: `polynome2ele', `ele2polynome'.


 -- Function: somrac (<L>, <k>)
     The list <L> contains elementary symmetric functions of a
     polynomial <P> . The function computes the polynomial whose roots
     are the <k> by <k> distinct sums of the roots of <P>.

     Also see `prodrac'.


30.2.6 Resolvents
-----------------

 -- Function: resolvante (<P>, <x>, <f>, [<x_1>,..., <x_d>])
     calculates the resolvent of the polynomial <P> in <x> of degree
     <n> >= <d> by the function <f> expressed in the variables <x_1>,
     ..., <x_d>.  For efficiency of computation it is important to not
     include in the list `[<x_1>, ..., <x_d>]' variables which do not
     appear in the transformation function <f>.

     To increase the efficiency of the computation one may set flags in
     `resolvante' so as to use appropriate algorithms:

     If the function <f> is unitary:
        * A polynomial in a single variable,

        *   linear,

        *   alternating,

        *   a sum,

        *   symmetric,

        *   a product,

        * the function of the Cayley resolvent (usable up to degree 5)

               (x1*x2 + x2*x3 + x3*x4 + x4*x5 + x5*x1 -
                    (x1*x3 + x3*x5 + x5*x2 + x2*x4 + x4*x1))^2

          general,
     the flag of `resolvante' may be, respectively:
        *   unitaire,

        *   lineaire,

        *   alternee,

        *   somme,

        *   produit,

        *   cayley,

        *   generale.

          (%i1) resolvante: unitaire$
          (%i2) resolvante (x^7 - 14*x^5 + 56*x^3 - 56*x + 22, x, x^3 - 1,
                [x]);

          " resolvante unitaire " [7, 0, 28, 0, 168, 0, 1120, - 154, 7840,
                                   - 2772, 56448, - 33880,

          413952, - 352352, 3076668, - 3363360, 23114112, - 30494464,

          175230832, - 267412992, 1338886528, - 2292126760]
            3       6      3       9      6      3
          [x  - 1, x  - 2 x  + 1, x  - 3 x  + 3 x  - 1,

           12      9      6      3       15      12       9       6      3
          x   - 4 x  + 6 x  - 4 x  + 1, x   - 5 x   + 10 x  - 10 x  + 5 x

                 18      15       12       9       6      3
           - 1, x   - 6 x   + 15 x   - 20 x  + 15 x  - 6 x  + 1,

           21      18       15       12       9       6      3
          x   - 7 x   + 21 x   - 35 x   + 35 x  - 21 x  + 7 x  - 1]
          [- 7, 1127, - 6139, 431767, - 5472047, 201692519, - 3603982011]
                 7      6        5         4          3           2
          (%o2) y  + 7 y  - 539 y  - 1841 y  + 51443 y  + 315133 y

                                                        + 376999 y + 125253
          (%i3) resolvante: lineaire$
          (%i4) resolvante (x^4 - 1, x, x1 + 2*x2 + 3*x3, [x1, x2, x3]);

          " resolvante lineaire "
                 24       20         16            12             8
          (%o4) y   + 80 y   + 7520 y   + 1107200 y   + 49475840 y

                                                              4
                                                 + 344489984 y  + 655360000
          (%i5) resolvante: general$
          (%i6) resolvante (x^4 - 1, x, x1 + 2*x2 + 3*x3, [x1, x2, x3]);

          " resolvante generale "
                 24       20         16            12             8
          (%o6) y   + 80 y   + 7520 y   + 1107200 y   + 49475840 y

                                                              4
                                                 + 344489984 y  + 655360000
          (%i7) resolvante (x^4 - 1, x, x1 + 2*x2 + 3*x3, [x1, x2, x3, x4]);

          " resolvante generale "
                 24       20         16            12             8
          (%o7) y   + 80 y   + 7520 y   + 1107200 y   + 49475840 y

                                                              4
                                                 + 344489984 y  + 655360000
          (%i8) direct ([x^4 - 1], x, x1 + 2*x2 + 3*x3, [[x1, x2, x3]]);
                 24       20         16            12             8
          (%o8) y   + 80 y   + 7520 y   + 1107200 y   + 49475840 y

                                                              4
                                                 + 344489984 y  + 655360000
          (%i9) resolvante :lineaire$
          (%i10) resolvante (x^4 - 1, x, x1 + x2 + x3, [x1, x2, x3]);

          " resolvante lineaire "
                                        4
          (%o10)                       y  - 1
          (%i11) resolvante: symetrique$
          (%i12) resolvante (x^4 - 1, x, x1 + x2 + x3, [x1, x2, x3]);

          " resolvante symetrique "
                                        4
          (%o12)                       y  - 1
          (%i13) resolvante (x^4 + x + 1, x, x1 - x2, [x1, x2]);

          " resolvante symetrique "
                                     6      2
          (%o13)                    y  - 4 y  - 1
          (%i14) resolvante: alternee$
          (%i15) resolvante (x^4 + x + 1, x, x1 - x2, [x1, x2]);

          " resolvante alternee "
                      12      8       6        4        2
          (%o15)     y   + 8 y  + 26 y  - 112 y  + 216 y  + 229
          (%i16) resolvante: produit$
          (%i17) resolvante (x^7 - 7*x + 3, x, x1*x2*x3, [x1, x2, x3]);

          " resolvante produit "
                  35      33         29        28         27        26
          (%o17) y   - 7 y   - 1029 y   + 135 y   + 7203 y   - 756 y

                   24           23          22            21           20
           + 1323 y   + 352947 y   - 46305 y   - 2463339 y   + 324135 y

                    19           18             17              15
           - 30618 y   - 453789 y   - 40246444 y   + 282225202 y

                       14              12             11            10
           - 44274492 y   + 155098503 y   + 12252303 y   + 2893401 y

                        9            8            7             6
           - 171532242 y  + 6751269 y  + 2657205 y  - 94517766 y

                      5             3
           - 3720087 y  + 26040609 y  + 14348907
          (%i18) resolvante: symetrique$
          (%i19) resolvante (x^7 - 7*x + 3, x, x1*x2*x3, [x1, x2, x3]);

          " resolvante symetrique "
                  35      33         29        28         27        26
          (%o19) y   - 7 y   - 1029 y   + 135 y   + 7203 y   - 756 y

                   24           23          22            21           20
           + 1323 y   + 352947 y   - 46305 y   - 2463339 y   + 324135 y

                    19           18             17              15
           - 30618 y   - 453789 y   - 40246444 y   + 282225202 y

                       14              12             11            10
           - 44274492 y   + 155098503 y   + 12252303 y   + 2893401 y

                        9            8            7             6
           - 171532242 y  + 6751269 y  + 2657205 y  - 94517766 y

                      5             3
           - 3720087 y  + 26040609 y  + 14348907
          (%i20) resolvante: cayley$
          (%i21) resolvante (x^5 - 4*x^2 + x + 1, x, a, []);

          " resolvante de Cayley "
                  6       5         4          3            2
          (%o21) x  - 40 x  + 4080 x  - 92928 x  + 3772160 x  + 37880832 x

                                                                 + 93392896

     For the Cayley resolvent, the 2 last arguments are neutral and the
     input polynomial must necessarily be of degree 5.

     See also:
     `resolvante_bipartite', `resolvante_produit_sym',
     `resolvante_unitaire', `resolvante_alternee1', `resolvante_klein',
     `resolvante_klein3', `resolvante_vierer', `resolvante_diedrale'.


 -- Function: resolvante_alternee1 (<P>, <x>)
     calculates the transformation `<P>(<x>)' of degree <n> by the
     function product(x_i - x_j, 1 <= i < j <= n - 1).

     See also:
     `resolvante_produit_sym', `resolvante_unitaire',
     `resolvante' , `resolvante_klein', `resolvante_klein3',
     `resolvante_vierer', `resolvante_diedrale', `resolvante_bipartite'.


 -- Function: resolvante_bipartite (<P>, <x>)
     calculates the transformation of `<P>(<x>)' of even degree <n> by
     the function x_1 x_2 ... x_[n/2] + x_[n/2 + 1] ... x_n.

          (%i1) resolvante_bipartite (x^6 + 108, x);
                        10        8           6             4
          (%o1)        y   - 972 y  + 314928 y  - 34012224 y

     See also:
     `resolvante_produit_sym', `resolvante_unitaire',
     `resolvante', `resolvante_klein', `resolvante_klein3',
     `resolvante_vierer', `resolvante_diedrale', `resolvante_alternee1'.


 -- Function: resolvante_diedrale (<P>, <x>)
     calculates the transformation of `<P>(<x>)' by the function `<x_1>
     <x_2> + <x_3> <x_4>'.

          (%i1) resolvante_diedrale (x^5 - 3*x^4 + 1, x);
                 15       12       11       10        9         8         7
          (%o1) x   - 21 x   - 81 x   - 21 x   + 207 x  + 1134 x  + 2331 x

                  6         5          4          3          2
           - 945 x  - 4970 x  - 18333 x  - 29079 x  - 20745 x  - 25326 x

           - 697

     See also:
     `resolvante_produit_sym', `resolvante_unitaire',
     `resolvante_alternee1', `resolvante_klein', `resolvante_klein3',
     `resolvante_vierer', `resolvante'.


 -- Function: resolvante_klein (<P>, <x>)
     calculates the transformation of `<P>(<x>)' by the function `<x_1>
     <x_2> <x_4> + <x_4>'.

     See also:
     `resolvante_produit_sym', `resolvante_unitaire',
     `resolvante_alternee1', `resolvante', `resolvante_klein3',
     `resolvante_vierer', `resolvante_diedrale'.


 -- Function: resolvante_klein3 (<P>, <x>)
     calculates the transformation of `<P>(<x>)' by the function `<x_1>
     <x_2> <x_4> + <x_4>'.

     See also:
     `resolvante_produit_sym', `resolvante_unitaire',
     `resolvante_alternee1', `resolvante_klein', `resolvante',
     `resolvante_vierer', `resolvante_diedrale'.


 -- Function: resolvante_produit_sym (<P>, <x>)
     calculates the list of all product resolvents of the polynomial
     `<P>(<x>)'.

          (%i1) resolvante_produit_sym (x^5 + 3*x^4 + 2*x - 1, x);
                  5      4             10      8       7       6       5
          (%o1) [y  + 3 y  + 2 y - 1, y   - 2 y  - 21 y  - 31 y  - 14 y

              4       3      2       10      8       7    6       5       4
           - y  + 14 y  + 3 y  + 1, y   + 3 y  + 14 y  - y  - 14 y  - 31 y

                 3      2       5      4
           - 21 y  - 2 y  + 1, y  - 2 y  - 3 y - 1, y - 1]
          (%i2) resolvante: produit$
          (%i3) resolvante (x^5 + 3*x^4 + 2*x - 1, x, a*b*c, [a, b, c]);

          " resolvante produit "
                 10      8       7    6        5       4       3     2
          (%o3) y   + 3 y  + 14 y  - y  - 14 y  - 31 y  - 21 y  - 2 y  + 1

     See also:
     `resolvante', `resolvante_unitaire',
     `resolvante_alternee1', `resolvante_klein',
     `resolvante_klein3', `resolvante_vierer',
     `resolvante_diedrale'.


 -- Function: resolvante_unitaire (<P>, <Q>, <x>)
     computes the resolvent of the polynomial `<P>(<x>)' by the
     polynomial `<Q>(<x>)'.

     See also:
     `resolvante_produit_sym', `resolvante',
     `resolvante_alternee1', `resolvante_klein', `resolvante_klein3',
     `resolvante_vierer', `resolvante_diedrale'.


 -- Function: resolvante_vierer (<P>, <x>)
     computes the transformation of `<P>(<x>)' by the function `<x_1>
     <x_2> - <x_3> <x_4>'.

     See also:
     `resolvante_produit_sym', `resolvante_unitaire',
     `resolvante_alternee1', `resolvante_klein', `resolvante_klein3',
     `resolvante', `resolvante_diedrale'.


30.2.7 Miscellaneous
--------------------

 -- Function: multinomial (<r>, <part>)
     where <r> is the weight of the partition <part>.  This function
     returns the associate multinomial coefficient: if the parts of
     <part> are <i_1>, <i_2>, ..., <i_k>, the result is `<r>!/(<i_1>!
     <i_2>! ... <i_k>!)'.


 -- Function: permut (<L>)
     returns the list of permutations of the list <L>.



File: maxima.info,  Node: Groups,  Next: Runtime Environment,  Prev: Symmetries,  Up: Top

31 Groups
*********

* Menu:

* Functions and Variables for Groups::


File: maxima.info,  Node: Functions and Variables for Groups,  Prev: Groups,  Up: Groups

31.1 Functions and Variables for Groups
=======================================

 -- Function: todd_coxeter (<relations>, <subgroup>)
 -- Function: todd_coxeter (<relations>)
     Find the order of G/H where G is the Free Group modulo
     <relations>, and H is the subgroup of G generated by <subgroup>.
     <subgroup> is an optional argument, defaulting to [].  In doing
     this it produces a multiplication table for the right action of G
     on G/H, where the cosets are enumerated [H,Hg2,Hg3,...].  This can
     be seen internally in the variable `todd_coxeter_state'.

     Example:

          (%i1) symet(n):=create_list(
                  if (j - i) = 1 then (p(i,j))^^3 else
                      if (not i = j) then (p(i,j))^^2 else
                          p(i,i) , j, 1, n-1, i, 1, j);
                                                                 <3>
          (%o1) symet(n) := create_list(if j - i = 1 then p(i, j)

                                          <2>
           else (if not i = j then p(i, j)    else p(i, i)), j, 1, n - 1,

          i, 1, j)
          (%i2) p(i,j) := concat(x,i).concat(x,j);
          (%o2)        p(i, j) := concat(x, i) . concat(x, j)
          (%i3) symet(5);
                   <2>           <3>    <2>           <2>           <3>
          (%o3) [x1   , (x1 . x2)   , x2   , (x1 . x3)   , (x2 . x3)   ,

                      <2>           <2>           <2>           <3>    <2>
                    x3   , (x1 . x4)   , (x2 . x4)   , (x3 . x4)   , x4   ]
          (%i4) todd_coxeter(%o3);

          Rows tried 426
          (%o4)                          120
          (%i5) todd_coxeter(%o3,[x1]);

          Rows tried 213
          (%o5)                          60
          (%i6) todd_coxeter(%o3,[x1,x2]);

          Rows tried 71
          (%o6)                          20



File: maxima.info,  Node: Runtime Environment,  Next: Miscellaneous Options,  Prev: Groups,  Up: Top

32 Runtime Environment
**********************

* Menu:

* Introduction for Runtime Environment::
* Interrupts::
* Functions and Variables for Runtime Environment::


File: maxima.info,  Node: Introduction for Runtime Environment,  Next: Interrupts,  Prev: Runtime Environment,  Up: Runtime Environment

32.1 Introduction for Runtime Environment
=========================================

`maxima-init.mac' is a file which is loaded automatically when Maxima
starts.  You can use `maxima-init.mac' to customize your Maxima
environment.  `maxima-init.mac', if it exists, is typically placed in
the directory named by `maxima_userdir', although it can be in any
directory searched by the function `file_search'.

   Here is an example `maxima-init.mac' file:

     setup_autoload ("specfun.mac", ultraspherical, assoc_legendre_p);
     showtime:all;

   In this example, `setup_autoload' tells Maxima to load the specified
file (`specfun.mac') if any of the functions (`ultraspherical',
`assoc_legendre_p') are called but not yet defined.  Thus you needn't
remember to load the file before calling the functions.

   The statement `showtime: all' tells Maxima to set the `showtime'
variable.  The `maxima-init.mac' file can contain any other assignments
or other Maxima statements.


File: maxima.info,  Node: Interrupts,  Next: Functions and Variables for Runtime Environment,  Prev: Introduction for Runtime Environment,  Up: Runtime Environment

32.2 Interrupts
===============

The user can stop a time-consuming computation with the ^C (control-C)
character.  The default action is to stop the computation and print
another user prompt.  In this case, it is not possible to restart a
stopped computation.

   If the Lisp variable `*debugger-hook*' is set to `nil', by executing

     :lisp (setq *debugger-hook* nil)

then upon receiving ^C, Maxima will enter the Lisp debugger, and the
user may use the debugger to inspect the Lisp environment.  The stopped
computation can be restarted by entering `continue' in the Lisp
debugger.  The means of returning to Maxima from the Lisp debugger
(other than running the computation to completion) is different for
each version of Lisp.

   On Unix systems, the character ^Z (control-Z) causes Maxima to stop
altogether, and control is returned to the shell prompt.  The `fg'
command causes Maxima to resume from the point at which it was stopped.


File: maxima.info,  Node: Functions and Variables for Runtime Environment,  Prev: Interrupts,  Up: Runtime Environment

32.3 Functions and Variables for Runtime Environment
====================================================

 -- System variable: maxima_tempdir
     `maxima_tempdir' names the directory in which Maxima creates some
     temporary files.  In particular, temporary files for plotting are
     created in `maxima_tempdir'.

     The initial value of `maxima_tempdir' is the user's home
     directory, if Maxima can locate it; otherwise Maxima makes a guess
     about a suitable directory.

     `maxima_tempdir' may be assigned a string which names a directory.


 -- System variable: maxima_userdir
     `maxima_userdir' names a directory which Maxima searches to find
     Maxima and Lisp files.  (Maxima searches some other directories as
     well; `file_search_maxima' and `file_search_lisp' are the complete
     lists.)

     The initial value of `maxima_userdir' is a subdirectory of the
     user's home directory, if Maxima can locate it; otherwise Maxima
     makes a guess about a suitable directory.

     `maxima_userdir' may be assigned a string which names a directory.
     However, assigning to `maxima_userdir' does not automatically
     change `file_search_maxima' and `file_search_lisp'; those
     variables must be changed separately.


 -- Function: room ()
 -- Function: room (true)
 -- Function: room (false)
     Prints out a description of the state of storage and stack
     management in Maxima.  `room' calls the Lisp function of the same
     name.

        * `room ()' prints out a moderate description.

        * `room (true)' prints out a verbose description.

        * `room (false)' prints out a terse description.


 -- Function: sstatus (<keyword>, <item>)
     When <keyword> is the symbol `feature', <item> is put on the list
     of system features.  After `sstatus (keyword, item)' is executed,
     `status (feature, item)' returns `true'.  If <keyword> is the
     symbol `nofeature', <item> is deleted from the list of system
     features.  This can be useful for package writers, to keep track
     of what features they have loaded in.

     See also `status'.


 -- Function: status (`feature')
 -- Function: status (`feature', <item>)
     Returns information about the presence or absence of certain
     system-dependent features.

        * `status (feature)' returns a list of system features. These
          include Lisp version, operating system type, etc. The list
          may vary from one Lisp type to another.

        * `status (feature, item)' returns `true' if <item> is on the
          list of items returned by `status (feature)' and `false'
          otherwise.  `status' quotes the argument <item>. The
          quote-quote operator `''' defeats quotation. A feature whose
          name contains a special character, such as a hyphen, must be
          given as a string argument. For example, `status (feature,
          "ansi-cl")'.

     See also `sstatus'.

     The variable `features' contains a list of features which apply to
     mathematical expressions. See `features' and `featurep' for more
     information.


 -- Function: system (<command>)
     Executes <command> as a separate process.  The command is passed
     to the default shell for execution.  `system' is not supported by
     all operating systems, but generally exists in Unix and Unix-like
     environments.

     Supposing `_hist.out' is a list of frequencies which you wish to
     plot as a bar graph using `xgraph'.

          (%i1) (with_stdout("_hist.out",
                     for i:1 thru length(hist) do (
                       print(i,hist[i]))),
                 system("xgraph -bar -brw .7 -nl < _hist.out"));

     In order to make the plot be done in the background (returning
     control to Maxima) and remove the temporary file after it is done
     do:

          system("(xgraph -bar -brw .7 -nl < _hist.out;  rm -f _hist.out)&")

 -- Function: time (%o1, %o2, %o3, ...)
     Returns a list of the times, in seconds, taken to compute the
     output lines `%o1', `%o2', `%o3', ... The time returned is Maxima's
     estimate of the internal computation time, not the elapsed time.
     `time' can only be applied to output line variables; for any other
     variables, `time' returns `unknown'.

     Set `showtime: true' to make Maxima print out the computation time
     and elapsed time with each output line.


 -- Function: timedate ()
 -- Function: timedate (<T>)
     `timedate()' with no argument returns a string representing the
     current time and date.  The string has the format `YYYY-MM-DD
     HH:MM:SS[+|-]ZZ:ZZ', where the fields are year, month, day, hours,
     minutes, seconds, and time zone offset in hours and minutes.

     `timedate(<T>)' returns the time <T> as a string with the format
     `YYYY-MM-DD HH:MM:SS[+|-]ZZ:ZZ'.  <T> is interpreted as the number
     of seconds since midnight, January 1, 1900, as returned by
     `absolute_real_time'.

     Example:

     `timedate' with no argument returns a string representing the
     current time and date.

          (%i1) d : timedate ();
          (%o1)                      2010-06-08 04:08:09+01:00
          (%i2) print ("timedate reports current time", d) $
          timedate reports current time 2010-06-08 04:08:09+01:00

     `timedate' with an argument returns a string representing the
     argument.

          (%i1) timedate (0);
          (%o1)                      1900-01-01 01:00:00+01:00
          (%i2) timedate (absolute_real_time () - 7*24*3600);
          (%o2)                      2010-06-01 04:19:51+01:00


 -- Function: absolute_real_time ()
     Returns the number of seconds since midnight, January 1, 1900 UTC.
     The return value is an integer.

     See also `elapsed_real_time' and `elapsed_run_time'.

     Example:

          (%i1) absolute_real_time ();
          (%o1)                      3385045277
          (%i2) 1900 + absolute_real_time () / (365.25 * 24 * 3600);
          (%o2)                   2007.265612087104


 -- Function: elapsed_real_time ()
     Returns the number of seconds (including fractions of a second)
     since Maxima was most recently started or restarted.  The return
     value is a floating-point number.

     See also `absolute_real_time' and `elapsed_run_time'.

     Example:

          (%i1) elapsed_real_time ();
          (%o1)                       2.559324
          (%i2) expand ((a + b)^500)$
          (%i3) elapsed_real_time ();
          (%o3)                       7.552087


 -- Function: elapsed_run_time ()
     Returns an estimate of the number of seconds (including fractions
     of a second) which Maxima has spent in computations since Maxima
     was most recently started or restarted.  The return value is a
     floating-point number.

     See also `absolute_real_time' and `elapsed_real_time'.

     Example:

          (%i1) elapsed_run_time ();
          (%o1)                         0.04
          (%i2) expand ((a + b)^500)$
          (%i3) elapsed_run_time ();
          (%o3)                         1.26



File: maxima.info,  Node: Miscellaneous Options,  Next: Rules and Patterns,  Prev: Runtime Environment,  Up: Top

33 Miscellaneous Options
************************

* Menu:

* Introduction to Miscellaneous Options::
* Share::
* Functions and Variables for Miscellaneous Options::


File: maxima.info,  Node: Introduction to Miscellaneous Options,  Next: Share,  Prev: Miscellaneous Options,  Up: Miscellaneous Options

33.1 Introduction to Miscellaneous Options
==========================================

In this section various options are discussed which have a global effect
on the operation of Maxima.  Also various lists such as the list of all
user defined functions, are discussed.


File: maxima.info,  Node: Share,  Next: Functions and Variables for Miscellaneous Options,  Prev: Introduction to Miscellaneous Options,  Up: Miscellaneous Options

33.2 Share
==========

The Maxima "share" directory contains programs and other files of
interest to Maxima users, but not part of the core implementation of
Maxima.  These programs are typically loaded via `load' or
`setup_autoload'.

   `:lisp *maxima-sharedir*' displays the location of the share
directory within the user's file system.

   `printfile ("share.usg")' prints an out-of-date list of share
packages.  Users may find it more informative to browse the share
directory using a file system browser.


File: maxima.info,  Node: Functions and Variables for Miscellaneous Options,  Prev: Share,  Up: Miscellaneous Options

33.3 Functions and Variables for Miscellaneous Options
======================================================

 -- System variable: askexp
     When `asksign' is called, `askexp' is the expression `asksign' is
     testing.

     At one time, it was possible for a user to inspect `askexp' by
     entering a Maxima break with control-A.


 -- Option variable: genindex
     Default value: `i'

     `genindex' is the alphabetic prefix used to generate the next
     variable of summation when necessary.


 -- Option variable: gensumnum
     Default value: 0

     `gensumnum' is the numeric suffix used to generate the next
     variable of summation.  If it is set to `false' then the index
     will consist only of `genindex' with no numeric suffix.


 -- Function: gensym ()
 -- Function: gensym (<x>)
     `gensym()' creates and returns a fresh symbol.

     The name of the new-symbol is the concatenation of a prefix, which
     defaults to "g", and a suffix, which is the decimal representation
     of a number that defaults to the value of a Lisp internal counter.

     If <x> is supplied, and is a string, then that string is used as a
     prefix instead of "g" for this call to gensym only.

     If <x> is supplied, and is an integer, then that integer, instead
     of the value of the internal Lisp integer, is used as the suffix
     for this call to gensym only.

     If and only if no explicit suffix is supplied, the Lisp internal
     integer is incremented after it is used.

     Examples:

          (%i1) gensym();
          (%o1)                         g887
          (%i2) gensym("new");
          (%o2)                        new888
          (%i3) gensym(123);
          (%o3)                         g123

 -- Option variable: packagefile
     Default value: `false'

     Package designers who use `save'  or `translate'  to create
     packages (files) for others to use may want to set `packagefile:
     true' to prevent information from being added to Maxima's
     information-lists (e.g.  `values',  `functions' ) except where
     necessary when the file is loaded in.  In this way, the contents
     of the package will not get in the user's way when he adds his own
     data.  Note that this will not solve the problem of possible name
     conflicts.  Also note that the flag simply affects what is output
     to the package file.  Setting the flag to `true' is also useful for
     creating Maxima init files.


 -- Function: remvalue (<name_1>, ..., <name_n>)
 -- Function: remvalue (all)
     Removes the values of user variables <name_1>, ..., <name_n>
     (which can be subscripted) from the system.

     `remvalue (all)' removes the values of all variables in `values',
     the list of all variables given names by the user (as opposed to
     those which are automatically assigned by Maxima).

     See also `values'.


 -- Function: rncombine (<expr>)
     Transforms <expr> by combining all terms of <expr> that have
     identical denominators or denominators that differ from each other
     by numerical factors only.  This is slightly different from the
     behavior of `combine', which collects terms that have identical
     denominators.

     Setting `pfeformat: true' and using `combine' yields results
     similar to those that can be obtained with `rncombine', but
     `rncombine' takes the additional step of cross-multiplying
     numerical denominator factors.  This results in neater forms, and
     the possibility of recognizing some cancellations.

     `load(rncomb)' loads this function.


 -- Function: setup_autoload (<filename>, <function_1>, ...,
          <function_n>)
     Specifies that if any of <function_1>, ..., <function_n> are
     referenced and not yet defined, <filename> is loaded via `load'.
     <filename> usually contains definitions for the functions
     specified, although that is not enforced.

     `setup_autoload' does not work for array functions.

     `setup_autoload' quotes its arguments.

     Example:

          (%i1) legendre_p (1, %pi);
          (%o1)                  legendre_p(1, %pi)
          (%i2) setup_autoload ("specfun.mac", legendre_p, ultraspherical);
          (%o2)                         done
          (%i3) ultraspherical (2, 1/2, %pi);
          Warning - you are redefining the Macsyma function ultraspherical
          Warning - you are redefining the Macsyma function legendre_p
                                      2
                           3 (%pi - 1)
          (%o3)            ------------ + 3 (%pi - 1) + 1
                                2
          (%i4) legendre_p (1, %pi);
          (%o4)                          %pi
          (%i5) legendre_q (1, %pi);
                                        %pi + 1
                                %pi log(-------)
                                        1 - %pi
          (%o5)                 ---------------- - 1
                                       2


 -- Function: tcl_output (<list>, <i0>, <skip>)
 -- Function: tcl_output (<list>, <i0>)
 -- Function: tcl_output ([<list_1>, ..., <list_n>], <i>)
     Prints elements of a list enclosed by curly braces `{ }', suitable
     as part of a program in the Tcl/Tk language.

     `tcl_output (<list>, <i0>, <skip>)' prints <list>, beginning with
     element <i0> and printing elements `<i0> + <skip>', `<i0> + 2
     <skip>', etc.

     `tcl_output (<list>, <i0>)' is equivalent to `tcl_output (<list>,
     <i0>, 2)'.

     `tcl_output ([<list_1>, ..., <list_n>], <i>)' prints the <i>'th
     elements of <list_1>, ..., <list_n>.

     Examples:

          (%i1) tcl_output ([1, 2, 3, 4, 5, 6], 1, 3)$

           {1.000000000     4.000000000
           }
          (%i2) tcl_output ([1, 2, 3, 4, 5, 6], 2, 3)$

           {2.000000000     5.000000000
           }
          (%i3) tcl_output ([3/7, 5/9, 11/13, 13/17], 1)$

           {((RAT SIMP) 3 7) ((RAT SIMP) 11 13)
           }
          (%i4) tcl_output ([x1, y1, x2, y2, x3, y3], 2)$

           {$Y1 $Y2 $Y3
           }
          (%i5) tcl_output ([[1, 2, 3], [11, 22, 33]], 1)$

           {SIMP 1.000000000     11.00000000
           }


File: maxima.info,  Node: Rules and Patterns,  Next: Sets,  Prev: Miscellaneous Options,  Up: Top

34 Rules and Patterns
*********************

* Menu:

* Introduction to Rules and Patterns::
* Functions and Variables for Rules and Patterns::


File: maxima.info,  Node: Introduction to Rules and Patterns,  Next: Functions and Variables for Rules and Patterns,  Prev: Rules and Patterns,  Up: Rules and Patterns

34.1 Introduction to Rules and Patterns
=======================================

This section describes user-defined pattern matching and simplification
rules.  There are two groups of functions which implement somewhat
different pattern matching schemes.  In one group are `tellsimp',
`tellsimpafter', `defmatch', `defrule', `apply1', `applyb1', and
`apply2'.  In the other group are `let' and `letsimp'.  Both schemes
define patterns in terms of pattern variables declared by
`matchdeclare'.

   Pattern-matching rules defined by `tellsimp' and `tellsimpafter' are
applied automatically by the Maxima simplifier.  Rules defined by
`defmatch', `defrule', and `let' are applied by an explicit function
call.

   There are additional mechanisms for rules applied to polynomials by
`tellrat', and for commutative and noncommutative algebra in `affine'
package.


File: maxima.info,  Node: Functions and Variables for Rules and Patterns,  Prev: Introduction to Rules and Patterns,  Up: Rules and Patterns

34.2 Functions and Variables for Rules and Patterns
===================================================

 -- Function: apply1 (<expr>, <rule_1>, ..., <rule_n>)
     Repeatedly applies <rule_1> to <expr> until it fails, then
     repeatedly applies the same rule to all subexpressions of <expr>,
     left to right, until <rule_1> has failed on all subexpressions.
     Call the result of transforming <expr> in this manner <expr_2>.
     Then <rule_2> is applied in the same fashion starting at the top
     of <expr_2>.  When <rule_n> fails on the final subexpression, the
     result is returned.

     `maxapplydepth' is the depth of the deepest subexpressions
     processed by `apply1' and `apply2'.

     See also `applyb1', `apply2', and `let'.


 -- Function: apply2 (<expr>, <rule_1>, ..., <rule_n>)
     If <rule_1> fails on a given subexpression, then <rule_2> is
     repeatedly applied, etc.  Only if all rules fail on a given
     subexpression is the whole set of rules repeatedly applied to the
     next subexpression.  If one of the rules succeeds, then the same
     subexpression is reprocessed, starting with the first rule.

     `maxapplydepth' is the depth of the deepest subexpressions
     processed by `apply1' and `apply2'.

     See also `apply1' and `let'.


 -- Function: applyb1 (<expr>, <rule_1>, ..., <rule_n>)
     Repeatedly applies <rule_1> to the deepest subexpression of <expr>
     until it fails, then repeatedly applies the same rule one level
     higher (i.e., larger subexpressions), until <rule_1> has failed on
     the top-level expression.  Then <rule_2> is applied in the same
     fashion to the result of <rule_1>.  After <rule_n> has been
     applied to the top-level expression, the result is returned.

     `applyb1' is similar to `apply1' but works from the bottom up
     instead of from the top down.

     `maxapplyheight' is the maximum height which `applyb1' reaches
     before giving up.

     See also `apply1', `apply2', and `let'.


 -- Option variable: current_let_rule_package
     Default value: `default_let_rule_package'

     `current_let_rule_package' is the name of the rule package that is
     used by functions in the `let' package (`letsimp', etc.) if no
     other rule package is specified.  This variable may be assigned
     the name of any rule package defined via the `let' command.

     If a call such as `letsimp (expr, rule_pkg_name)' is made, the
     rule package `rule_pkg_name' is used for that function call only,
     and the value of `current_let_rule_package' is not changed.


 -- Option variable: default_let_rule_package
     Default value: `default_let_rule_package'

     `default_let_rule_package' is the name of the rule package used
     when one is not explicitly set by the user with `let' or by
     changing the value of `current_let_rule_package'.


 -- Function: defmatch (<progname>, <pattern>, <x_1>, ..., <x_n>)
 -- Function: defmatch (<progname>, <pattern>)
     Defines a function `<progname>(<expr>, <x_1>, ..., <x_n>)' which
     tests <expr> to see if it matches <pattern>.

     <pattern> is an expression containing the pattern arguments <x_1>,
     ..., <x_n> (if any) and some pattern variables (if any).  The
     pattern arguments are given explicitly as arguments to `defmatch'
     while the pattern variables are declared by the `matchdeclare'
     function.  Any variable not declared as a pattern variable in
     `matchdeclare' or as a pattern argument in `defmatch' matches only
     itself.

     The first argument to the created function <progname> is an
     expression to be matched against the pattern and the other
     arguments are the actual arguments which correspond to the dummy
     variables <x_1>, ..., <x_n> in the pattern.

     If the match is successful, <progname> returns a list of equations
     whose left sides are the pattern arguments and pattern variables,
     and whose right sides are the subexpressions which the pattern
     arguments and variables matched.  The pattern variables, but not
     the pattern arguments, are assigned the subexpressions they match.
     If the match fails, <progname> returns `false'.

     A literal pattern (that is, a pattern which contains neither
     pattern arguments nor pattern variables) returns `true' if the
     match succeeds.

     See also `matchdeclare', `defrule', `tellsimp', and
     `tellsimpafter'.

     Examples:

     Define a function `linearp(expr, x)' which tests `expr' to see if
     it is of the form `a*x + b' such that `a' and `b' do not contain
     `x' and `a' is nonzero.  This match function matches expressions
     which are linear in any variable, because the pattern argument `x'
     is given to `defmatch'.

          (%i1) matchdeclare (a, lambda ([e], e#0 and freeof(x, e)), b,
                              freeof(x));
          (%o1)                         done
          (%i2) defmatch (linearp, a*x + b, x);
          (%o2)                        linearp
          (%i3) linearp (3*z + (y + 1)*z + y^2, z);
                                   2
          (%o3)              [b = y , a = y + 4, x = z]
          (%i4) a;
          (%o4)                         y + 4
          (%i5) b;
                                          2
          (%o5)                          y
          (%i6) x;
          (%o6)                           x

     Define a function `linearp(expr)' which tests `expr' to see if it
     is of the form `a*x + b' such that `a' and `b' do not contain `x'
     and `a' is nonzero.  This match function only matches expressions
     linear in `x', not any other variable, because no pattern argument
     is given to `defmatch'.

          (%i1) matchdeclare (a, lambda ([e], e#0 and freeof(x, e)), b,
                              freeof(x));
          (%o1)                         done
          (%i2) defmatch (linearp, a*x + b);
          (%o2)                        linearp
          (%i3) linearp (3*z + (y + 1)*z + y^2);
          (%o3)                         false
          (%i4) linearp (3*x + (y + 1)*x + y^2);
                                       2
          (%o4)                  [b = y , a = y + 4]

     Define a function `checklimits(expr)' which tests `expr' to see if
     it is a definite integral.

          (%i1) matchdeclare ([a, f], true);
          (%o1)                         done
          (%i2) constinterval (l, h) := constantp (h - l);
          (%o2)        constinterval(l, h) := constantp(h - l)
          (%i3) matchdeclare (b, constinterval (a));
          (%o3)                         done
          (%i4) matchdeclare (x, atom);
          (%o4)                         done
          (%i5) simp : false;
          (%o5)                         false
          (%i6) defmatch (checklimits, 'integrate (f, x, a, b));
          (%o6)                      checklimits
          (%i7) simp : true;
          (%o7)                         true
          (%i8) 'integrate (sin(t), t, %pi + x, 2*%pi + x);
                                 x + 2 %pi
                                /
                                [
          (%o8)                 I          sin(t) dt
                                ]
                                /
                                 x + %pi
          (%i9) checklimits (%);
          (%o9)    [b = x + 2 %pi, a = x + %pi, x = t, f = sin(t)]


 -- Function: defrule (<rulename>, <pattern>, <replacement>)
     Defines and names a replacement rule for the given pattern.  If
     the rule named <rulename> is applied to an expression (by
     `apply1', `applyb1', or `apply2'), every subexpression matching
     the pattern will be replaced by the replacement.  All variables in
     the replacement which have been assigned values by the pattern
     match are assigned those values in the replacement which is then
     simplified.

     The rules themselves can be treated as functions which transform
     an expression by one operation of the pattern match and
     replacement.  If the match fails, the rule function returns
     `false'.


 -- Function: disprule (<rulename_1>, ..., <rulename_2>)
 -- Function: disprule (all)
     Display rules with the names <rulename_1>, ..., <rulename_n>, as
     returned by `defrule', `tellsimp', or `tellsimpafter', or a
     pattern defined by `defmatch'.  Each rule is displayed with an
     intermediate expression label (`%t').

     `disprule (all)' displays all rules.

     `disprule' quotes its arguments.  `disprule' returns the list of
     intermediate expression labels corresponding to the displayed
     rules.

     See also `letrules', which displays rules defined by `let'.

     Examples:

          (%i1) tellsimpafter (foo (x, y), bar (x) + baz (y));
          (%o1)                   [foorule1, false]
          (%i2) tellsimpafter (x + y, special_add (x, y));
          (%o2)                   [+rule1, simplus]
          (%i3) defmatch (quux, mumble (x));
          (%o3)                         quux
          (%i4) disprule (foorule1, "+rule1", quux);
          (%t4)        foorule1 : foo(x, y) -> baz(y) + bar(x)

          (%t5)          +rule1 : y + x -> special_add(x, y)

          (%t6)                quux : mumble(x) -> []

          (%o6)                    [%t4, %t5, %t6]
          (%i6) ''%;
          (%o6) [foorule1 : foo(x, y) -> baz(y) + bar(x),
               +rule1 : y + x -> special_add(x, y), quux : mumble(x) -> []]


 -- Function: let (<prod>, <repl>, <predname>, <arg_1>, ..., <arg_n>)
 -- Function: let ([<prod>, <repl>, <predname>, <arg_1>, ..., <arg_n>],
          <package_name>)
     Defines a substitution rule for `letsimp' such that <prod> is
     replaced by <repl>.  <prod> is a product of positive or negative
     powers of the following terms:

        * Atoms which `letsimp' will search for literally unless
          previous to calling `letsimp' the `matchdeclare' function is
          used to associate a predicate with the atom.  In this case
          `letsimp' will match the atom to any term of a product
          satisfying the predicate.

        * Kernels such as `sin(x)', `n!', `f(x,y)', etc.  As with atoms
          above `letsimp' will look for a literal match unless
          `matchdeclare' is used to associate a predicate with the
          argument of the kernel.

     A term to a positive power will only match a term having at least
     that power.  A term to a negative power on the other hand will
     only match a term with a power at least as negative.  In the case
     of negative powers in <prod> the switch `letrat' must be set to
     `true'.  See also `letrat'.

     If a predicate is included in the `let' function followed by a
     list of arguments, a tentative match (i.e. one that would be
     accepted if the predicate were omitted) is accepted only if
     `predname (arg_1', ..., arg_n')' evaluates to `true' where
     <arg_i'> is the value matched to <arg_i>.  The <arg_i> may be the
     name of any atom or the argument of any kernel appearing in <prod>.
     <repl> may be any rational expression.  If any of the atoms or
     arguments from <prod> appear in <repl> the appropriate
     substitutions are made.   The global flag `letrat' controls the
     simplification of quotients by `letsimp'.  When `letrat' is
     `false', `letsimp' simplifies the numerator and denominator of
     <expr> separately, and does not simplify the quotient.
     Substitutions such as `n!/n' goes to `(n-1)!' then fail.  When
     `letrat' is `true', then the numerator, denominator, and the
     quotient are simplified in that order.

     These substitution functions allow you to work with several rule
     packages at once.  Each rule package can contain any number of
     `let' rules and is referenced by a user-defined name.  The command
     `let ([<prod>, <repl>, <predname>, <arg_1>, ..., <arg_n>],
     <package_name>)' adds the rule <predname> to the rule package
     <package_name>.  The command `letsimp (<expr>, <package_name>)'
     applies the rules in <package_name>.  `letsimp (<expr>,
     <package_name1>, <package_name2>, ...)' is equivalent to `letsimp
     (<expr>, <package_name1>)' followed by `letsimp (%,
     <package_name2>)', ...

     `current_let_rule_package' is the name of the rule package that is
     presently being used.  This variable may be assigned the name of
     any rule package defined via the `let' command.  Whenever any of
     the functions comprising the `let' package are called with no
     package name, the package named by `current_let_rule_package' is
     used.  If a call such as `letsimp (<expr>, <rule_pkg_name>)' is
     made, the rule package <rule_pkg_name> is used for that `letsimp'
     command only, and `current_let_rule_package' is not changed.  If
     not otherwise specified, `current_let_rule_package' defaults to
     `default_let_rule_package'.

          (%i1) matchdeclare ([a, a1, a2], true)$
          (%i2) oneless (x, y) := is (x = y-1)$
          (%i3) let (a1*a2!, a1!, oneless, a2, a1);
          (%o3)         a1 a2! --> a1! where oneless(a2, a1)
          (%i4) letrat: true$
          (%i5) let (a1!/a1, (a1-1)!);
                                  a1!
          (%o5)                   --- --> (a1 - 1)!
                                  a1
          (%i6) letsimp (n*m!*(n-1)!/m);
          (%o6)                      (m - 1)! n!
          (%i7) let (sin(a)^2, 1 - cos(a)^2);
                                  2               2
          (%o7)                sin (a) --> 1 - cos (a)
          (%i8) letsimp (sin(x)^4);
                                  4           2
          (%o8)                cos (x) - 2 cos (x) + 1


 -- Option variable: letrat
     Default value: `false'

     When `letrat' is `false', `letsimp' simplifies the numerator and
     denominator of a ratio separately, and does not simplify the
     quotient.

     When `letrat' is `true', the numerator, denominator, and their
     quotient are simplified in that order.

          (%i1) matchdeclare (n, true)$
          (%i2) let (n!/n, (n-1)!);
                                   n!
          (%o2)                    -- --> (n - 1)!
                                   n
          (%i3) letrat: false$
          (%i4) letsimp (a!/a);
                                         a!
          (%o4)                          --
                                         a
          (%i5) letrat: true$
          (%i6) letsimp (a!/a);
          (%o6)                       (a - 1)!


 -- Function: letrules ()
 -- Function: letrules (<package_name>)
     Displays the rules in a rule package.  `letrules ()' displays the
     rules in the current rule package.  `letrules (<package_name>)'
     displays the rules in <package_name>.

     The current rule package is named by `current_let_rule_package'.
     If not otherwise specified, `current_let_rule_package' defaults to
     `default_let_rule_package'.

     See also `disprule', which displays rules defined by `tellsimp' and
     `tellsimpafter'.


 -- Function: letsimp (<expr>)
 -- Function: letsimp (<expr>, <package_name>)
 -- Function: letsimp (<expr>, <package_name_1>, ..., <package_name_n>)
     Repeatedly applies the substitution rules defined by `let' until
     no further change is made to <expr>.

     `letsimp (<expr>)' uses the rules from `current_let_rule_package'.

     `letsimp (<expr>, <package_name>)' uses the rules from
     <package_name> without changing `current_let_rule_package'.

     `letsimp (<expr>, <package_name_1>, ..., <package_name_n>)' is
     equivalent to `letsimp (<expr>, <package_name_1>', followed by
     `letsimp (%, <package_name_2>)', and so on.


 -- Option variable: let_rule_packages
     Default value: `[default_let_rule_package]'

     `let_rule_packages' is a list of all user-defined let rule packages
     plus the default package `default_let_rule_package'.


 -- Function: matchdeclare (<a_1>, <pred_1>, ..., <a_n>, <pred_n>)
     Associates a predicate <pred_k> with a variable or list of
     variables <a_k> so that <a_k> matches expressions for which the
     predicate returns anything other than `false'.

     A predicate is the name of a function, or a lambda expression, or
     a function call or lambda call missing the last argument, or
     `true' or `all'.  Any expression matches `true' or `all'.  If the
     predicate is specified as a function call or lambda call, the
     expression to be tested is appended to the list of arguments; the
     arguments are evaluated at the time the match is evaluated.
     Otherwise, the predicate is specified as a function name or lambda
     expression, and the expression to be tested is the sole argument.
     A predicate function need not be defined when `matchdeclare' is
     called; the predicate is not evaluated until a match is attempted.

     A predicate may return a Boolean expression as well as `true' or
     `false'.  Boolean expressions are evaluated by `is' within the
     constructed rule function, so it is not necessary to call `is'
     within the predicate.

     If an expression satisfies a match predicate, the match variable
     is assigned the expression, except for match variables which are
     operands of addition `+' or multiplication `*'.  Only addition and
     multiplication are handled specially; other n-ary operators (both
     built-in and user-defined) are treated like ordinary functions.

     In the case of addition and multiplication, the match variable may
     be assigned a single expression which satisfies the match
     predicate, or a sum or product (respectively) of such expressions.
     Such multiple-term matching is greedy: predicates are evaluated
     in the order in which their associated variables appear in the
     match pattern, and a term which satisfies more than one predicate
     is taken by the first predicate which it satisfies.  Each
     predicate is tested against all operands of the sum or product
     before the next predicate is evaluated.  In addition, if 0 or 1
     (respectively) satisfies a match predicate, and there are no other
     terms which satisfy the predicate, 0 or 1 is assigned to the match
     variable associated with the predicate.

     The algorithm for processing addition and multiplication patterns
     makes some match results (for example, a pattern in which a "match
     anything" variable appears) dependent on the ordering of terms in
     the match pattern and in the expression to be matched.  However,
     if all match predicates are mutually exclusive, the match result
     is insensitive to ordering, as one match predicate cannot accept
     terms matched by another.

     Calling `matchdeclare' with a variable <a> as an argument changes
     the `matchdeclare' property for <a>, if one was already declared;
     only the most recent `matchdeclare' is in effect when a rule is
     defined.  Later changes to the `matchdeclare' property (via
     `matchdeclare' or `remove') do not affect existing rules.

     `propvars (matchdeclare)' returns the list of all variables for
     which there is a `matchdeclare' property.  `printprops (<a>,
     matchdeclare)' returns the predicate for variable `a'.
     `printprops (all, matchdeclare)' returns the list of predicates
     for all `matchdeclare' variables.  `remove (<a>, matchdeclare)'
     removes the `matchdeclare' property from <a>.

     The functions `defmatch', `defrule', `tellsimp', `tellsimpafter',
     and `let' construct rules which test expressions against patterns.

     `matchdeclare' quotes its arguments.  `matchdeclare' always
     returns `done'.

     Examples:

     A predicate is the name of a function, or a lambda expression, or
     a function call or lambda call missing the last argument, or
     `true' or `all'.

          (%i1) matchdeclare (aa, integerp);
          (%o1)                         done
          (%i2) matchdeclare (bb, lambda ([x], x > 0));
          (%o2)                         done
          (%i3) matchdeclare (cc, freeof (%e, %pi, %i));
          (%o3)                         done
          (%i4) matchdeclare (dd, lambda ([x, y], gcd (x, y) = 1) (1728));
          (%o4)                         done
          (%i5) matchdeclare (ee, true);
          (%o5)                         done
          (%i6) matchdeclare (ff, all);
          (%o6)                         done

     If an expression satisfies a match predicate, the match variable
     is assigned the expression.

          (%i1) matchdeclare (aa, integerp, bb, atom);
          (%o1)                         done
          (%i2) defrule (r1, bb^aa, ["integer" = aa, "atom" = bb]);
                              aa
          (%o2)        r1 : bb   -> [integer = aa, atom = bb]
          (%i3) r1 (%pi^8);
          (%o3)               [integer = 8, atom = %pi]

     In the case of addition and multiplication, the match variable may
     be assigned a single expression which satisfies the match
     predicate, or a sum or product (respectively) of such expressions.

          (%i1) matchdeclare (aa, atom, bb, lambda ([x], not atom(x)));
          (%o1)                         done
          (%i2) defrule (r1, aa + bb, ["all atoms" = aa, "all nonatoms" =
                         bb]);
          bb + aa partitions `sum'
          (%o2)  r1 : bb + aa -> [all atoms = aa, all nonatoms = bb]
          (%i3) r1 (8 + a*b + sin(x));
          (%o3)     [all atoms = 8, all nonatoms = sin(x) + a b]
          (%i4) defrule (r2, aa * bb, ["all atoms" = aa, "all nonatoms" =
                         bb]);
          bb aa partitions `product'
          (%o4)   r2 : aa bb -> [all atoms = aa, all nonatoms = bb]
          (%i5) r2 (8 * (a + b) * sin(x));
          (%o5)    [all atoms = 8, all nonatoms = (b + a) sin(x)]

     When matching arguments of `+' and `*', if all match predicates
     are mutually exclusive, the match result is insensitive to
     ordering, as one match predicate cannot accept terms matched by
     another.

          (%i1) matchdeclare (aa, atom, bb, lambda ([x], not atom(x)));
          (%o1)                         done
          (%i2) defrule (r1, aa + bb, ["all atoms" = aa, "all nonatoms" =
                         bb]);
          bb + aa partitions `sum'
          (%o2)  r1 : bb + aa -> [all atoms = aa, all nonatoms = bb]
          (%i3) r1 (8 + a*b + %pi + sin(x) - c + 2^n);
                                                               n
          (%o3) [all atoms = %pi + 8, all nonatoms = sin(x) + 2  - c + a b]
          (%i4) defrule (r2, aa * bb, ["all atoms" = aa, "all nonatoms" =
                         bb]);
          bb aa partitions `product'
          (%o4)   r2 : aa bb -> [all atoms = aa, all nonatoms = bb]
          (%i5) r2 (8 * (a + b) * %pi * sin(x) / c * 2^n);
                                                            n
                                                   (b + a) 2  sin(x)
          (%o5) [all atoms = 8 %pi, all nonatoms = -----------------]
                                                           c

     The functions `propvars' and `printprops' return information about
     match variables.

          (%i1) matchdeclare ([aa, bb, cc], atom, [dd, ee], integerp);
          (%o1)                         done
          (%i2) matchdeclare (ff, floatnump, gg, lambda ([x], x > 100));
          (%o2)                         done
          (%i3) propvars (matchdeclare);
          (%o3)             [aa, bb, cc, dd, ee, ff, gg]
          (%i4) printprops (ee, matchdeclare);
          (%o4)                    [integerp(ee)]
          (%i5) printprops (gg, matchdeclare);
          (%o5)              [lambda([x], x > 100, gg)]
          (%i6) printprops (all, matchdeclare);
          (%o6) [lambda([x], x > 100, gg), floatnump(ff), integerp(ee),
                                integerp(dd), atom(cc), atom(bb), atom(aa)]


 -- Option variable: maxapplydepth
     Default value: 10000

     `maxapplydepth' is the maximum depth to which `apply1' and
     `apply2' will delve.


 -- Option variable: maxapplyheight
     Default value: 10000

     `maxapplyheight' is the maximum height to which `applyb1' will
     reach before giving up.


 -- Function: remlet (<prod>, <name>)
 -- Function: remlet ()
 -- Function: remlet (all)
 -- Function: remlet (all, <name>)
     Deletes the substitution rule, <prod> -> repl, most recently
     defined by the `let' function.  If name is supplied the rule is
     deleted from the rule package name.

     `remlet()' and `remlet(all)' delete all substitution rules from the
     current rule package.  If the name of a rule package is supplied,
     e.g.  `remlet (all, <name>)', the rule package <name> is also
     deleted.

     If a substitution is to be changed using the same product,
     `remlet' need not be called, just redefine the substitution using
     the same product (literally) with the `let' function and the new
     replacement and/or predicate name.  Should `remlet (<prod>)' now be
     called the original substitution rule is revived.

     See also `remrule', which removes a rule defined by `tellsimp' or
     `tellsimpafter'.


 -- Function: remrule (<op>, <rulename>)
 -- Function: remrule (<op>, all)
     Removes rules defined by `tellsimp' or `tellsimpafter'.

     `remrule (<op>, <rulename>)' removes the rule with the name
     <rulename> from the operator <op>.  When <op> is a built-in or
     user-defined operator (as defined by `infix', `prefix', etc.),
     <op> and <rulename> must be enclosed in double quote marks.

     `remrule (<op>, all)' removes all rules for the operator <op>.

     See also `remlet', which removes a rule defined by `let'.

     Examples:

          (%i1) tellsimp (foo (aa, bb), bb - aa);
          (%o1)                   [foorule1, false]
          (%i2) tellsimpafter (aa + bb, special_add (aa, bb));
          (%o2)                   [+rule1, simplus]
          (%i3) infix ("@@");
          (%o3)                          @@
          (%i4) tellsimp (aa @@ bb, bb/aa);
          (%o4)                   [@@rule1, false]
          (%i5) tellsimpafter (quux (%pi, %e), %pi - %e);
          (%o5)                  [quuxrule1, false]
          (%i6) tellsimpafter (quux (%e, %pi), %pi + %e);
          (%o6)             [quuxrule2, quuxrule1, false]
          (%i7) [foo (aa, bb), aa + bb, aa @@ bb, quux (%pi, %e),
                 quux (%e, %pi)];
                                               bb
          (%o7) [bb - aa, special_add(aa, bb), --, %pi - %e, %pi + %e]
                                               aa
          (%i8) remrule (foo, foorule1);
          (%o8)                          foo
          (%i9) remrule ("+", ?\+rule1);
          (%o9)                           +
          (%i10) remrule ("@@", ?\@\@rule1);
          (%o10)                         @@
          (%i11) remrule (quux, all);
          (%o11)                        quux
          (%i12) [foo (aa, bb), aa + bb, aa @@ bb, quux (%pi, %e),
                  quux (%e, %pi)];
          (%o12) [foo(aa, bb), bb + aa, aa @@ bb, quux(%pi, %e),
                                                   quux(%e, %pi)]


 -- Function: tellsimp (<pattern>, <replacement>)
     is similar to `tellsimpafter' but places new information before
     old so that it is applied before the built-in simplification rules.

     `tellsimp' is used when it is important to modify the expression
     before the simplifier works on it, for instance if the simplifier
     "knows" something about the expression, but what it returns is not
     to your liking.  If the simplifier "knows" something about the
     main operator of the expression, but is simply not doing enough for
     you, you probably want to use `tellsimpafter'.

     The pattern may not be a sum, product, single variable, or number.

     The system variable `rules' is the list of rules defined by
     `defrule', `defmatch', `tellsimp', and `tellsimpafter'.

     Examples:

          (%i1) matchdeclare (x, freeof (%i));
          (%o1)                         done
          (%i2) %iargs: false$
          (%i3) tellsimp (sin(%i*x), %i*sinh(x));
          (%o3)                 [sinrule1, simp-%sin]
          (%i4) trigexpand (sin (%i*y + x));
          (%o4)         sin(x) cos(%i y) + %i cos(x) sinh(y)
          (%i5) %iargs:true$
          (%i6) errcatch(0^0);
           0
          0  has been generated
          (%o6)                          []
          (%i7) ev (tellsimp (0^0, 1), simp: false);
          (%o7)                  [^rule1, simpexpt]
          (%i8) 0^0;
          (%o8)                           1
          (%i9) remrule ("^", %th(2)[1]);
          (%o9)                           ^
          (%i10) tellsimp (sin(x)^2, 1 - cos(x)^2);
          (%o10)                 [^rule2, simpexpt]
          (%i11) (1 + sin(x))^2;
                                                2
          (%o11)                    (sin(x) + 1)
          (%i12) expand (%);
                                             2
          (%o12)               2 sin(x) - cos (x) + 2
          (%i13) sin(x)^2;
                                            2
          (%o13)                     1 - cos (x)
          (%i14) kill (rules);
          (%o14)                        done
          (%i15) matchdeclare (a, true);
          (%o15)                        done
          (%i16) tellsimp (sin(a)^2, 1 - cos(a)^2);
          (%o16)                 [^rule3, simpexpt]
          (%i17) sin(y)^2;
                                            2
          (%o17)                     1 - cos (y)


 -- Function: tellsimpafter (<pattern>, <replacement>)
     Defines a simplification rule which the Maxima simplifier applies
     after built-in simplification rules.  <pattern> is an expression,
     comprising pattern variables (declared by `matchdeclare') and
     other atoms and operators, considered literals for the purpose of
     pattern matching.  <replacement> is substituted for an actual
     expression which matches <pattern>; pattern variables in
     <replacement> are assigned the values matched in the actual
     expression.

     <pattern> may be any nonatomic expression in which the main
     operator is not a pattern variable; the simplification rule is
     associated with the main operator.  The names of functions (with
     one exception, described below), lists, and arrays may appear in
     <pattern> as the main operator only as literals (not pattern
     variables); this rules out expressions such as `aa(x)' and `bb[y]'
     as patterns, if `aa' and `bb' are pattern variables.  Names of
     functions, lists, and arrays which are pattern variables may
     appear as operators other than the main operator in <pattern>.

     There is one exception to the above rule concerning names of
     functions.  The name of a subscripted function in an expression
     such as `aa[x](y)' may be a pattern variable, because the main
     operator is not `aa' but rather the Lisp atom `mqapply'.  This is
     a consequence of the representation of expressions involving
     subscripted functions.

     Simplification rules are applied after evaluation (if not
     suppressed through quotation or the flag `noeval').  Rules
     established by `tellsimpafter' are applied in the order they were
     defined, and after any built-in rules.  Rules are applied
     bottom-up, that is, applied first to subexpressions before
     application to the whole expression.  It may be necessary to
     repeatedly simplify a result (for example, via the quote-quote
     operator `''' or the flag `infeval') to ensure that all rules are
     applied.

     Pattern variables are treated as local variables in simplification
     rules.  Once a rule is defined, the value of a pattern variable
     does not affect the rule, and is not affected by the rule.  An
     assignment to a pattern variable which results from a successful
     rule match does not affect the current assignment (or lack of it)
     of the pattern variable.  However, as with all atoms in Maxima,
     the properties of pattern variables (as declared by `put' and
     related functions) are global.

     The rule constructed by `tellsimpafter' is named after the main
     operator of <pattern>.  Rules for built-in operators, and
     user-defined operators defined by `infix', `prefix', `postfix',
     `matchfix', and `nofix', have names which are Lisp identifiers.
     Rules for other functions have names which are Maxima identifiers.

     The treatment of noun and verb forms is slightly confused.  If a
     rule is defined for a noun (or verb) form and a rule for the
     corresponding verb (or noun) form already exists, the
     newly-defined rule applies to both forms (noun and verb).  If a
     rule for the corresponding verb (or noun) form does not exist, the
     newly-defined rule applies only to the noun (or verb) form.

     The rule constructed by `tellsimpafter' is an ordinary Lisp
     function.  If the name of the rule is `$foorule1', the construct
     `:lisp (trace $foorule1)' traces the function, and `:lisp
     (symbol-function '$foorule1)' displays its definition.

     `tellsimpafter' quotes its arguments.  `tellsimpafter' returns the
     list of rules for the main operator of <pattern>, including the
     newly established rule.

     See also `matchdeclare', `defmatch', `defrule', `tellsimp', `let',
     `kill', `remrule', and `clear_rules'.

     Examples:

     <pattern> may be any nonatomic expression in which the main
     operator is not a pattern variable.

          (%i1) matchdeclare (aa, atom, [ll, mm], listp, xx, true)$
          (%i2) tellsimpafter (sin (ll), map (sin, ll));
          (%o2)                 [sinrule1, simp-%sin]
          (%i3) sin ([1/6, 1/4, 1/3, 1/2, 1]*%pi);
                              1  sqrt(2)  sqrt(3)
          (%o3)              [-, -------, -------, 1, 0]
                              2     2        2
          (%i4) tellsimpafter (ll^mm, map ("^", ll, mm));
          (%o4)                  [^rule1, simpexpt]
          (%i5) [a, b, c]^[1, 2, 3];
                                          2   3
          (%o5)                      [a, b , c ]
          (%i6) tellsimpafter (foo (aa (xx)), aa (foo (xx)));
          (%o6)                   [foorule1, false]
          (%i7) foo (bar (u - v));
          (%o7)                    bar(foo(u - v))

     Rules are applied in the order they were defined.  If two rules
     can match an expression, the rule which was defined first is
     applied.

          (%i1) matchdeclare (aa, integerp);
          (%o1)                         done
          (%i2) tellsimpafter (foo (aa), bar_1 (aa));
          (%o2)                   [foorule1, false]
          (%i3) tellsimpafter (foo (aa), bar_2 (aa));
          (%o3)              [foorule2, foorule1, false]
          (%i4) foo (42);
          (%o4)                       bar_1(42)

     Pattern variables are treated as local variables in simplification
     rules.  (Compare to `defmatch', which treats pattern variables as
     global variables.)

          (%i1) matchdeclare (aa, integerp, bb, atom);
          (%o1)                         done
          (%i2) tellsimpafter (foo(aa, bb), bar('aa=aa, 'bb=bb));
          (%o2)                   [foorule1, false]
          (%i3) bb: 12345;
          (%o3)                         12345
          (%i4) foo (42, %e);
          (%o4)                 bar(aa = 42, bb = %e)
          (%i5) bb;
          (%o5)                         12345

     As with all atoms, properties of pattern variables are global even
     though values are local.  In this example, an assignment property
     is declared via `define_variable'.  This is a property of the atom
     `bb' throughout Maxima.

          (%i1) matchdeclare (aa, integerp, bb, atom);
          (%o1)                         done
          (%i2) tellsimpafter (foo(aa, bb), bar('aa=aa, 'bb=bb));
          (%o2)                   [foorule1, false]
          (%i3) foo (42, %e);
          (%o3)                 bar(aa = 42, bb = %e)
          (%i4) define_variable (bb, true, boolean);
          (%o4)                         true
          (%i5) foo (42, %e);
          Error: bb was declared mode boolean, has value: %e
           -- an error.  Quitting.  To debug this try debugmode(true);

     Rules are named after main operators.  Names of rules for built-in
     and user-defined operators are Lisp identifiers, while names for
     other functions are Maxima identifiers.

          (%i1) tellsimpafter (foo (%pi + %e), 3*%pi);
          (%o1)                   [foorule1, false]
          (%i2) tellsimpafter (foo (%pi * %e), 17*%e);
          (%o2)              [foorule2, foorule1, false]
          (%i3) tellsimpafter (foo (%i ^ %e), -42*%i);
          (%o3)         [foorule3, foorule2, foorule1, false]
          (%i4) tellsimpafter (foo (9) + foo (13), quux (22));
          (%o4)                   [+rule1, simplus]
          (%i5) tellsimpafter (foo (9) * foo (13), blurf (22));
          (%o5)                  [*rule1, simptimes]
          (%i6) tellsimpafter (foo (9) ^ foo (13), mumble (22));
          (%o6)                  [^rule1, simpexpt]
          (%i7) rules;
          (%o7) [foorule1, foorule2, foorule3, +rule1, *rule1, ^rule1]
          (%i8) foorule_name: first (%o1);
          (%o8)                       foorule1
          (%i9) plusrule_name: first (%o4);
          (%o9)                        +rule1
          (%i10) remrule (foo, foorule1);
          (%o10)                         foo
          (%i11) remrule ("^", ?\^rule1);
          (%o11)                          ^
          (%i12) rules;
          (%o12)        [foorule2, foorule3, +rule1, *rule1]

     A worked example: anticommutative multiplication.

          (%i1) gt (i, j) := integerp(j) and i < j;
          (%o1)           gt(i, j) := integerp(j) and i < j
          (%i2) matchdeclare (i, integerp, j, gt(i));
          (%o2)                         done
          (%i3) tellsimpafter (s[i]^^2, 1);
          (%o3)                 [^^rule1, simpncexpt]
          (%i4) tellsimpafter (s[i] . s[j], -s[j] . s[i]);
          (%o4)                   [.rule1, simpnct]
          (%i5) s[1] . (s[1] + s[2]);
          (%o5)                    s  . (s  + s )
                                    1     2    1
          (%i6) expand (%);
          (%o6)                      1 - s  . s
                                          2    1
          (%i7) factor (expand (sum (s[i], i, 0, 9)^^5));
          (%o7) 100 (s  + s  + s  + s  + s  + s  + s  + s  + s  + s )
                      9    8    7    6    5    4    3    2    1    0


 -- Function: clear_rules ()
     Executes `kill (rules)' and then resets the next rule number to 1
     for addition `+', multiplication `*', and exponentiation `^'.



File: maxima.info,  Node: Sets,  Next: Function Definition,  Prev: Rules and Patterns,  Up: Top

35 Sets
*******

* Menu:

* Introduction to Sets::
* Functions and Variables for Sets::


File: maxima.info,  Node: Introduction to Sets,  Next: Functions and Variables for Sets,  Prev: Sets,  Up: Sets

35.1 Introduction to Sets
=========================

Maxima provides set functions, such as intersection and union, for
finite sets that are defined by explicit enumeration.  Maxima treats
lists and sets as distinct objects. This feature makes it possible to
work with sets that have members that are either lists or sets.

   In addition to functions for finite sets, Maxima provides some
functions related to combinatorics; these include the Stirling numbers
of the first and second kind, the Bell numbers, multinomial
coefficients, partitions of nonnegative integers, and a few others.
Maxima also defines a Kronecker delta function.

35.1.1 Usage
------------

To construct a set with members `a_1, ..., a_n', write `set(a_1, ...,
a_n)' or `{a_1, ..., a_n}'; to construct the empty set, write `set()'
or `{}'.  In input, `set(...)' and `{ ... }' are equivalent.  Sets are
always displayed with curly braces.

   If a member is listed more than once, simplification eliminates the
redundant member.

     (%i1) set();
     (%o1)                          {}
     (%i2) set(a, b, a);
     (%o2)                        {a, b}
     (%i3) set(a, set(b));
     (%o3)                       {a, {b}}
     (%i4) set(a, [b]);
     (%o4)                       {a, [b]}
     (%i5) {};
     (%o5)                          {}
     (%i6) {a, b, a};
     (%o6)                        {a, b}
     (%i7) {a, {b}};
     (%o7)                       {a, {b}}
     (%i8) {a, [b]};
     (%o8)                       {a, [b]}

   Two would-be elements <x> and <y> are redundant (i.e., considered
the same for the purpose of set construction) if and only if `is(<x> =
<y>)' yields `true'.  Note that `is(equal(<x>, <y>))' can yield `true'
while `is(<x> = <y>)' yields `false'; in that case the elements <x> and
<y> are considered distinct.

     (%i1) x: a/c + b/c;
                                   b   a
     (%o1)                         - + -
                                   c   c
     (%i2) y: a/c + b/c;
                                   b   a
     (%o2)                         - + -
                                   c   c
     (%i3) z: (a + b)/c;
                                   b + a
     (%o3)                         -----
                                     c
     (%i4) is (x = y);
     (%o4)                         true
     (%i5) is (y = z);
     (%o5)                         false
     (%i6) is (equal (y, z));
     (%o6)                         true
     (%i7) y - z;
                                b + a   b   a
     (%o7)                    - ----- + - + -
                                  c     c   c
     (%i8) ratsimp (%);
     (%o8)                           0
     (%i9) {x, y, z};
                               b + a  b   a
     (%o9)                    {-----, - + -}
                                 c    c   c

   To construct a set from the elements of a list, use `setify'.

     (%i1) setify ([b, a]);
     (%o1)                        {a, b}

   Set members `x' and `y' are equal provided `is(x = y)' evaluates to
`true'. Thus `rat(x)' and `x' are equal as set members; consequently,

     (%i1) {x, rat(x)};
     (%o1)                          {x}

   Further, since `is((x - 1)*(x + 1) = x^2 - 1)' evaluates to `false',
`(x - 1)*(x + 1)' and `x^2 - 1' are distinct set members; thus

     (%i1) {(x - 1)*(x + 1), x^2 - 1};
                                            2
     (%o1)               {(x - 1) (x + 1), x  - 1}

   To reduce this set to a singleton set, apply `rat' to each set
member:

     (%i1) {(x - 1)*(x + 1), x^2 - 1};
                                            2
     (%o1)               {(x - 1) (x + 1), x  - 1}
     (%i2) map (rat, %);
                                   2
     (%o2)/R/                    {x  - 1}

   To remove redundancies from other sets, you may need to use other
simplification functions. Here is an example that uses `trigsimp':

     (%i1) {1, cos(x)^2 + sin(x)^2};
                                 2         2
     (%o1)                {1, sin (x) + cos (x)}
     (%i2) map (trigsimp, %);
     (%o2)                          {1}

   A set is simplified when its members are non-redundant and sorted.
The current version of the set functions uses the Maxima function
`orderlessp' to order sets; however, future versions of the set
functions might use a different ordering function.

   Some operations on sets, such as substitution, automatically force a
re-simplification; for example,

     (%i1) s: {a, b, c}$
     (%i2) subst (c=a, s);
     (%o2)                        {a, b}
     (%i3) subst ([a=x, b=x, c=x], s);
     (%o3)                          {x}
     (%i4) map (lambda ([x], x^2), set (-1, 0, 1));
     (%o4)                        {0, 1}

   Maxima treats lists and sets as distinct objects; functions such as
`union' and `intersection' complain if any argument is not a set. If
you need to apply a set function to a list, use the `setify' function
to convert it to a set. Thus

     (%i1) union ([1, 2], {a, b});
     Function union expects a set, instead found [1,2]
      -- an error.  Quitting.  To debug this try debugmode(true);
     (%i2) union (setify ([1, 2]), {a, b});
     (%o2)                     {1, 2, a, b}

   To extract all set elements of a set `s' that satisfy a predicate
`f', use `subset(s, f)'. (A predicate is a boolean-valued function.)
For example, to find the equations in a given set that do not depend on
a variable `z', use

     (%i1) subset ({x + y + z, x - y + 4, x + y - 5},
                                         lambda ([e], freeof (z, e)));
     (%o1)               {- y + x + 4, y + x - 5}

   The section *Note Functions and Variables for Sets:: has a complete
list of the set functions in Maxima.

35.1.2 Set Member Iteration
---------------------------

There two ways to to iterate over set members. One way is the use
`map'; for example:

     (%i1) map (f, {a, b, c});
     (%o1)                  {f(a), f(b), f(c)}

   The other way is to use `for <x> in <s> do'

     (%i1) s: {a, b, c};
     (%o1)                       {a, b, c}
     (%i2) for si in s do print (concat (si, 1));
     a1
     b1
     c1
     (%o2)                         done

   The Maxima functions `first' and `rest' work correctly on sets.
Applied to a set, `first' returns the first displayed element of a set;
which element that is may be implementation-dependent. If `s' is a set,
then `rest(s)' is equivalent to `disjoin(first(s), s)'.  Currently,
there are other Maxima functions that work correctly on sets.  In
future versions of the set functions, `first' and `rest' may function
differently or not at all.

35.1.3 Bugs
-----------

The set functions use the Maxima function `orderlessp' to order set
members and the (Lisp-level) function `like' to test for set member
equality. Both of these functions have known bugs that may manifest if
you attempt to use sets with members that are lists or matrices that
contain expressions in canonical rational expression (CRE) form. An
example is

     (%i1) {[x], [rat (x)]};
     Maxima encountered a Lisp error:

       The value #:X1440 is not of type LIST.

     Automatically continuing.
     To reenable the Lisp debugger set *debugger-hook* to nil.

   This expression causes Maxima to halt with an error (the error
message depends on which version of Lisp your Maxima uses). Another
example is

     (%i1) setify ([[rat(a)], [rat(b)]]);
     Maxima encountered a Lisp error:

       The value #:A1440 is not of type LIST.

     Automatically continuing.
     To reenable the Lisp debugger set *debugger-hook* to nil.

   These bugs are caused by bugs in `orderlessp' and `like'; they are
not caused by bugs in the set functions. To illustrate, try the
expressions

     (%i1) orderlessp ([rat(a)], [rat(b)]);
     Maxima encountered a Lisp error:

       The value #:B1441 is not of type LIST.

     Automatically continuing.
     To reenable the Lisp debugger set *debugger-hook* to nil.
     (%i2) is ([rat(a)] = [rat(a)]);
     (%o2)                         false

   Until these bugs are fixed, do not construct sets with members that
are lists or matrices containing expressions in CRE form; a set with a
member in CRE form, however, shouldn't be a problem:

     (%i1) {x, rat (x)};
     (%o1)                          {x}

   Maxima's `orderlessp' has another bug that can cause problems with
set functions, namely that the ordering predicate `orderlessp' is not
transitive. The simplest known example that shows this is

     (%i1) q: x^2$
     (%i2) r: (x + 1)^2$
     (%i3) s: x*(x + 2)$
     (%i4) orderlessp (q, r);
     (%o4)                         true
     (%i5) orderlessp (r, s);
     (%o5)                         true
     (%i6) orderlessp (q, s);
     (%o6)                         false

   This bug can cause trouble with all set functions as well as with
Maxima functions in general. It is probable, but not certain, that this
bug can be avoided if all set members are either in CRE form or have
been simplified using `ratsimp'.

   Maxima's `orderless' and `ordergreat' mechanisms are incompatible
with the set functions. If you need to use either `orderless' or
`ordergreat', call those functions before constructing any sets, and do
not call `unorder'.

   If you find something that you think might be a set function bug,
please report it to the Maxima bug database. See `bug_report'.

35.1.4 Authors
--------------

Stavros Macrakis of Cambridge, Massachusetts and Barton Willis of the
University of Nebraska at Kearney (UNK) wrote the Maxima set functions
and their documentation.


File: maxima.info,  Node: Functions and Variables for Sets,  Prev: Introduction to Sets,  Up: Sets

35.2 Functions and Variables for Sets
=====================================

 -- Function: adjoin (<x>, <a>)
     Returns the union of the set <a> with `{<x>}'.

     `adjoin' complains if <a> is not a literal set.

     `adjoin(<x>, <a>)' and `union(set(<x>), <a>)' are equivalent;
     however, `adjoin' may be somewhat faster than `union'.

     See also `disjoin'.

     Examples:

          (%i1) adjoin (c, {a, b});
          (%o1)                       {a, b, c}
          (%i2) adjoin (a, {a, b});
          (%o2)                        {a, b}


 -- Function: belln (<n>)
     Represents the n-th Bell number.  `belln(n)' is the number of
     partitions of a set with <n> members.

     For nonnegative integers <n>, `belln(<n>)' simplifies to the n-th
     Bell number.  `belln' does not simplify for any other arguments.

     `belln' distributes over equations, lists, matrices, and sets.

     Examples:

     `belln' applied to nonnegative integers.

          (%i1) makelist (belln (i), i, 0, 6);
          (%o1)               [1, 1, 2, 5, 15, 52, 203]
          (%i2) is (cardinality (set_partitions ({})) = belln (0));
          (%o2)                         true
          (%i3) is (cardinality (set_partitions ({1, 2, 3, 4, 5, 6})) =
                                 belln (6));
          (%o3)                         true

     `belln' applied to arguments which are not nonnegative integers.

          (%i1) [belln (x), belln (sqrt(3)), belln (-9)];
          (%o1)        [belln(x), belln(sqrt(3)), belln(- 9)]


 -- Function: cardinality (<a>)
     Returns the number of distinct elements of the set <a>.

     `cardinality' ignores redundant elements even when simplification
     is disabled.

     Examples:

          (%i1) cardinality ({});
          (%o1)                           0
          (%i2) cardinality ({a, a, b, c});
          (%o2)                           3
          (%i3) simp : false;
          (%o3)                         false
          (%i4) cardinality ({a, a, b, c});
          (%o4)                           3


 -- Function: cartesian_product (<b_1>, ... , <b_n>)
     Returns a set of lists of the form `[<x_1>, ..., <x_n>]', where
     <x_1>, ..., <x_n> are elements of the sets <b_1>, ... , <b_n>,
     respectively.

     `cartesian_product' complains if any argument is not a literal set.

     Examples:

          (%i1) cartesian_product ({0, 1});
          (%o1)                      {[0], [1]}
          (%i2) cartesian_product ({0, 1}, {0, 1});
          (%o2)           {[0, 0], [0, 1], [1, 0], [1, 1]}
          (%i3) cartesian_product ({x}, {y}, {z});
          (%o3)                      {[x, y, z]}
          (%i4) cartesian_product ({x}, {-1, 0, 1});
          (%o4)              {[x, - 1], [x, 0], [x, 1]}


 -- Function: disjoin (<x>, <a>)
     Returns the set <a> without the member <x>.  If <x> is not a
     member of <a>, return <a> unchanged.

     `disjoin' complains if <a> is not a literal set.

     `disjoin(<x>, <a>)', `delete(<x>, <a>)', and `setdifference(<a>,
     set(<x>))' are all equivalent.  Of these, `disjoin' is generally
     faster than the others.

     Examples:

          (%i1) disjoin (a, {a, b, c, d});
          (%o1)                       {b, c, d}
          (%i2) disjoin (a + b, {5, z, a + b, %pi});
          (%o2)                      {5, %pi, z}
          (%i3) disjoin (a - b, {5, z, a + b, %pi});
          (%o3)                  {5, %pi, b + a, z}


 -- Function: disjointp (<a>, <b>)
     Returns `true' if and only if the sets <a> and <b> are disjoint.

     `disjointp' complains if either <a> or <b> is not a literal set.

     Examples:

          (%i1) disjointp ({a, b, c}, {1, 2, 3});
          (%o1)                         true
          (%i2) disjointp ({a, b, 3}, {1, 2, 3});
          (%o2)                         false


 -- Function: divisors (<n>)
     Represents the set of divisors of <n>.

     `divisors(<n>)' simplifies to a set of integers when <n> is a
     nonzero integer.  The set of divisors includes the members 1 and
     <n>.  The divisors of a negative integer are the divisors of its
     absolute value.

     `divisors' distributes over equations, lists, matrices, and sets.

     Examples:

     We can verify that 28 is a perfect number: the sum of its divisors
     (except for itself) is 28.

          (%i1) s: divisors(28);
          (%o1)                 {1, 2, 4, 7, 14, 28}
          (%i2) lreduce ("+", args(s)) - 28;
          (%o2)                          28

     `divisors' is a simplifying function.  Substituting 8 for `a' in
     `divisors(a)' yields the divisors without reevaluating
     `divisors(8)'.

          (%i1) divisors (a);
          (%o1)                      divisors(a)
          (%i2) subst (8, a, %);
          (%o2)                     {1, 2, 4, 8}

     `divisors' distributes over equations, lists, matrices, and sets.

          (%i1) divisors (a = b);
          (%o1)               divisors(a) = divisors(b)
          (%i2) divisors ([a, b, c]);
          (%o2)        [divisors(a), divisors(b), divisors(c)]
          (%i3) divisors (matrix ([a, b], [c, d]));
                            [ divisors(a)  divisors(b) ]
          (%o3)             [                          ]
                            [ divisors(c)  divisors(d) ]
          (%i4) divisors ({a, b, c});
          (%o4)        {divisors(a), divisors(b), divisors(c)}


 -- Function: elementp (<x>, <a>)
     Returns `true' if and only if <x> is a member of the set <a>.

     `elementp' complains if <a> is not a literal set.

     Examples:

          (%i1) elementp (sin(1), {sin(1), sin(2), sin(3)});
          (%o1)                         true
          (%i2) elementp (sin(1), {cos(1), cos(2), cos(3)});
          (%o2)                         false


 -- Function: emptyp (<a>)
     Return `true' if and only if <a> is the empty set or the empty
     list.

     Examples:

          (%i1) map (emptyp, [{}, []]);
          (%o1)                     [true, true]
          (%i2) map (emptyp, [a + b, {{}}, %pi]);
          (%o2)                 [false, false, false]


 -- Function: equiv_classes (<s>, <F>)
     Returns a set of the equivalence classes of the set <s> with
     respect to the equivalence relation <F>.

     <F> is a function of two variables defined on the Cartesian
     product of <s> with <s>.  The return value of <F> is either `true'
     or `false', or an expression <expr> such that `is(<expr>)' is
     either `true' or `false'.

     When <F> is not an equivalence relation, `equiv_classes' accepts
     it without complaint, but the result is generally incorrect in
     that case.

     Examples:

     The equivalence relation is a lambda expression which returns
     `true' or `false'.

          (%i1) equiv_classes ({1, 1.0, 2, 2.0, 3, 3.0},
                                  lambda ([x, y], is (equal (x, y))));
          (%o1)            {{1, 1.0}, {2, 2.0}, {3, 3.0}}

     The equivalence relation is the name of a relational function
     which `is' evaluates to `true' or `false'.

          (%i1) equiv_classes ({1, 1.0, 2, 2.0, 3, 3.0}, equal);
          (%o1)            {{1, 1.0}, {2, 2.0}, {3, 3.0}}

     The equivalence classes are numbers which differ by a multiple of
     3.

          (%i1) equiv_classes ({1, 2, 3, 4, 5, 6, 7},
                               lambda ([x, y], remainder (x - y, 3) = 0));
          (%o1)              {{1, 4, 7}, {2, 5}, {3, 6}}


 -- Function: every (<f>, <s>)
 -- Function: every (<f>, <L_1>, ..., <L_n>)
     Returns `true' if the predicate <f> is `true' for all given
     arguments.

     Given one set as the second argument, `every(<f>, <s>)' returns
     `true' if `is(<f>(<a_i>))' returns `true' for all <a_i> in <s>.
     `every' may or may not evaluate <f> for all <a_i> in <s>.  Since
     sets are unordered, `every' may evaluate `<f>(<a_i>)' in any order.

     Given one or more lists as arguments, `every(<f>, <L_1>, ...,
     <L_n>)' returns `true' if `is(<f>(<x_1>, ..., <x_n>))' returns
     `true' for all <x_1>, ..., <x_n> in <L_1>, ..., <L_n>,
     respectively.  `every' may or may not evaluate <f> for every
     combination <x_1>, ..., <x_n>.  `every' evaluates lists in the
     order of increasing index.

     Given an empty set `{}' or empty lists `[]' as arguments, `every'
     returns `false'.

     When the global flag `maperror' is `true', all lists <L_1>, ...,
     <L_n> must have equal lengths.  When `maperror' is `false', list
     arguments are effectively truncated to the length of the shortest
     list.

     Return values of the predicate <f> which evaluate (via `is') to
     something other than `true' or `false' are governed by the global
     flag `prederror'.  When `prederror' is `true', such values are
     treated as `false', and the return value from `every' is `false'.
     When `prederror' is `false', such values are treated as `unknown',
     and the return value from `every' is `unknown'.

     Examples:

     `every' applied to a single set.  The predicate is a function of
     one argument.

          (%i1) every (integerp, {1, 2, 3, 4, 5, 6});
          (%o1)                         true
          (%i2) every (atom, {1, 2, sin(3), 4, 5 + y, 6});
          (%o2)                         false

     `every' applied to two lists.  The predicate is a function of two
     arguments.

          (%i1) every ("=", [a, b, c], [a, b, c]);
          (%o1)                         true
          (%i2) every ("#", [a, b, c], [a, b, c]);
          (%o2)                         false

     Return values of the predicate <f> which evaluate to something
     other than `true' or `false' are governed by the global flag
     `prederror'.

          (%i1) prederror : false;
          (%o1)                         false
          (%i2) map (lambda ([a, b], is (a < b)), [x, y, z],
                             [x^2, y^2, z^2]);
          (%o2)              [unknown, unknown, unknown]
          (%i3) every ("<", [x, y, z], [x^2, y^2, z^2]);
          (%o3)                        unknown
          (%i4) prederror : true;
          (%o4)                         true
          (%i5) every ("<", [x, y, z], [x^2, y^2, z^2]);
          (%o5)                         false


 -- Function: extremal_subset (<s>, <f>, max)
 -- Function: extremal_subset (<s>, <f>, min)
     Returns the subset of <s> for which the function <f> takes on
     maximum or minimum values.

     `extremal_subset(<s>, <f>, max)' returns the subset of the set or
     list <s> for which the real-valued function <f> takes on its
     maximum value.

     `extremal_subset(<s>, <f>, min)' returns the subset of the set or
     list <s> for which the real-valued function <f> takes on its
     minimum value.

     Examples:

          (%i1) extremal_subset ({-2, -1, 0, 1, 2}, abs, max);
          (%o1)                       {- 2, 2}
          (%i2) extremal_subset ({sqrt(2), 1.57, %pi/2}, sin, min);
          (%o2)                       {sqrt(2)}


 -- Function: flatten (<expr>)
     Collects arguments of subexpressions which have the same operator
     as <expr> and constructs an expression from these collected
     arguments.

     Subexpressions in which the operator is different from the main
     operator of `expr' are copied without modification, even if they,
     in turn, contain some subexpressions in which the operator is the
     same as for `expr'.

     It may be possible for `flatten' to construct expressions in which
     the number of arguments differs from the declared arguments for an
     operator; this may provoke an error message from the simplifier or
     evaluator.  `flatten' does not try to detect such situations.

     Expressions with special representations, for example, canonical
     rational expressions (CRE), cannot be flattened; in such cases,
     `flatten' returns its argument unchanged.

     Examples:

     Applied to a list, `flatten' gathers all list elements that are
     lists.

          (%i1) flatten ([a, b, [c, [d, e], f], [[g, h]], i, j]);
          (%o1)            [a, b, c, d, e, f, g, h, i, j]

     Applied to a set, `flatten' gathers all members of set elements
     that are sets.

          (%i1) flatten ({a, {b}, {{c}}});
          (%o1)                       {a, b, c}
          (%i2) flatten ({a, {[a], {a}}});
          (%o2)                       {a, [a]}

     `flatten' is similar to the effect of declaring the main operator
     n-ary.  However, `flatten' has no effect on subexpressions which
     have an operator different from the main operator, while an n-ary
     declaration affects those.

          (%i1) expr: flatten (f (g (f (f (x)))));
          (%o1)                     f(g(f(f(x))))
          (%i2) declare (f, nary);
          (%o2)                         done
          (%i3) ev (expr);
          (%o3)                      f(g(f(x)))

     `flatten' treats subscripted functions the same as any other
     operator.

          (%i1) flatten (f[5] (f[5] (x, y), z));
          (%o1)                      f (x, y, z)
                                      5

     It may be possible for `flatten' to construct expressions in which
     the number of arguments differs from the declared arguments for an
     operator;

          (%i1) 'mod (5, 'mod (7, 4));
          (%o1)                   mod(5, mod(7, 4))
          (%i2) flatten (%);
          (%o2)                     mod(5, 7, 4)
          (%i3) ''%, nouns;
          Wrong number of arguments to mod
           -- an error.  Quitting.  To debug this try debugmode(true);


 -- Function: full_listify (<a>)
     Replaces every set operator in <a> by a list operator, and returns
     the result.  `full_listify' replaces set operators in nested
     subexpressions, even if the main operator is not `set'.

     `listify' replaces only the main operator.

     Examples:

          (%i1) full_listify ({a, b, {c, {d, e, f}, g}});
          (%o1)               [a, b, [c, [d, e, f], g]]
          (%i2) full_listify (F (G ({a, b, H({c, d, e})})));
          (%o2)              F(G([a, b, H([c, d, e])]))


 -- Function: fullsetify (<a>)
     When <a> is a list, replaces the list operator with a set operator,
     and applies `fullsetify' to each member which is a set.  When <a>
     is not a list, it is returned unchanged.

     `setify' replaces only the main operator.

     Examples:

     In line `(%o2)', the argument of `f' isn't converted to a set
     because the main operator of `f([b])' isn't a list.

          (%i1) fullsetify ([a, [a]]);
          (%o1)                       {a, {a}}
          (%i2) fullsetify ([a, f([b])]);
          (%o2)                      {a, f([b])}


 -- Function: identity (<x>)
     Returns <x> for any argument <x>.

     Examples:

     `identity' may be used as a predicate when the arguments are
     already Boolean values.

          (%i1) every (identity, [true, true]);
          (%o1)                         true

 -- Function: integer_partitions (<n>)
 -- Function: integer_partitions (<n>, <len>)
     Returns integer partitions of <n>, that is, lists of integers
     which sum to <n>.

     `integer_partitions(<n>)' returns the set of all partitions of the
     integer <n>.  Each partition is a list sorted from greatest to
     least.

     `integer_partitions(<n>, <len>)' returns all partitions that have
     length <len> or less; in this case, zeros are appended to each
     partition with fewer than <len> terms to make each partition have
     exactly <len> terms.  Each partition is a list sorted from
     greatest to least.

     A list [a_1, ..., a_m] is a partition of a nonnegative integer n
     when (1) each a_i is a nonzero integer, and (2) a_1 + ... + a_m =
     n. Thus 0 has no partitions.

     Examples:

          (%i1) integer_partitions (3);
          (%o1)               {[1, 1, 1], [2, 1], [3]}
          (%i2) s: integer_partitions (25)$
          (%i3) cardinality (s);
          (%o3)                         1958
          (%i4) map (lambda ([x], apply ("+", x)), s);
          (%o4)                         {25}
          (%i5) integer_partitions (5, 3);
          (%o5) {[2, 2, 1], [3, 1, 1], [3, 2, 0], [4, 1, 0], [5, 0, 0]}
          (%i6) integer_partitions (5, 2);
          (%o6)               {[3, 2], [4, 1], [5, 0]}

     To find all partitions that satisfy a condition, use the function
     `subset'; here is an example that finds all partitions of 10 that
     consist of prime numbers.

          (%i1) s: integer_partitions (10)$
          (%i2) cardinality (s);
          (%o2)                          42
          (%i3) xprimep(x) := integerp(x) and (x > 1) and primep(x)$
          (%i4) subset (s, lambda ([x], every (xprimep, x)));
          (%o4) {[2, 2, 2, 2, 2], [3, 3, 2, 2], [5, 3, 2], [5, 5], [7, 3]}


 -- Function: intersect (<a_1>, ..., <a_n>)
     `intersect' is the same as `intersection', which see.


 -- Function: intersection (<a_1>, ..., <a_n>)
     Returns a set containing the elements that are common to the sets
     <a_1> through <a_n>.

     `intersection' complains if any argument is not a literal set.

     Examples:

          (%i1) S_1 : {a, b, c, d};
          (%o1)                     {a, b, c, d}
          (%i2) S_2 : {d, e, f, g};
          (%o2)                     {d, e, f, g}
          (%i3) S_3 : {c, d, e, f};
          (%o3)                     {c, d, e, f}
          (%i4) S_4 : {u, v, w};
          (%o4)                       {u, v, w}
          (%i5) intersection (S_1, S_2);
          (%o5)                          {d}
          (%i6) intersection (S_2, S_3);
          (%o6)                       {d, e, f}
          (%i7) intersection (S_1, S_2, S_3);
          (%o7)                          {d}
          (%i8) intersection (S_1, S_2, S_3, S_4);
          (%o8)                          {}


 -- Function: kron_delta (<x1>, <x2>, ..., <xp>)
     Represents the Kronecker delta function.

     `kron_delta' simplifies to 1 when <xi> and <yj> are equal for all
     pairs of arguments, and it simplifies to 0 when <xi> and <yj> are
     not equal for some pair of arguments. Equality is determined using
     `is(equal(xi,xj))' and inequality by `is(notequal(xi,xj))'. For
     exactly one argument, `kron_delta' signals an error.

     Examples:

          (%i1) kron_delta(a,a);
          (%o1)                                  1
          (%i2) kron_delta(a,b,a,b);
          (%o2)                          kron_delta(a, b)
          (%i3) kron_delta(a,a,b,a+1);
          (%o3)                                  0
          (%i4) assume(equal(x,y));
          (%o4)                            [equal(x, y)]
          (%i5) kron_delta(x,y);
          (%o5)                                  1


 -- Function: listify (<a>)
     Returns a list containing the members of <a> when <a> is a set.
     Otherwise, `listify' returns <a>.

     `full_listify' replaces all set operators in <a> by list operators.

     Examples:

          (%i1) listify ({a, b, c, d});
          (%o1)                     [a, b, c, d]
          (%i2) listify (F ({a, b, c, d}));
          (%o2)                    F({a, b, c, d})


 -- Function: lreduce (<F>, <s>)
 -- Function: lreduce (<F>, <s>, <s_0>)
     Extends the binary function <F> to an n-ary function by
     composition, where <s> is a list.

     `lreduce(<F>, <s>)' returns `F(... F(F(s_1, s_2), s_3), ... s_n)'.
     When the optional argument <s_0> is present, the result is
     equivalent to `lreduce(<F>, cons(<s_0>, <s>))'.

     The function <F> is first applied to the leftmost list elements,
     thus the name "lreduce".

     See also `rreduce', `xreduce', and `tree_reduce'.

     Examples:

     `lreduce' without the optional argument.

          (%i1) lreduce (f, [1, 2, 3]);
          (%o1)                     f(f(1, 2), 3)
          (%i2) lreduce (f, [1, 2, 3, 4]);
          (%o2)                  f(f(f(1, 2), 3), 4)

     `lreduce' with the optional argument.

          (%i1) lreduce (f, [1, 2, 3], 4);
          (%o1)                  f(f(f(4, 1), 2), 3)

     `lreduce' applied to built-in binary operators.  `/' is the
     division operator.

          (%i1) lreduce ("^", args ({a, b, c, d}));
                                         b c d
          (%o1)                       ((a ) )
          (%i2) lreduce ("/", args ({a, b, c, d}));
                                          a
          (%o2)                         -----
                                        b c d


 -- Function: makeset (<expr>, <x>, <s>)
     Returns a set with members generated from the expression <expr>,
     where <x> is a list of variables in <expr>, and <s> is a set or
     list of lists.  To generate each set member, <expr> is evaluated
     with the variables <x> bound in parallel to a member of <s>.

     Each member of <s> must have the same length as <x>.  The list of
     variables <x> must be a list of symbols, without subscripts.  Even
     if there is only one symbol, <x> must be a list of one element,
     and each member of <s> must be a list of one element.

     See also `makelist'.

     Examples:

          (%i1) makeset (i/j, [i, j], [[1, a], [2, b], [3, c], [4, d]]);
                                     1  2  3  4
          (%o1)                     {-, -, -, -}
                                     a  b  c  d
          (%i2) S : {x, y, z}$
          (%i3) S3 : cartesian_product (S, S, S);
          (%o3) {[x, x, x], [x, x, y], [x, x, z], [x, y, x], [x, y, y],
          [x, y, z], [x, z, x], [x, z, y], [x, z, z], [y, x, x],
          [y, x, y], [y, x, z], [y, y, x], [y, y, y], [y, y, z],
          [y, z, x], [y, z, y], [y, z, z], [z, x, x], [z, x, y],
          [z, x, z], [z, y, x], [z, y, y], [z, y, z], [z, z, x],
          [z, z, y], [z, z, z]}
          (%i4) makeset (i + j + k, [i, j, k], S3);
          (%o4) {3 x, 3 y, y + 2 x, 2 y + x, 3 z, z + 2 x, z + y + x,
                                                 z + 2 y, 2 z + x, 2 z + y}
          (%i5) makeset (sin(x), [x], {[1], [2], [3]});
          (%o5)               {sin(1), sin(2), sin(3)}


 -- Function: moebius (<n>)
     Represents the Moebius function.

     When <n> is product of k distinct primes, `moebius(<n>)'
     simplifies to (-1)^k; when <n> = 1, it simplifies to 1; and it
     simplifies to 0 for all other positive integers.

     `moebius' distributes over equations, lists, matrices, and sets.

     Examples:

          (%i1) moebius (1);
          (%o1)                           1
          (%i2) moebius (2 * 3 * 5);
          (%o2)                          - 1
          (%i3) moebius (11 * 17 * 29 * 31);
          (%o3)                           1
          (%i4) moebius (2^32);
          (%o4)                           0
          (%i5) moebius (n);
          (%o5)                      moebius(n)
          (%i6) moebius (n = 12);
          (%o6)                    moebius(n) = 0
          (%i7) moebius ([11, 11 * 13, 11 * 13 * 15]);
          (%o7)                      [- 1, 1, 1]
          (%i8) moebius (matrix ([11, 12], [13, 14]));
                                     [ - 1  0 ]
          (%o8)                      [        ]
                                     [ - 1  1 ]
          (%i9) moebius ({21, 22, 23, 24});
          (%o9)                      {- 1, 0, 1}


 -- Function: multinomial_coeff (<a_1>, ..., <a_n>)
 -- Function: multinomial_coeff ()
     Returns the multinomial coefficient.

     When each <a_k> is a nonnegative integer, the multinomial
     coefficient gives the number of ways of placing `<a_1> + ... +
     <a_n>' distinct objects into n boxes with <a_k> elements in the
     k'th box. In general, `multinomial_coeff (<a_1>, ..., <a_n>)'
     evaluates to `(<a_1> + ... + <a_n>)!/(<a_1>! ... <a_n>!)'.

     `multinomial_coeff()' (with no arguments) evaluates to 1.

     `minfactorial' may be able to simplify the value returned by
     `multinomial_coeff'.

     Examples:

          (%i1) multinomial_coeff (1, 2, x);
                                      (x + 3)!
          (%o1)                       --------
                                        2 x!
          (%i2) minfactorial (%);
                               (x + 1) (x + 2) (x + 3)
          (%o2)                -----------------------
                                          2
          (%i3) multinomial_coeff (-6, 2);
                                       (- 4)!
          (%o3)                       --------
                                      2 (- 6)!
          (%i4) minfactorial (%);
          (%o4)                          10


 -- Function: num_distinct_partitions (<n>)
 -- Function: num_distinct_partitions (<n>, list)
     Returns the number of distinct integer partitions of <n> when <n>
     is a nonnegative integer.  Otherwise, `num_distinct_partitions'
     returns a noun expression.

     `num_distinct_partitions(<n>, list)' returns a list of the number
     of distinct partitions of 1, 2, 3, ..., <n>.

     A distinct partition of <n> is a list of distinct positive
     integers k_1, ..., k_m such that <n> = k_1 + ... + k_m.

     Examples:

          (%i1) num_distinct_partitions (12);
          (%o1)                          15
          (%i2) num_distinct_partitions (12, list);
          (%o2)      [1, 1, 1, 2, 2, 3, 4, 5, 6, 8, 10, 12, 15]
          (%i3) num_distinct_partitions (n);
          (%o3)              num_distinct_partitions(n)


 -- Function: num_partitions (<n>)
 -- Function: num_partitions (<n>, list)
     Returns the number of integer partitions of <n> when <n> is a
     nonnegative integer.  Otherwise, `num_partitions' returns a noun
     expression.

     `num_partitions(<n>, list)' returns a list of the number of
     integer partitions of 1, 2, 3, ..., <n>.

     For a nonnegative integer <n>, `num_partitions(<n>)' is equal to
     `cardinality(integer_partitions(<n>))'; however, `num_partitions'
     does not actually construct the set of partitions, so it is much
     faster.

     Examples:

          (%i1) num_partitions (5) = cardinality (integer_partitions (5));
          (%o1)                         7 = 7
          (%i2) num_partitions (8, list);
          (%o2)            [1, 1, 2, 3, 5, 7, 11, 15, 22]
          (%i3) num_partitions (n);
          (%o3)                   num_partitions(n)


 -- Function: partition_set (<a>, <f>)
     Partitions the set <a> according to the predicate <f>.

     `partition_set' returns a list of two sets.  The first set
     comprises the elements of <a> for which <f> evaluates to `false',
     and the second comprises any other elements of <a>.
     `partition_set' does not apply `is' to the return value of <f>.

     `partition_set' complains if <a> is not a literal set.

     See also `subset'.

     Examples:

          (%i1) partition_set ({2, 7, 1, 8, 2, 8}, evenp);
          (%o1)                   [{1, 7}, {2, 8}]
          (%i2) partition_set ({x, rat(y), rat(y) + z, 1},
                               lambda ([x], ratp(x)));
          (%o2)/R/              [{1, x}, {y, y + z}]


 -- Function: permutations (<a>)
     Returns a set of all distinct permutations of the members of the
     list or set <a>. Each permutation is a list, not a set.

     When <a> is a list, duplicate members of <a> are included in the
     permutations.

     `permutations' complains if <a> is not a literal list or set.

     See also `random_permutation'.

     Examples:

          (%i1) permutations ([a, a]);
          (%o1)                       {[a, a]}
          (%i2) permutations ([a, a, b]);
          (%o2)           {[a, a, b], [a, b, a], [b, a, a]}


 -- Function: powerset (<a>)
 -- Function: powerset (<a>, <n>)
     Returns the set of all subsets of <a>, or a subset of that set.

     `powerset(<a>)' returns the set of all subsets of the set <a>.
     `powerset(<a>)' has `2^cardinality(<a>)' members.

     `powerset(<a>, <n>)' returns the set of all subsets of <a> that
     have cardinality <n>.

     `powerset' complains if <a> is not a literal set, or if <n> is not
     a nonnegative integer.

     Examples:

          (%i1) powerset ({a, b, c});
          (%o1) {{}, {a}, {a, b}, {a, b, c}, {a, c}, {b}, {b, c}, {c}}
          (%i2) powerset ({w, x, y, z}, 4);
          (%o2)                    {{w, x, y, z}}
          (%i3) powerset ({w, x, y, z}, 3);
          (%o3)     {{w, x, y}, {w, x, z}, {w, y, z}, {x, y, z}}
          (%i4) powerset ({w, x, y, z}, 2);
          (%o4)   {{w, x}, {w, y}, {w, z}, {x, y}, {x, z}, {y, z}}
          (%i5) powerset ({w, x, y, z}, 1);
          (%o5)                 {{w}, {x}, {y}, {z}}
          (%i6) powerset ({w, x, y, z}, 0);
          (%o6)                         {{}}


 -- Function: random_permutation (<a>)
     Returns a random permutation of the set or list <a>, as
     constructed by the Knuth shuffle algorithm.

     The return value is a new list, which is distinct from the
     argument even if all elements happen to be the same.  However, the
     elements of the argument are not copied.

     Examples:

          (%i1) random_permutation ([a, b, c, 1, 2, 3]);
          (%o1)                  [c, 1, 2, 3, a, b]
          (%i2) random_permutation ([a, b, c, 1, 2, 3]);
          (%o2)                  [b, 3, 1, c, a, 2]
          (%i3) random_permutation ({x + 1, y + 2, z + 3});
          (%o3)                 [y + 2, z + 3, x + 1]
          (%i4) random_permutation ({x + 1, y + 2, z + 3});
          (%o4)                 [x + 1, y + 2, z + 3]


 -- Function: rreduce (<F>, <s>)
 -- Function: rreduce (<F>, <s>, <s_{n + 1}>)
     Extends the binary function <F> to an n-ary function by
     composition, where <s> is a list.

     `rreduce(<F>, <s>)' returns `F(s_1, ... F(s_{n - 2}, F(s_{n - 1},
     s_n)))'.  When the optional argument <s_{n + 1}> is present, the
     result is equivalent to `rreduce(<F>, endcons(<s_{n + 1}>, <s>))'.

     The function <F> is first applied to the rightmost list elements,
     thus the name "rreduce".

     See also `lreduce', `tree_reduce', and `xreduce'.

     Examples:

     `rreduce' without the optional argument.

          (%i1) rreduce (f, [1, 2, 3]);
          (%o1)                     f(1, f(2, 3))
          (%i2) rreduce (f, [1, 2, 3, 4]);
          (%o2)                  f(1, f(2, f(3, 4)))

     `rreduce' with the optional argument.

          (%i1) rreduce (f, [1, 2, 3], 4);
          (%o1)                  f(1, f(2, f(3, 4)))

     `rreduce' applied to built-in binary operators.  `/' is the
     division operator.

          (%i1) rreduce ("^", args ({a, b, c, d}));
                                           d
                                          c
                                         b
          (%o1)                         a
          (%i2) rreduce ("/", args ({a, b, c, d}));
                                         a c
          (%o2)                          ---
                                         b d


 -- Function: setdifference (<a>, <b>)
     Returns a set containing the elements in the set <a> that are not
     in the set <b>.

     `setdifference' complains if either <a> or <b> is not a literal
     set.

     Examples:

          (%i1) S_1 : {a, b, c, x, y, z};
          (%o1)                  {a, b, c, x, y, z}
          (%i2) S_2 : {aa, bb, c, x, y, zz};
          (%o2)                 {aa, bb, c, x, y, zz}
          (%i3) setdifference (S_1, S_2);
          (%o3)                       {a, b, z}
          (%i4) setdifference (S_2, S_1);
          (%o4)                     {aa, bb, zz}
          (%i5) setdifference (S_1, S_1);
          (%o5)                          {}
          (%i6) setdifference (S_1, {});
          (%o6)                  {a, b, c, x, y, z}
          (%i7) setdifference ({}, S_1);
          (%o7)                          {}


 -- Function: setequalp (<a>, <b>)
     Returns `true' if sets <a> and <b> have the same number of elements
     and `is(<x> = <y>)' is `true' for `x' in the elements of <a> and
     `y' in the elements of <b>, considered in the order determined by
     `listify'.  Otherwise, `setequalp' returns `false'.

     Examples:

          (%i1) setequalp ({1, 2, 3}, {1, 2, 3});
          (%o1)                         true
          (%i2) setequalp ({a, b, c}, {1, 2, 3});
          (%o2)                         false
          (%i3) setequalp ({x^2 - y^2}, {(x + y) * (x - y)});
          (%o3)                         false


 -- Function: setify (<a>)
     Constructs a set from the elements of the list <a>. Duplicate
     elements of the list <a> are deleted and the elements are sorted
     according to the predicate `orderlessp'.

     `setify' complains if <a> is not a literal list.

     Examples:

          (%i1) setify ([1, 2, 3, a, b, c]);
          (%o1)                  {1, 2, 3, a, b, c}
          (%i2) setify ([a, b, c, a, b, c]);
          (%o2)                       {a, b, c}
          (%i3) setify ([7, 13, 11, 1, 3, 9, 5]);
          (%o3)                {1, 3, 5, 7, 9, 11, 13}


 -- Function: setp (<a>)
     Returns `true' if and only if <a> is a Maxima set.

     `setp' returns `true' for unsimplified sets (that is, sets with
     redundant members) as well as simplified sets.

     `setp' is equivalent to the Maxima function `setp(a) := not
     atom(a) and op(a) = 'set'.

     Examples:

          (%i1) simp : false;
          (%o1)                         false
          (%i2) {a, a, a};
          (%o2)                       {a, a, a}
          (%i3) setp (%);
          (%o3)                         true


 -- Function: set_partitions (<a>)
 -- Function: set_partitions (<a>, <n>)
     Returns the set of all partitions of <a>, or a subset of that set.

     `set_partitions(<a>, <n>)' returns a set of all decompositions of
     <a> into <n> nonempty disjoint subsets.

     `set_partitions(<a>)' returns the set of all partitions.

     `stirling2' returns the cardinality of the set of partitions of a
     set.

     A set of sets P is a partition of a set S when

       1. each member of P is a nonempty set,

       2. distinct members of P are disjoint,

       3. the union of the members of P equals S.

     Examples:

     The empty set is a partition of itself, the conditions 1 and 2
     being vacuously true.

          (%i1) set_partitions ({});
          (%o1)                         {{}}

     The cardinality of the set of partitions of a set can be found
     using `stirling2'.

          (%i1) s: {0, 1, 2, 3, 4, 5}$
          (%i2) p: set_partitions (s, 3)$
          (%i3) cardinality(p) = stirling2 (6, 3);
          (%o3)                        90 = 90

     Each member of `p' should have <n> = 3 members; let's check.

          (%i1) s: {0, 1, 2, 3, 4, 5}$
          (%i2) p: set_partitions (s, 3)$
          (%i3) map (cardinality, p);
          (%o3)                          {3}

     Finally, for each member of `p', the union of its members should
     equal `s'; again let's check.

          (%i1) s: {0, 1, 2, 3, 4, 5}$
          (%i2) p: set_partitions (s, 3)$
          (%i3) map (lambda ([x], apply (union, listify (x))), p);
          (%o3)                 {{0, 1, 2, 3, 4, 5}}


 -- Function: some (<f>, <a>)
 -- Function: some (<f>, <L_1>, ..., <L_n>)
     Returns `true' if the predicate <f> is `true' for one or more
     given arguments.

     Given one set as the second argument, `some(<f>, <s>)' returns
     `true' if `is(<f>(<a_i>))' returns `true' for one or more <a_i> in
     <s>.  `some' may or may not evaluate <f> for all <a_i> in <s>.
     Since sets are unordered, `some' may evaluate `<f>(<a_i>)' in any
     order.

     Given one or more lists as arguments, `some(<f>, <L_1>, ...,
     <L_n>)' returns `true' if `is(<f>(<x_1>, ..., <x_n>))' returns
     `true' for one or more <x_1>, ..., <x_n> in <L_1>, ..., <L_n>,
     respectively.  `some' may or may not evaluate <f> for some
     combinations <x_1>, ..., <x_n>.  `some' evaluates lists in the
     order of increasing index.

     Given an empty set `{}' or empty lists `[]' as arguments, `some'
     returns `false'.

     When the global flag `maperror' is `true', all lists <L_1>, ...,
     <L_n> must have equal lengths.  When `maperror' is `false', list
     arguments are effectively truncated to the length of the shortest
     list.

     Return values of the predicate <f> which evaluate (via `is') to
     something other than `true' or `false' are governed by the global
     flag `prederror'.  When `prederror' is `true', such values are
     treated as `false'.  When `prederror' is `false', such values are
     treated as `unknown'.

     Examples:

     `some' applied to a single set.  The predicate is a function of
     one argument.

          (%i1) some (integerp, {1, 2, 3, 4, 5, 6});
          (%o1)                         true
          (%i2) some (atom, {1, 2, sin(3), 4, 5 + y, 6});
          (%o2)                         true

     `some' applied to two lists.  The predicate is a function of two
     arguments.

          (%i1) some ("=", [a, b, c], [a, b, c]);
          (%o1)                         true
          (%i2) some ("#", [a, b, c], [a, b, c]);
          (%o2)                         false

     Return values of the predicate <f> which evaluate to something
     other than `true' or `false' are governed by the global flag
     `prederror'.

          (%i1) prederror : false;
          (%o1)                         false
          (%i2) map (lambda ([a, b], is (a < b)), [x, y, z],
                     [x^2, y^2, z^2]);
          (%o2)              [unknown, unknown, unknown]
          (%i3) some ("<", [x, y, z], [x^2, y^2, z^2]);
          (%o3)                        unknown
          (%i4) some ("<", [x, y, z], [x^2, y^2, z + 1]);
          (%o4)                         true
          (%i5) prederror : true;
          (%o5)                         true
          (%i6) some ("<", [x, y, z], [x^2, y^2, z^2]);
          (%o6)                         false
          (%i7) some ("<", [x, y, z], [x^2, y^2, z + 1]);
          (%o7)                         true


 -- Function: stirling1 (<n>, <m>)
     Represents the Stirling number of the first kind.

     When <n> and <m> are nonnegative integers, the magnitude of
     `stirling1 (<n>, <m>)' is the number of permutations of a set with
     <n> members that have <m> cycles.  For details, see Graham, Knuth
     and Patashnik Concrete Mathematics.  Maxima uses a recursion
     relation to define `stirling1 (<n>, <m>)' for <m> less than 0; it
     is undefined for <n> less than 0 and for non-integer arguments.

     `stirling1' is a simplifying function.  Maxima knows the following
     identities.

       1. stirling1(0, n) = kron_delta(0, n) (Ref. [1])

       2. stirling1(n, n) = 1 (Ref. [1])

       3. stirling1(n, n - 1) = binomial(n, 2) (Ref. [1])

       4. stirling1(n + 1, 0) = 0 (Ref. [1])

       5. stirling1(n + 1, 1) = n! (Ref. [1])

       6. stirling1(n + 1, 2) = 2^n  - 1 (Ref. [1])

     These identities are applied when the arguments are literal
     integers or symbols declared as integers, and the first argument
     is nonnegative.  `stirling1' does not simplify for non-integer
     arguments.

     References:

     [1] Donald Knuth, The Art of Computer Programming, third edition,
     Volume 1, Section 1.2.6, Equations 48, 49, and 50.

     Examples:

          (%i1) declare (n, integer)$
          (%i2) assume (n >= 0)$
          (%i3) stirling1 (n, n);
          (%o3)                           1

     `stirling1' does not simplify for non-integer arguments.

          (%i1) stirling1 (sqrt(2), sqrt(2));
          (%o1)              stirling1(sqrt(2), sqrt(2))

     Maxima applies identities to `stirling1'.

          (%i1) declare (n, integer)$
          (%i2) assume (n >= 0)$
          (%i3) stirling1 (n + 1, n);
                                      n (n + 1)
          (%o3)                       ---------
                                          2
          (%i4) stirling1 (n + 1, 1);
          (%o4)                          n!


 -- Function: stirling2 (<n>, <m>)
     Represents the Stirling number of the second kind.

     When <n> and <m> are nonnegative integers, `stirling2 (<n>, <m>)'
     is the number of ways a set with cardinality <n> can be
     partitioned into <m> disjoint subsets.  Maxima uses a recursion
     relation to define `stirling2 (<n>, <m>)' for <m> less than 0; it
     is undefined for <n> less than 0 and for non-integer arguments.

     `stirling2' is a simplifying function.  Maxima knows the following
     identities.

       1. stirling2(0, n) = kron_delta(0, n) (Ref. [1])

       2. stirling2(n, n) = 1 (Ref. [1])

       3. stirling2(n, n - 1) = binomial(n, 2) (Ref. [1])

       4. stirling2(n + 1, 1) = 1 (Ref. [1])

       5. stirling2(n + 1, 2) = 2^n  - 1 (Ref. [1])

       6. stirling2(n, 0) = kron_delta(n, 0) (Ref. [2])

       7. stirling2(n, m) = 0 when m > n (Ref. [2])

       8. stirling2(n, m) = sum((-1)^(m - k) binomial(m k) k^n,i,1,m) /
          m!  when m and n are integers, and n is nonnegative. (Ref.
          [3])

     These identities are applied when the arguments are literal
     integers or symbols declared as integers, and the first argument
     is nonnegative.  `stirling2' does not simplify for non-integer
     arguments.

     References:

     [1] Donald Knuth. The Art of Computer Programming, third edition,
     Volume 1, Section 1.2.6, Equations 48, 49, and 50.

     [2] Graham, Knuth, and Patashnik. Concrete Mathematics, Table 264.

     [3] Abramowitz and Stegun. Handbook of Mathematical Functions,
     Section 24.1.4.

     Examples:

          (%i1) declare (n, integer)$
          (%i2) assume (n >= 0)$
          (%i3) stirling2 (n, n);
          (%o3)                           1

     `stirling2' does not simplify for non-integer arguments.

          (%i1) stirling2 (%pi, %pi);
          (%o1)                  stirling2(%pi, %pi)

     Maxima applies identities to `stirling2'.

          (%i1) declare (n, integer)$
          (%i2) assume (n >= 0)$
          (%i3) stirling2 (n + 9, n + 8);
                                   (n + 8) (n + 9)
          (%o3)                    ---------------
                                          2
          (%i4) stirling2 (n + 1, 2);
                                        n
          (%o4)                        2  - 1


 -- Function: subset (<a>, <f>)
     Returns the subset of the set <a> that satisfies the predicate <f>.

     `subset' returns a set which comprises the elements of <a> for
     which <f> returns anything other than `false'.  `subset' does not
     apply `is' to the return value of <f>.

     `subset' complains if <a> is not a literal set.

     See also `partition_set'.

     Examples:

          (%i1) subset ({1, 2, x, x + y, z, x + y + z}, atom);
          (%o1)                     {1, 2, x, z}
          (%i2) subset ({1, 2, 7, 8, 9, 14}, evenp);
          (%o2)                      {2, 8, 14}


 -- Function: subsetp (<a>, <b>)
     Returns `true' if and only if the set <a> is a subset of <b>.

     `subsetp' complains if either <a> or <b> is not a literal set.

     Examples:

          (%i1) subsetp ({1, 2, 3}, {a, 1, b, 2, c, 3});
          (%o1)                         true
          (%i2) subsetp ({a, 1, b, 2, c, 3}, {1, 2, 3});
          (%o2)                         false


 -- Function: symmdifference (<a_1>, ..., <a_n>)
     Returns the symmetric difference of sets <a_1>, ..., <a_n>.

     Given two arguments, `symmdifference (<a>, <b>)' is the same as
     `union (setdifference (<a>, <b>), setdifference (<b>, <a>))'.

     `symmdifference' complains if any argument is not a literal set.

     Examples:

          (%i1) S_1 : {a, b, c};
          (%o1)                       {a, b, c}
          (%i2) S_2 : {1, b, c};
          (%o2)                       {1, b, c}
          (%i3) S_3 : {a, b, z};
          (%o3)                       {a, b, z}
          (%i4) symmdifference ();
          (%o4)                          {}
          (%i5) symmdifference (S_1);
          (%o5)                       {a, b, c}
          (%i6) symmdifference (S_1, S_2);
          (%o6)                        {1, a}
          (%i7) symmdifference (S_1, S_2, S_3);
          (%o7)                        {1, b, z}
          (%i8) symmdifference ({}, S_1, S_2, S_3);
          (%o8)                        {1,b, z}


 -- Function: tree_reduce (<F>, <s>)
 -- Function: tree_reduce (<F>, <s>, <s_0>)
     Extends the binary function <F> to an n-ary function by
     composition, where <s> is a set or list.

     `tree_reduce' is equivalent to the following: Apply <F> to
     successive pairs of elements to form a new list `[<F>(<s_1>,
     <s_2>), <F>(<s_3>, <s_4>), ...]', carrying the final element
     unchanged if there are an odd number of elements.  Then repeat
     until the list is reduced to a single element, which is the return
     value.

     When the optional argument <s_0> is present, the result is
     equivalent `tree_reduce(<F>, cons(<s_0>, <s>)'.

     For addition of floating point numbers, `tree_reduce' may return a
     sum that has a smaller rounding error than either `rreduce' or
     `lreduce'.

     The elements of <s> and the partial results may be arranged in a
     minimum-depth binary tree, thus the name "tree_reduce".

     Examples:

     `tree_reduce' applied to a list with an even number of elements.

          (%i1) tree_reduce (f, [a, b, c, d]);
          (%o1)                  f(f(a, b), f(c, d))

     `tree_reduce' applied to a list with an odd number of elements.

          (%i1) tree_reduce (f, [a, b, c, d, e]);
          (%o1)               f(f(f(a, b), f(c, d)), e)


 -- Function: union (<a_1>, ..., <a_n>)
     Returns the union of the sets <a_1> through <a_n>.

     `union()' (with no arguments) returns the empty set.

     `union' complains if any argument is not a literal set.

     Examples:

          (%i1) S_1 : {a, b, c + d, %e};
          (%o1)                   {%e, a, b, d + c}
          (%i2) S_2 : {%pi, %i, %e, c + d};
          (%o2)                 {%e, %i, %pi, d + c}
          (%i3) S_3 : {17, 29, 1729, %pi, %i};
          (%o3)                {17, 29, 1729, %i, %pi}
          (%i4) union ();
          (%o4)                          {}
          (%i5) union (S_1);
          (%o5)                   {%e, a, b, d + c}
          (%i6) union (S_1, S_2);
          (%o6)              {%e, %i, %pi, a, b, d + c}
          (%i7) union (S_1, S_2, S_3);
          (%o7)       {17, 29, 1729, %e, %i, %pi, a, b, d + c}
          (%i8) union ({}, S_1, S_2, S_3);
          (%o8)       {17, 29, 1729, %e, %i, %pi, a, b, d + c}


 -- Function: xreduce (<F>, <s>)
 -- Function: xreduce (<F>, <s>, <s_0>)
     Extends the function <F> to an n-ary function by composition, or,
     if <F> is already n-ary, applies <F> to <s>.  When <F> is not
     n-ary, `xreduce' is the same as `lreduce'.  The argument <s> is a
     list.

     Functions known to be n-ary include addition `+', multiplication
     `*', `and', `or', `max', `min', and `append'.  Functions may also
     be declared n-ary by `declare(<F>, nary)'.  For these functions,
     `xreduce' is expected to be faster than either `rreduce' or
     `lreduce'.

     When the optional argument <s_0> is present, the result is
     equivalent to `xreduce(<s>, cons(<s_0>, <s>))'.

     Floating point addition is not exactly associative; be that as it
     may, `xreduce' applies Maxima's n-ary addition when <s> contains
     floating point numbers.

     Examples:

     `xreduce' applied to a function known to be n-ary.  `F' is called
     once, with all arguments.

          (%i1) declare (F, nary);
          (%o1)                         done
          (%i2) F ([L]) := L;
          (%o2)                      F([L]) := L
          (%i3) xreduce (F, [a, b, c, d, e]);
          (%o3)         [[[[[("[", simp), a], b], c], d], e]

     `xreduce' applied to a function not known to be n-ary.  `G' is
     called several times, with two arguments each time.

          (%i1) G ([L]) := L;
          (%o1)                      G([L]) := L
          (%i2) xreduce (G, [a, b, c, d, e]);
          (%o2)         [[[[[("[", simp), a], b], c], d], e]
          (%i3) lreduce (G, [a, b, c, d, e]);
          (%o3)                 [[[[a, b], c], d], e]



File: maxima.info,  Node: Function Definition,  Next: Program Flow,  Prev: Sets,  Up: Top

36 Function Definition
**********************

* Menu:

* Introduction to Function Definition::
* Function::
* Macros::
* Functions and Variables for Function Definition::


File: maxima.info,  Node: Introduction to Function Definition,  Next: Function,  Prev: Function Definition,  Up: Function Definition

36.1 Introduction to Function Definition
========================================


File: maxima.info,  Node: Function,  Next: Macros,  Prev: Introduction to Function Definition,  Up: Function Definition

36.2 Function
=============

36.2.1 Ordinary functions
-------------------------

To define a function in Maxima you use the `:=' operator.  E.g.

     f(x) := sin(x)

defines a function `f'.  Anonymous functions may also be created using
`lambda'.  For example

     lambda ([i, j], ...)

can be used instead of `f' where

     f(i,j) := block ([], ...);
     map (lambda ([i], i+1), l)

would return a list with 1 added to each term.

   You may also define a function with a variable number of arguments,
by having a final argument which is assigned to a list of the extra
arguments:

     (%i1) f ([u]) := u;
     (%o1)                      f([u]) := u
     (%i2) f (1, 2, 3, 4);
     (%o2)                     [1, 2, 3, 4]
     (%i3) f (a, b, [u]) := [a, b, u];
     (%o3)               f(a, b, [u]) := [a, b, u]
     (%i4) f (1, 2, 3, 4, 5, 6);
     (%o4)                 [1, 2, [3, 4, 5, 6]]

   The right hand side of a function is an expression.  Thus if you
want a sequence of expressions, you do

     f(x) := (expr1, expr2, ...., exprn);

   and the value of <exprn> is what is returned by the function.

   If you wish to make a `return' from some expression inside the
function then you must use `block' and `return'.

     block ([], expr1, ..., if (a > 10) then return(a), ..., exprn)

   is itself an expression, and so could take the place of the right
hand side of a function definition.  Here it may happen that the return
happens earlier than the last expression.

   The first `[]' in the block, may contain a list of variables and
variable assignments, such as `[a: 3, b, c: []]', which would cause the
three variables `a',`b',and `c' to not refer to their global values,
but rather have these special values for as long as the code executes
inside the `block', or inside functions called from inside the `block'.
This is called dynamic binding, since the variables last from the
start of the block to the time it exits.  Once you return from the
`block', or throw out of it, the old values (if any) of the variables
will be restored.  It is certainly a good idea to protect your
variables in this way.  Note that the assignments in the block
variables, are done in parallel.  This means, that if you had used `c:
a' in the above, the value of `c' would have been the value of `a' at
the time you just entered the block, but before `a' was bound.  Thus
doing something like

     block ([a: a], expr1, ... a: a+3, ..., exprn)

   will protect the external value of `a' from being altered, but would
let you access what that value was.  Thus the right hand side of the
assignments, is evaluated in the entering context, before any binding
occurs.  Using just `block ([x], ...' would cause the `x' to have itself
as value, just as if it would have if you entered a fresh Maxima
session.

   The actual arguments to a function are treated in exactly same way as
the variables in a block.  Thus in

     f(x) := (expr1, ..., exprn);

   and

     f(1);

   we would have a similar context for evaluation of the expressions as
if we had done

     block ([x: 1], expr1, ..., exprn)

   Inside functions, when the right hand side of a definition, may be
computed at runtime, it is useful to use `define' and possibly `buildq'.

36.2.2 Array functions
----------------------

An array function stores the function value the first time it is called
with a given argument, and returns the stored value, without
recomputing it, when that same argument is given.  Such a function is
often called a memoizing function.

   Array function names are appended to the global list `arrays' (not
the global list `functions').  `arrayinfo' returns the list of
arguments for which there are stored values, and `listarray' returns the
stored values.  `dispfun' and `fundef' return the array function
definition.

   `arraymake' constructs an array function call, analogous to
`funmake' for ordinary functions.  `arrayapply' applies an array
function to its arguments, analogous to `apply' for ordinary functions.
There is nothing exactly analogous to `map' for array functions,
although `map(lambda([<x>], <a>[<x>]), <L>)' or `makelist(<a>[<x>],
<x>, <L>)', where <L> is a list, are not too far off the mark.

   `remarray' removes an array function definition (including any stored
function values), analogous to `remfunction' for ordinary functions.

   `kill(<a>[<x>])' removes the value of the array function <a> stored
for the argument <x>; the next time <a> is called with argument <x>,
the function value is recomputed.  However, there is no way to remove
all of the stored values at once, except for `kill(<a>)' or
`remarray(<a>)', which also remove the function definition.


File: maxima.info,  Node: Macros,  Next: Functions and Variables for Function Definition,  Prev: Function,  Up: Function Definition

36.3 Macros
===========

 -- Function: buildq (<L>, <expr>)
     Substitutes variables named by the list <L> into the expression
     <expr>, in parallel, without evaluating <expr>.  The resulting
     expression is simplified, but not evaluated, after `buildq'
     carries out the substitution.

     The elements of <L> are symbols or assignment expressions
     `<symbol>: <value>', evaluated in parallel.  That is, the binding
     of a variable on the right-hand side of an assignment is the
     binding of that variable in the context from which `buildq' was
     called, not the binding of that variable in the variable list <L>.
     If some variable in <L> is not given an explicit assignment, its
     binding in `buildq' is the same as in the context from which
     `buildq' was called.

     Then the variables named by <L> are substituted into <expr> in
     parallel.  That is, the substitution for every variable is
     determined before any substitution is made, so the substitution
     for one variable has no effect on any other.

     If any variable <x> appears as `splice (<x>)' in <expr>, then <x>
     must be bound to a list, and the list is spliced (interpolated)
     into <expr> instead of substituted.

     Any variables in <expr> not appearing in <L> are carried into the
     result verbatim, even if they have bindings in the context from
     which `buildq' was called.

     Examples

     `a' is explicitly bound to `x', while `b' has the same binding
     (namely 29) as in the calling context, and `c' is carried through
     verbatim.  The resulting expression is not evaluated until the
     explicit evaluation `''%'.

          (%i1) (a: 17, b: 29, c: 1729)$
          (%i2) buildq ([a: x, b], a + b + c);
          (%o2)                      x + c + 29
          (%i3) ''%;
          (%o3)                       x + 1758

     `e' is bound to a list, which appears as such in the arguments of
     `foo', and interpolated into the arguments of `bar'.

          (%i1) buildq ([e: [a, b, c]], foo (x, e, y));
          (%o1)                 foo(x, [a, b, c], y)
          (%i2) buildq ([e: [a, b, c]], bar (x, splice (e), y));
          (%o2)                  bar(x, a, b, c, y)

     The result is simplified after substitution.  If simplification
     were applied before substitution, these two results would be the
     same.

          (%i1) buildq ([e: [a, b, c]], splice (e) + splice (e));
          (%o1)                    2 c + 2 b + 2 a
          (%i2) buildq ([e: [a, b, c]], 2 * splice (e));
          (%o2)                        2 a b c

     The variables in <L> are bound in parallel; if bound sequentially,
     the first result would be `foo (b, b)'.  Substitutions are carried
     out in parallel; compare the second result with the result of
     `subst', which carries out substitutions sequentially.

          (%i1) buildq ([a: b, b: a], foo (a, b));
          (%o1)                       foo(b, a)
          (%i2) buildq ([u: v, v: w, w: x, x: y, y: z, z: u],
                        bar (u, v, w, x, y, z));
          (%o2)                 bar(v, w, x, y, z, u)
          (%i3) subst ([u=v, v=w, w=x, x=y, y=z, z=u],
                       bar (u, v, w, x, y, z));
          (%o3)                 bar(u, u, u, u, u, u)

     Construct a list of equations with some variables or expressions
     on the left-hand side and their values on the right-hand side.
     `macroexpand' shows the expression returned by `show_values'.

          (%i1) show_values ([L]) ::= buildq ([L], map ("=", 'L, L));
          (%o1)   show_values([L]) ::= buildq([L], map("=", 'L, L))
          (%i2) (a: 17, b: 29, c: 1729)$
          (%i3) show_values (a, b, c - a - b);
          (%o3)          [a = 17, b = 29, c - b - a = 1683]
          (%i4) macroexpand (show_values (a, b, c - a - b));
          (%o4)    map(=, '([a, b, c - b - a]), [a, b, c - b - a])

     Given a function of several arguments, create another function for
     which some of the arguments are fixed.

          (%i1) curry (f, [a]) :=
                  buildq ([f, a], lambda ([[x]], apply (f, append (a, x))))$
          (%i2) by3 : curry ("*", 3);
          (%o2)        lambda([[x]], apply(*, append([3], x)))
          (%i3) by3 (a + b);
          (%o3)                       3 (b + a)


 -- Function: macroexpand (<expr>)
     Returns the macro expansion of <expr> without evaluating it, when
     `expr' is a macro function call.  Otherwise, `macroexpand' returns
     <expr>.

     If the expansion of <expr> yields another macro function call,
     that macro function call is also expanded.

     `macroexpand' quotes its argument.  However, if the expansion of a
     macro function call has side effects, those side effects are
     executed.

     See also `::=', `macros', and `macroexpand1'.

     Examples

          (%i1) g (x) ::= x / 99;
                                              x
          (%o1)                      g(x) ::= --
                                              99
          (%i2) h (x) ::= buildq ([x], g (x - a));
          (%o2)            h(x) ::= buildq([x], g(x - a))
          (%i3) a: 1234;
          (%o3)                         1234
          (%i4) macroexpand (h (y));
                                        y - a
          (%o4)                         -----
                                         99
          (%i5) h (y);
                                      y - 1234
          (%o5)                       --------
                                         99


 -- Function: macroexpand1 (<expr>)
     Returns the macro expansion of <expr> without evaluating it, when
     `expr' is a macro function call.  Otherwise, `macroexpand1'
     returns <expr>.

     `macroexpand1' quotes its argument.  However, if the expansion of
     a macro function call has side effects, those side effects are
     executed.

     If the expansion of <expr> yields another macro function call,
     that macro function call is not expanded.

     See also `::=', `macros', and `macroexpand'.

     Examples

          (%i1) g (x) ::= x / 99;
                                              x
          (%o1)                      g(x) ::= --
                                              99
          (%i2) h (x) ::= buildq ([x], g (x - a));
          (%o2)            h(x) ::= buildq([x], g(x - a))
          (%i3) a: 1234;
          (%o3)                         1234
          (%i4) macroexpand1 (h (y));
          (%o4)                       g(y - a)
          (%i5) h (y);
                                      y - 1234
          (%o5)                       --------
                                         99


 -- Global variable: macros
     Default value: `[]'

     `macros' is the list of user-defined macro functions.  The macro
     function definition operator `::=' puts a new macro function onto
     this list, and `kill', `remove', and `remfunction' remove macro
     functions from the list.

     See also `infolists'.


 -- Function: splice (<a>)
     Splices (interpolates) the list named by the atom <a> into an
     expression, but only if `splice' appears within `buildq';
     otherwise, `splice' is treated as an undefined function.  If
     appearing within `buildq' as <a> alone (without `splice'), <a> is
     substituted (not interpolated) as a list into the result.  The
     argument of `splice' can only be an atom; it cannot be a literal
     list or an expression which yields a list.

     Typically `splice' supplies the arguments for a function or
     operator.  For a function `f', the expression `f (splice (<a>))'
     within `buildq' expands to `f (<a>[1], <a>[2], <a>[3], ...)'.  For
     an operator `o', the expression `"o" (splice (<a>)' within
     `buildq' expands to `"o" (<a>[1], <a>[2], <a>[3], ...)', where `o'
     may be any type of operator (typically one which takes multiple
     arguments).  Note that the operator must be enclosed in double
     quotes `"'.

     Examples

          (%i1) buildq ([x: [1, %pi, z - y]], foo (splice (x)) / length (x));
                                 foo(1, %pi, z - y)
          (%o1)                -----------------------
                               length([1, %pi, z - y])
          (%i2) buildq ([x: [1, %pi]], "/" (splice (x)));
                                          1
          (%o2)                          ---
                                         %pi
          (%i3) matchfix ("<>", "<>");
          (%o3)                          <>
          (%i4) buildq ([x: [1, %pi, z - y]], "<>" (splice (x)));
          (%o4)                   <>1, %pi, z - y<>



File: maxima.info,  Node: Functions and Variables for Function Definition,  Prev: Macros,  Up: Function Definition

36.4 Functions and Variables for Function Definition
====================================================

 -- Function: apply (<F>, [<x_1>, ..., <x_n>])
     Constructs and evaluates an expression `<F>(<arg_1>, ...,
     <arg_n>)'.

     `apply' does not attempt to distinguish array functions from
     ordinary functions; when <F> is the name of an array function,
     `apply' evaluates `<F>(...)' (that is, a function call with
     parentheses instead of square brackets).  `arrayapply' evaluates a
     function call with square brackets in this case.

     Examples:

     `apply' evaluates its arguments.  In this example, `min' is
     applied to the value of `L'.

          (%i1) L : [1, 5, -10.2, 4, 3];
          (%o1)                 [1, 5, - 10.2, 4, 3]
          (%i2) apply (min, L);
          (%o2)                        - 10.2

     `apply' evaluates arguments, even if the function <F> quotes them.

          (%i1) F (x) := x / 1729;
                                             x
          (%o1)                     F(x) := ----
                                            1729
          (%i2) fname : F;
          (%o2)                           F
          (%i3) dispfun (F);
                                             x
          (%t3)                     F(x) := ----
                                            1729

          (%o3)                         [%t3]
          (%i4) dispfun (fname);
          fname is not the name of a user function.
           -- an error.  Quitting.  To debug this try debugmode(true);
          (%i5) apply (dispfun, [fname]);
                                             x
          (%t5)                     F(x) := ----
                                            1729
          (%o5)                         [%t5]

     `apply' evaluates the function name <F>.  Single quote `'' defeats
     evaluation.  `demoivre' is the name of a global variable and also
     a function.

          (%i1) demoivre;
          (%o1)                         false
          (%i2) demoivre (exp (%i * x));
          (%o2)                  %i sin(x) + cos(x)
          (%i3) apply (demoivre, [exp (%i * x)]);
          demoivre evaluates to false
          Improper name or value in functional position.
           -- an error.  Quitting.  To debug this try debugmode(true);
          (%i4) apply ('demoivre, [exp (%i * x)]);
          (%o4)                  %i sin(x) + cos(x)


 -- Function: block ([<v_1>, ..., <v_m>], <expr_1>, ..., <expr_n>)
 -- Function: block (<expr_1>, ..., <expr_n>)
     `block' evaluates <expr_1>, ..., <expr_n> in sequence and returns
     the value of the last expression evaluated.  The sequence can be
     modified by the `go', `throw', and `return' functions.  The last
     expression is <expr_n> unless `return' or an expression containing
     `throw' is evaluated.  Some variables <v_1>, ..., <v_m> can be
     declared local to the block; these are distinguished from global
     variables of the same names.  If no variables are declared local
     then the list may be omitted.  Within the block, any variable
     other than <v_1>, ..., <v_m> is a global variable.

     `block' saves the current values of the variables <v_1>, ...,
     <v_m> (if any) upon entry to the block, then unbinds the variables
     so that they evaluate to themselves.  The local variables may be
     bound to arbitrary values within the block but when the block is
     exited the saved values are restored, and the values assigned
     within the block are lost.

     The declaration `local(<v_1>, ..., <v_m>)' within `block' saves
     the properties associated with the symbols <v_1>, ..., <v_m>,
     removes any properties before evaluating other expressions, and
     restores any saved properties on exit from the block.  Some
     declarations are implemented as properties of a symbol, including
     `:=', `array', `dependencies', `atvalue', `matchdeclare',
     `atomgrad', `constant', `nonscalar', `assume', and some others.
     The effect of `local' is to make such declarations effective only
     within the block; otherwise declarations within a block are
     actually global declarations.

     `block' may appear within another `block'.  Local variables are
     established each time a new `block' is evaluated.  Local variables
     appear to be global to any enclosed blocks.  If a variable is
     non-local in a block, its value is the value most recently
     assigned by an enclosing block, if any, otherwise, it is the value
     of the variable in the global environment.  This policy may
     coincide with the usual understanding of "dynamic scope".

     The value of the block is the value of the last statement or the
     value of the argument to the function `return' which may be used
     to exit explicitly from the block. The function `go' may be used
     to transfer control to the statement of the block that is tagged
     with the argument to `go'.  To tag a statement, precede it by an
     atomic argument as another statement in the block.  For example:
     `block ([x], x:1, loop, x: x+1, ..., go(loop), ...)'.  The
     argument to `go' must be the name of a tag appearing within the
     block.  One cannot use `go' to transfer to a tag in a block other
     than the one containing the `go'.

     Blocks typically appear on the right side of a function definition
     but can be used in other places as well.


 -- Function: break (<expr_1>, ..., <expr_n>)
     Evaluates and prints <expr_1>, ..., <expr_n> and then causes a
     Maxima break at which point the user can examine and change his
     environment.  Upon typing `exit;' the computation resumes.


 -- Function: catch (<expr_1>, ..., <expr_n>)
     Evaluates <expr_1>, ..., <expr_n> one by one; if any leads to the
     evaluation of an expression of the form `throw (arg)', then the
     value of the `catch' is the value of `throw (arg)', and no further
     expressions are evaluated.  This "non-local return" thus goes
     through any depth of nesting to the nearest enclosing `catch'.  If
     there is no `catch' enclosing a `throw', an error message is
     printed.

     If the evaluation of the arguments does not lead to the evaluation
     of any `throw' then the value of `catch' is the value of <expr_n>.

          (%i1) lambda ([x], if x < 0 then throw(x) else f(x))$
          (%i2) g(l) := catch (map (''%, l))$
          (%i3) g ([1, 2, 3, 7]);
          (%o3)               [f(1), f(2), f(3), f(7)]
          (%i4) g ([1, 2, -3, 7]);
          (%o4)                          - 3

     The function `g' returns a list of `f' of each element of `l' if
     `l' consists only of non-negative numbers; otherwise, `g' "catches"
     the first negative element of `l' and "throws" it up.


 -- Function: compfile (<filename>, <f_1>, ..., <f_n>)
 -- Function: compfile (<filename>, functions)
 -- Function: compfile (<filename>, all)
     Translates Maxima functions into Lisp and writes the translated
     code into the file <filename>.

     `compfile(<filename>, <f_1>, ..., <f_n>)' translates the specified
     functions.  `compfile (<filename>, functions)' and `compfile
     (<filename>, all)' translate all user-defined functions.

     The Lisp translations are not evaluated, nor is the output file
     processed by the Lisp compiler.  `translate' creates and evaluates
     Lisp translations.  `compile_file' translates Maxima into Lisp,
     and then executes the Lisp compiler.

     See also `translate', `translate_file', and `compile_file'.


 -- Function: compile (<f_1>, ..., <f_n>)
 -- Function: compile (functions)
 -- Function: compile (all)
     Translates Maxima functions <f_1>, ..., <f_n> into Lisp, evaluates
     the Lisp translations, and calls the Lisp function `COMPILE' on
     each translated function.  `compile' returns a list of the names
     of the compiled functions.

     `compile (all)' or `compile (functions)' compiles all user-defined
     functions.

     `compile' quotes its arguments; the quote-quote operator `'''
     defeats quotation.


 -- Function: define (<f>(<x_1>, ..., <x_n>), <expr>)
 -- Function: define (<f>[<x_1>, ..., <x_n>], <expr>)
 -- Function: define (funmake (<f>, [<x_1>, ..., <x_n>]), <expr>)
 -- Function: define (arraymake (<f>, [<x_1>, ..., <x_n>]), <expr>)
 -- Function: define (ev (<expr_1>), <expr_2>)
     Defines a function named <f> with arguments <x_1>, ..., <x_n> and
     function body <expr>.  `define' always evaluates its second
     argument (unless explicitly quoted).  The function so defined may
     be an ordinary Maxima function (with arguments enclosed in
     parentheses) or an array function (with arguments enclosed in
     square brackets).

     When the last or only function argument <x_n> is a list of one
     element, the function defined by `define' accepts a variable
     number of arguments.  Actual arguments are assigned one-to-one to
     formal arguments <x_1>, ..., <x_(n - 1)>, and any further actual
     arguments, if present, are assigned to <x_n> as a list.

     When the first argument of `define' is an expression of the form
     `<f>(<x_1>, ..., <x_n>)' or `<f>[<x_1>, ..., <x_n>]', the function
     arguments are evaluated but <f> is not evaluated, even if there is
     already a function or variable by that name.

     When the first argument is an expression with operator `funmake',
     `arraymake', or `ev', the first argument is evaluated; this allows
     for the function name to be computed, as well as the body.

     All function definitions appear in the same namespace; defining a
     function `f' within another function `g' does not automatically
     limit the scope of `f' to `g'.  However, `local(f)' makes the
     definition of function `f' effective only within the block or
     other compound expression in which `local' appears.

     If some formal argument <x_k> is a quoted symbol (after
     evaluation), the function defined by `define' does not evaluate
     the corresponding actual argument.  Otherwise all actual arguments
     are evaluated.

     See also `:=' and `::='.

     Examples:

     `define' always evaluates its second argument (unless explicitly
     quoted).

          (%i1) expr : cos(y) - sin(x);
          (%o1)                    cos(y) - sin(x)
          (%i2) define (F1 (x, y), expr);
          (%o2)              F1(x, y) := cos(y) - sin(x)
          (%i3) F1 (a, b);
          (%o3)                    cos(b) - sin(a)
          (%i4) F2 (x, y) := expr;
          (%o4)                   F2(x, y) := expr
          (%i5) F2 (a, b);
          (%o5)                    cos(y) - sin(x)

     The function defined by `define' may be an ordinary Maxima
     function or an array function.

          (%i1) define (G1 (x, y), x.y - y.x);
          (%o1)               G1(x, y) := x . y - y . x
          (%i2) define (G2 [x, y], x.y - y.x);
          (%o2)                G2     := x . y - y . x
                                 x, y

     When the last or only function argument <x_n> is a list of one
     element, the function defined by `define' accepts a variable
     number of arguments.

          (%i1) define (H ([L]), '(apply ("+", L)));
          (%o1)                H([L]) := apply("+", L)
          (%i2) H (a, b, c);
          (%o2)                       c + b + a

     When the first argument is an expression with operator `funmake',
     `arraymake', or `ev', the first argument is evaluated.

          (%i1) [F : I, u : x];
          (%o1)                        [I, x]
          (%i2) funmake (F, [u]);
          (%o2)                         I(x)
          (%i3) define (funmake (F, [u]), cos(u) + 1);
          (%o3)                  I(x) := cos(x) + 1
          (%i4) define (arraymake (F, [u]), cos(u) + 1);
          (%o4)                   I  := cos(x) + 1
                                   x
          (%i5) define (foo (x, y), bar (y, x));
          (%o5)                foo(x, y) := bar(y, x)
          (%i6) define (ev (foo (x, y)), sin(x) - cos(y));
          (%o6)             bar(y, x) := sin(x) - cos(y)


 -- Function: define_variable (<name>, <default_value>, <mode>)
     Introduces a global variable into the Maxima environment.
     `define_variable' is useful in user-written packages, which are
     often translated or compiled.

     `define_variable' carries out the following steps:

       1. `mode_declare (<name>, <mode>)' declares the mode of <name> to
          the translator.  See `mode_declare' for a list of the
          possible modes.

       2. If the variable is unbound, <default_value> is assigned to
          <name>.

       3. `declare (<name>, special)' declares it special.

       4. Associates <name> with a test function to ensure that <name>
          is only assigned values of the declared mode.

     The `value_check' property can be assigned to any variable which
     has been defined via `define_variable' with a mode other than
     `any'.  The `value_check' property is a lambda expression or the
     name of a function of one variable, which is called when an
     attempt is made to assign a value to the variable.  The argument
     of the `value_check' function is the would-be assigned value.

     `define_variable' evaluates `default_value', and quotes `name' and
     `mode'.  `define_variable' returns the current value of `name',
     which is `default_value' if `name' was unbound before, and
     otherwise it is the previous value of `name'.

     Examples:

     `foo' is a Boolean variable, with the initial value `true'.

          (%i1) define_variable (foo, true, boolean);
          (%o1)                         true
          (%i2) foo;
          (%o2)                         true
          (%i3) foo: false;
          (%o3)                         false
          (%i4) foo: %pi;
          Error: foo was declared mode boolean, has value: %pi
           -- an error.  Quitting.  To debug this try debugmode(true);
          (%i5) foo;
          (%o5)                         false

     `bar' is an integer variable, which must be prime.

          (%i1) define_variable (bar, 2, integer);
          (%o1)                           2
          (%i2) qput (bar, prime_test, value_check);
          (%o2)                      prime_test
          (%i3) prime_test (y) := if not primep(y) then
                                     error (y, "is not prime.");
          (%o3) prime_test(y) := if not primep(y)

                                             then error(y, "is not prime.")
          (%i4) bar: 1439;
          (%o4)                         1439
          (%i5) bar: 1440;
          1440 is not prime.
          #0: prime_test(y=1440)
           -- an error.  Quitting.  To debug this try debugmode(true);
          (%i6) bar;
          (%o6)                         1439

     `baz_quux' is a variable which cannot be assigned a value.  The
     mode `any_check' is like `any', but `any_check' enables the
     `value_check' mechanism, and `any' does not.

          (%i1) define_variable (baz_quux, 'baz_quux, any_check);
          (%o1)                       baz_quux
          (%i2) F: lambda ([y], if y # 'baz_quux then
                           error ("Cannot assign to `baz_quux'."));
          (%o2) lambda([y], if y # 'baz_quux

                                  then error(Cannot assign to `baz_quux'.))
          (%i3) qput (baz_quux, ''F, value_check);
          (%o3) lambda([y], if y # 'baz_quux

                                  then error(Cannot assign to `baz_quux'.))
          (%i4) baz_quux: 'baz_quux;
          (%o4)                       baz_quux
          (%i5) baz_quux: sqrt(2);
          Cannot assign to `baz_quux'.
          #0: lambda([y],if y # 'baz_quux then
                           error("Cannot assign to `baz_quux'."))(y=sqrt(2))
           -- an error.  Quitting.  To debug this try debugmode(true);
          (%i6) baz_quux;
          (%o6)                       baz_quux


 -- Function: dispfun (<f_1>, ..., <f_n>)
 -- Function: dispfun (all)
     Displays the definition of the user-defined functions <f_1>, ...,
     <f_n>.  Each argument may be the name of a macro (defined with
     `::='), an ordinary function (defined with `:=' or `define'), an
     array function (defined with `:=' or `define', but enclosing
     arguments in square brackets `[ ]'), a subscripted function,
     (defined with `:=' or `define', but enclosing some arguments in
     square brackets and others in parentheses `( )') one of a family
     of subscripted functions selected by a particular subscript value,
     or a subscripted function defined with a constant subscript.

     `dispfun (all)' displays all user-defined functions as given by
     the `functions', `arrays', and `macros' lists, omitting
     subscripted functions defined with constant subscripts.

     `dispfun' creates an intermediate expression label (`%t1', `%t2',
     etc.)  for each displayed function, and assigns the function
     definition to the label.  In contrast, `fundef' returns the
     function definition.

     `dispfun' quotes its arguments; the quote-quote operator `'''
     defeats quotation.  `dispfun' returns the list of intermediate
     expression labels corresponding to the displayed functions.

     Examples:

          (%i1) m(x, y) ::= x^(-y);
                                               - y
          (%o1)                   m(x, y) ::= x
          (%i2) f(x, y) :=  x^(-y);
                                               - y
          (%o2)                    f(x, y) := x
          (%i3) g[x, y] :=  x^(-y);
                                              - y
          (%o3)                     g     := x
                                     x, y
          (%i4) h[x](y) :=  x^(-y);
                                              - y
          (%o4)                     h (y) := x
                                     x
          (%i5) i[8](y) :=  8^(-y);
                                              - y
          (%o5)                     i (y) := 8
                                     8
          (%i6) dispfun (m, f, g, h, h[5], h[10], i[8]);
                                               - y
          (%t6)                   m(x, y) ::= x
                                               - y
          (%t7)                    f(x, y) := x

                                              - y
          (%t8)                     g     := x
                                     x, y

                                              - y
          (%t9)                     h (y) := x
                                     x

                                              1
          (%t10)                     h (y) := --
                                      5        y
                                              5

                                               1
          (%t11)                    h  (y) := ---
                                     10         y
                                              10

                                              - y
          (%t12)                    i (y) := 8
                                     8

          (%o12)       [%t6, %t7, %t8, %t9, %t10, %t11, %t12]
          (%i12) ''%;
                               - y              - y            - y
          (%o12) [m(x, y) ::= x   , f(x, y) := x   , g     := x   ,
                                                      x, y
                            - y           1              1             - y
                  h (y) := x   , h (y) := --, h  (y) := ---, i (y) := 8   ]
                   x              5        y   10         y   8
                                          5             10


 -- Function: fullmap (<f>, <expr_1>, ...)
     Similar to `map', but `fullmap' keeps mapping down all
     subexpressions until the main operators are no longer the same.

     `fullmap' is used by the Maxima simplifier for certain matrix
     manipulations; thus, Maxima sometimes generates an error message
     concerning `fullmap' even though `fullmap' was not explicitly
     called by the user.

     Examples:

          (%i1) a + b * c;
          (%o1)                        b c + a
          (%i2) fullmap (g, %);
          (%o2)                   g(b) g(c) + g(a)
          (%i3) map (g, %th(2));
          (%o3)                     g(b c) + g(a)


 -- Function: fullmapl (<f>, <list_1>, ...)
     Similar to `fullmap', but `fullmapl' only maps onto lists and
     matrices.

     Example:

          (%i1) fullmapl ("+", [3, [4, 5]], [[a, 1], [0, -1.5]]);
          (%o1)                [[a + 3, 4], [4, 3.5]]


 -- System variable: functions
     Default value: `[]'

     `functions' is the list of ordinary Maxima functions in the
     current session.  An ordinary function is a function constructed by
     `define' or `:=' and called with parentheses `()'.  A function may
     be defined at the Maxima prompt or in a Maxima file loaded by
     `load' or `batch'.

     Array functions (called with square brackets, e.g., `F[x]') and
     subscripted functions (called with square brackets and
     parentheses, e.g., `F[x](y)') are listed by the global variable
     `arrays', and not by `functions'.

     Lisp functions are not kept on any list.

     Examples:

          (%i1) F_1 (x) := x - 100;
          (%o1)                   F_1(x) := x - 100
          (%i2) F_2 (x, y) := x / y;
                                                x
          (%o2)                    F_2(x, y) := -
                                                y
          (%i3) define (F_3 (x), sqrt (x));
          (%o3)                   F_3(x) := sqrt(x)
          (%i4) G_1 [x] := x - 100;
          (%o4)                    G_1  := x - 100
                                      x
          (%i5) G_2 [x, y] := x / y;
                                               x
          (%o5)                     G_2     := -
                                       x, y    y
          (%i6) define (G_3 [x], sqrt (x));
          (%o6)                    G_3  := sqrt(x)
                                      x
          (%i7) H_1 [x] (y) := x^y;
                                                y
          (%o7)                     H_1 (y) := x
                                       x
          (%i8) functions;
          (%o8)              [F_1(x), F_2(x, y), F_3(x)]
          (%i9) arrays;
          (%o9)                 [G_1, G_2, G_3, H_1]


 -- Function: fundef (<f>)
     Returns the definition of the function <f>.

     The argument may be the name of a macro (defined with `::='), an
     ordinary function (defined with `:=' or `define'), an array
     function (defined with `:=' or `define', but enclosing arguments
     in square brackets `[ ]'), a subscripted function, (defined with
     `:=' or `define', but enclosing some arguments in square brackets
     and others in parentheses `( )') one of a family of subscripted
     functions selected by a particular subscript value, or a
     subscripted function defined with a constant subscript.

     `fundef' quotes its argument; the quote-quote operator `'''
     defeats quotation.

     `fundef (<f>)' returns the definition of <f>.  In contrast,
     `dispfun (<f>)' creates an intermediate expression label and
     assigns the definition to the label.


 -- Function: funmake (<F>, [<arg_1>, ..., <arg_n>])
     Returns an expression `<F>(<arg_1>, ..., <arg_n>)'.  The return
     value is simplified, but not evaluated, so the function <F> is not
     called, even if it exists.

     `funmake' does not attempt to distinguish array functions from
     ordinary functions; when <F> is the name of an array function,
     `funmake' returns `<F>(...)' (that is, a function call with
     parentheses instead of square brackets).  `arraymake' returns a
     function call with square brackets in this case.

     `funmake' evaluates its arguments.

     Examples:

     `funmake' applied to an ordinary Maxima function.

          (%i1) F (x, y) := y^2 - x^2;
                                             2    2
          (%o1)                  F(x, y) := y  - x
          (%i2) funmake (F, [a + 1, b + 1]);
          (%o2)                    F(a + 1, b + 1)
          (%i3) ''%;
                                        2          2
          (%o3)                  (b + 1)  - (a + 1)

     `funmake' applied to a macro.

          (%i1) G (x) ::= (x - 1)/2;
                                            x - 1
          (%o1)                    G(x) ::= -----
                                              2
          (%i2) funmake (G, [u]);
          (%o2)                         G(u)
          (%i3) ''%;
                                        u - 1
          (%o3)                         -----
                                          2

     `funmake' applied to a subscripted function.

          (%i1) H [a] (x) := (x - 1)^a;
                                                  a
          (%o1)                   H (x) := (x - 1)
                                   a
          (%i2) funmake (H [n], [%e]);
                                                 n
          (%o2)               lambda([x], (x - 1) )(%e)
          (%i3) ''%;
                                              n
          (%o3)                       (%e - 1)
          (%i4) funmake ('(H [n]), [%e]);
          (%o4)                        H (%e)
                                        n
          (%i5) ''%;
                                              n
          (%o5)                       (%e - 1)

     `funmake' applied to a symbol which is not a defined function of
     any kind.

          (%i1) funmake (A, [u]);
          (%o1)                         A(u)
          (%i2) ''%;
          (%o2)                         A(u)

     `funmake' evaluates its arguments, but not the return value.

          (%i1) det(a,b,c) := b^2 -4*a*c;
                                              2
          (%o1)              det(a, b, c) := b  - 4 a c
          (%i2) (x : 8, y : 10, z : 12);
          (%o2)                          12
          (%i3) f : det;
          (%o3)                          det
          (%i4) funmake (f, [x, y, z]);
          (%o4)                    det(8, 10, 12)
          (%i5) ''%;
          (%o5)                         - 284

     Maxima simplifies `funmake''s return value.

          (%i1) funmake (sin, [%pi / 2]);
          (%o1)                           1


 -- Function: lambda ([<x_1>, ..., <x_m>], <expr_1>, ..., <expr_n>)
 -- Function: lambda ([[<L>]], <expr_1>, ..., <expr_n>)
 -- Function: lambda ([<x_1>, ..., <x_m>, [<L>]], <expr_1>, ...,
          <expr_n>)
     Defines and returns a lambda expression (that is, an anonymous
     function).  The function may have required arguments <x_1>, ...,
     <x_m> and/or optional arguments <L>, which appear within the
     function body as a list.  The return value of the function is
     <expr_n>.  A lambda expression can be assigned to a variable and
     evaluated like an ordinary function.  A lambda expression may
     appear in some contexts in which a function name is expected.

     When the function is evaluated, unbound local variables <x_1>, ...,
     <x_m> are created.  `lambda' may appear within `block' or another
     `lambda'; local variables are established each time another
     `block' or `lambda' is evaluated.  Local variables appear to be
     global to any enclosed `block' or `lambda'.  If a variable is not
     local, its value is the value most recently assigned in an
     enclosing `block' or `lambda', if any, otherwise, it is the value
     of the variable in the global environment.  This policy may
     coincide with the usual understanding of "dynamic scope".

     After local variables are established, <expr_1> through <expr_n>
     are evaluated in turn.  The special variable `%%', representing
     the value of the preceding expression, is recognized.  `throw' and
     `catch' may also appear in the list of expressions.

     `return' cannot appear in a lambda expression unless enclosed by
     `block', in which case `return' defines the return value of the
     block and not of the lambda expression, unless the block happens
     to be <expr_n>.  Likewise, `go' cannot appear in a lambda
     expression unless enclosed by `block'.

     `lambda' quotes its arguments; the quote-quote operator `'''
     defeats quotation.

     Examples:

        * A lambda expression can be assigned to a variable and
          evaluated like an ordinary function.

          (%i1) f: lambda ([x], x^2);
                                                2
          (%o1)                    lambda([x], x )
          (%i2) f(a);
                                          2
          (%o2)                          a

        * A lambda expression may appear in contexts in which a
          function evaluation is expected.

          (%i3) lambda ([x], x^2) (a);
                                          2
          (%o3)                          a
          (%i4) apply (lambda ([x], x^2), [a]);
                                          2
          (%o4)                          a
          (%i5) map (lambda ([x], x^2), [a, b, c, d, e]);
                                  2   2   2   2   2
          (%o5)                 [a , b , c , d , e ]

        * Argument variables are local variables.  Other variables
          appear to be global variables.  Global variables are
          evaluated at the time the lambda expression is evaluated,
          unless some special evaluation is forced by some means, such
          as `'''.

          (%i6) a: %pi$
          (%i7) b: %e$
          (%i8) g: lambda ([a], a*b);
          (%o8)                   lambda([a], a b)
          (%i9) b: %gamma$
          (%i10) g(1/2);
                                       %gamma
          (%o10)                       ------
                                         2
          (%i11) g2: lambda ([a], a*''b);
          (%o11)                lambda([a], a %gamma)
          (%i12) b: %e$
          (%i13) g2(1/2);
                                       %gamma
          (%o13)                       ------
                                         2

        * Lambda expressions may be nested.  Local variables within the
          outer lambda expression appear to be global to the inner
          expression unless masked by local variables of the same names.

          (%i14) h: lambda ([a, b], h2: lambda ([a], a*b), h2(1/2));
                                                             1
          (%o14)    lambda([a, b], h2 : lambda([a], a b), h2(-))
                                                             2
          (%i15) h(%pi, %gamma);
                                       %gamma
          (%o15)                       ------
                                         2

        * Since `lambda' quotes its arguments, lambda expression `i'
          below does not define a "multiply by `a'" function.  Such a
          function can be defined via `buildq', as in lambda expression
          `i2' below.

          (%i16) i: lambda ([a], lambda ([x], a*x));
          (%o16)            lambda([a], lambda([x], a x))
          (%i17) i(1/2);
          (%o17)                  lambda([x], a x)
          (%i18) i2: lambda([a], buildq([a: a], lambda([x], a*x)));
          (%o18)    lambda([a], buildq([a : a], lambda([x], a x)))
          (%i19) i2(1/2);
                                               x
          (%o19)                   lambda([x], -)
                                               2
          (%i20) i2(1/2)(%pi);
                                         %pi
          (%o20)                         ---
                                          2

        * A lambda expression may take a variable number of arguments,
          which are indicated by `[<L>]' as the sole or final argument.
          The arguments appear within the function body as a list.

          (%i1) f : lambda ([aa, bb, [cc]], aa * cc + bb);
          (%o1)          lambda([aa, bb, [cc]], aa cc + bb)
          (%i2) f (foo, %i, 17, 29, 256);
          (%o2)       [17 foo + %i, 29 foo + %i, 256 foo + %i]
          (%i3) g : lambda ([[aa]], apply ("+", aa));
          (%o3)             lambda([[aa]], apply(+, aa))
          (%i4) g (17, 29, x, y, z, %e);
          (%o4)                  z + y + x + %e + 46


 -- Function: local (<v_1>, ..., <v_n>)
     Saves the properties associated with the symbols <v_1>, ..., <v_n>,
     removes any properties before evaluating other expressions, and
     restores any saved properties on exit from the block or other
     compound expression in which `local' appears.

     Some declarations are implemented as properties of a symbol,
     including `:=', `array', `dependencies', `atvalue',
     `matchdeclare', `atomgrad', `constant', `nonscalar', `assume', and
     some others.  The effect of `local' is to make such declarations
     effective only within the block or other compound expression in
     which `local' appears; otherwise such declarations are global
     declarations.

     `local' can only appear in `block' or in the body of a function
     definition or `lambda' expression, and only one occurrence is
     permitted in each.

     `local' quotes its arguments.  `local' returns `done'.

     Example:

     A local function definition.

          (%i1) foo (x) := 1 - x;
          (%o1)                    foo(x) := 1 - x
          (%i2) foo (100);
          (%o2)                         - 99
          (%i3) block (local (foo), foo (x) := 2 * x, foo (100));
          (%o3)                          200
          (%i4) foo (100);
          (%o4)                         - 99


 -- Option variable: macroexpansion
     Default value: `false'

     `macroexpansion' controls whether the expansion (that is, the
     return value) of a macro function is substituted for the macro
     function call.  A substitution may speed up subsequent expression
     evaluations, at the cost of storing the expansion.

    `false'
          The expansion of a macro function is not substituted for the
          macro function call.

    `expand'
          The first time a macro function call is evaluated, the
          expansion is stored.  The expansion is not recomputed on
          subsequent calls; any side effects (such as `print' or
          assignment to global variables) happen only when the macro
          function call is first evaluated.  Expansion in an expression
          does not affect other expressions which have the same macro
          function call.

    `displace'
          The first time a macro function call is evaluated, the
          expansion is substituted for the call, thus modifying the
          expression from which the macro function was called.  The
          expansion is not recomputed on subsequent calls; any side
          effects happen only when the macro function call is first
          evaluated.  Expansion in an expression does not affect other
          expressions which have the same macro function call.

     Examples

     When `macroexpansion' is `false', a macro function is called every
     time the calling expression is evaluated, and the calling
     expression is not modified.

          (%i1) f (x) := h (x) / g (x);
                                            h(x)
          (%o1)                     f(x) := ----
                                            g(x)
          (%i2) g (x) ::= block (print ("x + 99 is equal to", x),
                                 return (x + 99));
          (%o2) g(x) ::= block(print("x + 99 is equal to", x),
                                                            return(x + 99))
          (%i3) h (x) ::= block (print ("x - 99 is equal to", x),
                                 return (x - 99));
          (%o3) h(x) ::= block(print("x - 99 is equal to", x),
                                                            return(x - 99))
          (%i4) macroexpansion: false;
          (%o4)                         false
          (%i5) f (a * b);
          x - 99 is equal to x
          x + 99 is equal to x
                                      a b - 99
          (%o5)                       --------
                                      a b + 99
          (%i6) dispfun (f);
                                            h(x)
          (%t6)                     f(x) := ----
                                            g(x)

          (%o6)                         done
          (%i7) f (a * b);
          x - 99 is equal to x
          x + 99 is equal to x
                                      a b - 99
          (%o7)                       --------
                                      a b + 99

     When `macroexpansion' is `expand', a macro function is called once,
     and the calling expression is not modified.

          (%i1) f (x) := h (x) / g (x);
                                            h(x)
          (%o1)                     f(x) := ----
                                            g(x)
          (%i2) g (x) ::= block (print ("x + 99 is equal to", x),
                                 return (x + 99));
          (%o2) g(x) ::= block(print("x + 99 is equal to", x),
                                                            return(x + 99))
          (%i3) h (x) ::= block (print ("x - 99 is equal to", x),
                                 return (x - 99));
          (%o3) h(x) ::= block(print("x - 99 is equal to", x),
                                                            return(x - 99))
          (%i4) macroexpansion: expand;
          (%o4)                        expand
          (%i5) f (a * b);
          x - 99 is equal to x
          x + 99 is equal to x
                                      a b - 99
          (%o5)                       --------
                                      a b + 99
          (%i6) dispfun (f);
                                            h(x)
          (%t6)                     f(x) := ----
                                            g(x)

          (%o6)                         done
          (%i7) f (a * b);
                                      a b - 99
          (%o7)                       --------
                                      a b + 99

     When `macroexpansion' is `expand', a macro function is called once,
     and the calling expression is modified.

          (%i1) f (x) := h (x) / g (x);
                                            h(x)
          (%o1)                     f(x) := ----
                                            g(x)
          (%i2) g (x) ::= block (print ("x + 99 is equal to", x),
                                 return (x + 99));
          (%o2) g(x) ::= block(print("x + 99 is equal to", x),
                                                            return(x + 99))
          (%i3) h (x) ::= block (print ("x - 99 is equal to", x),
                                 return (x - 99));
          (%o3) h(x) ::= block(print("x - 99 is equal to", x),
                                                            return(x - 99))
          (%i4) macroexpansion: displace;
          (%o4)                       displace
          (%i5) f (a * b);
          x - 99 is equal to x
          x + 99 is equal to x
                                      a b - 99
          (%o5)                       --------
                                      a b + 99
          (%i6) dispfun (f);
                                           x - 99
          (%t6)                    f(x) := ------
                                           x + 99

          (%o6)                         done
          (%i7) f (a * b);
                                      a b - 99
          (%o7)                       --------
                                      a b + 99


 -- Option variable: mode_checkp
     Default value: `true'

     When `mode_checkp' is `true', `mode_declare' checks the modes of
     bound variables.


 -- Option variable: mode_check_errorp
     Default value: `false'

     When `mode_check_errorp' is `true', `mode_declare' calls error.


 -- Option variable: mode_check_warnp
     Default value: `true'

     When `mode_check_warnp' is `true', mode errors are described.


 -- Function: mode_declare (<y_1>, <mode_1>, ..., <y_n>, <mode_n>)
     `mode_declare' is used to declare the modes of variables and
     functions for subsequent translation or compilation of functions.
     `mode_declare' is typically placed at the beginning of a function
     definition, at the beginning of a Maxima script, or executed at
     the interactive prompt.

     The arguments of `mode_declare' are pairs consisting of a variable
     and a mode which is one of `boolean', `fixnum', `number',
     `rational', or `float'.  Each variable may also be a list of
     variables all of which are declared to have the same mode.

     If a variable is an array, and if every element of the array which
     is referenced has a value then `array (yi, complete, dim1, dim2,
     ...)' rather than
          array(yi, dim1, dim2, ...)
     should be used when first declaring the bounds of the array.  If
     all the elements of the array are of mode `fixnum' (`float'), use
     `fixnum' (`float') instead of `complete'.  Also if every element
     of the array is of the same mode, say `m', then

          mode_declare (completearray (yi), m))

     should be used for efficient translation.

     Numeric code using arrays might run faster by declaring the
     expected size of the array, as in:

          mode_declare (completearray (a [10, 10]), float)

     for a floating point number array which is 10 x 10.

     One may declare the mode of the result of a function by using
     `function (f_1, f_2, ...)' as an argument; here `f_1', `f_2', ...
     are the names of functions.  For example the expression,

          mode_declare ([function (f_1, f_2, ...)], fixnum)

     declares that the values returned by `f_1', `f_2', ... are
     single-word integers.

     `modedeclare' is a synonym for `mode_declare'.


 -- Function: mode_identity (<arg_1>, <arg_2>)
     A special form used with `mode_declare' and `macros' to declare,
     e.g., a list of lists of flonums, or other compound data object.
     The first argument to `mode_identity' is a primitive value mode
     name as given to `mode_declare' (i.e., one of `float', `fixnum',
     `number', `list', or `any'), and the second argument is an
     expression which is evaluated and returned as the value of
     `mode_identity'.  However, if the return value is not allowed by
     the mode declared in the first argument, an error or warning is
     signalled.  The important thing is that the mode of the expression
     as determined by the Maxima to Lisp translator, will be that given
     as the first argument, independent of anything that goes on in the
     second argument.  E.g., `x: 3.3; mode_identity (fixnum, x);'
     yields an error.  `mode_identity (flonum, x)' returns 3.3 .  This
     has a number of uses, e.g., if you knew that `first (l)' returned a
     number then you might write `mode_identity (number, first (l))'.
     However, a more efficient way to do it would be to define a new
     primitive,

          firstnumb (x) ::= buildq ([x], mode_identity (number, x));

     and use `firstnumb' every time you take the first of a list of
     numbers.


 -- Function: remfunction (<f_1>, ..., <f_n>)
 -- Function: remfunction (all)
     Unbinds the function definitions of the symbols <f_1>, ..., <f_n>.
     The arguments may be the names of ordinary functions (created by
     `:='  or `define' ) or macro functions (created by `::=' ).

     `remfunction (all)' unbinds all function definitions.

     `remfunction' quotes its arguments.

     `remfunction' returns a list of the symbols for which the function
     definition was unbound.  `false' is returned in place of any
     symbol for which there is no function definition.

     `remfunction' does not apply to array functions or subscripted
     functions.  `remarray'  applies to those types of functions.


 -- Option variable: savedef
     Default value: `true'

     When `savedef' is `true', the Maxima version of a user function is
     preserved when the function is translated.  This permits the
     definition to be displayed by `dispfun' and allows the function to
     be edited.

     When `savedef' is `false', the names of translated functions are
     removed from the `functions' list.


 -- Option variable: transcompile
     Default value: `true'

     When `transcompile' is `true', `translate' and `translate_file'
     generate declarations to make the translated code more suitable
     for compilation.

     `compfile' sets `transcompile: true' for the duration.


 -- Function: translate (<f_1>, ..., <f_n>)
 -- Function: translate (functions)
 -- Function: translate (all)
     Translates the user-defined functions <f_1>, ..., <f_n> from the
     Maxima language into Lisp and evaluates the Lisp translations.
     Typically the translated functions run faster than the originals.

     `translate (all)' or `translate (functions)' translates all
     user-defined functions.

     Functions to be translated should include a call to `mode_declare'
     at the beginning when possible in order to produce more efficient
     code.  For example:

          f (x_1, x_2, ...) := block ([v_1, v_2, ...],
              mode_declare (v_1, mode_1, v_2, mode_2, ...), ...)

     where the <x_1>, <x_2>, ...  are the parameters to the function and
     the <v_1>, <v_2>, ... are the local variables.

     The names of translated functions are removed from the `functions'
     list if `savedef' is `false' (see below) and are added to the
     `props' lists.

     Functions should not be translated unless they are fully debugged.

     Expressions are assumed simplified; if they are not, correct but
     non-optimal code gets generated.  Thus, the user should not set
     the `simp' switch to `false' which inhibits simplification of the
     expressions to be translated.

     The switch `translate', if `true', causes automatic translation of
     a user's function to Lisp.

     Note that translated functions may not run identically to the way
     they did before translation as certain incompatabilities may exist
     between the Lisp and Maxima versions.  Principally, the `rat'
     function with more than one argument and the `ratvars' function
     should not be used if any variables are `mode_declare''d canonical
     rational expressions (CRE).  Also the `prederror: false' setting
     will not translate.

     `savedef' - if `true' will cause the Maxima version of a user
     function to remain when the function is `translate''d.  This
     permits the definition to be displayed by `dispfun' and allows the
     function to be edited.

     `transrun' - if `false' will cause the interpreted version of all
     functions to be run (provided they are still around) rather than
     the translated version.

     The result returned by `translate' is a list of the names of the
     functions translated.


 -- Function: translate_file (<maxima_filename>)
 -- Function: translate_file (<maxima_filename>, <lisp_filename>)
     Translates a file of Maxima code into a file of Lisp code.
     `translate_file' returns a list of three filenames: the name of
     the Maxima file, the name of the Lisp file, and the name of file
     containing additional information about the translation.
     `translate_file' evaluates its arguments.

     `translate_file ("foo.mac"); load("foo.LISP")' is the same as the
     command `batch ("foo.mac")' except for certain restrictions, the
     use of `''' and `%', for example.

     `translate_file (<maxima_filename>)' translates a Maxima file
     <maxima_filename> into a similarly-named Lisp file.  For example,
     `foo.mac' is translated into `foo.LISP'.  The Maxima filename may
     include a directory name or names, in which case the Lisp output
     file is written to the same directory from which the Maxima input
     comes.

     `translate_file (<maxima_filename>, <lisp_filename>)' translates a
     Maxima file <maxima_filename> into a Lisp file <lisp_filename>.
     `translate_file' ignores the filename extension, if any, of
     `lisp_filename'; the filename extension of the Lisp output file is
     always `LISP'.  The Lisp filename may include a directory name or
     names, in which case the Lisp output file is written to the
     specified directory.

     `translate_file' also writes a file of translator warning messages
     of various degrees of severity.  The filename extension of this
     file is `UNLISP'.  This file may contain valuable information,
     though possibly obscure, for tracking down bugs in translated code.
     The `UNLISP' file is always written to the same directory from
     which the Maxima input comes.

     `translate_file' emits Lisp code which causes some declarations
     and definitions to take effect as soon as the Lisp code is
     compiled.  See `compile_file' for more on this topic.

     See also
     `tr_array_as_ref',
     `tr_bound_function_applyp',
     `tr_exponent',
     `tr_file_tty_messagesp',
     `tr_float_can_branch_complex',
     `tr_function_call_default',
     `tr_numer',
     `tr_optimize_max_loop',
     `tr_semicompile',
     `tr_state_vars',
     `tr_warnings_get',
     `tr_warn_bad_function_calls',
     `tr_warn_fexpr',
     `tr_warn_meval',
     `tr_warn_mode',
     `tr_warn_undeclared',
     and `tr_warn_undefined_variable'.


 -- Option variable: transrun
     Default value: `true'

     When `transrun' is `false' will cause the interpreted version of
     all functions to be run (provided they are still around) rather
     than the translated version.


 -- Option variable: tr_array_as_ref
     Default value: `true'

     If `translate_fast_arrays' is `false', array references in Lisp
     code emitted by `translate_file' are affected by `tr_array_as_ref'.
     When `tr_array_as_ref' is `true', array names are evaluated,
     otherwise array names appear as literal symbols in translated code.

     `tr_array_as_ref' has no effect if `translate_fast_arrays' is
     `true'.


 -- Option variable: tr_bound_function_applyp
     Default value: `true'

     When `tr_bound_function_applyp' is `true', Maxima gives a warning
     if a bound variable (such as a function argument) is found being
     used as a function.  `tr_bound_function_applyp' does not affect
     the code generated in such cases.

     For example, an expression such as `g (f, x) := f (x+1)' will
     trigger the warning message.


 -- Option variable: tr_file_tty_messagesp
     Default value: `false'

     When `tr_file_tty_messagesp' is `true', messages generated by
     `translate_file' during translation of a file are displayed on the
     console and inserted into the UNLISP file.  When `false', messages
     about translation of the file are only inserted into the UNLISP
     file.


 -- Option variable: tr_float_can_branch_complex
     Default value: `true'

     Tells the Maxima-to-Lisp translator to assume that the functions
     `acos', `asin', `asec', and `acsc' can return complex results.

     The ostensible effect of `tr_float_can_branch_complex' is the
     following.  However, it appears that this flag has no effect on
     the translator output.

     When it is `true' then `acos(x)' is of mode `any' even if `x' is
     of mode `float' (as set by `mode_declare').  When `false' then
     `acos(x)' is of mode `float' if and only if `x' is of mode `float'.


 -- Option variable: tr_function_call_default
     Default value: `general'

     `false' means give up and call `meval', `expr' means assume Lisp
     fixed arg function.  `general', the default gives code good for
     `mexprs' and `mlexprs' but not `macros'.  `general' assures
     variable bindings are correct in compiled code.  In `general'
     mode, when translating F(X), if F is a bound variable, then it
     assumes that `apply (f, [x])' is meant, and translates a such,
     with appropriate warning.  There is no need to turn this off.
     With the default settings, no warning messages implies full
     compatibility of translated and compiled code with the Maxima
     interpreter.


 -- Option variable: tr_numer
     Default value: `false'

     When `tr_numer' is `true', `numer' properties are used for atoms
     which have them, e.g. `%pi'.


 -- Option variable: tr_optimize_max_loop
     Default value: 100

     `tr_optimize_max_loop' is the maximum number of times the
     macro-expansion and optimization pass of the translator will loop
     in considering a form.  This is to catch macro expansion errors,
     and non-terminating optimization properties.


 -- Option variable: tr_semicompile
     Default value: `false'

     When `tr_semicompile' is `true', `translate_file' and `compfile'
     output forms which will be macroexpanded but not compiled into
     machine code by the Lisp compiler.


 -- System variable: tr_state_vars
     Default value:
          [transcompile, tr_semicompile, tr_warn_undeclared, tr_warn_meval,
          tr_warn_fexpr, tr_warn_mode, tr_warn_undefined_variable,
          tr_function_call_default, tr_array_as_ref,tr_numer]

     The list of the switches that affect the form of the translated
     output.  This information is useful to system people when trying
     to debug the translator.  By comparing the translated product to
     what should have been produced for a given state, it is possible to
     track down bugs.


 -- Function: tr_warnings_get ()
     Prints a list of warnings which have been given by the translator
     during the current translation.


 -- Option variable: tr_warn_bad_function_calls
     Default value: `true'

     - Gives a warning when when function calls are being made which
     may not be correct due to improper declarations that were made at
     translate time.


 -- Option variable: tr_warn_fexpr
     Default value: `compfile'

     - Gives a warning if any FEXPRs are encountered.  FEXPRs should
     not normally be output in translated code, all legitimate special
     program forms are translated.


 -- Option variable: tr_warn_meval
     Default value: `compfile'

     - Gives a warning if the function `meval' gets called.  If `meval'
     is called that indicates problems in the translation.


 -- Option variable: tr_warn_mode
     Default value: `all'

     - Gives a warning when variables are assigned values inappropriate
     for their mode.


 -- Option variable: tr_warn_undeclared
     Default value: `compile'

     - Determines when to send warnings about undeclared variables to
     the TTY.


 -- Option variable: tr_warn_undefined_variable
     Default value: `all'

     - Gives a warning when undefined global variables are seen.


 -- Function: compile_file (<filename>)
 -- Function: compile_file (<filename>, <compiled_filename>)
 -- Function: compile_file (<filename>, <compiled_filename>,
          <lisp_filename>)
     Translates the Maxima file <filename> into Lisp, executes the Lisp
     compiler, and, if the translation and compilation succeed, loads
     the compiled code into Maxima.

     `compile_file' returns a list of the names of four files: the
     original Maxima file, the Lisp translation, notes on translation,
     and the compiled code.  If the compilation fails, the fourth item
     is `false'.

     Some declarations and definitions take effect as soon as the Lisp
     code is compiled (without loading the compiled code).  These
     include functions defined with the `:=' operator, macros define
     with the `::=' operator, `alias', `declare', `define_variable',
     `mode_declare', and `infix', `matchfix', `nofix', `postfix',
     `prefix', and `compfile'.

     Assignments and function calls are not evaluated until the
     compiled code is loaded.  In particular, within the Maxima file,
     assignments to the translation flags (`tr_numer', etc.) have no
     effect on the translation.

     <filename> may not contain `:lisp' statements.

     `compile_file' evaluates its arguments.


 -- Function: declare_translated (<f_1>, <f_2>, ...)
     When translating a file of Maxima code to Lisp, it is important
     for the translator to know which functions it sees in the file are
     to be called as translated or compiled functions, and which ones
     are just Maxima functions or undefined.  Putting this declaration
     at the top of the file, lets it know that although a symbol does
     which does not yet have a Lisp function value, will have one at
     call time.  `(MFUNCTION-CALL fn arg1 arg2 ...)' is generated when
     the translator does not know `fn' is going to be a Lisp function.



File: maxima.info,  Node: Program Flow,  Next: Debugging,  Prev: Function Definition,  Up: Top

37 Program Flow
***************

* Menu:

* Lisp and Maxima::
* Garbage Collection::
* Introduction to Program Flow::
* Functions and Variables for Program Flow::


File: maxima.info,  Node: Lisp and Maxima,  Next: Garbage Collection,  Prev: Program Flow,  Up: Program Flow

37.1 Lisp and Maxima
====================

Maxima is written in Lisp, and it is easy to access Lisp functions and
variables from Maxima and vice versa.  Lisp and Maxima symbols are
distinguished by a naming convention.  A Lisp symbol which begins with
a dollar sign `$' corresponds to a Maxima symbol without the dollar
sign.

   A Maxima symbol which begins with a question mark `?' corresponds to
a Lisp symbol without the question mark.  For example, the Maxima
symbol `foo' corresponds to the Lisp symbol `$FOO', while the Maxima
symbol `?foo' corresponds to the Lisp symbol `FOO'.  Note that `?foo'
is written without a space between `?' and `foo'; otherwise it might be
mistaken for `describe ("foo")'.

   Hyphen `-', asterisk `*', or other special characters in Lisp symbols
must be escaped by backslash `\' where they appear in Maxima code.  For
example, the Lisp identifier `*foo-bar*' is written `?\*foo\-bar\*' in
Maxima.

   Lisp code may be executed from within a Maxima session.  A single
line of Lisp (containing one or more forms) may be executed by the
special command `:lisp'.  For example,

     (%i1) :lisp (foo $x $y)

calls the Lisp function `foo' with Maxima variables `x' and `y' as
arguments.  The `:lisp' construct can appear at the interactive prompt
or in a file processed by `batch'  or `demo',  but not in a file
processed by `load',  `batchload',

   `translate_file',  or `compile_file'.

   The function `to_lisp'  opens an interactive Lisp session.  Entering
`(to-maxima)' closes the Lisp session and returns to Maxima.

   Lisp functions and variables which are to be visible in Maxima as
functions and variables with ordinary names (no special punctuation)
must have Lisp names beginning with the dollar sign `$'.

   Maxima is case-sensitive, distinguishing between lowercase and
uppercase letters in identifiers.  There are some rules governing the
translation of names between Lisp and Maxima.

  1. A Lisp identifier not enclosed in vertical bars corresponds to a
     Maxima identifier in lowercase.  Whether the Lisp identifier is
     uppercase, lowercase, or mixed case, is ignored.  E.g., Lisp
     `$foo', `$FOO', and `$Foo' all correspond to Maxima `foo'.  But
     this is because `$foo', `$FOO' and `$Foo' are converted by the
     Lisp reader by default to the Lisp symbol `$FOO'.

  2. A Lisp identifier which is all uppercase or all lowercase and
     enclosed in vertical bars corresponds to a Maxima identifier with
     case reversed.  That is, uppercase is changed to lowercase and
     lowercase to uppercase.  E.g., Lisp `|$FOO|' and `|$foo|'
     correspond to Maxima `foo' and `FOO', respectively.

  3. A Lisp identifier which is mixed uppercase and lowercase and
     enclosed in vertical bars corresponds to a Maxima identifier with
     the same case.  E.g., Lisp `|$Foo|' corresponds to Maxima `Foo'.

   The `#$' Lisp macro allows the use of Maxima expressions in Lisp
code.  `#$<expr>$' expands to a Lisp expression equivalent to the Maxima
expression <expr>.

     (msetq $foo #$[x, y]$)

This has the same effect as entering

     (%i1) foo: [x, y];

The Lisp function `displa' prints an expression in Maxima format.

     (%i1) :lisp #$[x, y, z]$
     ((MLIST SIMP) $X $Y $Z)
     (%i1) :lisp (displa '((MLIST SIMP) $X $Y $Z))
     [x, y, z]
     NIL

   Functions defined in Maxima are not ordinary Lisp functions.  The
Lisp function `mfuncall' calls a Maxima function.  For example:

     (%i1) foo(x,y) := x*y$
     (%i2) :lisp (mfuncall '$foo 'a 'b)
     ((MTIMES SIMP) A B)

   Some Lisp functions are shadowed in the Maxima package, namely the
following.


   complement     continue      //
   float          functionp     array
   exp            listen        signum
   atan           asin          acos
   asinh          acosh         atanh
   tanh           cosh          sinh
   tan            break         gcd


File: maxima.info,  Node: Garbage Collection,  Next: Introduction to Program Flow,  Prev: Lisp and Maxima,  Up: Program Flow

37.2 Garbage Collection
=======================

Symbolic computation tends to create a good deal of garbage (temporary
or intermediate results that are eventually not used), and effective
handling of this can be crucial to successful completion of some
programs.

   Under GCL, on UNIX systems where the mprotect system call is
available (including SUN OS 4.0 and some variants of BSD) a stratified
garbage collection is available.  This limits the collection to pages
which have been recently written to.  See the GCL documentation under
ALLOCATE and GBC.  At the Lisp level doing (setq si::*notify-gbc* t)
will help you determine which areas might need more space.

   For other Lisps that run Maxima, we refer the reader to the
documentation for that Lisp on how to control GC.


File: maxima.info,  Node: Introduction to Program Flow,  Next: Functions and Variables for Program Flow,  Prev: Garbage Collection,  Up: Program Flow

37.3 Introduction to Program Flow
=================================

Maxima provides a `do' loop for iteration, as well as more primitive
constructs such as `go'.


File: maxima.info,  Node: Functions and Variables for Program Flow,  Prev: Introduction to Program Flow,  Up: Program Flow

37.4 Functions and Variables for Program Flow
=============================================

 -- Function: backtrace ()
 -- Function: backtrace (<n>)
     Prints the call stack, that is, the list of functions which called
     the currently active function.

     `backtrace()' prints the entire call stack.

     `backtrace (<n>)' prints the <n> most recent functions, including
     the currently active function.

     `backtrace' can be called from a script, a function, or the
     interactive prompt (not only in a debugging context).

     Examples:

        * `backtrace()' prints the entire call stack.

               (%i1) h(x) := g(x/7)$
               (%i2) g(x) := f(x-11)$
               (%i3) f(x) := e(x^2)$
               (%i4) e(x) := (backtrace(), 2*x + 13)$
               (%i5) h(10);
               #0: e(x=4489/49)
               #1: f(x=-67/7)
               #2: g(x=10/7)
               #3: h(x=10)
                                             9615
               (%o5)                         ----
                                              49

        * `backtrace (<n>)' prints the <n> most recent functions,
          including the currently active function.

               (%i1) h(x) := (backtrace(1), g(x/7))$
               (%i2) g(x) := (backtrace(1), f(x-11))$
               (%i3) f(x) := (backtrace(1), e(x^2))$
               (%i4) e(x) := (backtrace(1), 2*x + 13)$
               (%i5) h(10);
               #0: h(x=10)
               #0: g(x=10/7)
               #0: f(x=-67/7)
               #0: e(x=4489/49)
                                             9615
               (%o5)                         ----
                                              49


 -- Special operator: do
     The `do' statement is used for performing iteration.  Due to its
     great generality the `do' statement will be described in two parts.
     First the usual form will be given which is analogous to that used
     in several other programming languages (Fortran, Algol, PL/I,
     etc.); then the other features will be mentioned.

     There are three variants of this form that differ only in their
     terminating conditions.  They are:

        * `for <variable>: <initial_value> step <increment>       thru
          <limit> do <body>'

        * `for <variable>: <initial_value> step <increment>       while
          <condition> do <body>'

        * `for <variable>: <initial_value> step <increment>
          unless <condition> do <body>'

     (Alternatively, the `step' may be given after the termination
     condition or limit.)

     <initial_value>, <increment>, <limit>, and <body> can be any
     expressions.  If the increment is 1 then "`step 1'" may be omitted.

     The execution of the `do' statement proceeds by first assigning
     the <initial_value> to the <variable> (henceforth called the
     control-variable).  Then: (1) If the control-variable has exceeded
     the limit of a `thru' specification, or if the condition of the
     `unless' is `true', or if the condition of the `while' is `false'
     then the `do' terminates.  (2) The <body> is evaluated.  (3) The
     increment is added to the control-variable.  The process from (1)
     to (3) is performed repeatedly until the termination condition is
     satisfied.  One may also give several termination conditions in
     which case the `do' terminates when any of them is satisfied.

     In general the `thru' test is satisfied when the control-variable
     is greater than the <limit> if the <increment> was non-negative,
     or when the control-variable is less than the <limit> if the
     <increment> was negative.  The <increment> and <limit> may be
     non-numeric expressions as long as this inequality can be
     determined.  However, unless the <increment> is syntactically
     negative (e.g. is a negative number) at the time the `do'
     statement is input, Maxima assumes it will be positive when the
     `do' is executed.  If it is not positive, then the `do' may not
     terminate properly.

     Note that the <limit>, <increment>, and termination condition are
     evaluated each time through the loop.  Thus if any of these involve
     much computation, and yield a result that does not change during
     all the executions of the <body>, then it is more efficient to set
     a variable to their value prior to the `do' and use this variable
     in the `do' form.

     The value normally returned by a `do' statement is the atom
     `done'.  However, the function `return' may be used inside the
     <body> to exit the `do' prematurely and give it any desired value.
     Note however that a `return' within a `do' that occurs in a
     `block' will exit only the `do' and not the `block'.  Note also
     that the `go' function may not be used to exit from a `do' into a
     surrounding `block'.

     The control-variable is always local to the `do' and thus any
     variable may be used without affecting the value of a variable with
     the same name outside of the `do'.  The control-variable is unbound
     after the `do' terminates.

          (%i1) for a:-3 thru 26 step 7 do display(a)$
                                       a = - 3

                                        a = 4

                                       a = 11

                                       a = 18

                                       a = 25

          (%i1) s: 0$
          (%i2) for i: 1 while i <= 10 do s: s+i;
          (%o2)                         done
          (%i3) s;
          (%o3)                          55

     Note that the condition `while i <= 10' is equivalent to `unless i
     > 10' and also `thru 10'.

          (%i1) series: 1$
          (%i2) term: exp (sin (x))$
          (%i3) for p: 1 unless p > 7 do
                    (term: diff (term, x)/p,
                     series: series + subst (x=0, term)*x^p)$
          (%i4) series;
                            7    6     5    4    2
                           x    x     x    x    x
          (%o4)            -- - --- - -- - -- + -- + x + 1
                           90   240   15   8    2

     which gives 8 terms of the Taylor series for `e^sin(x)'.

          (%i1) poly: 0$
          (%i2) for i: 1 thru 5 do
                    for j: i step -1 thru 1 do
                        poly: poly + i*x^j$
          (%i3) poly;
                            5      4       3       2
          (%o3)          5 x  + 9 x  + 12 x  + 14 x  + 15 x
          (%i4) guess: -3.0$
          (%i5) for i: 1 thru 10 do
                    (guess: subst (guess, x, 0.5*(x + 10/x)),
                     if abs (guess^2 - 10) < 0.00005 then return (guess));
          (%o5)                  - 3.162280701754386

     This example computes the negative square root of 10 using the
     Newton- Raphson iteration a maximum of 10 times.  Had the
     convergence criterion not been met the value returned would have
     been `done'.

     Instead of always adding a quantity to the control-variable one
     may sometimes wish to change it in some other way for each
     iteration.  In this case one may use `next <expression>' instead of
     `step <increment>'.  This will cause the control-variable to be
     set to the result of evaluating <expression> each time through the
     loop.

          (%i6) for count: 2 next 3*count thru 20 do display (count)$
                                      count = 2

                                      count = 6

                                     count = 18

     As an alternative to `for <variable>: <value> ...do...' the syntax
     `for <variable> from <value> ...do...'  may be used.  This permits
     the `from <value>' to be placed after the `step' or `next' value
     or after the termination condition.  If `from <value>' is omitted
     then 1 is used as the initial value.

     Sometimes one may be interested in performing an iteration where
     the control-variable is never actually used.  It is thus
     permissible to give only the termination conditions omitting the
     initialization and updating information as in the following
     example to compute the square-root of 5 using a poor initial guess.

          (%i1) x: 1000$
          (%i2) thru 20 do x: 0.5*(x + 5.0/x)$
          (%i3) x;
          (%o3)                   2.23606797749979
          (%i4) sqrt(5), numer;
          (%o4)                   2.23606797749979

     If it is desired one may even omit the termination conditions
     entirely and just give `do <body>' which will continue to evaluate
     the <body> indefinitely.  In this case the function `return'
     should be used to terminate execution of the `do'.

          (%i1) newton (f, x):= ([y, df, dfx], df: diff (f ('x), 'x),
                    do (y: ev(df), x: x - f(x)/y,
                        if abs (f (x)) < 5e-6 then return (x)))$
          (%i2) sqr (x) := x^2 - 5.0$
          (%i3) newton (sqr, 1000);
          (%o3)                   2.236068027062195

     (Note that `return', when executed, causes the current value of
     `x' to be returned as the value of the `do'.  The `block' is
     exited and this value of the `do' is returned as the value of the
     `block' because the `do' is the last statement in the block.)

     One other form of the `do' is available in Maxima.  The syntax is:

          for <variable> in <list> <end_tests> do <body>

     The elements of <list> are any expressions which will successively
     be assigned to the `variable' on each iteration of the <body>.
     The optional termination tests <end_tests> can be used to
     terminate execution of the `do'; otherwise it will terminate when
     the <list> is exhausted or when a `return' is executed in the
     <body>.  (In fact, `list' may be any non-atomic expression, and
     successive parts are taken.)

          (%i1)  for f in [log, rho, atan] do ldisp(f(1))$
          (%t1)                                  0
          (%t2)                                rho(1)
                                               %pi
          (%t3)                                 ---
                                                4
          (%i4) ev(%t3,numer);
          (%o4)                             0.78539816


 -- Function: errcatch (<expr_1>, ..., <expr_n>)
     Evaluates <expr_1>, ..., <expr_n> one by one and returns
     `[<expr_n>]' (a list) if no error occurs.  If an error occurs in
     the evaluation of any argument, `errcatch' prevents the error from
     propagating and returns the empty list `[]' without evaluating any
     more arguments.

     `errcatch' is useful in `batch' files where one suspects an error
     might occur which would terminate the `batch' if the error weren't
     caught.


 -- Function: error (<expr_1>, ..., <expr_n>)
 -- System variable: error
     Evaluates and prints <expr_1>, ..., <expr_n>, and then causes an
     error return to top level Maxima or to the nearest enclosing
     `errcatch'.

     The variable `error' is set to a list describing the error.  The
     first element of `error' is a format string, which merges all the
     strings among the arguments <expr_1>, ..., <expr_n>, and the
     remaining elements are the values of any non-string arguments.

     `errormsg()' formats and prints `error'.  This is effectively
     reprinting the most recent error message.


 -- Option variable: error_size
     Default value: 10

     `error_size' modifies error messages according to the size of
     expressions which appear in them.  If the size of an expression
     (as determined by the Lisp function `ERROR-SIZE') is greater than
     `error_size', the expression is replaced in the message by a
     symbol, and the symbol is assigned the expression.  The symbols
     are taken from the list `error_syms'.

     Otherwise, the expression is smaller than `error_size', and the
     expression is displayed in the message.

     See also `error' and `error_syms'.

     Example:

     The size of `U', as determined by `ERROR-SIZE', is 24.

          (%i1) U: (C^D^E + B + A)/(cos(X-1) + 1)$

          (%i2) error_size: 20$

          (%i3) error ("Example expression is", U);

          Example expression is errexp1
           -- an error.  Quitting.  To debug this try debugmode(true);
          (%i4) errexp1;
                                      E
                                     D
                                    C   + B + A
          (%o4)                    --------------
                                   cos(X - 1) + 1
          (%i5) error_size: 30$

          (%i6) error ("Example expression is", U);

                                   E
                                  D
                                 C   + B + A
          Example expression is --------------
                                cos(X - 1) + 1
           -- an error.  Quitting.  To debug this try debugmode(true);


 -- Option variable: error_syms
     Default value: `[errexp1, errexp2, errexp3]'

     In error messages, expressions larger than `error_size' are
     replaced by symbols, and the symbols are set to the expressions.
     The symbols are taken from the list `error_syms'.  The first
     too-large expression is replaced by `error_syms[1]', the second by
     `error_syms[2]', and so on.

     If there are more too-large expressions than there are elements of
     `error_syms', symbols are constructed automatically, with the
     <n>-th symbol equivalent to `concat ('errexp, <n>)'.

     See also `error' and `error_size'.


 -- Function: errormsg ()
     Reprints the most recent error message.  The variable `error'
     holds the message, and `errormsg' formats and prints it.


 -- Option variable: errormsg
     Default value: `true'

     When `false' the output of error messages is suppressed.

     The option variable `errormsg' can not be set in a block to a local
     value.  The global value of `errormsg' is always present.

          (%i1) errormsg;
          (%o1)                                true
          (%i2) sin(a,b);
          Wrong number of arguments to sin
           -- an error. To debug this try: debugmode(true);
          (%i3) errormsg:false;
          (%o3)                                false
          (%i4) sin(a,b);

           -- an error. To debug this try: debugmode(true);

     The option variable `errormsg' can not be set in a block to a
     local value.

          (%i1) f(bool):=block([errormsg:bool],
                               print ("value of errormsg is",errormsg))$
          (%i2) errormsg:true;
          (%o2)                                true
          (%i3) f(false);
          value of errormsg is true
          (%o3)                                true
          (%i4) errormsg:false;
          (%o4)                                false
          (%i5) f(true);
          value of errormsg is false
          (%o5)                                false


 -- Special operator: for
     Used in iterations.  See `do' for a description of Maxima's
     iteration facilities.


 -- Function: go (<tag>)
     is used within a `block' to transfer control to the statement of
     the block which is tagged with the argument to `go'.  To tag a
     statement, precede it by an atomic argument as another statement in
     the `block'.  For example:

          block ([x], x:1, loop, x+1, ..., go(loop), ...)

     The argument to `go' must be the name of a tag appearing in the
     same `block'.  One cannot use `go' to transfer to tag in a `block'
     other than the one containing the `go'.


 -- Special operator: if
     Represents conditional evaluation.  Various forms of `if'
     expressions are recognized.

     `if <cond_1> then <expr_1> else <expr_0>' evaluates to <expr_1> if
     <cond_1> evaluates to `true', otherwise the expression evaluates
     to <expr_0>.

     The command `if <cond_1> then <expr_1> elseif <cond_2> then
     <expr_2> elseif ... else <expr_0>' evaluates to <expr_k> if
     <cond_k> is `true' and all preceding conditions are `false'.  If
     none of the conditions are `true', the expression evaluates to
     `expr_0'.

     A trailing `else false' is assumed if `else' is missing.  That is,
     the command `if <cond_1> then <expr_1>' is equivalent to `if
     <cond_1> then <expr_1> else false', and the command `if <cond_1>
     then <expr_1> elseif ... elseif <cond_n> then <expr_n>' is
     equivalent to `if <cond_1> then <expr_1> elseif ... elseif
     <cond_n> then <expr_n> else false'.

     The alternatives <expr_0>, ..., <expr_n> may be any Maxima
     expressions, including nested `if' expressions.  The alternatives
     are neither simplified nor evaluated unless the corresponding
     condition is `true'.

     The conditions <cond_1>, ..., <cond_n> are expressions which
     potentially or actually evaluate to `true' or `false'.  When a
     condition does not actually evaluate to `true' or `false', the
     behavior of `if' is governed by the global flag `prederror'.  When
     `prederror' is `true', it is an error if any evaluated condition
     does not evaluate to `true' or `false'.  Otherwise, conditions
     which do not evaluate to `true' or `false' are accepted, and the
     result is a conditional expression.

     Among other elements, conditions may comprise relational and
     logical operators as follows.

          Operation            Symbol      Type

          less than            <           relational infix
          less than            <=
            or equal to                    relational infix
          equality (syntactic) =           relational infix
          negation of =        #           relational infix
          equality (value)     equal       relational function
          negation of equal    notequal    relational function
          greater than         >=
            or equal to                    relational infix
          greater than         >           relational infix
          and                  and         logical infix
          or                   or          logical infix
          not                  not         logical prefix


 -- Function: map (<f>, <expr_1>, ..., <expr_n>)
     Returns an expression whose leading operator is the same as that
     of the expressions <expr_1>, ..., <expr_n> but whose subparts are
     the results of applying <f> to the corresponding subparts of the
     expressions.  <f> is either the name of a function of n arguments
     or is a `lambda' form of n arguments.

     `maperror' - if `false' will cause all of the mapping functions to
     (1) stop when they finish going down the shortest <expr_i> if not
     all of the <expr_i> are of the same length and (2) apply <f> to
     [<expr_1>, <expr_2>, ...]  if the <expr_i> are not all the same
     type of object.  If `maperror' is `true' then an error message
     will be given in the above two instances.

     One of the uses of this function is to `map' a function (e.g.
     `partfrac') onto each term of a very large expression where it
     ordinarily wouldn't be possible to use the function on the entire
     expression due to an exhaustion of list storage space in the
     course of the computation.

          (%i1) map(f,x+a*y+b*z);
          (%o1)                        f(b z) + f(a y) + f(x)
          (%i2) map(lambda([u],partfrac(u,x)),x+1/(x^3+4*x^2+5*x+2));
                                     1       1        1
          (%o2)                     ----- - ----- + -------- + x
                                   x + 2   x + 1          2
                                                   (x + 1)
          (%i3) map(ratsimp, x/(x^2+x)+(y^2+y)/y);
                                                1
          (%o3)                            y + ----- + 1
                                              x + 1
          (%i4) map("=",[a,b],[-0.5,3]);
          (%o4)                          [a = - 0.5, b = 3]


 -- Function: mapatom (<expr>)
     Returns `true' if and only if <expr> is treated by the mapping
     routines as an atom.  "Mapatoms" are atoms, numbers (including
     rational numbers), and subscripted variables.


 -- Option variable: maperror
     Default value: `true'

     When `maperror' is `false', causes all of the mapping functions,
     for example

          map (<f>, <expr_1>, <expr_2>, ...)

     to (1) stop when they finish going down the shortest <expr_i> if
     not all of the <expr_i> are of the same length and (2) apply <f>
     to [<expr_1>, <expr_2>, ...] if the <expr_i> are not all the same
     type of object.

     If `maperror' is `true' then an error message is displayed in the
     above two instances.


 -- Option variable: mapprint
     Default value: `true'

     When `mapprint' is `true', various information messages from
     `map', `mapl', and `fullmap' are produced in certain situations.
     These include situations where `map' would use `apply', or `map'
     is truncating on the shortest list.

     If `mapprint' is `false', these messages are suppressed.


 -- Function: maplist (<f>, <expr_1>, ..., <expr_n>)
     Returns a list of the applications of <f> to the parts of the
     expressions <expr_1>, ..., <expr_n>.  <f> is the name of a
     function, or a lambda expression.

     `maplist' differs from `map(<f>, <expr_1>, ..., <expr_n>)' which
     returns an expression with the same main operator as <expr_i> has
     (except for simplifications and the case where `map' does an
     `apply').


 -- Option variable: prederror
     Default value: `false'

     When `prederror' is `true', an error message is displayed whenever
     the predicate of an `if' statement or an `is' function fails to
     evaluate to either `true' or `false'.

     If `false', `unknown' is returned instead in this case.  The
     `prederror: false' mode is not supported in translated code;
     however, `maybe' is supported in translated code.

     See also `is' and `maybe'.


 -- Function: return (<value>)
     May be used to exit explicitly from a block, bringing its
     argument.  See `block' for more information.


 -- Function: scanmap (<f>, <expr>)
 -- Function: scanmap (<f>, <expr>, bottomup)
     Recursively applies <f> to <expr>, in a top down manner.  This is
     most useful when complete factorization is desired, for example:

          (%i1) exp:(a^2+2*a+1)*y + x^2$
          (%i2) scanmap(factor,exp);
                                              2      2
          (%o2)                         (a + 1)  y + x

     Note the way in which `scanmap' applies the given function
     `factor' to the constituent subexpressions of <expr>; if another
     form of <expr> is presented to `scanmap' then the result may be
     different.  Thus, `%o2' is not recovered when `scanmap' is applied
     to the expanded form of `exp':

          (%i3) scanmap(factor,expand(exp));
                                     2                  2
          (%o3)                      a  y + 2 a y + y + x

     Here is another example of the way in which `scanmap' recursively
     applies a given function to all subexpressions, including
     exponents:

          (%i4) expr : u*v^(a*x+b) + c$
          (%i5) scanmap('f, expr);
                              f(f(f(a) f(x)) + f(b))
          (%o5) f(f(f(u) f(f(v)                      )) + f(c))

     `scanmap (<f>, <expr>, bottomup)' applies <f> to <expr> in a
     bottom-up manner.  E.g., for undefined `f',

          scanmap(f,a*x+b) ->
             f(a*x+b) -> f(f(a*x)+f(b)) -> f(f(f(a)*f(x))+f(b))
          scanmap(f,a*x+b,bottomup) -> f(a)*f(x)+f(b)
              -> f(f(a)*f(x))+f(b) ->
               f(f(f(a)*f(x))+f(b))

     In this case, you get the same answer both ways.


 -- Function: throw (<expr>)
     Evaluates <expr> and throws the value back to the most recent
     `catch'.  `throw' is used with `catch' as a nonlocal return
     mechanism.


 -- Special operator: while
 -- Special operator: unless
     See `do'.


 -- Function: outermap (<f>, <a_1>, ..., <a_n>)
     Applies the function <f> to each one of the elements of the outer
     product <a_1> cross <a_2> ... cross <a_n>.

     <f> is the name of a function of n arguments or a lambda expression
     of n arguments.  Each argument <a_k> may be a list or nested list,
     or a matrix, or any other kind of expression.

     The `outermap' return value is a nested structure.  Let <x> be the
     return value.  Then <x> has the same structure as the first list,
     nested list, or matrix argument, `<x>[i_1]...[i_m]' has the same
     structure as the second list, nested list, or matrix argument,
     `<x>[i_1]...[i_m][j_1]...[j_n]' has the same structure as the third
     list, nested list, or matrix argument, and so on, where <m>, <n>,
     ... are the numbers of indices required to access the elements of
     each argument (one for a list, two for a matrix, one or more for a
     nested list).  Arguments which are not lists or matrices have no
     effect on the structure of the return value.

     Note that the effect of `outermap' is different from that of
     applying <f> to each one of the elements of the outer product
     returned by `cartesian_product'.  `outermap' preserves the
     structure of the arguments in the return value, while
     `cartesian_product' does not.

     `outermap' evaluates its arguments.

     See also `map', `maplist', and `apply'.

     Examples:

     Elementary examples of `outermap'.  To show the argument
     combinations more clearly, `F' is left undefined.

          (%i1) outermap(F, [a, b, c], [1, 2, 3]);
          (%o1) [[F(a, 1), F(a, 2), F(a, 3)], [F(b, 1), F(b, 2), F(b, 3)],
                                               [F(c, 1), F(c, 2), F(c, 3)]]
          (%i2) outermap(F, matrix([a, b],[c, d]), matrix([1, 2],[3, 4]));
                   [ [ F(a, 1)  F(a, 2) ]  [ F(b, 1)  F(b, 2) ] ]
                   [ [                  ]  [                  ] ]
                   [ [ F(a, 3)  F(a, 4) ]  [ F(b, 3)  F(b, 4) ] ]
          (%o2)    [                                            ]
                   [ [ F(c, 1)  F(c, 2) ]  [ F(d, 1)  F(d, 2) ] ]
                   [ [                  ]  [                  ] ]
                   [ [ F(c, 3)  F(c, 4) ]  [ F(d, 3)  F(d, 4) ] ]
          (%i3) outermap (F, [a, b], x, matrix ([1, 2], [3, 4]));
                 [ F(a, x, 1)  F(a, x, 2) ]  [ F(b, x, 1)  F(b, x, 2) ]
          (%o3) [[                        ], [                        ]]
                 [ F(a, x, 3)  F(a, x, 4) ]  [ F(b, x, 3)  F(b, x, 4) ]
          (%i4) outermap (F, [a, b], matrix ([1, 2]), matrix ([x], [y]));
                 [ [ F(a, 1, x) ]  [ F(a, 2, x) ] ]
          (%o4) [[ [            ]  [            ] ],
                 [ [ F(a, 1, y) ]  [ F(a, 2, y) ] ]
                                        [ [ F(b, 1, x) ]  [ F(b, 2, x) ] ]
                                        [ [            ]  [            ] ]]
                                        [ [ F(b, 1, y) ]  [ F(b, 2, y) ] ]
          (%i5) outermap ("+", [a, b, c], [1, 2, 3]);
          (%o5) [[a + 1, a + 2, a + 3], [b + 1, b + 2, b + 3],
                                                     [c + 1, c + 2, c + 3]]

     A closer examination of the `outermap' return value.  The first,
     second, and third arguments are a matrix, a list, and a matrix,
     respectively.  The return value is a matrix.  Each element of that
     matrix is a list, and each element of each list is a matrix.

          (%i1) arg_1 :  matrix ([a, b], [c, d]);
                                      [ a  b ]
          (%o1)                       [      ]
                                      [ c  d ]
          (%i2) arg_2 : [11, 22];
          (%o2)                       [11, 22]
          (%i3) arg_3 : matrix ([xx, yy]);
          (%o3)                      [ xx  yy ]
          (%i4) xx_0 : outermap(lambda([x, y, z], x / y + z), arg_1,
                                                             arg_2, arg_3);
                         [  [      a        a  ]  [      a        a  ]  ]
                         [ [[ xx + --  yy + -- ], [ xx + --  yy + -- ]] ]
                         [  [      11       11 ]  [      22       22 ]  ]
          (%o4)  Col 1 = [                                              ]
                         [  [      c        c  ]  [      c        c  ]  ]
                         [ [[ xx + --  yy + -- ], [ xx + --  yy + -- ]] ]
                         [  [      11       11 ]  [      22       22 ]  ]
                           [  [      b        b  ]  [      b        b  ]  ]
                           [ [[ xx + --  yy + -- ], [ xx + --  yy + -- ]] ]
                           [  [      11       11 ]  [      22       22 ]  ]
                   Col 2 = [                                              ]
                           [  [      d        d  ]  [      d        d  ]  ]
                           [ [[ xx + --  yy + -- ], [ xx + --  yy + -- ]] ]
                           [  [      11       11 ]  [      22       22 ]  ]
          (%i5) xx_1 : xx_0 [1][1];
                     [      a        a  ]  [      a        a  ]
          (%o5)     [[ xx + --  yy + -- ], [ xx + --  yy + -- ]]
                     [      11       11 ]  [      22       22 ]
          (%i6) xx_2 : xx_0 [1][1] [1];
                                [      a        a  ]
          (%o6)                 [ xx + --  yy + -- ]
                                [      11       11 ]
          (%i7) xx_3 : xx_0 [1][1] [1] [1][1];
                                            a
          (%o7)                        xx + --
                                            11
          (%i8) [op (arg_1), op (arg_2), op (arg_3)];
          (%o8)                  [matrix, [, matrix]
          (%i9) [op (xx_0), op (xx_1), op (xx_2)];
          (%o9)                  [matrix, [, matrix]

     `outermap' preserves the structure of the arguments in the return
     value, while `cartesian_product' does not.

          (%i1) outermap (F, [a, b, c], [1, 2, 3]);
          (%o1) [[F(a, 1), F(a, 2), F(a, 3)], [F(b, 1), F(b, 2), F(b, 3)],
                                               [F(c, 1), F(c, 2), F(c, 3)]]
          (%i2) setify (flatten (%));
          (%o2) {F(a, 1), F(a, 2), F(a, 3), F(b, 1), F(b, 2), F(b, 3),
                                                 F(c, 1), F(c, 2), F(c, 3)}
          (%i3) map(lambda([L], apply(F, L)),
                               cartesian_product({a, b, c}, {1, 2, 3}));
          (%o3) {F(a, 1), F(a, 2), F(a, 3), F(b, 1), F(b, 2), F(b, 3),
                                                 F(c, 1), F(c, 2), F(c, 3)}
          (%i4) is (equal (%, %th (2)));
          (%o4)                         true



File: maxima.info,  Node: Debugging,  Next: asympa,  Prev: Program Flow,  Up: Top

38 Debugging
************

* Menu:

* Source Level Debugging::
* Keyword Commands::
* Functions and Variables for Debugging::


File: maxima.info,  Node: Source Level Debugging,  Next: Keyword Commands,  Up: Debugging

38.1 Source Level Debugging
===========================

Maxima has a built-in source level debugger.  The user can set a
breakpoint at a function, and then step line by line from there.  The
call stack may be examined, together with the variables bound at that
level.

   The command `:help' or `:h' shows the list of debugger commands.
(In general, commands may be abbreviated if the abbreviation is unique.
If not unique, the alternatives will be listed.)  Within the debugger,
the user can also use any ordinary Maxima functions to examine, define,
and manipulate variables and expressions.

   A breakpoint is set by the `:br' command at the Maxima prompt.
Within the debugger, the user can advance one line at a time using the
`:n' ("next") command.  The `:bt' ("backtrace") command shows a list of
stack frames.  The `:r' ("resume") command exits the debugger and
continues with execution.  These commands are demonstrated in the
example below.

     (%i1) load ("/tmp/foobar.mac");

     (%o1)                           /tmp/foobar.mac

     (%i2) :br foo
     Turning on debugging debugmode(true)
     Bkpt 0 for foo (in /tmp/foobar.mac line 1)

     (%i2) bar (2,3);
     Bkpt 0:(foobar.mac 1)
     /tmp/foobar.mac:1::

     (dbm:1) :bt                        <-- :bt typed here gives a backtrace
     #0: foo(y=5)(foobar.mac line 1)
     #1: bar(x=2,y=3)(foobar.mac line 9)

     (dbm:1) :n                         <-- Here type :n to advance line
     (foobar.mac 2)
     /tmp/foobar.mac:2::

     (dbm:1) :n                         <-- Here type :n to advance line
     (foobar.mac 3)
     /tmp/foobar.mac:3::

     (dbm:1) u;                         <-- Investigate value of u
     28

     (dbm:1) u: 33;                     <-- Change u to be 33
     33

     (dbm:1) :r                         <-- Type :r to resume the computation

     (%o2)                                1094

   The file `/tmp/foobar.mac' is the following:

     foo(y) := block ([u:y^2],
       u: u+3,
       u: u^2,
       u);

     bar(x,y) := (
       x: x+2,
       y: y+2,
       x: foo(y),
       x+y);

   USE OF THE DEBUGGER THROUGH EMACS

   If the user is running the code under GNU emacs in a shell window
(dbl shell), or is running the graphical interface version, Xmaxima,
then if he stops at a break point, he will see his current position in
the source file which will be displayed in the other half of the
window, either highlighted in red, or with a little arrow pointing at
the right line.  He can advance single lines at a time by typing M-n
(Alt-n).

   Under Emacs you should run in a `dbl' shell, which requires the
`dbl.el' file in the elisp directory.  Make sure you install the elisp
files or add the Maxima elisp directory to your path: e.g., add the
following to your `.emacs' file or the `site-init.el'

     (setq load-path (cons "/usr/share/maxima/5.9.1/emacs" load-path))
     (autoload 'dbl "dbl")

   then in emacs

     M-x dbl

   should start a shell window in which you can run programs, for
example Maxima, gcl, gdb etc.   This shell window also knows about
source level debugging, and display of source code in the other window.

   The user may set a break point at a certain line of the file by
typing `C-x space'.  This figures out which function the cursor is in,
and then it sees which line of that function the cursor is on.   If the
cursor is on, say, line 2 of `foo', then it will insert in the other
window the command, "`:br foo 2'", to break `foo' at its second line.
To have this enabled, the user must have maxima-mode.el turned on in
the window in which the file `foobar.mac' is visiting.  There are
additional commands available in that file window, such as evaluating
the function into the Maxima, by typing `Alt-Control-x'.


File: maxima.info,  Node: Keyword Commands,  Next: Functions and Variables for Debugging,  Prev: Source Level Debugging,  Up: Debugging

38.2 Keyword Commands
=====================

Keyword commands are special keywords which are not interpreted as
Maxima expressions.  A keyword command can be entered at the Maxima
prompt or the debugger prompt, although not at the break prompt.
Keyword commands start with a colon, '`:''.  For example, to evaluate a
Lisp form you may type `:lisp' followed by the form to be evaluated.

     (%i1) :lisp (+ 2 3)
     5

   The number of arguments taken depends on the particular command.
Also, you need not type the whole command, just enough to be unique
among the break keywords.   Thus `:br' would suffice for `:break'.

   The keyword commands are listed below.

`:break F n'
     Set a breakpoint in function `F' at line offset `n' from the
     beginning of the function.  If `F' is given as a string, then it
     is assumed to be a file, and `n' is the offset from the beginning
     of the file.  The offset is optional. If not given, it is assumed
     to be zero (first line of the function or file).

`:bt'
     Print a backtrace of the stack frames

`:continue'
     Continue the computation

`:delete'
     Delete the specified breakpoints, or all if none are specified

`:disable'
     Disable the specified breakpoints, or all if none are specified

`:enable'
     Enable the specified breakpoints, or all if none are specified

`:frame n'
     Print stack frame `n', or the current frame if none is specified

`:help'
     Print help on a debugger command, or all commands if none is
     specified

`:info'
     Print information about item

`:lisp some-form'
     Evaluate `some-form' as a Lisp form

`:lisp-quiet some-form'
     Evaluate Lisp form `some-form' without any output

`:next'
     Like `:step', except `:next' steps over function calls

`:quit'
     Quit the current debugger level without completing the computation

`:resume'
     Continue the computation

`:step'
     Continue the computation until it reaches a new source line

`:top'
     Return to the Maxima prompt (from any debugger level) without
     completing the computation


File: maxima.info,  Node: Functions and Variables for Debugging,  Prev: Keyword Commands,  Up: Debugging

38.3 Functions and Variables for Debugging
==========================================

 -- Option variable: debugmode
     Default value: `false'

     When a Maxima error occurs, Maxima will start the debugger if
     `debugmode' is `true'.  The user may enter commands to examine the
     call stack, set breakpoints, step through Maxima code, and so on.
     See `debugging' for a list of debugger commands.

     Enabling `debugmode' will not catch Lisp errors.


 -- Option variable: refcheck
     Default value: `false'

     When `refcheck' is `true', Maxima prints a message each time a
     bound variable is used for the first time in a computation.


 -- Option variable: setcheck
     Default value: `false'

     If `setcheck' is set to a list of variables (which can be
     subscripted), Maxima prints a message whenever the variables, or
     subscripted occurrences of them, are bound with the ordinary
     assignment operator `:', the `::' assignment operator, or function
     argument binding, but not the function assignment `:=' nor the
     macro assignment `::=' operators.  The message comprises the name
     of the variable and the value it is bound to.

     `setcheck' may be set to `all' or `true' thereby including all
     variables.

     Each new assignment of `setcheck' establishes a new list of
     variables to check, and any variables previously assigned to
     `setcheck' are forgotten.

     The names assigned to `setcheck' must be quoted if they would
     otherwise evaluate to something other than themselves.  For
     example, if `x', `y', and `z' are already bound, then enter

          setcheck: ['x, 'y, 'z]$

     to put them on the list of variables to check.

     No printout is generated when a variable on the `setcheck' list is
     assigned to itself, e.g., `X: 'X'.


 -- Option variable: setcheckbreak
     Default value: `false'

     When `setcheckbreak' is `true', Maxima will present a break prompt
     whenever a variable on the `setcheck' list is assigned a new value.
     The break occurs before the assignment is carried out.  At this
     point, `setval' holds the value to which the variable is about to
     be assigned.  Hence, one may assign a different value by assigning
     to `setval'.

     See also `setcheck' and `setval'.


 -- System variable: setval
     Holds the value to which a variable is about to be set when a
     `setcheckbreak' occurs.  Hence, one may assign a different value
     by assigning to `setval'.

     See also `setcheck' and `setcheckbreak'.


 -- Function: timer (<f_1>, ..., <f_n>)
 -- Function: timer (all)
 -- Function: timer ()
     Given functions <f_1>, ..., <f_n>, `timer' puts each one on the
     list of functions for which timing statistics are collected.
     `timer(f)$ timer(g)$' puts `f' and then `g' onto the list; the
     list accumulates from one call to the next.

     `timer(all)' puts all user-defined functions (as named by the
     global variable `functions') on the list of timed functions.

     With no arguments,  `timer' returns the list of timed functions.

     Maxima records how much time is spent executing each function on
     the list of timed functions.  `timer_info' returns the timing
     statistics, including the average time elapsed per function call,
     the number of calls, and the total time elapsed.  `untimer'
     removes functions from the list of timed functions.

     `timer' quotes its arguments.  `f(x) := x^2$ g:f$ timer(g)$' does
     not put `f' on the timer list.

     If `trace(f)' is in effect, then `timer(f)' has no effect; `trace'
     and `timer' cannot both be in effect at the same time.

     See also `timer_devalue'.


 -- Function: untimer (<f_1>, ..., <f_n>)
 -- Function: untimer ()
     Given functions <f_1>, ..., <f_n>, `untimer' removes each function
     from the timer list.

     With no arguments, `untimer' removes all functions currently on
     the timer list.

     After `untimer (f)' is executed, `timer_info (f)' still returns
     previously collected timing statistics, although `timer_info()'
     (with no arguments) does not return information about any function
     not currently on the timer list.  `timer (f)' resets all timing
     statistics to zero and puts `f' on the timer list again.


 -- Option variable: timer_devalue
     Default value: `false'

     When `timer_devalue' is `true', Maxima subtracts from each timed
     function the time spent in other timed functions.  Otherwise, the
     time reported for each function includes the time spent in other
     functions.  Note that time spent in untimed functions is not
     subtracted from the total time.

     See also `timer' and `timer_info'.


 -- Function: timer_info (<f_1>, ..., <f_n>)
 -- Function: timer_info ()
     Given functions <f_1>, ..., <f_n>, `timer_info' returns a matrix
     containing timing information for each function.  With no
     arguments, `timer_info' returns timing information for all
     functions currently on the timer list.

     The matrix returned by `timer_info' contains the function name,
     time per function call, number of function calls, total time, and
     `gctime', which meant "garbage collection time" in the original
     Macsyma but is now always zero.

     The data from which `timer_info' constructs its return value can
     also be obtained by the `get' function:

          get(f, 'calls);  get(f, 'runtime);  get(f, 'gctime);

     See also `timer'.


 -- Function: trace (<f_1>, ..., <f_n>)
 -- Function: trace (all)
 -- Function: trace ()
     Given functions <f_1>, ..., <f_n>, `trace' instructs Maxima to
     print out debugging information whenever those functions are
     called.  `trace(f)$ trace(g)$' puts `f' and then `g' onto the list
     of functions to be traced; the list accumulates from one call to
     the next.

     `trace(all)' puts all user-defined functions (as named by the
     global variable `functions') on the list of functions to be traced.

     With no arguments, `trace' returns a list of all the functions
     currently being traced.

     The `untrace' function disables tracing.  See also `trace_options'.

     `trace' quotes its arguments.  Thus, `f(x) := x^2$ g:f$ trace(g)$'
     does not put `f' on the trace list.

     When a function is redefined, it is removed from the timer list.
     Thus after `timer(f)$ f(x) := x^2$', function `f' is no longer on
     the timer list.

     If `timer (f)' is in effect, then `trace (f)' has no effect;
     `trace' and `timer' can't both be in effect for the same function.


 -- Function: trace_options (<f>, <option_1>, ..., <option_n>)
 -- Function: trace_options (<f>)
     Sets the trace options for function <f>.  Any previous options are
     superseded.  `trace_options (<f>, ...)' has no effect unless
     `trace (<f>)' is also called (either before or after
     `trace_options').

     `trace_options (<f>)' resets all options to their default values.

     The option keywords are:

        * `noprint' Do not print a message at function entry and exit.

        * `break' Put a breakpoint before the function is entered, and
          after the function is exited.  See `break'.

        * `lisp_print' Display arguments and return values as Lisp
          objects.

        * `info' Print `-> true' at function entry and exit.

        * `errorcatch' Catch errors, giving the option to signal an
          error, retry the function call, or specify a return value.

     Trace options are specified in two forms.  The presence of the
     option keyword alone puts the option into effect unconditionally.
     (Note that option <foo> is not put into effect by specifying
     `<foo>: true' or a similar form; note also that keywords need not
     be quoted.) Specifying the option keyword with a predicate
     function makes the option conditional on the predicate.

     The argument list to the predicate function is always `[level,
     direction, function, item]' where `level' is the recursion level
     for the function,  `direction' is either `enter' or `exit',
     `function' is the name of the function, and `item' is the argument
     list (on entering) or the return value (on exiting).

     Here is an example of unconditional trace options:

          (%i1) ff(n) := if equal(n, 0) then 1 else n * ff(n - 1)$

          (%i2) trace (ff)$

          (%i3) trace_options (ff, lisp_print, break)$

          (%i4) ff(3);

     Here is the same function, with the `break' option conditional on
     a predicate:

          (%i5) trace_options (ff, break(pp))$

          (%i6) pp (level, direction, function, item) := block (print (item),
              return (function = 'ff and level = 3 and direction = exit))$

          (%i7) ff(6);


 -- Function: untrace (<f_1>, ..., <f_n>)
 -- Function: untrace ()
     Given functions <f_1>, ..., <f_n>, `untrace' disables tracing
     enabled by the `trace' function.  With no arguments, `untrace'
     disables tracing for all functions.

     `untrace' returns a list of the functions for which it disabled
     tracing.



File: maxima.info,  Node: asympa,  Next: augmented_lagrangian,  Prev: Debugging,  Up: Top

39 asympa
*********

* Menu:

* Introduction to asympa::
* Functions and variables for asympa::


File: maxima.info,  Node: Introduction to asympa,  Next: Functions and variables for asympa,  Prev: asympa,  Up: asympa

39.1 Introduction to asympa
===========================

 -- Function: asympa
     `asympa' is a package for asymptotic analysis. The package contains
     simplification functions for asymptotic analysis, including the
     "big O" and "little o" functions that are widely used in
     complexity analysis and numerical analysis.

     `load ("asympa")' loads this package.



File: maxima.info,  Node: Functions and variables for asympa,  Prev: Introduction to asympa,  Up: asympa

39.2 Functions and variables for asympa
=======================================


File: maxima.info,  Node: augmented_lagrangian,  Next: Bernstein,  Prev: asympa,  Up: Top

40 augmented_lagrangian
***********************

* Menu:

* Functions and Variables for augmented_lagrangian::


File: maxima.info,  Node: Functions and Variables for augmented_lagrangian,  Prev: augmented_lagrangian,  Up: augmented_lagrangian

40.1 Functions and Variables for augmented_lagrangian
=====================================================

 -- Function: augmented_lagrangian_method (<FOM>, <xx>, <C>, <yy>)
 -- Function: augmented_lagrangian_method (<FOM>, <xx>, <C>, <yy>,
          optional_args)
 -- Function: augmented_lagrangian_method ([<FOM>, <grad>], <xx>, <C>,
          <yy>)
 -- Function: augmented_lagrangian_method ([<FOM>, <grad>], <xx>, <C>,
          <yy>, optional_args)
     Returns an approximate minimum of the expression <FOM> with
     respect to the variables <xx>, holding the constraints <C> equal
     to zero.  <yy> is a list of initial guesses for <xx>.  The method
     employed is the augmented Lagrangian method (see Refs [1] and [2]).

     <grad>, if present, is the gradient of <FOM> with respect to <xx>,
     represented as a list of expressions, one for each variable in
     <xx>.  If not present, the gradient is constructed automatically.

     <FOM> and each element of <grad>, if present, must be ordinary
     expressions, not names of functions or lambda expressions.

     `optional_args' represents additional arguments, specified as
     `<symbol> = <value>'.  The optional arguments recognized are:

    `niter'
          Number of iterations of the augmented Lagrangian algorithm

    `lbfgs_tolerance'
          Tolerance supplied to LBFGS

    `iprint'
          IPRINT parameter (a list of two integers which controls
          verbosity) supplied to LBFGS

    `%lambda'
          Initial value of `%lambda' to be used for calculating the
          augmented Lagrangian

     This implementation minimizes the augmented Lagrangian by applying
     the limited-memory BFGS (LBFGS) algorithm, which is a quasi-Newton
     algorithm.

     `load(augmented_lagrangian)' loads this function.

     See also `lbfgs'.

     References:

     [1]
     `http://www-fp.mcs.anl.gov/otc/Guide/OptWeb/continuous/constrained/nonlinearcon/auglag.html'

     [2] `http://www.cs.ubc.ca/spider/ascher/542/chap10.pdf'

     Examples:

          (%i1) load (lbfgs);
          (%o1)     /maxima/share/lbfgs/lbfgs.mac
          (%i2) load (augmented_lagrangian);
          (%o2)
             /maxima/share/contrib/augmented_lagrangian.mac
          (%i3) FOM: x^2 + 2*y^2;
                                         2    2
          (%o3)                       2 y  + x
          (%i4) xx: [x, y];
          (%o4)                        [x, y]
          (%i5) C: [x + y - 1];
          (%o5)                      [y + x - 1]
          (%i6) yy: [1, 1];
          (%o6)                        [1, 1]
          (%i7) augmented_lagrangian_method(FOM, xx, C, yy, iprint=[-1,0]);
          (%o7) [[x = 0.66665984108002, y = 0.33334027245545],
                                           %lambda = [- 1.333337940892525]]

     Same example as before, but this time the gradient is supplied as
     an argument.

          (%i1) load (lbfgs)$
          (%i2) load (augmented_lagrangian)$
          (%i3) FOM: x^2 + 2*y^2;
                                         2    2
          (%o3)                       2 y  + x
          (%i4) FOM: x^2 + 2*y^2;
                                         2    2
          (%o4)                       2 y  + x
          (%i5) xx: [x, y];
          (%o5)                        [x, y]
          (%i6) grad : [2*x, 4*y];
          (%o6)                      [2 x, 4 y]
          (%i7) C: [x + y - 1];
          (%o7)                      [y + x - 1]
          (%i8) yy: [1, 1];
          (%o8)                        [1, 1]
          (%i9) augmented_lagrangian_method ([FOM, grad], xx, C, yy,
                                             iprint = [-1, 0]);
          (%o9) [[x = 0.666659841080025, y = .3333402724554462],
                                           %lambda = [- 1.333337940892543]]



File: maxima.info,  Node: Bernstein,  Next: bode,  Prev: augmented_lagrangian,  Up: Top

41 Bernstein
************

* Menu:

* Functions and Variables for Bernstein::


File: maxima.info,  Node: Functions and Variables for Bernstein,  Prev: Bernstein,  Up: Bernstein

41.1 Functions and Variables for Bernstein
==========================================

 -- Function: bernstein_poly (<k>, <n>, <x>)
     Provided `k' is not a negative integer, the Bernstein polynomials
     are defined by `bernstein_poly(k,n,x) = binomial(n,k) x^k
     (1-x)^(n-k)'; for a negative integer `k', the Bernstein polynomial
     `bernstein_poly(k,n,x)' vanishes.  When either `k' or `n' are non
     integers, the option variable `bernstein_explicit' controls the
     expansion of the Bernstein polynomials into its explicit form;
     example:

          (%i1) load(bernstein)$

          (%i2) bernstein_poly(k,n,x);
          (%o2)                bernstein_poly(k, n, x)
          (%i3) bernstein_poly(k,n,x), bernstein_explicit : true;
                                                 n - k  k
          (%o3)            binomial(n, k) (1 - x)      x

     The Bernstein polynomials have both a gradef property and an
     integrate property:

          (%i4) diff(bernstein_poly(k,n,x),x);
          (%o4) (bernstein_poly(k - 1, n - 1, x)
                                           - bernstein_poly(k, n - 1, x)) n
          (%i5) integrate(bernstein_poly(k,n,x),x);
          (%o5)
                                                                      k + 1
           hypergeometric([k + 1, k - n], [k + 2], x) binomial(n, k) x
           ----------------------------------------------------------------
                                        k + 1

     For numeric inputs, both real and complex, the Bernstein
     polynomials evaluate to a numeric result:

          (%i6) bernstein_poly(5,9, 1/2 + %i);
                                  39375 %i   39375
          (%o6)                   -------- + -----
                                    128       256
          (%i7) bernstein_poly(5,9, 0.5b0 + %i);
          (%o7)           3.076171875b2 %i + 1.5380859375b2

     To use `bernstein_poly', first `load("bernstein")'.


 -- Variable: bernstein_explicit
     Default value: `false'

     When either `k' or `n' are non integers, the option variable
     `bernstein_explicit' controls the expansion of `bernstein(k,n,x)'
     into its explicit form; example:

          (%i1) bernstein_poly(k,n,x);
          (%o1)                bernstein_poly(k, n, x)
          (%i2) bernstein_poly(k,n,x), bernstein_explicit : true;
                                                 n - k  k
          (%o2)            binomial(n, k) (1 - x)      x
     When both `k' and `n' are explicitly integers, `bernstein(k,n,x)'
     _always_ expands to its explicit form.


 -- Function: multibernstein_poly (<[k1,k2,..., kp]>, <[n1,n2,...,
          np]>, <[x1,x2,..., xp]>)
     The multibernstein polynomial `multibernstein_poly (<[k1, k2, ...,
     kp]>, <[n1, n2, ..., np]>, <[x1, x2, ..., xp]>)' is the product of
     bernstein polynomials `bernstein_poly(k1, n1, x1)
     bernstein_poly(k2, n2, x2) ... bernstein_poly(kp, np, xp)'.

     To use `multibernstein_poly', first `load("bernstein")'.


 -- Function: bernstein_approx (<f>, <[x1, x1, ..., xn]>, n)
     Return the `n'-th order uniform Bernstein polynomial approximation
     for the function `(x1, x2, ..., xn) |--> f'.  Examples

          (%i1) bernstein_approx(f(x),[x], 2);
                           2       1                          2
          (%o1)      f(1) x  + 2 f(-) (1 - x) x + f(0) (1 - x)
                                   2
          (%i2) bernstein_approx(f(x,y),[x,y], 2);
                         2  2       1                2
          (%o2) f(1, 1) x  y  + 2 f(-, 1) (1 - x) x y
                                    2
                            2  2          1   2
           + f(0, 1) (1 - x)  y  + 2 f(1, -) x  (1 - y) y
                                          2
                 1  1                               1         2
           + 4 f(-, -) (1 - x) x (1 - y) y + 2 f(0, -) (1 - x)  (1 - y) y
                 2  2                               2
                      2        2       1                      2
           + f(1, 0) x  (1 - y)  + 2 f(-, 0) (1 - x) x (1 - y)
                                       2
                            2        2
           + f(0, 0) (1 - x)  (1 - y)

     To use `bernstein_approx', first `load("bernstein")'.


 -- Function: bernstein_expand (<e>, <[x1, x1, ..., xn]>)
     Express the _polynomial_ `e' exactly as a linear combination of
     multi-variable Bernstein polynomials.

          (%i1) bernstein_expand(x*y+1,[x,y]);
          (%o1)    2 x y + (1 - x) y + x (1 - y) + (1 - x) (1 - y)
          (%i2) expand(%);
          (%o2)                        x y + 1

     Maxima signals an error when the first argument isn't a polynomial.

     To use `bernstein_expand', first `load("bernstein")'.



File: maxima.info,  Node: bode,  Next: cobyla,  Prev: Bernstein,  Up: Top

42 bode
*******

* Menu:

* Functions and Variables for bode::


File: maxima.info,  Node: Functions and Variables for bode,  Prev: bode,  Up: bode

42.1 Functions and Variables for bode
=====================================

 -- Function: bode_gain (<H>, <range>, ...<plot_opts>...)
     Function to draw Bode gain plots.

     Examples (1 through 7 from
          `http://www.swarthmore.edu/NatSci/echeeve1/Ref/Bode/BodeHow.html',
     8 from Ron Crummett):
          (%i1) load("bode")$

          (%i2) H1 (s) := 100 * (1 + s) / ((s + 10) * (s + 100))$

          (%i3) bode_gain (H1 (s), [w, 1/1000, 1000])$

          (%i4) H2 (s) := 1 / (1 + s/omega0)$

          (%i5) bode_gain (H2 (s), [w, 1/1000, 1000]), omega0 = 10$

          (%i6) H3 (s) := 1 / (1 + s/omega0)^2$

          (%i7) bode_gain (H3 (s), [w, 1/1000, 1000]), omega0 = 10$

          (%i8) H4 (s) := 1 + s/omega0$

          (%i9) bode_gain (H4 (s), [w, 1/1000, 1000]), omega0 = 10$

          (%i10) H5 (s) := 1/s$

          (%i11) bode_gain (H5 (s), [w, 1/1000, 1000])$

          (%i12) H6 (s) := 1/((s/omega0)^2 + 2 * zeta * (s/omega0) + 1)$

          (%i13) bode_gain (H6 (s), [w, 1/1000, 1000]),
                            omega0 = 10, zeta = 1/10$

          (%i14) H7 (s) := (s/omega0)^2 + 2 * zeta * (s/omega0) + 1$

          (%i15) bode_gain (H7 (s), [w, 1/1000, 1000]),
                            omega0 = 10, zeta = 1/10$

          (%i16) H8 (s) := 0.5 / (0.0001 * s^3 + 0.002 * s^2 + 0.01 * s)$

          (%i17) bode_gain (H8 (s), [w, 1/1000, 1000])$

     To use this function write first `load("bode")'. See also
     `bode_phase'


 -- Function: bode_phase (<H>, <range>, ...<plot_opts>...)
     Function to draw Bode phase plots.

     Examples (1 through 7 from
          `http://www.swarthmore.edu/NatSci/echeeve1/Ref/Bode/BodeHow.html',
     8 from Ron Crummett):
          (%i1) load("bode")$

          (%i2) H1 (s) := 100 * (1 + s) / ((s + 10) * (s + 100))$

          (%i3) bode_phase (H1 (s), [w, 1/1000, 1000])$

          (%i4) H2 (s) := 1 / (1 + s/omega0)$

          (%i5) bode_phase (H2 (s), [w, 1/1000, 1000]), omega0 = 10$

          (%i6) H3 (s) := 1 / (1 + s/omega0)^2$

          (%i7) bode_phase (H3 (s), [w, 1/1000, 1000]), omega0 = 10$

          (%i8) H4 (s) := 1 + s/omega0$

          (%i9) bode_phase (H4 (s), [w, 1/1000, 1000]), omega0 = 10$

          (%i10) H5 (s) := 1/s$

          (%i11) bode_phase (H5 (s), [w, 1/1000, 1000])$

          (%i12) H6 (s) := 1/((s/omega0)^2 + 2 * zeta * (s/omega0) + 1)$

          (%i13) bode_phase (H6 (s), [w, 1/1000, 1000]),
                             omega0 = 10, zeta = 1/10$

          (%i14) H7 (s) := (s/omega0)^2 + 2 * zeta * (s/omega0) + 1$

          (%i15) bode_phase (H7 (s), [w, 1/1000, 1000]),
                             omega0 = 10, zeta = 1/10$

          (%i16) H8 (s) := 0.5 / (0.0001 * s^3 + 0.002 * s^2 + 0.01 * s)$

          (%i17) bode_phase (H8 (s), [w, 1/1000, 1000])$

          (%i18) block ([bode_phase_unwrap : false],
                        bode_phase (H8 (s), [w, 1/1000, 1000]));

          (%i19) block ([bode_phase_unwrap : true],
                        bode_phase (H8 (s), [w, 1/1000, 1000]));

     To use this function write first `load("bode")'. See also
     `bode_gain'



File: maxima.info,  Node: cobyla,  Next: contrib_ode,  Prev: bode,  Up: Top

43 cobyla
*********

* Menu:

* Introduction to cobyla::
* Functions and Variables for cobyla::
* Examples for cobyla::


File: maxima.info,  Node: Introduction to cobyla,  Next: Functions and Variables for cobyla,  Prev: cobyla,  Up: cobyla

43.1 Introduction to cobyla
===========================

`fmin_cobyla' is a Common Lisp translation (via `f2cl') of the Fortran
constrained optimization routine COBYLA by Powell[1][2][3].

   COBYLA minimizes an objective function F(X) subject to M inequality
constraints of the form g(X) >= 0 on X, where X is a vector of
variables that has N components.

   Equality constraints g(X)=0 can often be implemented by a pair of
inequality constraints g(X)>=0 and -g(X)>= 0.  Maxima's interface to
COBYLA allows equality constraints and internally converts the equality
constraints to a pair of inequality constraints.

   The algorithm employs linear approximations to the objective and
constraint functions, the approximations being formed by linear
interpolation at N+1 points in the space of the variables.  The
interpolation points are regarded as vertices of a simplex. The
parameter RHO controls the size of the simplex and it is reduced
automatically from RHOBEG to RHOEND. For each RHO the subroutine tries
to achieve a good vector of variables for the current size, and then
RHO is reduced until the value RHOEND is reached. Therefore RHOBEG and
RHOEND should be set to reasonable initial changes to and the required
accuracy in the variables respectively, but this accuracy should be
viewed as a subject for experimentation because it is not guaranteed.
The routine treats each constraint individually when calculating a
change to the variables, rather than lumping the constraints together
into a single penalty function. The name of the subroutine is derived
from the phrase Constrained Optimization BY Linear Approximations.

   References:

   [1] Fortran Code is from
`http://plato.asu.edu/sub/nlores.html#general'

   [2] M. J. D. Powell, "A direct search optimization method that
models the objective and constraint functions by linear interpolation,"
in Advances in Optimization and Numerical Analysis, eds. S. Gomez and
J.-P. Hennart (Kluwer Academic: Dordrecht, 1994), p. 51-67.

   [3] M. J. D. Powell, "Direct search algorithms for optimization
calculations," Acta Numerica 7, 287-336 (1998).  Also available as
University of Cambridge, Department of Applied Mathematics and
Theoretical Physics,  Numerical Analysis Group, Report NA1998/04 from
`http://www.damtp.cam.ac.uk/user/na/reports.html'


File: maxima.info,  Node: Functions and Variables for cobyla,  Next: Examples for cobyla,  Prev: Introduction to cobyla,  Up: cobyla

43.2 Functions and Variables for cobyla
=======================================

 -- Function: fmin_cobyla (<F>, <X>, <Y>)
 -- Function: fmin_cobyla (<F>, <X>, <Y>, optional_args)
     Returns an approximate minimum of the expression <F> with respect
     to the variables <X>, subject to an optional set of constraints.
     <Y> is a list of initial guesses for <X>.

     <F> must be an ordinary expressions, not names of functions or
     lambda expressions.

     `optional_args' represents additional arguments, specified as
     `<symbol> = <value>'.  The optional arguments recognized are:

    `constraints'
          List of inequality and equality constraints that must be
          satisfied by <X>.  The inequality constraints must be actual
          inequalities of the form `g(<X>) >= h(<X>)' or `g(<X>) <=
          h(<X>)'.  The equality constraints must be of the form
          `g(<X>) = h(<X>)'.

    `rhobeg'
          Initial value of the internal RHO variable which controls the
          size of simplex.  (Defaults to 1.0)

    `rhoend'
          The desired final value rho parameter.  It is approximately
          the accuracy in the variables. (Defaults to 1d-6.)

    `iprint'
          Verbose output level.  (Defaults to 0)
             * 0 - No output

             * 1 - Summary at the end of the calculation

             * 2 - Each new value of RHO and SIGMA is printed, including
               the vector of variables, some function information when
               RHO is reduced.

             * 3 - Like 2, but information is printed when F(X) is
               computed.

    `maxfun'
          The maximum number of function evaluations.  (Defaults to
          1000).

     On return, a vector is given:
       1. The value of the variables giving the minimum.  This is a
          list of elements of the form `<var> = <value>' for each of the
          variables listed in <X>.

       2. The minimized function value

       3. The number of function evaluations.

       4. Return code with the following meanings
            1.  0 - No errors.

            2.  1 - Limit on maximum number of function evaluations
               reached.

            3.  2 - Rounding errors inhibiting progress.

     `load(fmin_cobyla)' loads this function.


 -- Function: bf_fmin_cobyla (<F>, <X>, <Y>)
 -- Function: bf_fmin_cobyla (<F>, <X>, <Y>, optional_args)
     This function is identical to `fmin_cobyla', except that bigfloat
     operations are used, and the default value for <rhoend> is
     `10^(fpprec/2)'.

     See `fmin_cobyla' for more information.

     `load(fmin_cobyla)' loads this function.



File: maxima.info,  Node: Examples for cobyla,  Prev: Functions and Variables for cobyla,  Up: cobyla

43.3 Examples for cobyla
========================

Minimize x1*x2 with 1-x1^2-x2^2 >= 0.  The theoretical solution is x1 =
1/sqrt(2), x2 = -1/sqrt(2).

     (%i1) load(fmin_cobyla)$
     (%i2) fmin_cobyla(x1*x2, [x1, x2], [1,1],
                       constraints = [x1^2+x2^2<=1], iprint=1);
        Normal return from subroutine COBYLA

        NFVALS =   66   F =-5.000000E-01    MAXCV = 1.999845E-12
        X = 7.071058E-01  -7.071077E-01
     (%o2) [[x1 = 0.70710584934848, x2 = - 0.7071077130248],
            - 0.49999999999926, [[-1.999955756559757e-12],[]], 66]

   There are additional examples in the share/cobyla/ex directory.


File: maxima.info,  Node: contrib_ode,  Next: descriptive,  Prev: cobyla,  Up: Top

44 contrib_ode
**************

* Menu:

* Introduction to contrib_ode::
* Functions and Variables for contrib_ode::
* Possible improvements to contrib_ode::
* Test cases for contrib_ode::
* References for contrib_ode::


File: maxima.info,  Node: Introduction to contrib_ode,  Next: Functions and Variables for contrib_ode,  Prev: contrib_ode,  Up: contrib_ode

44.1 Introduction to contrib_ode
================================

Maxima's ordinary differential equation (ODE) solver `ode2' solves
elementary linear ODEs of first and second order.  The function
`contrib_ode' extends `ode2' with additional methods for linear and
non-linear first order ODEs and linear homogeneous second order ODEs.
The code is still under development and the calling sequence may change
in future releases.  Once the code has stabilized it may be moved from
the contrib directory and integrated into Maxima.

   This package must be loaded with the command `load('contrib_ode)'
before use.

   The calling convention for `contrib_ode' is identical to `ode2'.  It
takes three arguments: an ODE (only the left hand side need be given if
the right hand side is 0), the dependent variable, and the independent
variable.  When successful, it returns a list of solutions.

   The form of the solution differs from `ode2'.  As non-linear
equations can have multiple solutions, `contrib_ode' returns a list of
solutions.  Each  solution can have a number of forms:
   * an explicit solution for the dependent variable,

   * an implicit solution for the dependent variable,

   * a parametric solution in terms of variable `%t', or

   * a tranformation into another ODE in variable `%u'.


   `%c' is used to represent the constant of integration for first
order equations.  `%k1' and `%k2' are the constants for second order
equations.  If `contrib_ode' cannot obtain a solution for whatever
reason, it returns `false', after perhaps printing out an error message.

   It is necessary to return a list of solutions, as even first order
non-linear ODEs can have multiple solutions.  For example:

     (%i1) load('contrib_ode)$

     (%i2) eqn:x*'diff(y,x)^2-(1+x*y)*'diff(y,x)+y=0;

                         dy 2             dy
     (%o2)            x (--)  - (x y + 1) -- + y = 0
                         dx               dx
     (%i3) contrib_ode(eqn,y,x);

                                                  x
     (%o3)             [y = log(x) + %c, y = %c %e ]
     (%i4) method;

     (%o4)                        factor

   Nonlinear ODEs can have singular solutions without constants of
integration, as in the second solution of the following example:

     (%i1) load('contrib_ode)$

     (%i2) eqn:'diff(y,x)^2+x*'diff(y,x)-y=0;

                            dy 2     dy
     (%o2)                 (--)  + x -- - y = 0
                            dx       dx
     (%i3) contrib_ode(eqn,y,x);

                                                2
                                      2        x
     (%o3)              [y = %c x + %c , y = - --]
                                               4
     (%i4) method;

     (%o4)                       clairault

   The following ODE has two parametric solutions in terms of the dummy
variable `%t'.  In this case the parametric solutions can be manipulated
to give explicit solutions.

     (%i1) load('contrib_ode)$

     (%i2) eqn:'diff(y,x)=(x+y)^2;

                               dy          2
     (%o2)                     -- = (y + x)
                               dx
     (%i3) contrib_ode(eqn,y,x);

     (%o3) [[x = %c - atan(sqrt(%t)), y = - x - sqrt(%t)],
                          [x = atan(sqrt(%t)) + %c, y = sqrt(%t) - x]]
     (%i4) method;

     (%o4)                       lagrange

   The following example (Kamke 1.112) demonstrates an implicit
solution.

     (%i1) load('contrib_ode)$

     (%i2) assume(x>0,y>0);

     (%o2)                    [x > 0, y > 0]
     (%i3) eqn:x*'diff(y,x)-x*sqrt(y^2+x^2)-y;

                          dy           2    2
     (%o3)              x -- - x sqrt(y  + x ) - y
                          dx
     (%i4) contrib_ode(eqn,y,x);

                                       y
     (%o4)                  [x - asinh(-) = %c]
                                       x
     (%i5) method;

     (%o5)                          lie

   The following Riccati equation is transformed into a linear second
order ODE in the variable `%u'.  Maxima is unable to solve the new ODE,
so it is returned unevaluated.
     (%i1) load('contrib_ode)$

     (%i2) eqn:x^2*'diff(y,x)=a+b*x^n+c*x^2*y^2;

                         2 dy      2  2      n
     (%o2)              x  -- = c x  y  + b x  + a
                           dx
     (%i3) contrib_ode(eqn,y,x);

                    d%u
                    ---                            2
                    dx        2     n - 2   a     d %u
     (%o3)  [[y = - ----, %u c  (b x      + --) + ---- c = 0]]
                    %u c                     2      2
                                            x     dx
     (%i4) method;

     (%o4)                        riccati

   For first order ODEs `contrib_ode' calls `ode2'.  It then tries the
following methods: factorization, Clairault, Lagrange, Riccati, Abel
and Lie symmetry methods.  The Lie method is not attempted on Abel
equations if the Abel method fails, but it is tried if the Riccati
method returns an unsolved second order ODE.

   For second order ODEs `contrib_ode' calls `ode2' then `odelin'.

   Extensive debugging traces and messages are displayed if the command
`put('contrib_ode,true,'verbose)' is executed.


File: maxima.info,  Node: Functions and Variables for contrib_ode,  Next: Possible improvements to contrib_ode,  Prev: Introduction to contrib_ode,  Up: contrib_ode

44.2 Functions and Variables for contrib_ode
============================================

 -- Function: contrib_ode (<eqn>, <y>, <x>)
     Returns a list of solutions of the ODE <eqn> with independent
     variable <x> and dependent variable <y>.


 -- Function: odelin (<eqn>, <y>, <x>)
     `odelin' solves linear homogeneous ODEs of first and second order
     with independent variable <x> and dependent variable <y>.  It
     returns a fundamental solution set of the ODE.

     For second order ODEs, `odelin' uses a method, due to Bronstein
     and Lafaille, that searches for solutions in terms of given
     special functions.

          (%i1) load('contrib_ode);

          (%i2) odelin(x*(x+1)*'diff(y,x,2)+(x+5)*'diff(y,x,1)+(-4)*y,y,x);
          ...trying factor method
          ...solving 7 equations in 4 variables
          ...trying the Bessel solver
          ...solving 1 equations in 2 variables
          ...trying the F01 solver
          ...solving 1 equations in 3 variables
          ...trying the spherodial wave solver
          ...solving 1 equations in 4 variables
          ...trying the square root Bessel solver
          ...solving 1 equations in 2 variables
          ...trying the 2F1 solver
          ...solving 9 equations in 5 variables
                 gauss_a(- 6, - 2, - 3, - x)  gauss_b(- 6, - 2, - 3, - x)
          (%o2) {---------------------------, ---------------------------}
                              4                            4
                             x                            x


 -- Function: ode_check (<eqn>, <soln>)
     Returns the value of ODE <eqn> after substituting a possible
     solution <soln>.  The value is equivalent to zero if <soln> is a
     solution of <eqn>.

          (%i1) load('contrib_ode)$

          (%i2) eqn:'diff(y,x,2)+(a*x+b)*y;

                                   2
                                  d y
          (%o2)                   --- + (a x + b) y
                                    2
                                  dx
          (%i3) ans:[y = bessel_y(1/3,2*(a*x+b)^(3/2)/(3*a))*%k2*sqrt(a*x+b)
                   +bessel_j(1/3,2*(a*x+b)^(3/2)/(3*a))*%k1*sqrt(a*x+b)];

                                            3/2
                              1  2 (a x + b)
          (%o3) [y = bessel_y(-, --------------) %k2 sqrt(a x + b)
                              3       3 a
                                                    3/2
                                      1  2 (a x + b)
                           + bessel_j(-, --------------) %k1 sqrt(a x + b)]
                                      3       3 a
          (%i4) ode_check(eqn,ans[1]);

          (%o4)                           0


 -- System variable: method
     The variable `method' is set to the successful solution method.


 -- Variable: %c
     `%c' is the integration constant for first order ODEs.


 -- Variable: %k1
     `%k1' is the first integration constant for second order ODEs.


 -- Variable: %k2
     `%k2' is the second integration constant for second order ODEs.


 -- Function: gauss_a (<a>, <b>, <c>, <x>)
     `gauss_a(a,b,c,x)' and `gauss_b(a,b,c,x)' are 2F1 geometric
     functions.  They represent any two independent solutions of the
     hypergeometric differential equation `x(1-x) diff(y,x,2) +
     [c-(a+b+1)x diff(y,x) - aby = 0' (A&S 15.5.1).

     The only use of these functions is in solutions of ODEs returned by
     `odelin' and `contrib_ode'.  The definition and use of these
     functions may change in future releases of Maxima.

     See also `gauss_b', `dgauss_a' and `gauss_b'.


 -- Function: gauss_b (<a>, <b>, <c>, <x>)
     See `gauss_a'.


 -- Function: dgauss_a (<a>, <b>, <c>, <x>)
     The derivative with respect to <x> of `gauss_a(<a>, <b>, <c>,
     <x>)'.


 -- Function: dgauss_b (<a>, <b>, <c>, <x>)
     The derivative with respect to <x> of `gauss_b(<a>, <b>, <c>,
     <x>)'.


 -- Function: kummer_m (<a>, <b>, <x>)
     Kummer's M function, as defined in Abramowitz and Stegun, Handbook
     of Mathematical Functions, Section 13.1.2.

     The only use of this function is in solutions of ODEs returned by
     `odelin' and `contrib_ode'.  The definition and use of this
     function may change in future releases of Maxima.

     See also `kummer_u', `dkummer_m' and `dkummer_u'.


 -- Function: kummer_u (<a>, <b>, <x>)
     Kummer's U function, as defined in Abramowitz and Stegun, Handbook
     of Mathematical Functions, Section 13.1.3.

     See `kummer_m'.


 -- Function: dkummer_m (<a>, <b>, <x>)
     The derivative with respect to <x> of `kummer_m(<a>, <b>, <x>)'.


 -- Function: dkummer_u (<a>, <b>, <x>)
     The derivative with respect to <x> of `kummer_u(<a>, <b>, <x>)'.



File: maxima.info,  Node: Possible improvements to contrib_ode,  Next: Test cases for contrib_ode,  Prev: Functions and Variables for contrib_ode,  Up: contrib_ode

44.3 Possible improvements to contrib_ode
=========================================

These routines are work in progress.  I still need to:

   * Extend the FACTOR method `ode1_factor' to work for multiple roots.

   * Extend the FACTOR method `ode1_factor' to attempt to solve higher
     order factors.  At present it only attemps to solve linear
     factors.

   * Fix the LAGRANGE routine `ode1_lagrange' to prefer real roots over
      complex roots.

   * Add additional methods for Riccati equations.

   * Improve the detection of Abel equations of second kind.  The
     exisiting   pattern matching is weak.

   * Work on the Lie symmetry group routine `ode1_lie'.  There are
     quite a   few problems with it: some parts are unimplemented; some
     test cases   seem to run forever; other test cases crash; yet
     others return very   complex "solutions".  I wonder if it really
     ready for release yet.

   * Add more test cases.



File: maxima.info,  Node: Test cases for contrib_ode,  Next: References for contrib_ode,  Prev: Possible improvements to contrib_ode,  Up: contrib_ode

44.4 Test cases for contrib_ode
===============================

The routines have been tested on a approximately one thousand  test
cases from Murphy, Kamke, Zwillinger and elsewhere.  These are included
in the tests subdirectory.

   * The Clairault routine `ode1_clairault' finds all known solutions,
     including singular solutions, of the Clairault equations in
     Murphy and   Kamke.

   * The other routines often return a single solution when multiple
     solutions exist.

   * Some of the "solutions" from `ode1_lie' are overly complex and
     impossible to check.

   * There are some crashes.



File: maxima.info,  Node: References for contrib_ode,  Prev: Test cases for contrib_ode,  Up: contrib_ode

44.5 References for contrib_ode
===============================

  1. E. Kamke, Differentialgleichungen Losungsmethoden und Losungen,
     Vol 1,     Geest & Portig, Leipzig, 1961

  2. G. M. Murphy, Ordinary Differential Equations and Their Solutions,
        Van Nostrand, New York, 1960

  3. D. Zwillinger, Handbook of Differential Equations, 3rd edition,
     Academic Press, 1998

  4. F. Schwarz, Symmetry Analysis of Abel's Equation, Studies in
     Applied Mathematics, 100:269-294 (1998)

  5. F. Schwarz, Algorithmic Solution of Abel's Equation,     Computing
     61, 39-49 (1998)

  6. E. S. Cheb-Terrab, A. D. Roche, Symmetries and First Order     ODE
     Patterns, Computer Physics Communications 113 (1998), p 239.
     (`http://lie.uwaterloo.ca/papers/ode_vii.pdf')

  7. E. S. Cheb-Terrab, T. Kolokolnikov,  First Order ODEs,
     Symmetries and Linear Transformations, European Journal of
     Applied Mathematics, Vol. 14, No. 2, pp. 231-246 (2003).
     (`http://arxiv.org/abs/math-ph/0007023',
     `http://lie.uwaterloo.ca/papers/ode_iv.pdf')

  8. G. W. Bluman, S. C. Anco, Symmetry and Integration Methods for
     Differential Equations, Springer, (2002)

  9. M. Bronstein, S. Lafaille, Solutions of linear ordinary
     differential equations in terms of special functions, Proceedings
     of ISSAC 2002, Lille, ACM Press, 23-28.
     (`http://www-sop.inria.fr/cafe/Manuel.Bronstein/publications/issac2002.pdf')



File: maxima.info,  Node: descriptive,  Next: diag,  Prev: contrib_ode,  Up: Top

45 descriptive
**************

* Menu:

* Introduction to descriptive::
* Functions and Variables for data manipulation::
* Functions and Variables for descriptive statistics::
* Functions and Variables for statistical graphs::


File: maxima.info,  Node: Introduction to descriptive,  Next: Functions and Variables for data manipulation,  Prev: descriptive,  Up: descriptive

45.1 Introduction to descriptive
================================

Package `descriptive' contains a set of functions for making
descriptive statistical computations and graphing.  Together with the
source code there are three data sets in your Maxima tree:
`pidigits.data', `wind.data' and `biomed.data'.

   Any statistics manual can be used as a reference to the functions in
package `descriptive'.

   For comments, bugs or suggestions, please contact me at <'mario AT
edu DOT xunta DOT es'>.

   Here is a simple example on how the descriptive functions in
`descriptive' do they work, depending on the nature of their arguments,
lists or matrices,

     (%i1) load (descriptive)$
     (%i2) /* univariate sample */   mean ([a, b, c]);
                                 c + b + a
     (%o2)                       ---------
                                     3
     (%i3) matrix ([a, b], [c, d], [e, f]);
                                 [ a  b ]
                                 [      ]
     (%o3)                       [ c  d ]
                                 [      ]
                                 [ e  f ]
     (%i4) /* multivariate sample */ mean (%);
                           e + c + a  f + d + b
     (%o4)                [---------, ---------]
                               3          3

   Note that in multivariate samples the mean is calculated for each
column.

   In case of several samples with possible different sizes, the Maxima
function `map' can be used to get the desired results for each sample,

     (%i1) load (descriptive)$
     (%i2) map (mean, [[a, b, c], [d, e]]);
                             c + b + a  e + d
     (%o2)                  [---------, -----]
                                 3        2

   In this case, two samples of sizes 3 and 2 were stored into a list.

   Univariate samples must be stored in lists like

     (%i1) s1 : [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
     (%o1)           [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]

   and multivariate samples in matrices as in

     (%i1) s2 : matrix ([13.17, 9.29], [14.71, 16.88], [18.50, 16.88],
                  [10.58, 6.63], [13.33, 13.25], [13.21,  8.12]);
                             [ 13.17  9.29  ]
                             [              ]
                             [ 14.71  16.88 ]
                             [              ]
                             [ 18.5   16.88 ]
     (%o1)                   [              ]
                             [ 10.58  6.63  ]
                             [              ]
                             [ 13.33  13.25 ]
                             [              ]
                             [ 13.21  8.12  ]

   In this case, the number of columns equals the random variable
dimension and the number of rows is the sample size.

   Data can be introduced by hand, but big samples are usually stored
in plain text files. For example, file `pidigits.data' contains the
first 100 digits of number `%pi':
           3
           1
           4
           1
           5
           9
           2
           6
           5
           3 ...

   In order to load these digits in Maxima,

     (%i1) s1 : read_list (file_search ("pidigits.data"))$
     (%i2) length (s1);
     (%o2)                          100

   On the other hand, file `wind.data' contains daily average wind
speeds at 5 meteorological stations in the Republic of Ireland (This is
part of a data set taken at 12 meteorological stations. The original
file is freely downloadable from the StatLib Data Repository and its
analysis is discused in Haslett, J., Raftery, A. E. (1989) <Space-time
Modelling with Long-memory Dependence: Assessing Ireland's Wind Power
Resource, with Discussion>. Applied Statistics 38, 1-50). This loads
the data:

     (%i1) s2 : read_matrix (file_search ("wind.data"))$
     (%i2) length (s2);
     (%o2)                          100
     (%i3) s2 [%]; /* last record */
     (%o3)            [3.58, 6.0, 4.58, 7.62, 11.25]

   Some samples contain non numeric data. As an example, file
`biomed.data' (which is part of another bigger one downloaded from the
StatLib Data Repository) contains four blood measures taken from two
groups of patients, `A' and `B', of different ages,

     (%i1) s3 : read_matrix (file_search ("biomed.data"))$
     (%i2) length (s3);
     (%o2)                          100
     (%i3) s3 [1]; /* first record */
     (%o3)            [A, 30, 167.0, 89.0, 25.6, 364]

   The first individual belongs to group `A', is 30 years old and
his/her blood measures were 167.0, 89.0, 25.6 and 364.

   One must take care when working with categorical data. In the next
example, symbol `a' is asigned a value in some previous moment and then
a sample with categorical value `a' is taken,

     (%i1) a : 1$
     (%i2) matrix ([a, 3], [b, 5]);
                                 [ 1  3 ]
     (%o2)                       [      ]
                                 [ b  5 ]


File: maxima.info,  Node: Functions and Variables for data manipulation,  Next: Functions and Variables for descriptive statistics,  Prev: Introduction to descriptive,  Up: descriptive

45.2 Functions and Variables for data manipulation
==================================================

 -- Function: build_sample (<list>)
 -- Function: build_sample (<matrix>)
     Builds a sample from a table of absolute frequencies.  The input
     table can be a matrix or a list of lists, all of them of equal
     size. The number of columns or the length of the lists must be
     greater than 1. The last element of each row or list is
     interpreted as the absolute frequency.  The output is always a
     sample in matrix form.

     Examples:

     Univariate frequency table.

          (%i1) load (descriptive)$
          (%i2) sam1: build_sample([[6,1], [j,2], [2,1]]);
                                 [ 6 ]
                                 [   ]
                                 [ j ]
          (%o2)                  [   ]
                                 [ j ]
                                 [   ]
                                 [ 2 ]
          (%i3) mean(sam1);
                                2 j + 8
          (%o3)                [-------]
                                   4
          (%i4) barsplot(sam1) $

     Multivariate frequency table.

          (%i1) load (descriptive)$
          (%i2) sam2: build_sample([[6,3,1], [5,6,2], [u,2,1],[6,8,2]]) ;
                                     [ 6  3 ]
                                     [      ]
                                     [ 5  6 ]
                                     [      ]
                                     [ 5  6 ]
          (%o2)                      [      ]
                                     [ u  2 ]
                                     [      ]
                                     [ 6  8 ]
                                     [      ]
                                     [ 6  8 ]
          (%i3) cov(sam2);
                 [   2                 2                            ]
                 [  u  + 158   (u + 28)     2 u + 174   11 (u + 28) ]
                 [  -------- - ---------    --------- - ----------- ]
          (%o3)  [     6          36            6           12      ]
                 [                                                  ]
                 [ 2 u + 174   11 (u + 28)            21            ]
                 [ --------- - -----------            --            ]
                 [     6           12                 4             ]
          (%i4) barsplot(sam2, grouping=stacked) $


 -- Function: continuous_freq (<list>)
 -- Function: continuous_freq (<list>, <m>)
     The argument of `continuous_freq' must be a list of numbers.
     Divides the range in intervals and counts how many values are
     inside them. The second argument is optional and either equals the
     number of classes we want, 10 by default, or equals a list
     containing the class limits and the number of classes we want, or
     a list containing only the limits.  Argument <list> must be a list
     of (2 or 3) real numbers.  If sample values are all equal, this
     function returns only one class of amplitude 2.

     Examples:

     Optional argument indicates the number of classes we want.  The
     first list in the output contains the interval limits, and the
     second the corresponding counts: there are 16 digits inside the
     interval `[0, 1.8]', 24 digits in `(1.8, 3.6]', and so on.

          (%i1) load (descriptive)$
          (%i2) s1 : read_list (file_search ("pidigits.data"))$
          (%i3) continuous_freq (s1, 5);
          (%o3) [[0, 1.8, 3.6, 5.4, 7.2, 9.0], [16, 24, 18, 17, 25]]

     Optional argument indicates we want 7 classes with limits -2 and
     12:

          (%i1) load (descriptive)$
          (%i2) s1 : read_list (file_search ("pidigits.data"))$
          (%i3) continuous_freq (s1, [-2,12,7]);
          (%o3) [[- 2, 0, 2, 4, 6, 8, 10, 12], [8, 20, 22, 17, 20, 13, 0]]

     Optional argument indicates we want the default number of classes
     with limits -2 and 12:

          (%i1) load (descriptive)$
          (%i2) s1 : read_list (file_search ("pidigits.data"))$
          (%i3) continuous_freq (s1, [-2,12]);
                          3  4  11  18     32  39  46  53
          (%o3)  [[- 2, - -, -, --, --, 5, --, --, --, --, 12],
                          5  5  5   5      5   5   5   5
                         [0, 8, 20, 12, 18, 9, 8, 25, 0, 0]]


 -- Function: discrete_freq (<list>)
     Counts absolute frequencies in discrete samples, both numeric and
     categorical. Its unique argument is a list,

          (%i1) load (descriptive)$
          (%i2) s1 : read_list (file_search ("pidigits.data"))$
          (%i3) discrete_freq (s1);
          (%o3) [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
                                       [8, 8, 12, 12, 10, 8, 9, 8, 12, 13]]

     The first list gives the sample values and the second their
     absolute frequencies. Commands `? col' and `? transpose' should
     help you to understand the last input.


 -- Function: standardize (<list>)
 -- Function: standardize (<matrix>)
     Subtracts to each element of the list the sample mean and divides
     the result by the standard deviation. When the input is a matrix,
     `standardize' subtracts to each row the multivariate mean, and then
     divides each component by the corresponding standard deviation.


 -- Function: subsample (<data_matrix>, <predicate_function>)
 -- Function: subsample (<data_matrix>, <predicate_function>,
          <col_num1>, <col_num2>, ...)
     This is a sort of variant of the Maxima `submatrix' function.  The
     first argument is the data matrix, the second is a predicate
     function and optional additional arguments are the numbers of the
     columns to be taken.  Its behaviour is better understood with
     examples.

     These are multivariate records in which the wind speed in the
     first meteorological station were greater than 18.  See that in
     the lambda expression the <i>-th component is refered to as `v[i]'.
          (%i1) load (descriptive)$
          (%i2) s2 : read_matrix (file_search ("wind.data"))$
          (%i3) subsample (s2, lambda([v], v[1] > 18));
                        [ 19.38  15.37  15.12  23.09  25.25 ]
                        [                                   ]
                        [ 18.29  18.66  19.08  26.08  27.63 ]
          (%o3)         [                                   ]
                        [ 20.25  21.46  19.95  27.71  23.38 ]
                        [                                   ]
                        [ 18.79  18.96  14.46  26.38  21.84 ]

     In the following example, we request only the first, second and
     fifth components of those records with wind speeds greater or
     equal than 16 in station number 1 and less than 25 knots in
     station number 4. The sample contains only data from stations 1, 2
     and 5. In this case, the predicate function is defined as an
     ordinary Maxima function.
          (%i1) load (descriptive)$
          (%i2) s2 : read_matrix (file_search ("wind.data"))$
          (%i3) g(x):= x[1] >= 16 and x[4] < 25$
          (%i4) subsample (s2, g, 1, 2, 5);
                               [ 19.38  15.37  25.25 ]
                               [                     ]
                               [ 17.33  14.67  19.58 ]
          (%o4)                [                     ]
                               [ 16.92  13.21  21.21 ]
                               [                     ]
                               [ 17.25  18.46  23.87 ]

     Here is an example with the categorical variables of `biomed.data'.
     We want the records corresponding to those patients in group `B'
     who are older than 38 years.
          (%i1) load (descriptive)$
          (%i2) s3 : read_matrix (file_search ("biomed.data"))$
          (%i3) h(u):= u[1] = B and u[2] > 38 $
          (%i4) subsample (s3, h);
                          [ B  39  28.0  102.3  17.1  146 ]
                          [                               ]
                          [ B  39  21.0  92.4   10.3  197 ]
                          [                               ]
                          [ B  39  23.0  111.5  10.0  133 ]
                          [                               ]
                          [ B  39  26.0  92.6   12.3  196 ]
          (%o4)           [                               ]
                          [ B  39  25.0  98.7   10.0  174 ]
                          [                               ]
                          [ B  39  21.0  93.2   5.9   181 ]
                          [                               ]
                          [ B  39  18.0  95.0   11.3  66  ]
                          [                               ]
                          [ B  39  39.0  88.5   7.6   168 ]

     Probably, the statistical analysis will involve only the blood
     measures,
          (%i1) load (descriptive)$
          (%i2) s3 : read_matrix (file_search ("biomed.data"))$
          (%i3) subsample (s3, lambda([v], v[1] = B and v[2] > 38),
                           3, 4, 5, 6);
                             [ 28.0  102.3  17.1  146 ]
                             [                        ]
                             [ 21.0  92.4   10.3  197 ]
                             [                        ]
                             [ 23.0  111.5  10.0  133 ]
                             [                        ]
                             [ 26.0  92.6   12.3  196 ]
          (%o3)              [                        ]
                             [ 25.0  98.7   10.0  174 ]
                             [                        ]
                             [ 21.0  93.2   5.9   181 ]
                             [                        ]
                             [ 18.0  95.0   11.3  66  ]
                             [                        ]
                             [ 39.0  88.5   7.6   168 ]

     This is the multivariate mean of `s3',
          (%i1) load (descriptive)$
          (%i2) s3 : read_matrix (file_search ("biomed.data"))$
          (%i3) mean (s3);
                 65 B + 35 A  317          6 NA + 8144.999999999999
          (%o3) [-----------, ---, 87.178, ------------------------,
                     100      10                     100
                                                              3 NA + 19587
                                                      18.123, ------------]
                                                                  100

     Here, the first component is meaningless, since `A' and `B' are
     categorical, the second component is the mean age of individuals
     in rational form, and the fourth and last values exhibit some
     strange behaviour. This is because symbol `NA' is used here to
     indicate <non available> data, and the two means are nonsense. A
     possible solution would be to take out from the matrix those rows
     with `NA' symbols, although this deserves some loss of information.
          (%i1) load (descriptive)$
          (%i2) s3 : read_matrix (file_search ("biomed.data"))$
          (%i3) g(v):= v[4] # NA and v[6] # NA $
          (%i4) mean (subsample (s3, g, 3, 4, 5, 6));
          (%o4) [79.4923076923077, 86.2032967032967, 16.93186813186813,
                                                                      2514
                                                                      ----]
                                                                       13


 -- Function: tranform_sample (<matrix>, <varlist>, <exprlist>)
     Transforms the sample <matrix>, where each column is called
     according to <varlist>, following expressions in <exprlist>.

     Examples:

     The second argument assigns names to the three columns. With these
     names, a list of expressions define the transformation of the
     sample.

          (%i1) load (descriptive)$
          (%i2) data: matrix([3,2,7],[3,7,2],[8,2,4],[5,2,4]) $
          (%i3) tranform_sample(data, [a,b,c], [c, a*b, log(a)]);
                                         [ 7  6   log(3) ]
                                         [               ]
                                         [ 2  21  log(3) ]
          (%o3)                          [               ]
                                         [ 4  16  log(8) ]
                                         [               ]
                                         [ 4  10  log(5) ]

     Add a constant column and remove the third variable.

          (%i1) load (descriptive)$
          (%i2) data: matrix([3,2,7],[3,7,2],[8,2,4],[5,2,4]) $
          (%i3) tranform_sample(data, [a,b,c], [makelist(1,k,length(data)),a,b]);
                                            [ 1  3  2 ]
                                            [         ]
                                            [ 1  3  7 ]
          (%o3)                             [         ]
                                            [ 1  8  2 ]
                                            [         ]
                                            [ 1  5  2 ]



File: maxima.info,  Node: Functions and Variables for descriptive statistics,  Next: Functions and Variables for statistical graphs,  Prev: Functions and Variables for data manipulation,  Up: descriptive

45.3 Functions and Variables for descriptive statistics
=======================================================

 -- Function: mean (<list>)
 -- Function: mean (<matrix>)
     This is the sample mean, defined as
                                 n
                               ====
                       _   1   \
                       x = -    >    x
                           n   /      i
                               ====
                               i = 1

     Example:

          (%i1) load (descriptive)$
          (%i2) s1 : read_list (file_search ("pidigits.data"))$
          (%i3) mean (s1);
                                         471
          (%o3)                          ---
                                         100
          (%i4) %, numer;
          (%o4)                         4.71
          (%i5) s2 : read_matrix (file_search ("wind.data"))$
          (%i6) mean (s2);
          (%o6)     [9.9485, 10.1607, 10.8685, 15.7166, 14.8441]


 -- Function: var (<list>)
 -- Function: var (<matrix>)
     This is the sample variance, defined as
                               n
                             ====
                     2   1   \          _ 2
                    s  = -    >    (x - x)
                         n   /       i
                             ====
                             i = 1

     Example:

          (%i1) load (descriptive)$
          (%i2) s1 : read_list (file_search ("pidigits.data"))$
          (%i3) var (s1), numer;
          (%o3)                   8.425899999999999

     See also function `var1'.


 -- Function: var1 (<list>)
 -- Function: var1 (<matrix>)
     This is the sample variance, defined as
                               n
                             ====
                         1   \          _ 2
                        ---   >    (x - x)
                        n-1  /       i
                             ====
                             i = 1

     Example:

          (%i1) load (descriptive)$
          (%i2) s1 : read_list (file_search ("pidigits.data"))$
          (%i3) var1 (s1), numer;
          (%o3)                    8.5110101010101
          (%i4) s2 : read_matrix (file_search ("wind.data"))$
          (%i5) var1 (s2);
          (%o5) [17.39586540404041, 15.13912778787879, 15.63204924242424,
                                      32.50152569696971, 24.66977392929294]

     See also function `var'.


 -- Function: std (<list>)
 -- Function: std (<matrix>)
     This is the the square root of function `var', the variance with
     denominator n.

     Example:

          (%i1) load (descriptive)$
          (%i2) s1 : read_list (file_search ("pidigits.data"))$
          (%i3) std (s1), numer;
          (%o3)                   2.902740084816414
          (%i4) s2 : read_matrix (file_search ("wind.data"))$
          (%i5) std (s2);
          (%o5) [4.149928523480858, 3.871399812729241, 3.933920277534866,
                                      5.672434260526957, 4.941970881136392]

     See also functions `var' and `std1'.


 -- Function: std1 (<list>)
 -- Function: std1 (<matrix>)
     This is the the square root of function `var1', the variance with
     denominator n-1.

     Example:

          (%i1) load (descriptive)$
          (%i2) s1 : read_list (file_search ("pidigits.data"))$
          (%i3) std1 (s1), numer;
          (%o3)                   2.917363553109228
          (%i4) s2 : read_matrix (file_search ("wind.data"))$
          (%i5) std1 (s2);
          (%o5) [4.170835096721089, 3.89090320978032, 3.953738641137555,
                                      5.701010936401517, 4.966867617451963]

     See also functions `var1' and `std'.


 -- Function: noncentral_moment (<list>, <k>)
 -- Function: noncentral_moment (<matrix>, <k>)
     The non central moment of order k, defined as
                                 n
                               ====
                           1   \      k
                           -    >    x
                           n   /      i
                               ====
                               i = 1

     Example:

          (%i1) load (descriptive)$
          (%i2) s1 : read_list (file_search ("pidigits.data"))$
          (%i3) noncentral_moment (s1, 1), numer; /* the mean */
          (%o3)                         4.71
          (%i5) s2 : read_matrix (file_search ("wind.data"))$
          (%i6) noncentral_moment (s2, 5);
          (%o6) [319793.8724761505, 320532.1923892463,
                391249.5621381556, 2502278.205988911, 1691881.797742255]

     See also function `central_moment'.


 -- Function: central_moment (<list>, <k>)
 -- Function: central_moment (<matrix>, <k>)
     The central moment of order k, defined as
                              n
                            ====
                        1   \          _ k
                        -    >    (x - x)
                        n   /       i
                            ====
                            i = 1

     Example:

          (%i1) load (descriptive)$
          (%i2) s1 : read_list (file_search ("pidigits.data"))$
          (%i3) central_moment (s1, 2), numer; /* the variance */
          (%o3)                   8.425899999999999
          (%i5) s2 : read_matrix (file_search ("wind.data"))$
          (%i6) central_moment (s2, 3);
          (%o6) [11.29584771375004, 16.97988248298583, 5.626661952750102,
                                       37.5986572057918, 25.85981904394192]

     See also functions `central_moment' and `mean'.


 -- Function: cv (<list>)
 -- Function: cv (<matrix>)
     The variation coefficient is the quotient between the sample
     standard deviation (`std') and the `mean',

          (%i1) load (descriptive)$
          (%i2) s1 : read_list (file_search ("pidigits.data"))$
          (%i3) cv (s1), numer;
          (%o3)                   .6193977819764815
          (%i4) s2 : read_matrix (file_search ("wind.data"))$
          (%i5) cv (s2);
          (%o5) [.4192426091090204, .3829365309260502, 0.363779605385983,
                                      .3627381836021478, .3346021393989506]

     See also functions `std' and `mean'.


 -- Function: smin (<list>)
 -- Function: smin (<matrix>)
     This is the minimum value of the sample <list>.  When the argument
     is a matrix, `smin' returns a list containing the minimum values
     of the columns, which are associated to statistical variables.

          (%i1) load (descriptive)$
          (%i2) s1 : read_list (file_search ("pidigits.data"))$
          (%i3) smin (s1);
          (%o3)                           0
          (%i4) s2 : read_matrix (file_search ("wind.data"))$
          (%i5) smin (s2);
          (%o5)             [0.58, 0.5, 2.67, 5.25, 5.17]

     See also function `smax'.


 -- Function: smax (<list>)
 -- Function: smax (<matrix>)
     This is the maximum value of the sample <list>.  When the argument
     is a matrix, `smax' returns a list containing the maximum values
     of the columns, which are associated to statistical variables.

          (%i1) load (descriptive)$
          (%i2) s1 : read_list (file_search ("pidigits.data"))$
          (%i3) smax (s1);
          (%o3)                           9
          (%i4) s2 : read_matrix (file_search ("wind.data"))$
          (%i5) smax (s2);
          (%o5)          [20.25, 21.46, 20.04, 29.63, 27.63]

     See also function `smin'.


 -- Function: range (<list>)
 -- Function: range (<matrix>)
     The range is the difference between the extreme values.

     Example:

          (%i1) load (descriptive)$
          (%i2) s1 : read_list (file_search ("pidigits.data"))$
          (%i3) range (s1);
          (%o3)                           9
          (%i4) s2 : read_matrix (file_search ("wind.data"))$
          (%i5) range (s2);
          (%o5)          [19.67, 20.96, 17.37, 24.38, 22.46]


 -- Function: quantile (<list>, <p>)
 -- Function: quantile (<matrix>, <p>)
     This is the <p>-quantile, with <p> a number in [0, 1], of the
     sample <list>.  Although there are several definitions for the
     sample quantile (Hyndman, R. J., Fan, Y. (1996) <Sample quantiles
     in statistical packages>. American Statistician, 50, 361-365), the
     one based on linear interpolation is implemented in package
     `descriptive'.

     Example:

          (%i1) load (descriptive)$
          (%i2) s1 : read_list (file_search ("pidigits.data"))$
          (%i3) /* 1st and 3rd quartiles */
                   [quantile (s1, 1/4), quantile (s1, 3/4)], numer;
          (%o3)                      [2.0, 7.25]
          (%i4) s2 : read_matrix (file_search ("wind.data"))$
          (%i5) quantile (s2, 1/4);
          (%o5)    [7.2575, 7.477500000000001, 7.82, 11.28, 11.48]


 -- Function: median (<list>)
 -- Function: median (<matrix>)
     Once the sample is ordered, if the sample size is odd the median
     is the central value, otherwise it is the mean of the two central
     values.

     Example:

          (%i1) load (descriptive)$
          (%i2) s1 : read_list (file_search ("pidigits.data"))$
          (%i3) median (s1);
                                          9
          (%o3)                           -
                                          2
          (%i4) s2 : read_matrix (file_search ("wind.data"))$
          (%i5) median (s2);
          (%o5)         [10.06, 9.855, 10.73, 15.48, 14.105]

     The median is the 1/2-quantile.

     See also function `quantile'.


 -- Function: qrange (<list>)
 -- Function: qrange (<matrix>)
     The interquartilic range is the difference between the third and
     first quartiles, `quantile(<list>,3/4) - quantile(<list>,1/4)',

          (%i1) load (descriptive)$
          (%i2) s1 : read_list (file_search ("pidigits.data"))$
          (%i3) qrange (s1);
                                         21
          (%o3)                          --
                                         4
          (%i4) s2 : read_matrix (file_search ("wind.data"))$
          (%i5) qrange (s2);
          (%o5) [5.385, 5.572499999999998, 6.022500000000001,
                                      8.729999999999999, 6.649999999999999]

     See also function `quantile'.


 -- Function: mean_deviation (<list>)
 -- Function: mean_deviation (<matrix>)
     The mean deviation, defined as
                               n
                             ====
                         1   \          _
                         -    >    |x - x|
                         n   /       i
                             ====
                             i = 1

     Example:

          (%i1) load (descriptive)$
          (%i2) s1 : read_list (file_search ("pidigits.data"))$
          (%i3) mean_deviation (s1);
                                         51
          (%o3)                          --
                                         20
          (%i4) s2 : read_matrix (file_search ("wind.data"))$
          (%i5) mean_deviation (s2);
          (%o5) [3.287959999999999, 3.075342, 3.23907, 4.715664000000001,
                                                         4.028546000000002]

     See also function `mean'.


 -- Function: median_deviation (<list>)
 -- Function: median_deviation (<matrix>)
     The median deviation, defined as
                           n
                         ====
                     1   \
                     -    >    |x - med|
                     n   /       i
                         ====
                         i = 1
     where `med' is the median of <list>.

     Example:

          (%i1) load (descriptive)$
          (%i2) s1 : read_list (file_search ("pidigits.data"))$
          (%i3) median_deviation (s1);
                                          5
          (%o3)                           -
                                          2
          (%i4) s2 : read_matrix (file_search ("wind.data"))$
          (%i5) median_deviation (s2);
          (%o5)           [2.75, 2.755, 3.08, 4.315, 3.31]

     See also function `mean'.


 -- Function: harmonic_mean (<list>)
 -- Function: harmonic_mean (<matrix>)
     The harmonic mean, defined as
                            n
                         --------
                          n
                         ====
                         \     1
                          >    --
                         /     x
                         ====   i
                         i = 1

     Example:

          (%i1) load (descriptive)$
          (%i2) y : [5, 7, 2, 5, 9, 5, 6, 4, 9, 2, 4, 2, 5]$
          (%i3) harmonic_mean (y), numer;
          (%o3)                   3.901858027632205
          (%i4) s2 : read_matrix (file_search ("wind.data"))$
          (%i5) harmonic_mean (s2);
          (%o5) [6.948015590052786, 7.391967752360356, 9.055658197151745,
                                      13.44199028193692, 13.01439145898509]

     See also functions `mean' and `geometric_mean'.


 -- Function: geometric_mean (<list>)
 -- Function: geometric_mean (<matrix>)
     The geometric mean, defined as
                           /  n      \ 1/n
                           | /===\   |
                           |  ! !    |
                           |  ! !  x |
                           |  ! !   i|
                           | i = 1   |
                           \         /

     Example:

          (%i1) load (descriptive)$
          (%i2) y : [5, 7, 2, 5, 9, 5, 6, 4, 9, 2, 4, 2, 5]$
          (%i3) geometric_mean (y), numer;
          (%o3)                   4.454845412337012
          (%i4) s2 : read_matrix (file_search ("wind.data"))$
          (%i5) geometric_mean (s2);
          (%o5) [8.82476274347979, 9.22652604739361, 10.0442675714889,
                                      14.61274126349021, 13.96184163444275]

     See also functions `mean' and `harmonic_mean'.


 -- Function: kurtosis (<list>)
 -- Function: kurtosis (<matrix>)
     The kurtosis coefficient, defined as
                              n
                            ====
                      1     \          _ 4
                     ----    >    (x - x)  - 3
                        4   /       i
                     n s    ====
                            i = 1

     Example:

          (%i1) load (descriptive)$
          (%i2) s1 : read_list (file_search ("pidigits.data"))$
          (%i3) kurtosis (s1), numer;
          (%o3)                  - 1.273247946514421
          (%i4) s2 : read_matrix (file_search ("wind.data"))$
          (%i5) kurtosis (s2);
          (%o5) [- .2715445622195385, 0.119998784429451,
               - .4275233490482861, - .6405361979019522, - .4952382132352935]

     See also functions `mean', `var' and `skewness'.


 -- Function: skewness (<list>)
 -- Function: skewness (<matrix>)
     The skewness coefficient, defined as
                              n
                            ====
                      1     \          _ 3
                     ----    >    (x - x)
                        3   /       i
                     n s    ====
                            i = 1

     Example:

          (%i1) load (descriptive)$
          (%i2) s1 : read_list (file_search ("pidigits.data"))$
          (%i3) skewness (s1), numer;
          (%o3)                  .009196180476450424
          (%i4) s2 : read_matrix (file_search ("wind.data"))$
          (%i5) skewness (s2);
          (%o5) [.1580509020000978, .2926379232061854, .09242174416107717,
                                      .2059984348148687, .2142520248890831]

     See also functions `mean', `var' and `kurtosis'.


 -- Function: pearson_skewness (<list>)
 -- Function: pearson_skewness (<matrix>)
     Pearson's skewness coefficient, defined as
                          _
                       3 (x - med)
                       -----------
                            s
     where <med> is the median of <list>.

     Example:

          (%i1) load (descriptive)$
          (%i2) s1 : read_list (file_search ("pidigits.data"))$
          (%i3) pearson_skewness (s1), numer;
          (%o3)                   .2159484029093895
          (%i4) s2 : read_matrix (file_search ("wind.data"))$
          (%i5) pearson_skewness (s2);
          (%o5) [- .08019976629211892, .2357036272952649,
                   .1050904062491204, .1245042340592368, .4464181795804519]

     See also functions `mean', `var' and `median'.


 -- Function: quartile_skewness (<list>)
 -- Function: quartile_skewness (<matrix>)
     The quartile skewness coefficient, defined as
                         c    - 2 c    + c
                          3/4      1/2    1/4
                         --------------------
                             c    - c
                              3/4    1/4
     where c_p is the <p>-quantile of sample <list>.

     Example:

          (%i1) load (descriptive)$
          (%i2) s1 : read_list (file_search ("pidigits.data"))$
          (%i3) quartile_skewness (s1), numer;
          (%o3)                  .04761904761904762
          (%i4) s2 : read_matrix (file_search ("wind.data"))$
          (%i5) quartile_skewness (s2);
          (%o5) [- 0.0408542246982353, .1467025572005382,
                 0.0336239103362392, .03780068728522298, .2105263157894735]

     See also function `quantile'.


 -- Function: cov (<matrix>)
     The covariance matrix of the multivariate sample, defined as
                        n
                       ====
                    1  \           _        _
                S = -   >    (X  - X) (X  - X)'
                    n  /       j        j
                       ====
                       j = 1
     where X_j is the j-th row of the sample matrix.

     Example:

          (%i1) load (descriptive)$
          (%i2) s2 : read_matrix (file_search ("wind.data"))$
          (%i3) fpprintprec : 7$  /* change precision for pretty output */
          (%i4) cov (s2);
                [ 17.22191  13.61811  14.37217  19.39624  15.42162 ]
                [                                                  ]
                [ 13.61811  14.98774  13.30448  15.15834  14.9711  ]
                [                                                  ]
          (%o4) [ 14.37217  13.30448  15.47573  17.32544  16.18171 ]
                [                                                  ]
                [ 19.39624  15.15834  17.32544  32.17651  20.44685 ]
                [                                                  ]
                [ 15.42162  14.9711   16.18171  20.44685  24.42308 ]

     See also function `cov1'.


 -- Function: cov1 (<matrix>)
     The covariance matrix of the multivariate sample, defined as
                        n
                       ====
                   1   \           _        _
             S  = ---   >    (X  - X) (X  - X)'
              1   n-1  /       j        j
                       ====
                       j = 1
     where X_j is the j-th row of the sample matrix.

     Example:

          (%i1) load (descriptive)$
          (%i2) s2 : read_matrix (file_search ("wind.data"))$
          (%i3) fpprintprec : 7$ /* change precision for pretty output */
          (%i4) cov1 (s2);
                [ 17.39587  13.75567  14.51734  19.59216  15.5774  ]
                [                                                  ]
                [ 13.75567  15.13913  13.43887  15.31145  15.12232 ]
                [                                                  ]
          (%o4) [ 14.51734  13.43887  15.63205  17.50044  16.34516 ]
                [                                                  ]
                [ 19.59216  15.31145  17.50044  32.50153  20.65338 ]
                [                                                  ]
                [ 15.5774   15.12232  16.34516  20.65338  24.66977 ]

     See also function `cov'.


 -- Function: global_variances (<matrix>)
 -- Function: global_variances (<matrix>, <options> ...)
     Function `global_variances' returns a list of global variance
     measures:

        * <total variance>: `trace(S_1)',

        * <mean variance>: `trace(S_1)/p',

        * <generalized variance>: `determinant(S_1)',

        * <generalized standard deviation>: `sqrt(determinant(S_1))',

        * <efective variance> `determinant(S_1)^(1/p)', (defined in:
          Pen~a, D. (2002) <Ana'lisis de datos multivariantes>;
          McGraw-Hill, Madrid.)

        * <efective standard deviation>: `determinant(S_1)^(1/(2*p))'.
     where <p> is the dimension of the multivariate random variable and
     S_1 the covariance matrix returned by `cov1'.

     Option:

        * `'data', default `'true', indicates whether the input matrix
          contains the sample data, in which case the covariance matrix
          `cov1' must be calculated, or not, and then the covariance
          matrix (symmetric) must be given, instead of the data.

     Example:

          (%i1) load (descriptive)$
          (%i2) s2 : read_matrix (file_search ("wind.data"))$
          (%i3) global_variances (s2);
          (%o3) [105.338342060606, 21.06766841212119, 12874.34690469686,
                   113.4651792608501, 6.636590811800795, 2.576158149609762]

     Calculate the `global_variances' from the covariance matrix.

          (%i1) load (descriptive)$
          (%i2) s2 : read_matrix (file_search ("wind.data"))$
          (%i3) s : cov1 (s2)$
          (%i4) global_variances (s, data=false);
          (%o4) [105.338342060606, 21.06766841212119, 12874.34690469686,
                   113.4651792608501, 6.636590811800795, 2.576158149609762]

     See also `cov' and `cov1'.


 -- Function: cor (<matrix>)
 -- Function: cor (<matrix>, <logical_value>)
     The correlation matrix of the multivariate sample.

     Option:

        * `'data', default `'true', indicates whether the input matrix
          contains the sample data, in which case the covariance matrix
          `cov1' must be calculated, or not, and then the covariance
          matrix (symmetric) must be given, instead of the data.

     Example:

          (%i1) load (descriptive)$
          (%i2) fpprintprec : 7 $
          (%i3) s2 : read_matrix (file_search ("wind.data"))$
          (%i4) cor (s2);
                [   1.0     .8476339  .8803515  .8239624  .7519506 ]
                [                                                  ]
                [ .8476339    1.0     .8735834  .6902622  0.782502 ]
                [                                                  ]
          (%o4) [ .8803515  .8735834    1.0     .7764065  .8323358 ]
                [                                                  ]
                [ .8239624  .6902622  .7764065    1.0     .7293848 ]
                [                                                  ]
                [ .7519506  0.782502  .8323358  .7293848    1.0    ]

     Calculate de correlation matrix from the covariance matrix.

          (%i1) load (descriptive)$
          (%i2) fpprintprec : 7 $
          (%i3) s2 : read_matrix (file_search ("wind.data"))$
          (%i4) s : cov1 (s2)$
          (%i5) cor (s, data=false); /* this is faster */
                [   1.0     .8476339  .8803515  .8239624  .7519506 ]
                [                                                  ]
                [ .8476339    1.0     .8735834  .6902622  0.782502 ]
                [                                                  ]
          (%o5) [ .8803515  .8735834    1.0     .7764065  .8323358 ]
                [                                                  ]
                [ .8239624  .6902622  .7764065    1.0     .7293848 ]
                [                                                  ]
                [ .7519506  0.782502  .8323358  .7293848    1.0    ]

     See also `cov' and `cov1'.


 -- Function: list_correlations (<matrix>)
 -- Function: list_correlations (<matrix>, <options> ...)
     Function `list_correlations' returns a list of correlation
     measures:

        * <precision matrix>: the inverse of the covariance matrix S_1,
                      -1     ij
                     S   = (s  )
                      1         i,j = 1,2,...,p

        * <multiple correlation vector>:  (R_1^2, R_2^2, ..., R_p^2),
          with
                      2          1
                     R  = 1 - -------
                      i        ii
                              s   s
                                   ii
          being an indicator of the goodness of fit of the linear
          multivariate regression model on X_i when the rest of
          variables are used as regressors.

        * <partial correlation matrix>: with element (i, j) being
                                        ij
                                       s
                     r        = - ------------
                      ij.rest     / ii  jj\ 1/2
                                  |s   s  |
                                  \       /


     Option:

        * `'data', default `'true', indicates whether the input matrix
          contains the sample data, in which case the covariance matrix
          `cov1' must be calculated, or not, and then the covariance
          matrix (symmetric) must be given, instead of the data.

     Example:

          (%i1) load (descriptive)$
          (%i2) s2 : read_matrix (file_search ("wind.data"))$
          (%i3) z : list_correlations (s2)$
          (%i4) fpprintprec : 5$ /* for pretty output */
          (%i5) z[1];  /* precision matrix */
                [  .38486   - .13856   - .15626   - .10239    .031179  ]
                [                                                      ]
                [ - .13856   .34107    - .15233    .038447   - .052842 ]
                [                                                      ]
          (%o5) [ - .15626  - .15233    .47296    - .024816  - .10054  ]
                [                                                      ]
                [ - .10239   .038447   - .024816   .10937    - .034033 ]
                [                                                      ]
                [ .031179   - .052842  - .10054   - .034033   .14834   ]
          (%i6) z[2];  /* multiple correlation vector */
          (%o6)      [.85063, .80634, .86474, .71867, .72675]
          (%i7) z[3];  /* partial correlation matrix */
                [  - 1.0     .38244   .36627   .49908   - .13049 ]
                [                                                ]
                [  .38244    - 1.0    .37927  - .19907   .23492  ]
                [                                                ]
          (%o7) [  .36627    .37927   - 1.0    .10911    .37956  ]
                [                                                ]
                [  .49908   - .19907  .10911   - 1.0     .26719  ]
                [                                                ]
                [ - .13049   .23492   .37956   .26719    - 1.0   ]

     See also `cov' and `cov1'.


 -- Function: principal_components (<matrix>)
 -- Function: principal_components (<matrix>, <options> ...)
     Calculates the principal componentes of a multivariate sample.
     Principal components are used in multivariate statistical analysis
     to reduce the dimensionality of the sample.

     Option:

        * `'data', default `'true', indicates whether the input matrix
          contains the sample data, in which case the covariance matrix
          `cov1' must be calculated, or not, and then the covariance
          matrix (symmetric) must be given, instead of the data.

     The output of function `principal_components' is a list with the
     following results:

        * variances of the principal components,

        * percentage of total variance explained by each principal
          component,

        * rotation matrix.

     Examples:

     In this sample, the first component explains 83.13 per cent of
     total variance.

          (%i1) load (descriptive)$
          (%i2) s2 : read_matrix (file_search ("wind.data"))$
          (%i3) fpprintprec:4 $
          (%i4) res: principal_components(s2);
          0 errors, 0 warnings
          (%o4) [[87.57, 8.753, 5.515, 1.889, 1.613],
          [83.13, 8.31, 5.235, 1.793, 1.531],
          [ .4149  .03379   - .4757  - 0.581   - .5126 ]
          [                                            ]
          [ 0.369  - .3657  - .4298   .7237    - .1469 ]
          [                                            ]
          [ .3959  - .2178  - .2181  - .2749    .8201  ]]
          [                                            ]
          [ .5548   .7744    .1857    .2319    .06498  ]
          [                                            ]
          [ .4765  - .4669   0.712   - .09605  - .1969 ]
          (%i5) /* accumulated percentages  */
              block([ap: copy(res[2])],
                for k:2 thru length(ap) do ap[k]: ap[k]+ap[k-1],
                ap);
          (%o5)                 [83.13, 91.44, 96.68, 98.47, 100.0]
          (%i6) /* sample dimension */
                p: length(first(res));
          (%o6)                                  5
          (%i7) /* plot percentages to select number of
                   principal components for further work */
               draw2d(
                  fill_density = 0.2,
                  apply(bars, makelist([k, res[2][k], 1/2], k, p)),
                  points_joined = true,
                  point_type    = filled_circle,
                  point_size    = 3,
                  points(makelist([k, res[2][k]], k, p)),
                  xlabel = "Variances",
                  ylabel = "Percentages",
                  xtics  = setify(makelist([concat("PC",k),k], k, p))) $

     In case de covariance matrix is known, it can be passed to the
     function, but option `data=false' must be used.

          (%i1) load (descriptive)$
          (%i2) S: matrix([1,-2,0],[-2,5,0],[0,0,2]);
                                          [  1   - 2  0 ]
                                          [             ]
          (%o2)                           [ - 2   5   0 ]
                                          [             ]
                                          [  0    0   2 ]
          (%i3) fpprintprec:4 $
          (%i4) /* the argumment is a covariance matrix */
                res: principal_components(S, data=false);
          0 errors, 0 warnings
                                                            [ - .3827  0.0  .9239 ]
                                                            [                     ]
          (%o4) [[5.828, 2.0, .1716], [72.86, 25.0, 2.145], [  .9239   0.0  .3827 ]]
                                                            [                     ]
                                                            [   0.0    1.0   0.0  ]
          (%i5) /* transformation to get the principal components
                   from original records */
                matrix([a1,b2,c3],[a2,b2,c2]).last(res);
                       [ .9239 b2 - .3827 a1  1.0 c3  .3827 b2 + .9239 a1 ]
          (%o5)        [                                                  ]
                       [ .9239 b2 - .3827 a2  1.0 c2  .3827 b2 + .9239 a2 ]



File: maxima.info,  Node: Functions and Variables for statistical graphs,  Prev: Functions and Variables for descriptive statistics,  Up: descriptive

45.4 Functions and Variables for statistical graphs
===================================================

 -- Function: barsplot (<data1>, <data2>, ..., <option_1>, <option_2>,
          ...)
 -- Function: barsplot_description (...)
     Plots bars diagrams for discrete statistical variables, both for
     one or multiple samples.

     <data> can be a list of outcomes representing one sample, or a
     matrix of <m> rows and <n> columns, representing <n> samples of
     size <m> each.

     Available options are:

        * <box_width> (default, `3/4'): relative width of rectangles.
          This value must be in the range `[0,1]'.

        * <grouping> (default, `clustered'): indicates how multiple
          samples are shown. Valid values are: `clustered' and
          `stacked'.

        * <groups_gap> (default, `1'): a positive integer number
          representing the gap between two consecutive groups of bars.

        * <bars_colors> (default, `[]'): a list of colors for multiple
          samples.  When there are more samples than specified colors,
          the extra necesary colors are chosen at random. See `color'
          to learn more about them.

        * <frequency> (default, `absolute'): indicates the scale of the
          ordinates. Possible values are:  `absolute', `relative', and
          `percent'.

        * <ordering> (default, `orderlessp'): possible values are
          `orderlessp' or `ordergreatp', indicating how statistical
          outcomes should be ordered on the <x>-axis.

        * <sample_keys> (default, `[]'): a list with the strings to be
          used in the legend.  When the list length is other than 0 or
          the number of samples, an error message is returned.

        * <start_at> (default, `0'): indicates where the plot begins to
          be plotted on the x axis.

        * All global `draw' options, except `xtics', which is
          internally assigned by `barsplot'.  If you want to set your
          own values for this option or want to build complex scenes,
          make use of `barsplot_description'. See example below.

        * The following local `draw' options: `key', `color',
          `fill_color', `fill_density' and `line_width'. See also
          `bars'.


     Function `barsplot_description' creates a graphic object suitable
     for creating complex scenes, together with other graphic objects.
     There is also a function `wxbarsplot' for creating embedded
     histograms in interfaces wxMaxima and iMaxima.

     Examples:

     Univariate sample in matrix form. Absolute frequencies.

          (%i1) load (descriptive)$
          (%i2) m : read_matrix (file_search ("biomed.data"))$
          (%i3) barsplot(
                  col(m,2),
                  title        = "Ages",
                  xlabel       = "years",
                  box_width    = 1/2,
                  fill_density = 3/4)$

     Two samples of different sizes, with relative frequencies and user
     declared colors.

          (%i1) load (descriptive)$
          (%i2) l1:makelist(random(10),k,1,50)$
          (%i3) l2:makelist(random(10),k,1,100)$
          (%i4) barsplot(
                  l1,l2,
                  box_width    = 1,
                  fill_density = 1,
                  bars_colors  = [black, grey],
                  frequency = relative,
                  sample_keys = ["A", "B"])$

     Four non numeric samples of equal size.

          (%i1) load (descriptive)$
          (%i2) barsplot(
                  makelist([Yes, No, Maybe][random(3)+1],k,1,50),
                  makelist([Yes, No, Maybe][random(3)+1],k,1,50),
                  makelist([Yes, No, Maybe][random(3)+1],k,1,50),
                  makelist([Yes, No, Maybe][random(3)+1],k,1,50),
                  title  = "Asking for something to four groups",
                  ylabel = "# of individuals",
                  groups_gap   = 3,
                  fill_density = 0.5,
                  ordering     = ordergreatp)$

     Stacked bars.

          (%i1) load (descriptive)$
          (%i2) barsplot(
                  makelist([Yes, No, Maybe][random(3)+1],k,1,50),
                  makelist([Yes, No, Maybe][random(3)+1],k,1,50),
                  makelist([Yes, No, Maybe][random(3)+1],k,1,50),
                  makelist([Yes, No, Maybe][random(3)+1],k,1,50),
                  title  = "Asking for something to four groups",
                  ylabel = "# of individuals",
                  grouping     = stacked,,
                  fill_density = 0.5,
                  ordering     = ordergreatp)$

     `barsplot' in a multiplot context.

          (%i1) load (descriptive)$
          (%i2) l1:makelist(random(10),k,1,50)$
          (%i3) l2:makelist(random(10),k,1,100)$
          (%i4) bp1 :
                  barsplot_description(
                   l1,
                   box_width = 1,
                   fill_density = 0.5,
                   bars_colors = [blue],
                   frequency = relative)$
          (%i5) bp2 :
                  barsplot_description(
                   l2,
                   box_width = 1,
                   fill_density = 0.5,
                   bars_colors = [red],
                   frequency = relative)$
          (%i6) draw(gr2d(bp1), gr2d(bp2))$

     For bars diagrams related options, see `bars' of package `draw'.
     See also functions `histogram' and `piechart'.


 -- Function: boxplot (<data>)
 -- Function: boxplot (<data>, <option_1>, <option_2>, ...)
 -- Function: boxplot_description (...)
     This function plots box-and-whishker diagrams. Argument <data> can
     be a list, which is not of great interest, since these diagrams
     are mainly used for comparing different samples, or a matrix, so
     it is possible to compare two or more components of a multivariate
     statistical variable.  But it is also allowed <data> to be a list
     of samples with possible different sample sizes, in fact this is
     the only function in package `descriptive' that admits this type
     of data structure.

     Available options are:

        * <box_width> (default, `3/4'): relative width of boxes.  This
          value must be in the range `[0,1]'.

        * <box_orientation> (default, `vertical'): possible values:
          `vertical' and `horizontal'.

        * All `draw' options, except `points_joined', `point_size',
          `point_type', `xtics', `ytics', `xrange', and `yrange', which
          are internally assigned by `boxplot'.  If you want to set
          your own values for this options or want to build complex
          scenes, make use of `boxplot_description'.

        * The following local `draw' options: `key', `color', and
          `line_width'.


     Function `boxplot_description' creates a graphic object suitable
     for creating complex scenes, together with other graphic objects.
     There is also a function `wxboxplot' for creating embedded
     histograms in interfaces wxMaxima and iMaxima.

     Examples:

     Box-and-whishker diagram from a multivariate sample.

          (%i1) load (descriptive)$
          (%i2) s2 : read_matrix(file_search("wind.data"))$
          (%i3) boxplot(s2,
                  box_width  = 0.2,
                  title      = "Windspeed in knots",
                  xlabel     = "Stations",
                  color      = red,
                  line_width = 2)$

     Box-and-whishker diagram from three samples of different sizes.

          (%i1) load (descriptive)$
          (%i2) A :
                 [[6, 4, 6, 2, 4, 8, 6, 4, 6, 4, 3, 2],
                  [8, 10, 7, 9, 12, 8, 10],
                  [16, 13, 17, 12, 11, 18, 13, 18, 14, 12]]$
          (%i3) boxplot (A, box_orientation = horizontal)$


 -- Function: histogram (<list>)
 -- Function: histogram (<list>, <option_1>, <option_2>, ...)
 -- Function: histogram (<one_column_matrix>)
 -- Function: histogram (<one_column_matrix>, <option_1>, <option_2>,
          ...)
 -- Function: histogram (<one_row_matrix>)
 -- Function: histogram (<one_row_matrix>, <option_1>, <option_2>, ...)
 -- Function: histogram_description (...)
     This function plots an histogram from a continuous sample.  Sample
     data must be stored in a list of numbers or a one dimensional
     matrix.

     Available options are:

        * <nclasses> (default, `10'): number of classes of the
          histogram, or a list indicating the limits of the classes and
          the number of them, or only the limits.

        * <frequency> (default, `absolute'): indicates the scale of the
          ordinates. Possible values are:  `absolute', `relative',
          `percent', and `density'. With `density', the histogram area
          has a total area of one.

        * <htics> (default, `auto'): format of the histogram tics.
          Possible values are: `auto', `endpoints', `intervals', or a
          list of labels.

        * All global `draw' options, except `xrange', `yrange', and
          `xtics', which are internally assigned by `histogram'.  If
          you want to set your own values for these options, make use of
          `histogram_description'. See examples bellow.

        * The following local `draw' options: `key', `color',
          `fill_color', `fill_density' and `line_width'. See also
          `bars'.


     Function `histogram_description' creates a graphic object suitable
     for creating complex scenes, together with other graphic objects.
     There is also a function `wxhistogram' for creating embedded
     histograms in interfaces wxMaxima and iMaxima.

     Examples:

     A simple with eight classes:

          (%i1) load (descriptive)$
          (%i2) s1 : read_list (file_search ("pidigits.data"))$
          (%i3) histogram (
                     s1,
                     nclasses     = 8,
                     title        = "pi digits",
                     xlabel       = "digits",
                     ylabel       = "Absolute frequency",
                     fill_color   = grey,
                     fill_density = 0.6)$

     Setting the limits of the histogram to -2 and 12, with 3 classes.
     Also, we introduce predefined tics:

          (%i1) load (descriptive)$
          (%i2) s1 : read_list (file_search ("pidigits.data"))$
          (%i3) histogram (
                     s1,
                     nclasses     = [-2,12,3],
                     htics        = ["A", "B", "C"],
                     terminal     = png,
                     fill_color   = "#23afa0",
                     fill_density = 0.6)$

     We make use of `histogram_description' for setting the `xrange'
     and adding an explicit curve into the scene:

          (%i1) load (descriptive)$
          (%i2) ( load("distrib"),
                  m: 14, s: 2,
                  s2: random_normal(m, s, 1000) ) $
          (%i3) draw2d(
                  grid   = true,
                  xrange = [5, 25],
                  histogram_description(
                    s2,
                    nclasses     = 9,
                    frequency    = density,
                    fill_density = 0.5),
                  explicit(pdf_normal(x,m,s), x, m - 3*s, m + 3* s))$


 -- Function: piechart (<list>)
 -- Function: piechart (<list>, <option_1>, <option_2>, ...)
 -- Function: piechart (<one_column_matrix>)
 -- Function: piechart (<one_column_matrix>, <option_1>, <option_2>,
          ...)
 -- Function: piechart (<one_row_matrix>)
 -- Function: piechart (<one_row_matrix>, <option_1>, <option_2>, ...)
 -- Function: piechart_description (...)
     Similar to `barsplot', but plots sectors instead of rectangles.

     Available options are:

        * <sector_colors> (default, `[]'): a list of colors for sectors.
          When there are more sectors than specified colors, the extra
          necesary colors are chosen at random. See `color' to learn
          more about them.

        * <pie_center> (default, `[0,0]'): diagram's center.

        * <pie_radius> (default, `1'): diagram's radius.

        * All global `draw' options, except `key', which is internally
          assigned by `piechart'.  If you want to set your own values
          for this option or want to build complex scenes, make use of
          `piechart_description'.

        * The following local `draw' options: `key', `color',
          `fill_density' and `line_width'. See also `ellipse'.


     Function `piechart_description' creates a graphic object suitable
     for creating complex scenes, together with other graphic objects.
     There is also a function `wxpiechart' for creating embedded
     histograms in interfaces wxMaxima and iMaxima.

     Example:

          (%i1) load (descriptive)$
          (%i2) s1 : read_list (file_search ("pidigits.data"))$
          (%i3) piechart(
                  s1,
                  xrange  = [-1.1, 1.3],
                  yrange  = [-1.1, 1.1],
                  title   = "Digit frequencies in pi")$

     See also function `barsplot'.


 -- Function: scatterplot (<list>)
 -- Function: scatterplot (<list>, <option_1>, <option_2>, ...)
 -- Function: scatterplot (<matrix>)
 -- Function: scatterplot (<matrix>, <option_1>, <option_2>, ...)
 -- Function: scatterplot_description (...)
     Plots scatter diagrams both for univariate (<list>) and
     multivariate (<matrix>) samples.

     Available options are the same admitted by `histogram'.

     Function `scatterplot_description' creates a graphic object
     suitable for creating complex scenes, together with other graphic
     objects. There is also a function `wxscatterplot' for creating
     embedded histograms in interfaces wxMaxima and iMaxima.

     Examples:

     Univariate scatter diagram from a simulated Gaussian sample.

          (%i1) load (descriptive)$
          (%i2) load (distrib)$
          (%i3) scatterplot(
                  random_normal(0,1,200),
                  xaxis      = true,
                  point_size = 2,
                  dimensions = [600,150])$

     Two dimensional scatter plot.

          (%i1) load (descriptive)$
          (%i2) s2 : read_matrix (file_search ("wind.data"))$
          (%i3) scatterplot(
                 submatrix(s2, 1,2,3),
                 title      = "Data from stations #4 and #5",
                 point_type = diamant,
                 point_size = 2,
                 color      = blue)$

     Three dimensional scatter plot.

          (%i1) load (descriptive)$
          (%i2) s2 : read_matrix (file_search ("wind.data"))$
          (%i3) scatterplot(submatrix (s2, 1,2), nclasses=4)$

     Five dimensional scatter plot, with five classes histograms.

          (%i1) load (descriptive)$
          (%i2) s2 : read_matrix (file_search ("wind.data"))$
          (%i3) scatterplot(
                  s2,
                  nclasses     = 5,
                  frequency    = relative,
                  fill_color   = blue,
                  fill_density = 0.3,
                  xtics        = 5)$

     For plotting isolated or line-joined points in two and three
     dimensions, see `points'. See also `histogram'.


 -- Function: starplot (<data1>, <data2>, ..., <option_1>, <option_2>,
          ...)
 -- Function: starplot_description (...)
     Plots star diagrams for discrete statistical variables, both for
     one or multiple samples.

     <data> can be a list of outcomes representing one sample, or a
     matrix of <m> rows and <n> columns, representing <n> samples of
     size <m> each.

     Available options are:

        * <stars_colors> (default, `[]'): a list of colors for multiple
          samples.  When there are more samples than specified colors,
          the extra necesary colors are chosen at random. See `color'
          to learn more about them.

        * <frequency> (default, `absolute'): indicates the scale of the
          radii. Possible values are:  `absolute' and `relative'.

        * <ordering> (default, `orderlessp'): possible values are
          `orderlessp' or `ordergreatp', indicating how statistical
          outcomes should be ordered.

        * <sample_keys> (default, `[]'): a list with the strings to be
          used in the legend.  When the list length is other than 0 or
          the number of samples, an error message is returned.

        * <star_center> (default, `[0,0]'): diagram's center.

        * <star_radius> (default, `1'): diagram's radius.

        * All global `draw' options, except `points_joined',
          `point_type', and `key', which are internally assigned by
          `starplot'.  If you want to set your own values for this
          options or want to build complex scenes, make use of
          `starplot_description'.

        * The following local `draw' option: `line_width'.


     Function `starplot_description' creates a graphic object suitable
     for creating complex scenes, together with other graphic objects.
     There is also a function `wxstarplot' for creating embedded
     histograms in interfaces wxMaxima and iMaxima.

     Example:

     Plot based on absolute frequencies.  Location and radius defined
     by the user.

          (%i1) load (descriptive)$
          (%i2) l1: makelist(random(10),k,1,50)$
          (%i3) l2: makelist(random(10),k,1,200)$
          (%i4) starplot(
                  l1, l2,
                  stars_colors = [blue,red],
                  sample_keys = ["1st sample", "2nd sample"],
                  star_center = [1,2],
                  star_radius = 4,
                  proportional_axes = xy,
                  line_width = 2 ) $


 -- Function: stemplot (<data>)
 -- Function: stemplot (<data>, <option>)
     Plots stem and leaf diagrams.

     Unique available option is:

        * <leaf_unit> (default, `1'): indicates the unit of the leaves;
          must be a power of 10.


     Example:

          (%i1) load (descriptive)$
          (%i2) load(distrib)$
          (%i3) stemplot(
                  random_normal(15, 6, 100),
                  leaf_unit = 0.1);
          -5|4
           0|37
           1|7
           3|6
           4|4
           5|4
           6|57
           7|0149
           8|3
           9|1334588
          10|07888
          11|01144467789
          12|12566889
          13|24778
          14|047
          15|223458
          16|4
          17|11557
          18|000247
          19|4467799
          20|00
          21|1
          22|2335
          23|01457
          24|12356
          25|455
          27|79
          key: 6|3 =  6.3
          (%o3)                  done



File: maxima.info,  Node: diag,  Next: distrib,  Prev: descriptive,  Up: Top

46 diag
*******

* Menu:

* Functions and Variables for diag::


File: maxima.info,  Node: Functions and Variables for diag,  Prev: diag,  Up: diag

46.1 Functions and Variables for diag
=====================================

 -- Function: diag (<lm>)
     Constructs a square matrix with the matrices of <lm> in the
     diagonal. <lm> is a list of matrices or scalars.

     Example:
          (%i1) load("diag")$

          (%i2) a1:matrix([1,2,3],[0,4,5],[0,0,6])$

          (%i3) a2:matrix([1,1],[1,0])$

          (%i4) diag([a1,x,a2]);
                             [ 1  2  3  0  0  0 ]
                             [                  ]
                             [ 0  4  5  0  0  0 ]
                             [                  ]
                             [ 0  0  6  0  0  0 ]
          (%o4)              [                  ]
                             [ 0  0  0  x  0  0 ]
                             [                  ]
                             [ 0  0  0  0  1  1 ]
                             [                  ]
                             [ 0  0  0  0  1  0 ]

     To use this function write first `load("diag")'.


 -- Function: JF (<lambda>,<n>)
     Returns the Jordan cell of order <n> with eigenvalue <lambda>.

     Example:
          (%i1) load("diag")$

          (%i2) JF(2,5);
                              [ 2  1  0  0  0 ]
                              [               ]
                              [ 0  2  1  0  0 ]
                              [               ]
          (%o2)               [ 0  0  2  1  0 ]
                              [               ]
                              [ 0  0  0  2  1 ]
                              [               ]
                              [ 0  0  0  0  2 ]
          (%i3) JF(3,2);
                                   [ 3  1 ]
          (%o3)                    [      ]
                                   [ 0  3 ]

     To use this function write first `load("diag")'.


 -- Function: jordan (<mat>)
     Returns the Jordan form of matrix <mat>, but codified in a Maxima
     list.  To get the corresponding matrix, call function `dispJordan'
     using as argument the output of `jordan'.

     Example:
          (%i1) load("diag")$

          (%i3) a:matrix([2,0,0,0,0,0,0,0],
                         [1,2,0,0,0,0,0,0],
                         [-4,1,2,0,0,0,0,0],
                         [2,0,0,2,0,0,0,0],
                         [-7,2,0,0,2,0,0,0],
                         [9,0,-2,0,1,2,0,0],
                         [-34,7,1,-2,-1,1,2,0],
                         [145,-17,-16,3,9,-2,0,3])$

          (%i34) jordan(a);
          (%o4)             [[2, 3, 3, 1], [3, 1]]
          (%i5) dispJordan(%);
                          [ 2  1  0  0  0  0  0  0 ]
                          [                        ]
                          [ 0  2  1  0  0  0  0  0 ]
                          [                        ]
                          [ 0  0  2  0  0  0  0  0 ]
                          [                        ]
                          [ 0  0  0  2  1  0  0  0 ]
          (%o5)           [                        ]
                          [ 0  0  0  0  2  1  0  0 ]
                          [                        ]
                          [ 0  0  0  0  0  2  0  0 ]
                          [                        ]
                          [ 0  0  0  0  0  0  2  0 ]
                          [                        ]
                          [ 0  0  0  0  0  0  0  3 ]

     To use this function write first `load("diag")'. See also
     `dispJordan' and `minimalPoly'.


 -- Function: dispJordan (<l>)
     Returns the Jordan matrix associated to the codification given by
     the Maxima list <l>, which is the output given by function
     `jordan'.

     Example:
          (%i1) load("diag")$

          (%i2) b1:matrix([0,0,1,1,1],
                          [0,0,0,1,1],
                          [0,0,0,0,1],
                          [0,0,0,0,0],
                          [0,0,0,0,0])$

          (%i3) jordan(b1);
          (%o3)                  [[0, 3, 2]]
          (%i4) dispJordan(%);
                              [ 0  1  0  0  0 ]
                              [               ]
                              [ 0  0  1  0  0 ]
                              [               ]
          (%o4)               [ 0  0  0  0  0 ]
                              [               ]
                              [ 0  0  0  0  1 ]
                              [               ]
                              [ 0  0  0  0  0 ]

     To use this function write first `load("diag")'. See also `jordan'
     and `minimalPoly'.


 -- Function: minimalPoly (<l>)
     Returns the minimal polynomial associated to the codification
     given by the Maxima list <l>, which is the output given by
     function `jordan'.

     Example:
          (%i1) load("diag")$

          (%i2) a:matrix([2,1,2,0],
                         [-2,2,1,2],
                         [-2,-1,-1,1],
                         [3,1,2,-1])$

          (%i3) jordan(a);
          (%o3)               [[- 1, 1], [1, 3]]
          (%i4) minimalPoly(%);
                                      3
          (%o4)                (x - 1)  (x + 1)

     To use this function write first `load("diag")'. See also `jordan'
     and `dispJordan'.


 -- Function: ModeMatrix (<A>,<l>)
     Returns the matrix <M> such that (M^^-1).A.M=J, where <J> is the
     Jordan form of <A>. The Maxima list <l> is the codified form of
     the Jordan form as returned by function `jordan'.

     Example:
          (%i1) load("diag")$

          (%i2) a:matrix([2,1,2,0],
                    [-2,2,1,2],
                    [-2,-1,-1,1],
                    [3,1,2,-1])$

          (%i3) jordan(a);
          (%o3)               [[- 1, 1], [1, 3]]
          (%i4) M: ModeMatrix(a,%);
                            [  1    - 1   1   1 ]
                            [                   ]
                            [   1               ]
                            [ - -   - 1   0   0 ]
                            [   9               ]
                            [                   ]
          (%o4)             [   13              ]
                            [ - --   1   - 1  0 ]
                            [   9               ]
                            [                   ]
                            [  17               ]
                            [  --   - 1   1   1 ]
                            [  9                ]
          (%i5) is(  (M^^-1).a.M = dispJordan(%o3)  );
          (%o5)                      true
     Note that `dispJordan(%o3)' is the Jordan form of matrix `a'.

     To use this function write first `load("diag")'. See also `jordan'
     and `dispJordan'.


 -- Function: mat_function (<f>,<mat>)
     Returns f(mat), where <f> is an analytic function and <mat> a
     matrix. This computation is based on Cauchy's integral formula,
     which states that if `f(x)' is analytic and

          mat = diag([JF(m1,n1),...,JF(mk,nk)]),

     then

          f(mat) = ModeMatrix*diag([f(JF(m1,n1)), ..., f(JF(mk,nk))])
                                                        *ModeMatrix^^(-1)

     Note that there are about 6 or 8 other methods for this
     calculation.

     Some examples follow.

     Example 1:
          (%i1) load("diag")$

          (%i2) b2:matrix([0,1,0], [0,0,1], [-1,-3,-3])$

          (%i3) mat_function(exp,t*b2);
                         2   - t
                        t  %e          - t     - t
          (%o3) matrix([-------- + t %e    + %e   ,
                           2
                  - t     - t                           - t
           2    %e      %e        - t           - t   %e
          t  (- ----- - ----- + %e   ) + t (2 %e    - -----)
                  t       2                             t
                         t
                                   - t          - t     - t
                 - t       - t   %e        2  %e      %e
           + 2 %e   , t (%e    - -----) + t  (----- - -----)
                                   t            2       t
                         2   - t            - t     - t
               - t      t  %e        2    %e      %e        - t
           + %e   ], [- --------, - t  (- ----- - ----- + %e   ),
                           2                t       2
                                                   t
                  - t     - t      2   - t
             2  %e      %e        t  %e          - t
          - t  (----- - -----)], [-------- - t %e   ,
                  2       t          2
                  - t     - t                           - t
           2    %e      %e        - t           - t   %e
          t  (- ----- - ----- + %e   ) - t (2 %e    - -----),
                  t       2                             t
                         t
                - t     - t                 - t
           2  %e      %e            - t   %e
          t  (----- - -----) - t (%e    - -----)])
                2       t                   t
          (%i4) ratsimp(%);
                         [   2              - t ]
                         [ (t  + 2 t + 2) %e    ]
                         [ -------------------- ]
                         [          2           ]
                         [                      ]
                         [         2   - t      ]
          (%o4)  Col 1 = [        t  %e         ]
                         [      - --------      ]
                         [           2          ]
                         [                      ]
                         [     2          - t   ]
                         [   (t  - 2 t) %e      ]
                         [   ----------------   ]
                         [          2           ]
                   [      2        - t    ]
                   [    (t  + t) %e       ]
                   [                      ]
           Col 2 = [     2            - t ]
                   [ - (t  - t - 1) %e    ]
                   [                      ]
                   [     2          - t   ]
                   [   (t  - 3 t) %e      ]
                   [        2   - t       ]
                   [       t  %e          ]
                   [       --------       ]
                   [          2           ]
                   [                      ]
                   [      2          - t  ]
           Col 3 = [    (t  - 2 t) %e     ]
                   [  - ----------------  ]
                   [           2          ]
                   [                      ]
                   [   2              - t ]
                   [ (t  - 4 t + 2) %e    ]
                   [ -------------------- ]
                   [          2           ]

     Example 2:
          (%i5) b1:matrix([0,0,1,1,1],
                          [0,0,0,1,1],
                          [0,0,0,0,1],
                          [0,0,0,0,0],
                          [0,0,0,0,0])$

          (%i6) mat_function(exp,t*b1);
                            [              2     ]
                            [             t      ]
                            [ 1  0  t  t  -- + t ]
                            [             2      ]
                            [                    ]
          (%o6)             [ 0  1  0  t    t    ]
                            [                    ]
                            [ 0  0  1  0    t    ]
                            [                    ]
                            [ 0  0  0  1    0    ]
                            [                    ]
                            [ 0  0  0  0    1    ]
          (%i7) minimalPoly(jordan(b1));
                                       3
          (%o7)                       x
          (%i8) ident(5)+t*b1+1/2*(t^2)*b1^^2;
                            [              2     ]
                            [             t      ]
                            [ 1  0  t  t  -- + t ]
                            [             2      ]
                            [                    ]
          (%o8)             [ 0  1  0  t    t    ]
                            [                    ]
                            [ 0  0  1  0    t    ]
                            [                    ]
                            [ 0  0  0  1    0    ]
                            [                    ]
                            [ 0  0  0  0    1    ]
          (%i9) mat_function(exp,%i*t*b1);
                       [                           2 ]
                       [                          t  ]
                       [ 1  0  %i t  %i t  %i t - -- ]
                       [                          2  ]
                       [                             ]
          (%o9)        [ 0  1   0    %i t    %i t    ]
                       [                             ]
                       [ 0  0   1     0      %i t    ]
                       [                             ]
                       [ 0  0   0     1        0     ]
                       [                             ]
                       [ 0  0   0     0        1     ]
          (%i10) mat_function(cos,t*b1)+%i*mat_function(sin,t*b1);
                        [                           2 ]
                        [                          t  ]
                        [ 1  0  %i t  %i t  %i t - -- ]
                        [                          2  ]
                        [                             ]
          (%o10)        [ 0  1   0    %i t    %i t    ]
                        [                             ]
                        [ 0  0   1     0      %i t    ]
                        [                             ]
                        [ 0  0   0     1        0     ]
                        [                             ]
                        [ 0  0   0     0        1     ]

     Example 3:
          (%i11) a1:matrix([2,1,0,0,0,0],
                           [-1,4,0,0,0,0],
                           [-1,1,2,1,0,0],
                           [-1,1,-1,4,0,0],
                           [-1,1,-1,1,3,0],
                           [-1,1,-1,1,1,2])$

          (%i12) fpow(x):=block([k],declare(k,integer),x^k)$

          (%i13) mat_function(fpow,a1);
                          [  k      k - 1 ]         [      k - 1    ]
                          [ 3  - k 3      ]         [   k 3         ]
                          [               ]         [               ]
                          [       k - 1   ]         [  k      k - 1 ]
                          [  - k 3        ]         [ 3  + k 3      ]
                          [               ]         [               ]
                          [       k - 1   ]         [      k - 1    ]
                          [  - k 3        ]         [   k 3         ]
          (%o13)  Col 1 = [               ] Col 2 = [               ]
                          [       k - 1   ]         [      k - 1    ]
                          [  - k 3        ]         [   k 3         ]
                          [               ]         [               ]
                          [       k - 1   ]         [      k - 1    ]
                          [  - k 3        ]         [   k 3         ]
                          [               ]         [               ]
                          [       k - 1   ]         [      k - 1    ]
                          [  - k 3        ]         [   k 3         ]
                   [       0       ]         [       0       ]
                   [               ]         [               ]
                   [       0       ]         [       0       ]
                   [               ]         [               ]
                   [  k      k - 1 ]         [      k - 1    ]
                   [ 3  - k 3      ]         [   k 3         ]
                   [               ]         [               ]
           Col 3 = [       k - 1   ] Col 4 = [  k      k - 1 ]
                   [  - k 3        ]         [ 3  + k 3      ]
                   [               ]         [               ]
                   [       k - 1   ]         [      k - 1    ]
                   [  - k 3        ]         [   k 3         ]
                   [               ]         [               ]
                   [       k - 1   ]         [      k - 1    ]
                   [  - k 3        ]         [   k 3         ]
                   [    0    ]
                   [         ]         [ 0  ]
                   [    0    ]         [    ]
                   [         ]         [ 0  ]
                   [    0    ]         [    ]
                   [         ]         [ 0  ]
           Col 5 = [    0    ] Col 6 = [    ]
                   [         ]         [ 0  ]
                   [    k    ]         [    ]
                   [   3     ]         [ 0  ]
                   [         ]         [    ]
                   [  k    k ]         [  k ]
                   [ 3  - 2  ]         [ 2  ]

     To use this function write first `load("diag")'.



File: maxima.info,  Node: distrib,  Next: draw,  Prev: diag,  Up: Top

47 distrib
**********

* Menu:

* Introduction to distrib::
* Functions and Variables for continuous distributions::
* Functions and Variables for discrete distributions::


File: maxima.info,  Node: Introduction to distrib,  Next: Functions and Variables for continuous distributions,  Prev: distrib,  Up: distrib

47.1 Introduction to distrib
============================

Package `distrib' contains a set of functions for making probability
computations on both discrete and continuous univariate models.

   What follows is a short reminder of basic probabilistic related
definitions.

   Let f(x) be the <density function> of an absolute continuous random
variable X. The <distribution function> is defined as
                            x
                           /
                           [
                    F(x) = I     f(u) du
                           ]
                           /
                            minf
   which equals the probability <Pr(X <= x)>.

   The <mean> value is a localization parameter and is defined as
                          inf
                         /
                         [
                E[X]  =  I   x f(x) dx
                         ]
                         /
                          minf

   The <variance> is a measure of variation,
                      inf
                     /
                     [                    2
              V[X] = I     f(x) (x - E[X])  dx
                     ]
                     /
                      minf
   which is a positive real number. The square root of the variance is
the <standard deviation>, D[X]=sqrt(V[X]), and it is another measure of
variation.

   The <skewness coefficient> is a measure of non-symmetry,
                      inf
                     /
                 1   [                    3
       SK[X] = ----- I     f(x) (x - E[X])  dx
                   3 ]
               D[X]  /
                      minf

   And the <kurtosis coefficient> measures the peakedness of the
distribution,
                      inf
                     /
                 1   [                    4
       KU[X] = ----- I     f(x) (x - E[X])  dx - 3
                   4 ]
               D[X]  /
                      minf
   If X is gaussian, KU[X]=0. In fact, both skewness and kurtosis are
shape parameters used to measure the non-gaussianity of a distribution.

   If the random variable X is discrete, the density, or <probability>,
function f(x) takes positive values within certain countable set of
numbers x_i, and zero elsewhere. In this case, the distribution
function is
                            ====
                            \
                     F(x) =  >    f(x )
                            /        i
                            ====
                           x <= x
                            i

   The mean, variance, standard deviation, skewness coefficient and
kurtosis coefficient take the form
                            ====
                            \
                     E[X] =  >  x  f(x ) ,
                            /    i    i
                            ====
                             x
                              i

                     ====
                     \                     2
             V[X] =   >    f(x ) (x - E[X])  ,
                     /        i    i
                     ====
                      x
                       i

                    D[X] = sqrt(V[X]),

                          ====
                   1      \                     3
       SK[X] =  -------    >    f(x ) (x - E[X])
                D[X]^3    /        i    i
                          ====
                           x
                            i
   and
                          ====
                   1      \                     4
       KU[X] =  -------    >    f(x ) (x - E[X])   - 3 ,
                D[X]^4    /        i    i
                          ====
                           x
                            i
   respectively.

   There is a naming convention in package `distrib'. Every function
name has two parts, the first one makes reference to the function or
parameter we want to calculate,
     Functions:
        Density function            (pdf_*)
        Distribution function       (cdf_*)
        Quantile                    (quantile_*)
        Mean                        (mean_*)
        Variance                    (var_*)
        Standard deviation          (std_*)
        Skewness coefficient        (skewness_*)
        Kurtosis coefficient        (kurtosis_*)
        Random variate              (random_*)

   The second part is an explicit reference to the probabilistic model,
     Continuous distributions:
        Normal              (*normal)
        Student             (*student_t)
        Chi^2               (*chi2)
        Noncentral Chi^2    (*noncentral_chi2)
        F                   (*f)
        Exponential         (*exp)
        Lognormal           (*lognormal)
        Gamma               (*gamma)
        Beta                (*beta)
        Continuous uniform  (*continuous_uniform)
        Logistic            (*logistic)
        Pareto              (*pareto)
        Weibull             (*weibull)
        Rayleigh            (*rayleigh)
        Laplace             (*laplace)
        Cauchy              (*cauchy)
        Gumbel              (*gumbel)

     Discrete distributions:
        Binomial             (*binomial)
        Poisson              (*poisson)
        Bernoulli            (*bernoulli)
        Geometric            (*geometric)
        Discrete uniform     (*discrete_uniform)
        hypergeometric       (*hypergeometric)
        Negative binomial    (*negative_binomial)
        Finite discrete      (*general_finite_discrete)

   For example, `pdf_student_t(x,n)' is the density function of the
Student distribution with <n> degrees of freedom, `std_pareto(a,b)' is
the standard deviation of the Pareto distribution with parameters <a>
and <b> and `kurtosis_poisson(m)' is the kurtosis coefficient of the
Poisson distribution with mean <m>.

   In order to make use of package `distrib' you need first to load it
by typing
     (%i1) load(distrib)$

   For comments, bugs or suggestions, please contact the author at
<'mario AT edu DOT xunta DOT es'>.


File: maxima.info,  Node: Functions and Variables for continuous distributions,  Next: Functions and Variables for discrete distributions,  Prev: Introduction to distrib,  Up: distrib

47.2 Functions and Variables for continuous distributions
=========================================================

 -- Function: pdf_normal (<x>,<m>,<s>)
     Returns the value at <x> of the density function of a Normal(m,s)
     random variable, with s>0. To make use of this function, write
     first `load(distrib)'.


 -- Function: cdf_normal (<x>,<m>,<s>)
     Returns the value at <x> of the distribution function of a
     Normal(m,s) random variable, with s>0. This function is defined in
     terms of Maxima's built-in error function `erf'.

          (%i1) load (distrib)$
          (%i2) assume(s>0)$ cdf_normal(x,m,s);
                                       x - m
                                 erf(---------)
                                     sqrt(2) s    1
          (%o3)                  -------------- + -
                                       2          2

     See also `erf'.


 -- Function: quantile_normal (<q>,<m>,<s>)
     Returns the <q>-quantile of a Normal(m,s) random variable, with
     s>0; in other words, this is the inverse of `cdf_normal'. Argument
     <q> must be an element of [0,1]. To make use of this function,
     write first `load(distrib)'.

          (%i1) load (distrib)$
          (%i2) quantile_normal(95/100,0,1);
                                                9
          (%o2)             sqrt(2) inverse_erf(--)
                                                10
          (%i3) float(%);
          (%o3)               1.644853626951472


 -- Function: mean_normal (<m>,<s>)
     Returns the mean of a Normal(m,s) random variable, with s>0,
     namely <m>. To make use of this function, write first
     `load(distrib)'.


 -- Function: var_normal (<m>,<s>)
     Returns the variance of a Normal(m,s) random variable, with s>0,
     namely <s^2>. To make use of this function, write first
     `load(distrib)'.


 -- Function: std_normal (<m>,<s>)
     Returns the standard deviation of a Normal(m,s) random variable,
     with s>0, namely <s>. To make use of this function, write first
     `load(distrib)'.


 -- Function: skewness_normal (<m>,<s>)
     Returns the skewness coefficient of a Normal(m,s) random variable,
     with s>0, which is always equal to 0. To make use of this
     function, write first `load(distrib)'.


 -- Function: kurtosis_normal (<m>,<s>)
     Returns the kurtosis coefficient of a Normal(m,s) random variable,
     with s>0, which is always equal to 0. To make use of this
     function, write first `load(distrib)'.


 -- Function: random_normal (<m>,<s>)
 -- Function: random_normal (<m>,<s>,<n>)
     Returns a Normal(m,s) random variate, with s>0. Calling
     `random_normal' with a third argument <n>, a random sample of size
     <n> will be simulated.

     This is an implementation of the Box-Mueller algorithm, as
     described in Knuth, D.E. (1981) <Seminumerical Algorithms. The Art
     of Computer Programming.> Addison-Wesley.

     To make use of this function, write first `load(distrib)'.


 -- Function: pdf_student_t (<x>,<n>)
     Returns the value at <x> of the density function of a Student
     random variable t(n), with n>0 degrees of freedom. To make use of
     this function, write first `load(distrib)'.


 -- Function: cdf_student_t (<x>,<n>)
     Returns the value at <x> of the distribution function of a Student
     random variable t(n), with n>0 degrees of freedom.

          (%i1) load (distrib)$
          (%i2) cdf_student_t(1/2, 7/3);
                                                   7  1  28
                       beta_incomplete_regularized(-, -, --)
                                                   6  2  31
          (%o2)    1 - -------------------------------------
                                         2
          (%i3) float(%);
          (%o3)                .6698450596140415


 -- Function: quantile_student_t (<q>,<n>)
     Returns the <q>-quantile of a Student random variable t(n), with
     n>0; in other words, this is the inverse of `cdf_student_t'.
     Argument <q> must be an element of [0,1]. To make use of this
     function, write first `load(distrib)'.


 -- Function: mean_student_t (<n>)
     Returns the mean of a Student random variable t(n), with n>0,
     which is always equal to 0. To make use of this function, write
     first `load(distrib)'.


 -- Function: var_student_t (<n>)
     Returns the variance of a Student random variable t(n), with n>2.

          (%i1) load (distrib)$
          (%i2) assume(n>2)$  var_student_t(n);
                                          n
          (%o3)                         -----
                                        n - 2


 -- Function: std_student_t (<n>)
     Returns the standard deviation of a Student random variable t(n),
     with n>2. To make use of this function, write first
     `load(distrib)'.


 -- Function: skewness_student_t (<n>)
     Returns the skewness coefficient of a Student random variable
     t(n), with n>3, which is always equal to 0. To make use of this
     function, write first `load(distrib)'.


 -- Function: kurtosis_student_t (<n>)
     Returns the kurtosis coefficient of a Student random variable
     t(n), with n>4. To make use of this function, write first
     `load(distrib)'.


 -- Function: random_student_t (<n>)
 -- Function: random_student_t (<n>,<m>)
     Returns a Student random variate t(n), with n>0. Calling
     `random_student_t' with a second argument <m>, a random sample of
     size <m> will be simulated.

     The implemented algorithm is based on the fact that if <Z> is a
     normal random variable N(0,1) and S^2 is a chi square random
     variable with <n> degrees of freedom, Chi^2(n), then
                                     Z
                           X = -------------
                               /   2  \ 1/2
                               |  S   |
                               | ---  |
                               \  n   /
     is a Student random variable with <n> degrees of freedom, t(n).

     To make use of this function, write first `load(distrib)'.


 -- Function: pdf_noncentral_student_t (<x>,<n>,<ncp>)
     Returns the value at <x> of the density function of a noncentral
     Student random variable nc_t(n,ncp), with n>0 degrees of freedom
     and noncentrality parameter ncp. To make use of this function,
     write first `load(distrib)'.

     Sometimes an extra work is necessary to get the final result.

          (%i1) load (distrib)$
          (%i2) expand(pdf_noncentral_student_t(3,5,0.1));
                 .01370030107589574 sqrt(5)
          (%o2)  --------------------------
                 sqrt(2) sqrt(14) sqrt(%pi)
             1.654562884111515E-4 sqrt(5)
           + ----------------------------
                      sqrt(%pi)
             .02434921505438663 sqrt(5)
           + --------------------------
                        %pi
          (%i3) float(%);
          (%o3)          .02080593159405669


 -- Function: cdf_noncentral_student_t (<x>,<n>,<ncp>)
     Returns the value at <x> of the distribution function of a
     noncentral Student random variable nc_t(n,ncp), with n>0 degrees
     of freedom and noncentrality parameter ncp. This function has no
     closed form and it is numerically computed if the global variable
     `numer' equals `true' or at least one of the arguments is a float,
     otherwise it returns a nominal expression.

          (%i1) load (distrib)$
          (%i2) cdf_noncentral_student_t(-2,5,-5);
          (%o2) cdf_noncentral_student_t(- 2, 5, - 5)
          (%i3) cdf_noncentral_student_t(-2.0,5,-5);
          (%o3)          .9952030093319743


 -- Function: quantile_noncentral_student_t (<q>,<n>,<ncp>)
     Returns the <q>-quantile of a noncentral Student random variable
     nc_t(n,ncp), with n>0 degrees of freedom and noncentrality
     parameter ncp; in other words, this is the inverse of
     `cdf_noncentral_student_t'. Argument <q> must be an element of
     [0,1]. To make use of this function, write first `load(distrib)'.


 -- Function: mean_noncentral_student_t (<n>,<ncp>)
     Returns the mean of a noncentral Student random variable
     nc_t(n,ncp), with n>1 degrees of freedom and noncentrality
     parameter ncp. To make use of this function, write first
     `load(distrib)'.

          (%i1) load (distrib)$
          (%i2) (assume(df>1), mean_noncentral_student_t(df,k));
                             df - 1
                       gamma(------) sqrt(df) k
                               2
          (%o2)        ------------------------
                                        df
                          sqrt(2) gamma(--)
                                        2


 -- Function: var_noncentral_student_t (<n>,<ncp>)
     Returns the variance of a noncentral Student random variable
     nc_t(n,ncp), with n>2 degrees of freedom and noncentrality
     parameter ncp. To make use of this function, write first
     `load(distrib)'.


 -- Function: std_noncentral_student_t (<n>,<ncp>)
     Returns the standard deviation of a noncentral Student random
     variable nc_t(n,ncp), with n>2 degrees of freedom and
     noncentrality parameter ncp. To make use of this function, write
     first `load(distrib)'.


 -- Function: skewness_noncentral_student_t (<n>,<ncp>)
     Returns the skewness coefficient of a noncentral Student random
     variable nc_t(n,ncp), with n>3 degrees of freedom and
     noncentrality parameter ncp. To make use of this function, write
     first `load(distrib)'.


 -- Function: kurtosis_noncentral_student_t (<n>,<ncp>)
     Returns the kurtosis coefficient of a noncentral Student random
     variable nc_t(n,ncp), with n>4 degrees of freedom and
     noncentrality parameter ncp. To make use of this function, write
     first `load(distrib)'.


 -- Function: random_noncentral_student_t (<n>,<ncp>)
 -- Function: random_noncentral_student_t (<n>,<ncp>,<m>)
     Returns a noncentral Student random variate nc_t(n,ncp), with n>0.
     Calling `random_noncentral_student_t' with a third argument <m>, a
     random sample of size <m> will be simulated.

     The implemented algorithm is based on the fact that if <X> is a
     normal random variable N(ncp,1) and S^2 is a chi square random
     variable with <n> degrees of freedom, Chi^2(n), then
                                     X
                           U = -------------
                               /   2  \ 1/2
                               |  S   |
                               | ---  |
                               \  n   /
     is a noncentral Student random variable with <n> degrees of
     freedom and noncentrality parameter ncp, nc_t(n,ncp).

     To make use of this function, write first `load(distrib)'.


 -- Function: pdf_chi2 (<x>,<n>)
     Returns the value at <x> of the density function of a Chi-square
     random variable Chi^2(n), with n>0.

     The Chi^2(n) random variable is equivalent to the Gamma(n/2,2),
     therefore when Maxima has not enough information to get the
     result, a noun form based on the gamma density is returned.

          (%i1) load (distrib)$
          (%i2) pdf_chi2(x,n);
                                              n
          (%o2)                  pdf_gamma(x, -, 2)
                                              2
          (%i3) assume(x>0, n>0)$  pdf_chi2(x,n);
                                   n/2 - 1   - x/2
                                  x        %e
          (%o4)                   ----------------
                                    n/2       n
                                   2    gamma(-)
                                              2


 -- Function: cdf_chi2 (<x>,<n>)
     Returns the value at <x> of the distribution function of a
     Chi-square random variable Chi^2(n), with n>0.

          (%i1) load (distrib)$
          (%i2) cdf_chi2(3,4);
                                                         3
          (%o2)      1 - gamma_incomplete_regularized(2, -)
                                                         2
          (%i3) float(%);
          (%o3)               .4421745996289256


 -- Function: quantile_chi2 (<q>,<n>)
     Returns the <q>-quantile of a Chi-square random variable Chi^2(n),
     with n>0; in other words, this is the inverse of `cdf_chi2'.
     Argument <q> must be an element of [0,1].

     This function has no closed form and it is numerically computed if
     the global variable `numer' equals `true',  otherwise it returns a
     nominal expression based on the gamma quantile function, since the
     Chi^2(n) random variable is equivalent to the Gamma(n/2,2).

          (%i1) load (distrib)$
          (%i2) quantile_chi2(0.99,9);
          (%o2)                   21.66599433346194
          (%i3) quantile_chi2(0.99,n);
                                                  n
          (%o3)              quantile_gamma(0.99, -, 2)
                                                  2


 -- Function: mean_chi2 (<n>)
     Returns the mean of a Chi-square random variable Chi^2(n), with
     n>0.

     The Chi^2(n) random variable is equivalent to the Gamma(n/2,2),
     therefore when Maxima has not enough information to get the
     result, a noun form based on the gamma mean is returned.

          (%i1) load (distrib)$
          (%i2) mean_chi2(n);
                                             n
          (%o2)                   mean_gamma(-, 2)
                                             2
          (%i3) assume(n>0)$ mean_chi2(n);
          (%o4)                           n


 -- Function: var_chi2 (<n>)
     Returns the variance of a Chi-square random variable Chi^2(n),
     with n>0.

     The Chi^2(n) random variable is equivalent to the Gamma(n/2,2),
     therefore when Maxima has not enough information to get the
     result, a noun form based on the gamma variance is returned.

          (%i1) load (distrib)$
          (%i2) var_chi2(n);
                                             n
          (%o2)                    var_gamma(-, 2)
                                             2
          (%i3) assume(n>0)$ var_chi2(n);
          (%o4)                          2 n


 -- Function: std_chi2 (<n>)
     Returns the standard deviation of a Chi-square random variable
     Chi^2(n), with n>0.

     The Chi^2(n) random variable is equivalent to the Gamma(n/2,2),
     therefore when Maxima has not enough information to get the
     result, a noun form based on the gamma standard deviation is
     returned.

          (%i1) load (distrib)$
          (%i2) std_chi2(n);
                                             n
          (%o2)                    std_gamma(-, 2)
                                             2
          (%i3) assume(n>0)$ std_chi2(n);
          (%o4)                    sqrt(2) sqrt(n)


 -- Function: skewness_chi2 (<n>)
     Returns the skewness coefficient of a Chi-square random variable
     Chi^2(n), with n>0.

     The Chi^2(n) random variable is equivalent to the Gamma(n/2,2),
     therefore when Maxima has not enough information to get the
     result, a noun form based on the gamma skewness coefficient is
     returned.

          (%i1) load (distrib)$
          (%i2) skewness_chi2(n);
                                               n
          (%o2)                 skewness_gamma(-, 2)
                                               2
          (%i3) assume(n>0)$ skewness_chi2(n);
                                      2 sqrt(2)
          (%o4)                       ---------
                                       sqrt(n)


 -- Function: kurtosis_chi2 (<n>)
     Returns the kurtosis coefficient of a Chi-square random variable
     Chi^2(n), with n>0.

     The Chi^2(n) random variable is equivalent to the Gamma(n/2,2),
     therefore when Maxima has not enough information to get the
     result, a noun form based on the gamma kurtosis coefficient is
     returned.

          (%i1) load (distrib)$
          (%i2) kurtosis_chi2(n);
                                               n
          (%o2)                 kurtosis_gamma(-, 2)
                                               2
          (%i3) assume(n>0)$ kurtosis_chi2(n);
                                         12
          (%o4)                          --
                                         n


 -- Function: random_chi2 (<n>)
 -- Function: random_chi2 (<n>,<m>)
     Returns a Chi-square random variate Chi^2(n), with n>0. Calling
     `random_chi2' with a second argument <m>, a random sample of size
     <m> will be simulated.

     The simulation is based on the Ahrens-Cheng algorithm. See
     `random_gamma' for details.

     To make use of this function, write first `load(distrib)'.


 -- Function: pdf_noncentral_chi2 (<x>,<n>,<ncp>)
     Returns the value at <x> of the density function of a noncentral
     Chi-square random variable nc_Chi^2(n,ncp), with n>0 and
     noncentrality parameter ncp>=0. To make use of this function,
     write first `load(distrib)'.


 -- Function: cdf_noncentral_chi2 (<x>,<n>,<ncp>)
     Returns the value at <x> of the distribution function of a
     noncentral Chi-square random variable nc_Chi^2(n,ncp), with n>0
     and noncentrality parameter ncp>=0. To make use of this function,
     write first `load(distrib)'.


 -- Function: quantile_noncentral_chi2 (<q>,<n>,<ncp>)
     Returns the <q>-quantile of a noncentral Chi-square random
     variable nc_Chi^2(n,ncp), with n>0 and noncentrality parameter
     ncp>=0; in other words, this is the inverse of
     `cdf_noncentral_chi2'. Argument <q> must be an element of [0,1].

     This function has no closed form and it is numerically computed if
     the global variable `numer' equals `true',  otherwise it returns a
     nominal expression.


 -- Function: mean_noncentral_chi2 (<n>,<ncp>)
     Returns the mean of a noncentral Chi-square random variable
     nc_Chi^2(n,ncp), with n>0 and noncentrality parameter ncp>=0.


 -- Function: var_noncentral_chi2 (<n>,<ncp>)
     Returns the variance of a noncentral Chi-square random variable
     nc_Chi^2(n,ncp), with n>0 and noncentrality parameter ncp>=0.


 -- Function: std_noncentral_chi2 (<n>,<ncp>)
     Returns the standard deviation of a noncentral Chi-square random
     variable nc_Chi^2(n,ncp), with n>0 and noncentrality parameter
     ncp>=0.


 -- Function: skewness_noncentral_chi2 (<n>,<ncp>)
     Returns the skewness coefficient of a noncentral Chi-square random
     variable nc_Chi^2(n,ncp), with n>0 and noncentrality parameter
     ncp>=0.


 -- Function: kurtosis_noncentral_chi2 (<n>,<ncp>)
     Returns the kurtosis coefficient of a noncentral Chi-square random
     variable nc_Chi^2(n,ncp), with n>0 and noncentrality parameter
     ncp>=0.


 -- Function: random_noncentral_chi2 (<n>,<ncp>)
 -- Function: random_noncentral_chi2 (<n>,<ncp>,<m>)
     Returns a noncentral Chi-square random variate nc_Chi^2(n,ncp),
     with n>0 and noncentrality parameter ncp>=0. Calling
     `random_noncentral_chi2' with a third argument <m>, a random
     sample of size <m> will be simulated.

     To make use of this function, write first `load(distrib)'.


 -- Function: pdf_f (<x>,<m>,<n>)
     Returns the value at <x> of the density function of a F random
     variable F(m,n), with m,n>0. To make use of this function, write
     first `load(distrib)'.


 -- Function: cdf_f (<x>,<m>,<n>)
     Returns the value at <x> of the distribution function of a F
     random variable F(m,n), with m,n>0.

          (%i1) load (distrib)$
          (%i2) cdf_f(2,3,9/4);
                                                   9  3  3
          (%o2)    1 - beta_incomplete_regularized(-, -, --)
                                                   8  2  11
          (%i3) float(%);
          (%o3)                 0.66756728179008


 -- Function: quantile_f (<q>,<m>,<n>)
     Returns the <q>-quantile of a F random variable F(m,n), with
     m,n>0; in other words, this is the inverse of `cdf_f'. Argument
     <q> must be an element of [0,1].

     This function has no closed form and it is numerically computed if
     the global variable `numer' equals `true',  otherwise it returns a
     nominal expression.

          (%i1) load (distrib)$
          (%i2) quantile_f(2/5,sqrt(3),5);
                                         2
          (%o2)               quantile_f(-, sqrt(3), 5)
                                         5
          (%i3) %,numer;
          (%o3)                   0.518947838573693


 -- Function: mean_f (<m>,<n>)
     Returns the mean of a F random variable F(m,n), with m>0, n>2. To
     make use of this function, write first `load(distrib)'.


 -- Function: var_f (<m>,<n>)
     Returns the variance of a F random variable F(m,n), with m>0, n>4.
     To make use of this function, write first `load(distrib)'.


 -- Function: std_f (<m>,<n>)
     Returns the standard deviation of a F random variable F(m,n), with
     m>0, n>4. To make use of this function, write first
     `load(distrib)'.


 -- Function: skewness_f (<m>,<n>)
     Returns the skewness coefficient of a F random variable F(m,n),
     with m>0, n>6. To make use of this function, write first
     `load(distrib)'.


 -- Function: kurtosis_f (<m>,<n>)
     Returns the kurtosis coefficient of a F random variable F(m,n),
     with m>0, n>8. To make use of this function, write first
     `load(distrib)'.


 -- Function: random_f (<m>,<n>)
 -- Function: random_f (<m>,<n>,<k>)
     Returns a F random variate F(m,n), with m,n>0. Calling `random_f'
     with a third argument <k>, a random sample of size <k> will be
     simulated.

     The simulation algorithm is based on the fact that if <X> is a
     Chi^2(m) random variable and Y is a Chi^2(n) random variable, then
                                  n X
                              F = ---
                                  m Y
     is a F random variable with <m> and <n> degrees of freedom, F(m,n).

     To make use of this function, write first `load(distrib)'.


 -- Function: pdf_exp (<x>,<m>)
     Returns the value at <x> of the density function of an
     Exponential(m) random variable, with m>0.

     The Exponential(m) random variable is equivalent to the
     Weibull(1,1/m), therefore when Maxima has not enough information
     to get the result, a noun form based on the Weibull density is
     returned.

          (%i1) load (distrib)$
          (%i2) pdf_exp(x,m);
                                                  1
          (%o2)                 pdf_weibull(x, 1, -)
                                                  m
          (%i3) assume(x>0,m>0)$  pdf_exp(x,m);
                                          - m x
          (%o4)                       m %e


 -- Function: cdf_exp (<x>,<m>)
     Returns the value at <x> of the distribution function of an
     Exponential(m) random variable, with m>0.

     The Exponential(m) random variable is equivalent to the
     Weibull(1,1/m), therefore when Maxima has not enough information
     to get the result, a noun form based on the Weibull distribution
     is returned.

          (%i1) load (distrib)$
          (%i2) cdf_exp(x,m);
                                                  1
          (%o2)                 cdf_weibull(x, 1, -)
                                                  m
          (%i3) assume(x>0,m>0)$  cdf_exp(x,m);
                                           - m x
          (%o4)                      1 - %e


 -- Function: quantile_exp (<q>,<m>)
     Returns the <q>-quantile of an Exponential(m) random variable,
     with m>0; in other words, this is the inverse of `cdf_exp'.
     Argument <q> must be an element of [0,1].

     The Exponential(m) random variable is equivalent to the
     Weibull(1,1/m), therefore when Maxima has not enough information
     to get the result, a noun form based on the Weibull quantile is
     returned.

          (%i1) load (distrib)$
          (%i2) quantile_exp(0.56,5);
          (%o2)                   .1641961104139661
          (%i3) quantile_exp(0.56,m);
                                                      1
          (%o3)             quantile_weibull(0.56, 1, -)
                                                      m


 -- Function: mean_exp (<m>)
     Returns the mean of an Exponential(m) random variable, with m>0.

     The Exponential(m) random variable is equivalent to the
     Weibull(1,1/m), therefore when Maxima has not enough information
     to get the result, a noun form based on the Weibull mean is
     returned.

          (%i1) load (distrib)$
          (%i2) mean_exp(m);
                                                 1
          (%o2)                  mean_weibull(1, -)
                                                 m
          (%i3) assume(m>0)$  mean_exp(m);
                                          1
          (%o4)                           -
                                          m


 -- Function: var_exp (<m>)
     Returns the variance of an Exponential(m) random variable, with
     m>0.

     The Exponential(m) random variable is equivalent to the
     Weibull(1,1/m), therefore when Maxima has not enough information
     to get the result, a noun form based on the Weibull variance is
     returned.

          (%i1) load (distrib)$
          (%i2) var_exp(m);
                                                 1
          (%o2)                   var_weibull(1, -)
                                                 m
          (%i3) assume(m>0)$  var_exp(m);
                                         1
          (%o4)                          --
                                          2
                                         m


 -- Function: std_exp (<m>)
     Returns the standard deviation of an Exponential(m) random
     variable, with m>0.

     The Exponential(m) random variable is equivalent to the
     Weibull(1,1/m), therefore when Maxima has not enough information
     to get the result, a noun form based on the Weibull standard
     deviation is returned.

          (%i1) load (distrib)$
          (%i2) std_exp(m);
                                                 1
          (%o2)                   std_weibull(1, -)
                                                 m
          (%i3) assume(m>0)$  std_exp(m);
                                          1
          (%o4)                           -
                                          m


 -- Function: skewness_exp (<m>)
     Returns the skewness coefficient of an Exponential(m) random
     variable, with m>0.

     The Exponential(m) random variable is equivalent to the
     Weibull(1,1/m), therefore when Maxima has not enough information
     to get the result, a noun form based on the Weibull skewness
     coefficient is returned.

          (%i1) load (distrib)$
          (%i2) skewness_exp(m);
                                                   1
          (%o2)                skewness_weibull(1, -)
                                                   m
          (%i3) assume(m>0)$  skewness_exp(m);
          (%o4)                           2


 -- Function: kurtosis_exp (<m>)
     Returns the kurtosis coefficient of an Exponential(m) random
     variable, with m>0.

     The Exponential(m) random variable is equivalent to the
     Weibull(1,1/m), therefore when Maxima has not enough information
     to get the result, a noun form based on the Weibull kurtosis
     coefficient is returned.

          (%i1) load (distrib)$
          (%i2) kurtosis_exp(m);
                                                   1
          (%o2)                kurtosis_weibull(1, -)
                                                   m
          (%i3) assume(m>0)$  kurtosis_exp(m);
          (%o4)                           6


 -- Function: random_exp (<m>)
 -- Function: random_exp (<m>,<k>)
     Returns an Exponential(m) random variate, with m>0. Calling
     `random_exp' with a second argument <k>, a random sample of size
     <k> will be simulated.

     The simulation algorithm is based on the general inverse method.

     To make use of this function, write first `load(distrib)'.


 -- Function: pdf_lognormal (<x>,<m>,<s>)
     Returns the value at <x> of the density function of a
     Lognormal(m,s) random variable, with s>0. To make use of this
     function, write first `load(distrib)'.


 -- Function: cdf_lognormal (<x>,<m>,<s>)
     Returns the value at <x> of the distribution function of a
     Lognormal(m,s) random variable, with s>0. This function is defined
     in terms of Maxima's built-in error function `erf'.

          (%i1) load (distrib)$
          (%i2) assume(x>0, s>0)$  cdf_lognormal(x,m,s);
                                     log(x) - m
                                 erf(----------)
                                     sqrt(2) s     1
          (%o3)                  --------------- + -
                                        2          2

     See also `erf'.


 -- Function: quantile_lognormal (<q>,<m>,<s>)
     Returns the <q>-quantile of a Lognormal(m,s) random variable, with
     s>0; in other words, this is the inverse of `cdf_lognormal'.
     Argument <q> must be an element of [0,1]. To make use of this
     function, write first `load(distrib)'.

          (%i1) load (distrib)$
          (%i2) quantile_lognormal(95/100,0,1);
                            sqrt(2) inverse_erf(9/10)
          (%o2)           %e
          (%i3) float(%);
          (%o3)               5.180251602233015


 -- Function: mean_lognormal (<m>,<s>)
     Returns the mean of a Lognormal(m,s) random variable, with s>0. To
     make use of this function, write first `load(distrib)'.


 -- Function: var_lognormal (<m>,<s>)
     Returns the variance of a Lognormal(m,s) random variable, with
     s>0. To make use of this function, write first `load(distrib)'.


 -- Function: std_lognormal (<m>,<s>)
     Returns the standard deviation of a Lognormal(m,s) random
     variable, with s>0. To make use of this function, write first
     `load(distrib)'.


 -- Function: skewness_lognormal (<m>,<s>)
     Returns the skewness coefficient of a Lognormal(m,s) random
     variable, with s>0. To make use of this function, write first
     `load(distrib)'.


 -- Function: kurtosis_lognormal (<m>,<s>)
     Returns the kurtosis coefficient of a Lognormal(m,s) random
     variable, with s>0. To make use of this function, write first
     `load(distrib)'.


 -- Function: random_lognormal (<m>,<s>)
 -- Function: random_lognormal (<m>,<s>,<n>)
     Returns a Lognormal(m,s) random variate, with s>0. Calling
     `random_lognormal' with a third argument <n>, a random sample of
     size <n> will be simulated.

     Log-normal variates are simulated by means of random normal
     variates. See `random_normal' for details.

     To make use of this function, write first `load(distrib)'.


 -- Function: pdf_gamma (<x>,<a>,<b>)
     Returns the value at <x> of the density function of a Gamma(a,b)
     random variable, with a,b>0. To make use of this function, write
     first `load(distrib)'.


 -- Function: cdf_gamma (<x>,<a>,<b>)
     Returns the value at <x> of the distribution function of a
     Gamma(a,b) random variable, with a,b>0.

          (%i1) load (distrib)$
          (%i2) cdf_gamma(3,5,21);
                                                        1
          (%o2)     1 - gamma_incomplete_regularized(5, -)
                                                        7
          (%i3) float(%);
          (%o3)              4.402663157376807E-7


 -- Function: quantile_gamma (<q>,<a>,<b>)
     Returns the <q>-quantile of a Gamma(a,b) random variable, with
     a,b>0; in other words, this is the inverse of `cdf_gamma'.
     Argument <q> must be an element of [0,1]. To make use of this
     function, write first `load(distrib)'.


 -- Function: mean_gamma (<a>,<b>)
     Returns the mean of a Gamma(a,b) random variable, with a,b>0. To
     make use of this function, write first `load(distrib)'.


 -- Function: var_gamma (<a>,<b>)
     Returns the variance of a Gamma(a,b) random variable, with a,b>0.
     To make use of this function, write first `load(distrib)'.


 -- Function: std_gamma (<a>,<b>)
     Returns the standard deviation of a Gamma(a,b) random variable,
     with a,b>0. To make use of this function, write first
     `load(distrib)'.


 -- Function: skewness_gamma (<a>,<b>)
     Returns the skewness coefficient of a Gamma(a,b) random variable,
     with a,b>0. To make use of this function, write first
     `load(distrib)'.


 -- Function: kurtosis_gamma (<a>,<b>)
     Returns the kurtosis coefficient of a Gamma(a,b) random variable,
     with a,b>0. To make use of this function, write first
     `load(distrib)'.


 -- Function: random_gamma (<a>,<b>)
 -- Function: random_gamma (<a>,<b>,<n>)
     Returns a Gamma(a,b) random variate, with a,b>0. Calling
     `random_gamma' with a third argument <n>, a random sample of size
     <n> will be simulated.

     The implemented algorithm is a combinantion of two procedures,
     depending on the value of parameter <a>:

     For a>=1, Cheng, R.C.H. and Feast, G.M. (1979). <Some simple gamma
     variate generators>. Appl. Stat., 28, 3, 290-295.

     For 0<a<1, Ahrens, J.H. and Dieter, U. (1974). <Computer methods
     for sampling from gamma, beta, poisson and binomial
     cdf_tributions>. Computing, 12, 223-246.

     To make use of this function, write first `load(distrib)'.


 -- Function: pdf_beta (<x>,<a>,<b>)
     Returns the value at <x> of the density function of a Beta(a,b)
     random variable, with a,b>0. To make use of this function, write
     first `load(distrib)'.


 -- Function: cdf_beta (<x>,<a>,<b>)
     Returns the value at <x> of the distribution function of a
     Beta(a,b) random variable, with a,b>0.

          (%i1) load (distrib)$
          (%i2) cdf_beta(1/3,15,2);
                                       11
          (%o2)                     --------
                                    14348907
          (%i3) float(%);
          (%o3)              7.666089131388195E-7


 -- Function: quantile_beta (<q>,<a>,<b>)
     Returns the <q>-quantile of a Beta(a,b) random variable, with
     a,b>0; in other words, this is the inverse of `cdf_beta'. Argument
     <q> must be an element of [0,1]. To make use of this function,
     write first `load(distrib)'.


 -- Function: mean_beta (<a>,<b>)
     Returns the mean of a Beta(a,b) random variable, with a,b>0. To
     make use of this function, write first `load(distrib)'.


 -- Function: var_beta (<a>,<b>)
     Returns the variance of a Beta(a,b) random variable, with a,b>0.
     To make use of this function, write first `load(distrib)'.


 -- Function: std_beta (<a>,<b>)
     Returns the standard deviation of a Beta(a,b) random variable,
     with a,b>0. To make use of this function, write first
     `load(distrib)'.


 -- Function: skewness_beta (<a>,<b>)
     Returns the skewness coefficient of a Beta(a,b) random variable,
     with a,b>0. To make use of this function, write first
     `load(distrib)'.


 -- Function: kurtosis_beta (<a>,<b>)
     Returns the kurtosis coefficient of a Beta(a,b) random variable,
     with a,b>0. To make use of this function, write first
     `load(distrib)'.


 -- Function: random_beta (<a>,<b>)
 -- Function: random_beta (<a>,<b>,<n>)
     Returns a Beta(a,b) random variate, with a,b>0. Calling
     `random_beta' with a third argument <n>, a random sample of size
     <n> will be simulated.

     The implemented algorithm is defined in Cheng, R.C.H.  (1978).
     <Generating Beta Variates with Nonintegral Shape Parameters>.
     Communications of the ACM, 21:317-322

     To make use of this function, write first `load(distrib)'.


 -- Function: pdf_continuous_uniform (<x>,<a>,<b>)
     Returns the value at <x> of the density function of a Continuous
     Uniform(a,b) random variable, with a<b. To make use of this
     function, write first `load(distrib)'.


 -- Function: cdf_continuous_uniform (<x>,<a>,<b>)
     Returns the value at <x> of the distribution function of a
     Continuous Uniform(a,b) random variable, with a<b. To make use of
     this function, write first `load(distrib)'.


 -- Function: quantile_continuous_uniform (<q>,<a>,<b>)
     Returns the <q>-quantile of a Continuous Uniform(a,b) random
     variable, with a<b; in other words, this is the inverse of
     `cdf_continuous_uniform'. Argument <q> must be an element of
     [0,1]. To make use of this function, write first `load(distrib)'.


 -- Function: mean_continuous_uniform (<a>,<b>)
     Returns the mean of a Continuous Uniform(a,b) random variable,
     with a<b. To make use of this function, write first
     `load(distrib)'.


 -- Function: var_continuous_uniform (<a>,<b>)
     Returns the variance of a Continuous Uniform(a,b) random variable,
     with a<b. To make use of this function, write first
     `load(distrib)'.


 -- Function: std_continuous_uniform (<a>,<b>)
     Returns the standard deviation of a Continuous Uniform(a,b) random
     variable, with a<b. To make use of this function, write first
     `load(distrib)'.


 -- Function: skewness_continuous_uniform (<a>,<b>)
     Returns the skewness coefficient of a Continuous Uniform(a,b)
     random variable, with a<b. To make use of this function, write
     first `load(distrib)'.


 -- Function: kurtosis_continuous_uniform (<a>,<b>)
     Returns the kurtosis coefficient of a Continuous Uniform(a,b)
     random variable, with a<b. To make use of this function, write
     first `load(distrib)'.


 -- Function: random_continuous_uniform (<a>,<b>)
 -- Function: random_continuous_uniform (<a>,<b>,<n>)
     Returns a Continuous Uniform(a,b) random variate, with a<b.
     Calling `random_continuous_uniform' with a third argument <n>, a
     random sample of size <n> will be simulated.

     This is a direct application of the `random' built-in Maxima
     function.

     See also `random'. To make use of this function, write first
     `load(distrib)'.


 -- Function: pdf_logistic (<x>,<a>,<b>)
     Returns the value at <x> of the density function of a
     Logistic(a,b) random variable , with b>0. To make use of this
     function, write first `load(distrib)'.


 -- Function: cdf_logistic (<x>,<a>,<b>)
     Returns the value at <x> of the distribution function of a
     Logistic(a,b) random variable , with b>0. To make use of this
     function, write first `load(distrib)'.


 -- Function: quantile_logistic (<q>,<a>,<b>)
     Returns the <q>-quantile of a Logistic(a,b) random variable , with
     b>0; in other words, this is the inverse of `cdf_logistic'.
     Argument <q> must be an element of [0,1]. To make use of this
     function, write first `load(distrib)'.


 -- Function: mean_logistic (<a>,<b>)
     Returns the mean of a Logistic(a,b) random variable , with b>0. To
     make use of this function, write first `load(distrib)'.


 -- Function: var_logistic (<a>,<b>)
     Returns the variance of a Logistic(a,b) random variable , with
     b>0. To make use of this function, write first `load(distrib)'.


 -- Function: std_logistic (<a>,<b>)
     Returns the standard deviation of a Logistic(a,b) random variable
     , with b>0. To make use of this function, write first
     `load(distrib)'.


 -- Function: skewness_logistic (<a>,<b>)
     Returns the skewness coefficient of a Logistic(a,b) random
     variable , with b>0. To make use of this function, write first
     `load(distrib)'.


 -- Function: kurtosis_logistic (<a>,<b>)
     Returns the kurtosis coefficient of a Logistic(a,b) random
     variable , with b>0. To make use of this function, write first
     `load(distrib)'.


 -- Function: random_logistic (<a>,<b>)
 -- Function: random_logistic (<a>,<b>,<n>)
     Returns a Logistic(a,b) random variate, with b>0. Calling
     `random_logistic' with a third argument <n>, a random sample of
     size <n> will be simulated.

     The implemented algorithm is based on the general inverse method.

     To make use of this function, write first `load(distrib)'.


 -- Function: pdf_pareto (<x>,<a>,<b>)
     Returns the value at <x> of the density function of a Pareto(a,b)
     random variable, with a,b>0. To make use of this function, write
     first `load(distrib)'.


 -- Function: cdf_pareto (<x>,<a>,<b>)
     Returns the value at <x> of the distribution function of a
     Pareto(a,b) random variable, with a,b>0. To make use of this
     function, write first `load(distrib)'.


 -- Function: quantile_pareto (<q>,<a>,<b>)
     Returns the <q>-quantile of a Pareto(a,b) random variable, with
     a,b>0; in other words, this is the inverse of `cdf_pareto'.
     Argument <q> must be an element of [0,1]. To make use of this
     function, write first `load(distrib)'.


 -- Function: mean_pareto (<a>,<b>)
     Returns the mean of a Pareto(a,b) random variable, with a>1,b>0.
     To make use of this function, write first `load(distrib)'.


 -- Function: var_pareto (<a>,<b>)
     Returns the variance of a Pareto(a,b) random variable, with
     a>2,b>0. To make use of this function, write first `load(distrib)'.


 -- Function: std_pareto (<a>,<b>)
     Returns the standard deviation of a Pareto(a,b) random variable,
     with a>2,b>0. To make use of this function, write first
     `load(distrib)'.


 -- Function: skewness_pareto (<a>,<b>)
     Returns the skewness coefficient of a Pareto(a,b) random variable,
     with a>3,b>0. To make use of this function, write first
     `load(distrib)'.


 -- Function: kurtosis_pareto (<a>,<b>)
     Returns the kurtosis coefficient of a Pareto(a,b) random variable,
     with a>4,b>0. To make use of this function, write first
     `load(distrib)'.


 -- Function: random_pareto (<a>,<b>)
 -- Function: random_pareto (<a>,<b>,<n>)
     Returns a Pareto(a,b) random variate, with a>0,b>0. Calling
     `random_pareto' with a third argument <n>, a random sample of size
     <n> will be simulated.

     The implemented algorithm is based on the general inverse method.

     To make use of this function, write first `load(distrib)'.


 -- Function: pdf_weibull (<x>,<a>,<b>)
     Returns the value at <x> of the density function of a Weibull(a,b)
     random variable, with a,b>0. To make use of this function, write
     first `load(distrib)'.


 -- Function: cdf_weibull (<x>,<a>,<b>)
     Returns the value at <x> of the distribution function of a
     Weibull(a,b) random variable, with a,b>0. To make use of this
     function, write first `load(distrib)'.


 -- Function: quantile_weibull (<q>,<a>,<b>)
     Returns the <q>-quantile of a Weibull(a,b) random variable, with
     a,b>0; in other words, this is the inverse of `cdf_weibull'.
     Argument <q> must be an element of [0,1]. To make use of this
     function, write first `load(distrib)'.


 -- Function: mean_weibull (<a>,<b>)
     Returns the mean of a Weibull(a,b) random variable, with a,b>0. To
     make use of this function, write first `load(distrib)'.


 -- Function: var_weibull (<a>,<b>)
     Returns the variance of a Weibull(a,b) random variable, with
     a,b>0. To make use of this function, write first `load(distrib)'.


 -- Function: std_weibull (<a>,<b>)
     Returns the standard deviation of a Weibull(a,b) random variable,
     with a,b>0. To make use of this function, write first
     `load(distrib)'.


 -- Function: skewness_weibull (<a>,<b>)
     Returns the skewness coefficient of a Weibull(a,b) random
     variable, with a,b>0. To make use of this function, write first
     `load(distrib)'.


 -- Function: kurtosis_weibull (<a>,<b>)
     Returns the kurtosis coefficient of a Weibull(a,b) random
     variable, with a,b>0. To make use of this function, write first
     `load(distrib)'.


 -- Function: random_weibull (<a>,<b>)
 -- Function: random_weibull (<a>,<b>,<n>)
     Returns a Weibull(a,b) random variate, with a,b>0. Calling
     `random_weibull' with a third argument <n>, a random sample of
     size <n> will be simulated.

     The implemented algorithm is based on the general inverse method.

     To make use of this function, write first `load(distrib)'.


 -- Function: pdf_rayleigh (<x>,<b>)
     Returns the value at <x> of the density function of a Rayleigh(b)
     random variable, with b>0.

     The Rayleigh(b) random variable is equivalent to the
     Weibull(2,1/b), therefore when Maxima has not enough information
     to get the result, a noun form based on the Weibull density is
     returned.

          (%i1) load (distrib)$
          (%i2) pdf_rayleigh(x,b);
                                                  1
          (%o2)                 pdf_weibull(x, 2, -)
                                                  b
          (%i3) assume(x>0,b>0)$ pdf_rayleigh(x,b);
                                              2  2
                                     2     - b  x
          (%o4)                   2 b  x %e


 -- Function: cdf_rayleigh (<x>,<b>)
     Returns the value at <x> of the distribution function of a
     Rayleigh(b) random variable, with b>0.

     The Rayleigh(b) random variable is equivalent to the
     Weibull(2,1/b), therefore when Maxima has not enough information
     to get the result, a noun form based on the Weibull distribution
     is returned.

          (%i1) load (distrib)$
          (%i2) cdf_rayleigh(x,b);
                                                  1
          (%o2)                 cdf_weibull(x, 2, -)
                                                  b
          (%i3) assume(x>0,b>0)$ cdf_rayleigh(x,b);
                                             2  2
                                          - b  x
          (%o4)                     1 - %e


 -- Function: quantile_rayleigh (<q>,<b>)
     Returns the <q>-quantile of a Rayleigh(b) random variable, with
     b>0; in other words, this is the inverse of `cdf_rayleigh'.
     Argument <q> must be an element of [0,1].

     The Rayleigh(b) random variable is equivalent to the
     Weibull(2,1/b), therefore when Maxima has not enough information
     to get the result, a noun form based on the Weibull quantile is
     returned.

          (%i1) load (distrib)$
          (%i2) quantile_rayleigh(0.99,b);
                                                      1
          (%o2)             quantile_weibull(0.99, 2, -)
                                                      b
          (%i3) assume(x>0,b>0)$ quantile_rayleigh(0.99,b);
                                  2.145966026289347
          (%o4)                   -----------------
                                          b


 -- Function: mean_rayleigh (<b>)
     Returns the mean of a Rayleigh(b) random variable, with b>0.

     The Rayleigh(b) random variable is equivalent to the
     Weibull(2,1/b), therefore when Maxima has not enough information
     to get the result, a noun form based on the Weibull mean is
     returned.

          (%i1) load (distrib)$
          (%i2) mean_rayleigh(b);
                                                 1
          (%o2)                  mean_weibull(2, -)
                                                 b
          (%i3) assume(b>0)$ mean_rayleigh(b);
                                      sqrt(%pi)
          (%o4)                       ---------
                                         2 b


 -- Function: var_rayleigh (<b>)
     Returns the variance of a Rayleigh(b) random variable, with b>0.

     The Rayleigh(b) random variable is equivalent to the
     Weibull(2,1/b), therefore when Maxima has not enough information
     to get the result, a noun form based on the Weibull variance is
     returned.

          (%i1) load (distrib)$
          (%i2) var_rayleigh(b);
                                                 1
          (%o2)                   var_weibull(2, -)
                                                 b
          (%i3) assume(b>0)$ var_rayleigh(b);
                                           %pi
                                       1 - ---
                                            4
          (%o4)                        -------
                                          2
                                         b


 -- Function: std_rayleigh (<b>)
     Returns the standard deviation of a Rayleigh(b) random variable,
     with b>0.

     The Rayleigh(b) random variable is equivalent to the
     Weibull(2,1/b), therefore when Maxima has not enough information
     to get the result, a noun form based on the Weibull standard
     deviation is returned.

          (%i1) load (distrib)$
          (%i2) std_rayleigh(b);
                                                 1
          (%o2)                   std_weibull(2, -)
                                                 b
          (%i3) assume(b>0)$ std_rayleigh(b);
                                             %pi
                                    sqrt(1 - ---)
                                              4
          (%o4)                     -------------
                                          b


 -- Function: skewness_rayleigh (<b>)
     Returns the skewness coefficient of a Rayleigh(b) random variable,
     with b>0.

     The Rayleigh(b) random variable is equivalent to the
     Weibull(2,1/b), therefore when Maxima has not enough information
     to get the result, a noun form based on the Weibull skewness
     coefficient is returned.

          (%i1) load (distrib)$
          (%i2) skewness_rayleigh(b);
                                                   1
          (%o2)                skewness_weibull(2, -)
                                                   b
          (%i3) assume(b>0)$ skewness_rayleigh(b);
                                   3/2
                                %pi      3 sqrt(%pi)
                                ------ - -----------
                                  4           4
          (%o4)                 --------------------
                                         %pi 3/2
                                    (1 - ---)
                                          4


 -- Function: kurtosis_rayleigh (<b>)
     Returns the kurtosis coefficient of a Rayleigh(b) random variable,
     with b>0.

     The Rayleigh(b) random variable is equivalent to the
     Weibull(2,1/b), therefore when Maxima has not enough information
     to get the result, a noun form based on the Weibull kurtosis
     coefficient is returned.

          (%i1) load (distrib)$
          (%i2) kurtosis_rayleigh(b);
                                                   1
          (%o2)                kurtosis_weibull(2, -)
                                                   b
          (%i3) assume(b>0)$ kurtosis_rayleigh(b);
                                            2
                                       3 %pi
                                   2 - ------
                                         16
          (%o4)                    ---------- - 3
                                        %pi 2
                                   (1 - ---)
                                         4


 -- Function: random_rayleigh (<b>)
 -- Function: random_rayleigh (<b>,<n>)
     Returns a Rayleigh(b) random variate, with b>0. Calling
     `random_rayleigh' with a second argument <n>, a random sample of
     size <n> will be simulated.

     The implemented algorithm is based on the general inverse method.

     To make use of this function, write first `load(distrib)'.


 -- Function: pdf_laplace (<x>,<a>,<b>)
     Returns the value at <x> of the density function of a Laplace(a,b)
     random variable, with b>0. To make use of this function, write
     first `load(distrib)'.


 -- Function: cdf_laplace (<x>,<a>,<b>)
     Returns the value at <x> of the distribution function of a
     Laplace(a,b) random variable, with b>0. To make use of this
     function, write first `load(distrib)'.


 -- Function: quantile_laplace (<q>,<a>,<b>)
     Returns the <q>-quantile of a Laplace(a,b) random variable, with
     b>0; in other words, this is the inverse of `cdf_laplace'.
     Argument <q> must be an element of [0,1]. To make use of this
     function, write first `load(distrib)'.


 -- Function: mean_laplace (<a>,<b>)
     Returns the mean of a Laplace(a,b) random variable, with b>0. To
     make use of this function, write first `load(distrib)'.


 -- Function: var_laplace (<a>,<b>)
     Returns the variance of a Laplace(a,b) random variable, with b>0.
     To make use of this function, write first `load(distrib)'.


 -- Function: std_laplace (<a>,<b>)
     Returns the standard deviation of a Laplace(a,b) random variable,
     with b>0. To make use of this function, write first
     `load(distrib)'.


 -- Function: skewness_laplace (<a>,<b>)
     Returns the skewness coefficient of a Laplace(a,b) random
     variable, with b>0. To make use of this function, write first
     `load(distrib)'.


 -- Function: kurtosis_laplace (<a>,<b>)
     Returns the kurtosis coefficient of a Laplace(a,b) random
     variable, with b>0. To make use of this function, write first
     `load(distrib)'.


 -- Function: random_laplace (<a>,<b>)
 -- Function: random_laplace (<a>,<b>,<n>)
     Returns a Laplace(a,b) random variate, with b>0. Calling
     `random_laplace' with a third argument <n>, a random sample of
     size <n> will be simulated.

     The implemented algorithm is based on the general inverse method.

     To make use of this function, write first `load(distrib)'.


 -- Function: pdf_cauchy (<x>,<a>,<b>)
     Returns the value at <x> of the density function of a Cauchy(a,b)
     random variable, with b>0. To make use of this function, write
     first `load(distrib)'.


 -- Function: cdf_cauchy (<x>,<a>,<b>)
     Returns the value at <x> of the distribution function of a
     Cauchy(a,b) random variable, with b>0. To make use of this
     function, write first `load(distrib)'.


 -- Function: quantile_cauchy (<q>,<a>,<b>)
     Returns the <q>-quantile of a Cauchy(a,b) random variable, with
     b>0; in other words, this is the inverse of `cdf_cauchy'. Argument
     <q> must be an element of [0,1]. To make use of this function,
     write first `load(distrib)'.


 -- Function: random_cauchy (<a>,<b>)
 -- Function: random_cauchy (<a>,<b>,<n>)
     Returns a Cauchy(a,b) random variate, with b>0. Calling
     `random_cauchy' with a third argument <n>, a random sample of size
     <n> will be simulated.

     The implemented algorithm is based on the general inverse method.

     To make use of this function, write first `load(distrib)'.


 -- Function: pdf_gumbel (<x>,<a>,<b>)
     Returns the value at <x> of the density function of a Gumbel(a,b)
     random variable, with b>0. To make use of this function, write
     first `load(distrib)'.


 -- Function: cdf_gumbel (<x>,<a>,<b>)
     Returns the value at <x> of the distribution function of a
     Gumbel(a,b) random variable, with b>0. To make use of this
     function, write first `load(distrib)'.


 -- Function: quantile_gumbel (<q>,<a>,<b>)
     Returns the <q>-quantile of a Gumbel(a,b) random variable, with
     b>0; in other words, this is the inverse of `cdf_gumbel'. Argument
     <q> must be an element of [0,1]. To make use of this function,
     write first `load(distrib)'.


 -- Function: mean_gumbel (<a>,<b>)
     Returns the mean of a Gumbel(a,b) random variable, with b>0.

          (%i1) load (distrib)$
          (%i2) assume(b>0)$  mean_gumbel(a,b);
          (%o3)                     %gamma b + a
     where symbol `%gamma' stands for the Euler-Mascheroni constant.
     See also `%gamma'.


 -- Function: var_gumbel (<a>,<b>)
     Returns the variance of a Gumbel(a,b) random variable, with b>0.
     To make use of this function, write first `load(distrib)'.


 -- Function: std_gumbel (<a>,<b>)
     Returns the standard deviation of a Gumbel(a,b) random variable,
     with b>0. To make use of this function, write first
     `load(distrib)'.


 -- Function: skewness_gumbel (<a>,<b>)
     Returns the skewness coefficient of a Gumbel(a,b) random variable,
     with b>0.

          (%i1) load (distrib)$
          (%i2) assume(b>0)$ skewness_gumbel(a,b);
                                 12 sqrt(6) zeta(3)
          (%o3)                  ------------------
                                           3
                                        %pi
          (%i4) numer:true$ skewness_gumbel(a,b);
          (%o5)                   1.139547099404649
     where `zeta' stands for the Riemann's zeta function.


 -- Function: kurtosis_gumbel (<a>,<b>)
     Returns the kurtosis coefficient of a Gumbel(a,b) random variable,
     with b>0. To make use of this function, write first
     `load(distrib)'.


 -- Function: random_gumbel (<a>,<b>)
 -- Function: random_gumbel (<a>,<b>,<n>)
     Returns a Gumbel(a,b) random variate, with b>0. Calling
     `random_gumbel' with a third argument <n>, a random sample of size
     <n> will be simulated.

     The implemented algorithm is based on the general inverse method.

     To make use of this function, write first `load(distrib)'.



File: maxima.info,  Node: Functions and Variables for discrete distributions,  Prev: Functions and Variables for continuous distributions,  Up: distrib

47.3 Functions and Variables for discrete distributions
=======================================================

 -- Function: pdf_general_finite_discrete (<x>,<v>)
     Returns the value at <x> of the probability function of a general
     finite discrete random variable, with vector probabilities v, such
     that `Pr(X=i) = v_i'. Vector v can be a list of nonnegative
     expressions, whose components will be normalized to get a vector
     of probabilities. To make use of this function, write first
     `load(distrib)'.

          (%i1) load (distrib)$
          (%i2) pdf_general_finite_discrete(2, [1/7, 4/7, 2/7]);
                                          4
          (%o2)                           -
                                          7
          (%i3) pdf_general_finite_discrete(2, [1, 4, 2]);
                                          4
          (%o3)                           -
                                          7


 -- Function: cdf_general_finite_discrete (<x>,<v>)
     Returns the value at <x> of the distribution function of a general
     finite discrete random variable, with vector probabilities v.

     See `pdf_general_finite_discrete' for more details.

          (%i1) load (distrib)$
          (%i2) cdf_general_finite_discrete(2, [1/7, 4/7, 2/7]);
                                          5
          (%o2)                           -
                                          7
          (%i3) cdf_general_finite_discrete(2, [1, 4, 2]);
                                          5
          (%o3)                           -
                                          7
          (%i4) cdf_general_finite_discrete(2+1/2, [1, 4, 2]);
                                          5
          (%o4)                           -
                                          7


 -- Function: quantile_general_finite_discrete (<q>,<v>)
     Returns the <q>-quantile of a general finite discrete random
     variable, with vector probabilities v.

     See `pdf_general_finite_discrete' for more details.


 -- Function: mean_general_finite_discrete (<v>)
     Returns the mean of a general finite discrete random variable,
     with vector probabilities v.

     See `pdf_general_finite_discrete' for more details.


 -- Function: var_general_finite_discrete (<v>)
     Returns the variance of a general finite discrete random variable,
     with vector probabilities v.

     See `pdf_general_finite_discrete' for more details.


 -- Function: std_general_finite_discrete (<v>)
     Returns the standard deviation of a general finite discrete random
     variable, with vector probabilities v.

     See `pdf_general_finite_discrete' for more details.


 -- Function: skewness_general_finite_discrete (<v>)
     Returns the skewness coefficient of a general finite discrete
     random variable, with vector probabilities v.

     See `pdf_general_finite_discrete' for more details.


 -- Function: kurtosis_general_finite_discrete (<v>)
     Returns the kurtosis coefficient of a general finite discrete
     random variable, with vector probabilities v.

     See `pdf_general_finite_discrete' for more details.


 -- Function: random_general_finite_discrete (<v>)
 -- Function: random_general_finite_discrete (<v>,<m>)
     Returns a general finite discrete random variate, with vector
     probabilities v. Calling `random_general_finite_discrete' with a
     second argument <m>, a random sample of size <m> will be simulated.

     See `pdf_general_finite_discrete' for more details.

          (%i1) load (distrib)$
          (%i2) random_general_finite_discrete([1,3,1,5]);
          (%o2)                          4
          (%i3) random_general_finite_discrete([1,3,1,5], 10);
          (%o3)           [4, 2, 2, 3, 2, 4, 4, 1, 2, 2]


 -- Function: pdf_binomial (<x>,<n>,<p>)
     Returns the value at <x> of the probability function of a
     Binomial(n,p) random variable, with 0<p<1 and n a positive
     integer. To make use of this function, write first `load(distrib)'.
                                      4 (%o6)
       -                                   7


 -- Function: cdf_binomial (<x>,<n>,<p>)
     Returns the value at <x> of the distribution function of a
     Binomial(n,p) random variable, with 0<p<1 and n a positive integer.

          (%i1) load (distrib)$
          (%i2) cdf_binomial(5,7,1/6);
                                      7775
          (%o2)                       ----
                                      7776
          (%i3) float(%);
          (%o3)               .9998713991769548


 -- Function: quantile_binomial (<q>,<n>,<p>)
     Returns the <q>-quantile of a Binomial(n,p) random variable, with
     0<p<1 and n a positive integer; in other words, this is the
     inverse of `cdf_binomial'. Argument <q> must be an element of
     [0,1]. To make use of this function, write first `load(distrib)'.


 -- Function: mean_binomial (<n>,<p>)
     Returns the mean of a Binomial(n,p) random variable, with 0<p<1
     and n a positive integer. To make use of this function, write
     first `load(distrib)'.


 -- Function: var_binomial (<n>,<p>)
     Returns the variance of a Binomial(n,p) random variable, with
     0<p<1 and n a positive integer. To make use of this function,
     write first `load(distrib)'.


 -- Function: std_binomial (<n>,<p>)
     Returns the standard deviation of a Binomial(n,p) random variable,
     with 0<p<1 and n a positive integer. To make use of this function,
     write first `load(distrib)'.


 -- Function: skewness_binomial (<n>,<p>)
     Returns the skewness coefficient of a Binomial(n,p) random
     variable, with 0<p<1 and n a positive integer. To make use of this
     function, write first `load(distrib)'.


 -- Function: kurtosis_binomial (<n>,<p>)
     Returns the kurtosis coefficient of a Binomial(n,p) random
     variable, with 0<p<1 and n a positive integer. To make use of this
     function, write first `load(distrib)'.


 -- Function: random_binomial (<n>,<p>)
 -- Function: random_binomial (<n>,<p>,<m>)
     Returns a Binomial(n,p) random variate, with 0<p<1 and n a
     positive integer. Calling `random_binomial' with a third argument
     <m>, a random sample of size <m> will be simulated.

     The implemented algorithm is based on the one described in
     Kachitvichyanukul, V. and Schmeiser, B.W. (1988) <Binomial Random
     Variate Generation>. Communications of the ACM, 31, Feb., 216.

     To make use of this function, write first `load(distrib)'.


 -- Function: pdf_poisson (<x>,<m>)
     Returns the value at <x> of the probability function of a
     Poisson(m) random variable, with m>0. To make use of this
     function, write first `load(distrib)'.


 -- Function: cdf_poisson (<x>,<m>)
     Returns the value at <x> of the distribution function of a
     Poisson(m) random variable, with m>0.

          (%i1) load (distrib)$
          (%i2) cdf_poisson(3,5);
          (%o2)       gamma_incomplete_regularized(4, 5)
          (%i3) float(%);
          (%o3)               .2650259152973623


 -- Function: quantile_poisson (<q>,<m>)
     Returns the <q>-quantile of a Poisson(m) random variable, with
     m>0; in other words, this is the inverse of `cdf_poisson'.
     Argument <q> must be an element of [0,1]. To make use of this
     function, write first `load(distrib)'.


 -- Function: mean_poisson (<m>)
     Returns the mean of a Poisson(m) random variable, with  m>0. To
     make use of this function, write first `load(distrib)'.


 -- Function: var_poisson (<m>)
     Returns the variance of a Poisson(m) random variable, with  m>0.
     To make use of this function, write first `load(distrib)'.


 -- Function: std_poisson (<m>)
     Returns the standard deviation of a Poisson(m) random variable,
     with m>0. To make use of this function, write first
     `load(distrib)'.


 -- Function: skewness_poisson (<m>)
     Returns the skewness coefficient of a Poisson(m) random variable,
     with m>0. To make use of this function, write first
     `load(distrib)'.


 -- Function: kurtosis_poisson (<m>)
     Returns the kurtosis coefficient of a Poisson random variable
     Poi(m), with m>0. To make use of this function, write first
     `load(distrib)'.


 -- Function: random_poisson (<m>)
 -- Function: random_poisson (<m>,<n>)
     Returns a Poisson(m) random variate, with m>0. Calling
     `random_poisson' with a second argument <n>, a random sample of
     size <n> will be simulated.

     The implemented algorithm is the one described in Ahrens, J.H. and
     Dieter, U. (1982) <Computer Generation of Poisson Deviates From
     Modified Normal Distributions>. ACM Trans. Math. Software, 8, 2,
     June,163-179.

     To make use of this function, write first `load(distrib)'.


 -- Function: pdf_bernoulli (<x>,<p>)
     Returns the value at <x> of the probability function of a
     Bernoulli(p) random variable, with 0<p<1.

     The Bernoulli(p) random variable is equivalent to the
     Binomial(1,p), therefore when Maxima has not enough information to
     get the result, a noun form based on the binomial probability
     function is returned.

          (%i1) load (distrib)$
          (%i2) pdf_bernoulli(1,p);
          (%o2)                 pdf_binomial(1, 1, p)
          (%i3) assume(0<p,p<1)$ pdf_bernoulli(1,p);
          (%o4)                           p


 -- Function: cdf_bernoulli (<x>,<p>)
     Returns the value at <x> of the distribution function of a
     Bernoulli(p) random variable, with 0<p<1. To make use of this
     function, write first `load(distrib)'.


 -- Function: quantile_bernoulli (<q>,<p>)
     Returns the <q>-quantile of a Bernoulli(p) random variable, with
     0<p<1; in other words, this is the inverse of `cdf_bernoulli'.
     Argument <q> must be an element of [0,1]. To make use of this
     function, write first `load(distrib)'.


 -- Function: mean_bernoulli (<p>)
     Returns the mean of a Bernoulli(p) random variable, with 0<p<1.

     The Bernoulli(p) random variable is equivalent to the
     Binomial(1,p), therefore when Maxima has not enough information to
     get the result, a noun form based on the binomial mean is returned.

          (%i1) load (distrib)$
          (%i2) mean_bernoulli(p);
          (%o2)                  mean_binomial(1, p)
          (%i3) assume(0<p,p<1)$ mean_bernoulli(p);
          (%o4)                           p


 -- Function: var_bernoulli (<p>)
     Returns the variance of a Bernoulli(p) random variable, with 0<p<1.

     The Bernoulli(p) random variable is equivalent to the
     Binomial(1,p), therefore when Maxima has not enough information to
     get the result, a noun form based on the binomial variance is
     returned.

          (%i1) load (distrib)$
          (%i2) var_bernoulli(p);
          (%o2)                  var_binomial(1, p)
          (%i3) assume(0<p,p<1)$ var_bernoulli(p);
          (%o4)                       (1 - p) p


 -- Function: std_bernoulli (<p>)
     Returns the standard deviation of a Bernoulli(p) random variable,
     with 0<p<1.

     The Bernoulli(p) random variable is equivalent to the
     Binomial(1,p), therefore when Maxima has not enough information to
     get the result, a noun form based on the binomial standard
     deviation is returned.

          (%i1) load (distrib)$
          (%i2) std_bernoulli(p);
          (%o2)                  std_binomial(1, p)
          (%i3) assume(0<p,p<1)$ std_bernoulli(p);
          (%o4)                  sqrt(1 - p) sqrt(p)


 -- Function: skewness_bernoulli (<p>)
     Returns the skewness coefficient of a Bernoulli(p) random
     variable, with 0<p<1.

     The Bernoulli(p) random variable is equivalent to the
     Binomial(1,p), therefore when Maxima has not enough information to
     get the result, a noun form based on the binomial skewness
     coefficient is returned.

          (%i1) load (distrib)$
          (%i2) skewness_bernoulli(p);
          (%o2)                skewness_binomial(1, p)
          (%i3) assume(0<p,p<1)$ skewness_bernoulli(p);
                                       1 - 2 p
          (%o4)                  -------------------
                                 sqrt(1 - p) sqrt(p)


 -- Function: kurtosis_bernoulli (<p>)
     Returns the kurtosis coefficient of a Bernoulli(p) random
     variable, with 0<p<1.

     The Bernoulli(p) random variable is equivalent to the
     Binomial(1,p), therefore when Maxima has not enough information to
     get the result, a noun form based on the binomial kurtosis
     coefficient is returned.

          (%i1) load (distrib)$
          (%i2) kurtosis_bernoulli(p);
          (%o2)                kurtosis_binomial(1, p)
          (%i3) assume(0<p,p<1)$ kurtosis_bernoulli(p);
                                   1 - 6 (1 - p) p
          (%o4)                    ---------------
                                      (1 - p) p


 -- Function: random_bernoulli (<p>)
 -- Function: random_bernoulli (<p>,<n>)
     Returns a Bernoulli(p) random variate, with 0<p<1. Calling
     `random_bernoulli' with a second argument <n>, a random sample of
     size <n> will be simulated.

     This is a direct application of the `random' built-in Maxima
     function.

     See also `random'. To make use of this function, write first
     `load(distrib)'.


 -- Function: pdf_geometric (<x>,<p>)
     Returns the value at <x> of the probability function of a
     Geometric(p) random variable, with 0<p<1. To make use of this
     function, write first `load(distrib)'.


 -- Function: cdf_geometric (<x>,<p>)
     Returns the value at <x> of the distribution function of a
     Geometric(p) random variable, with 0<p<1. To make use of this
     function, write first `load(distrib)'.


 -- Function: quantile_geometric (<q>,<p>)
     Returns the <q>-quantile of a Geometric(p) random variable, with
     0<p<1; in other words, this is the inverse of `cdf_geometric'.
     Argument <q> must be an element of [0,1]. To make use of this
     function, write first `load(distrib)'.


 -- Function: mean_geometric (<p>)
     Returns the mean of a Geometric(p) random variable, with 0<p<1. To
     make use of this function, write first `load(distrib)'.


 -- Function: var_geometric (<p>)
     Returns the variance of a Geometric(p) random variable, with
     0<p<1. To make use of this function, write first `load(distrib)'.


 -- Function: std_geometric (<p>)
     Returns the standard deviation of a Geometric(p) random variable,
     with 0<p<1. To make use of this function, write first
     `load(distrib)'.


 -- Function: skewness_geometric (<p>)
     Returns the skewness coefficient of a Geometric(p) random
     variable, with 0<p<1. To make use of this function, write first
     `load(distrib)'.


 -- Function: kurtosis_geometric (<p>)
     Returns the kurtosis coefficient of a geometric random variable
     Geo(p), with 0<p<1. To make use of this function, write first
     `load(distrib)'.


 -- Function: random_geometric (<p>)
 -- Function: random_geometric (<p>,<n>)
     Returns a Geometric(p) random variate, with 0<p<1. Calling
     `random_geometric' with a second argument <n>, a random sample of
     size <n> will be simulated.

     The algorithm is based on simulation of Bernoulli trials.

     To make use of this function, write first `load(distrib)'.


 -- Function: pdf_discrete_uniform (<x>,<n>)
     Returns the value at <x> of the probability function of a Discrete
     Uniform(n) random variable, with n a strictly positive integer. To
     make use of this function, write first `load(distrib)'.


 -- Function: cdf_discrete_uniform (<x>,<n>)
     Returns the value at <x> of the distribution function of a
     Discrete Uniform(n) random variable, with n a strictly positive
     integer. To make use of this function, write first `load(distrib)'.


 -- Function: quantile_discrete_uniform (<q>,<n>)
     Returns the <q>-quantile of a Discrete Uniform(n) random variable,
     with n a strictly positive integer; in other words, this is the
     inverse of `cdf_discrete_uniform'. Argument <q> must be an element
     of [0,1]. To make use of this function, write first
     `load(distrib)'.


 -- Function: mean_discrete_uniform (<n>)
     Returns the mean of a Discrete Uniform(n) random variable, with n
     a strictly positive integer. To make use of this function, write
     first `load(distrib)'.


 -- Function: var_discrete_uniform (<n>)
     Returns the variance of a Discrete Uniform(n) random variable,
     with n a strictly positive integer. To make use of this function,
     write first `load(distrib)'.


 -- Function: std_discrete_uniform (<n>)
     Returns the standard deviation of a Discrete Uniform(n) random
     variable, with n a strictly positive integer. To make use of this
     function, write first `load(distrib)'.


 -- Function: skewness_discrete_uniform (<n>)
     Returns the skewness coefficient of a Discrete Uniform(n) random
     variable, with n a strictly positive integer. To make use of this
     function, write first `load(distrib)'.


 -- Function: kurtosis_discrete_uniform (<n>)
     Returns the kurtosis coefficient of a Discrete Uniform(n) random
     variable, with n a strictly positive integer. To make use of this
     function, write first `load(distrib)'.


 -- Function: random_discrete_uniform (<n>)
 -- Function: random_discrete_uniform (<n>,<m>)
     Returns a Discrete Uniform(n) random variate, with n a strictly
     positive integer. Calling `random_discrete_uniform' with a second
     argument <m>, a random sample of size <m> will be simulated.

     This is a direct application of the `random' built-in Maxima
     function.

     See also `random'. To make use of this function, write first
     `load(distrib)'.


 -- Function: pdf_hypergeometric (<x>,<n1>,<n2>,<n>)
     Returns the value at <x> of the probability function of a
     Hypergeometric(n1,n2,n) random variable, with <n1>, <n2> and <n>
     non negative integers and n<=n1+n2.  Being <n1> the number of
     objects of class A, <n2> the number of objects of class B, and <n>
     the size of the sample without replacement, this function returns
     the probability of event "exactly <x> objects are of class A".

     To make use of this function, write first `load(distrib)'.


 -- Function: cdf_hypergeometric (<x>,<n1>,<n2>,<n>)
     Returns the value at <x> of the distribution function of a
     Hypergeometric(n1,n2,n) random variable, with <n1>, <n2> and <n>
     non negative integers and n<=n1+n2.  See `pdf_hypergeometric' for
     a more complete description.

     To make use of this function, write first `load(distrib)'.


 -- Function: quantile_hypergeometric (<q>,<n1>,<n2>,<n>)
     Returns the <q>-quantile of a Hypergeometric(n1,n2,n) random
     variable, with <n1>, <n2> and <n> non negative integers and
     n<=n1+n2; in other words, this is the inverse of
     `cdf_hypergeometric'. Argument <q> must be an element of [0,1]. To
     make use of this function, write first `load(distrib)'.


 -- Function: mean_hypergeometric (<n1>,<n2>,<n>)
     Returns the mean of a discrete uniform random variable
     Hyp(n1,n2,n), with <n1>, <n2> and <n> non negative integers and
     n<=n1+n2. To make use of this function, write first
     `load(distrib)'.


 -- Function: var_hypergeometric (<n1>,<n2>,<n>)
     Returns the variance of a hypergeometric  random variable
     Hyp(n1,n2,n), with <n1>, <n2> and <n> non negative integers and
     n<=n1+n2. To make use of this function, write first
     `load(distrib)'.


 -- Function: std_hypergeometric (<n1>,<n2>,<n>)
     Returns the standard deviation of a Hypergeometric(n1,n2,n) random
     variable, with <n1>, <n2> and <n> non negative integers and
     n<=n1+n2. To make use of this function, write first
     `load(distrib)'.


 -- Function: skewness_hypergeometric (<n1>,<n2>,<n>)
     Returns the skewness coefficient of a Hypergeometric(n1,n2,n)
     random variable, with <n1>, <n2> and <n> non negative integers and
     n<=n1+n2. To make use of this function, write first
     `load(distrib)'.


 -- Function: kurtosis_hypergeometric (<n1>,<n2>,<n>)
     Returns the kurtosis coefficient of a Hypergeometric(n1,n2,n)
     random variable, with <n1>, <n2> and <n> non negative integers and
     n<=n1+n2. To make use of this function, write first
     `load(distrib)'.


 -- Function: random_hypergeometric (<n1>,<n2>,<n>)
 -- Function: random_hypergeometric (<n1>,<n2>,<n>,<m>)
     Returns a Hypergeometric(n1,n2,n) random variate, with <n1>, <n2>
     and <n> non negative integers and n<=n1+n2. Calling
     `random_hypergeometric' with a fourth argument <m>, a random
     sample of size <m> will be simulated.

     Algorithm described in Kachitvichyanukul, V., Schmeiser, B.W.
     (1985) <Computer generation of hypergeometric random variates.>
     Journal of Statistical Computation and Simulation 22, 127-145.

     To make use of this function, write first `load(distrib)'.


 -- Function: pdf_negative_binomial (<x>,<n>,<p>)
     Returns the value at <x> of the probability function of a Negative
     Binomial(n,p) random variable, with 0<p<1 and n a positive number.
     To make use of this function, write first `load(distrib)'.


 -- Function: cdf_negative_binomial (<x>,<n>,<p>)
     Returns the value at <x> of the distribution function of a
     Negative Binomial(n,p) random variable, with 0<p<1 and n a
     positive number.

          (%i1) load (distrib)$
          (%i2) cdf_negative_binomial(3,4,1/8);
                                      3271
          (%o2)                      ------
                                     524288
          (%i3) float(%);
          (%o3)              .006238937377929687


 -- Function: quantile_negative_binomial (<q>,<n>,<p>)
     Returns the <q>-quantile of a Negative Binomial(n,p) random
     variable, with 0<p<1 and n a positive number; in other words, this
     is the inverse of `cdf_negative_binomial'. Argument <q> must be an
     element of [0,1]. To make use of this function, write first
     `load(distrib)'.


 -- Function: mean_negative_binomial (<n>,<p>)
     Returns the mean of a Negative Binomial(n,p) random variable, with
     0<p<1 and n a positive number. To make use of this function, write
     first `load(distrib)'.


 -- Function: var_negative_binomial (<n>,<p>)
     Returns the variance of a Negative Binomial(n,p) random variable,
     with 0<p<1 and n a positive number. To make use of this function,
     write first `load(distrib)'.


 -- Function: std_negative_binomial (<n>,<p>)
     Returns the standard deviation of a Negative Binomial(n,p) random
     variable, with 0<p<1 and n a positive number. To make use of this
     function, write first `load(distrib)'.


 -- Function: skewness_negative_binomial (<n>,<p>)
     Returns the skewness coefficient of a Negative Binomial(n,p)
     random variable, with 0<p<1 and n a positive number. To make use
     of this function, write first `load(distrib)'.


 -- Function: kurtosis_negative_binomial (<n>,<p>)
     Returns the kurtosis coefficient of a Negative Binomial(n,p)
     random variable, with 0<p<1 and n a positive number. To make use
     of this function, write first `load(distrib)'.


 -- Function: random_negative_binomial (<n>,<p>)
 -- Function: random_negative_binomial (<n>,<p>,<m>)
     Returns a Negative Binomial(n,p) random variate, with 0<p<1 and n
     a positive number. Calling `random_negative_binomial' with a third
     argument <m>, a random sample of size <m> will be simulated.

     Algorithm described in Devroye, L. (1986) <Non-Uniform Random
     Variate Generation>. Springer Verlag, p. 480.

     To make use of this function, write first `load(distrib)'.



File: maxima.info,  Node: draw,  Next: drawdf,  Prev: distrib,  Up: Top

48 draw
*******

* Menu:

* Introduction to draw::
* Functions and Variables for draw::
* Functions and Variables for pictures::
* Functions and Variables for worldmap::


File: maxima.info,  Node: Introduction to draw,  Next: Functions and Variables for draw,  Prev: draw,  Up: draw

48.1 Introduction to draw
=========================

`draw' is a Maxima-Gnuplot interface.

   There are three main functions to be used at Maxima level: `draw2d',
`draw3d' and `draw'.

   Follow this link for more elaborated examples of this package:

   `http://riotorto.users.sourceforge.net/gnuplot'

   You need Gnuplot 4.2 or newer to run this program.


File: maxima.info,  Node: Functions and Variables for draw,  Next: Functions and Variables for pictures,  Prev: Introduction to draw,  Up: draw

48.2 Functions and Variables for draw
=====================================

48.2.1 Scenes
-------------

 -- Scene constructor: gr2d (<graphic option>, ..., <graphic object>,
          ...)
     Function `gr2d' builds an object describing a 2D scene. Arguments
     are graphic options, graphic objects, or lists containing both
     graphic options and objects.  This scene is interpreted
     sequentially: graphic options affect those graphic objects placed
     on its right. Some graphic options affect the global appearence of
     the scene.

     This is the list of graphic objects available for scenes in two
     dimensions: `bars', `ellipse', `explicit', `image', `implicit',
     `label', `parametric', `points', `polar', `polygon',
     `quadrilateral', `rectangle', `triangle', `vector', and `geomap'
     (this one defined in package `worldmap').

     See also `draw' and `draw2d'.

     To make use of this object, write first `load(draw)'.


 -- Scene constructor: gr3d (<graphic option>, ..., <graphic object>,
          ...)
     Function `gr3d' builds an object describing a 3d scene. Arguments
     are graphic options, graphic objects, or lists containing both
     graphic options and objects. This scene is interpreted
     sequentially: graphic options affect those graphic objects placed
     on its right. Some graphic options affect the global appearence of
     the scene.

     This is the list of graphic objects available for scenes in three
     dimensions:
     `cylindrical', `elevation_grid', `explicit', `implicit', `label',
     `mesh', `parametric',
     `parametric_surface', `points', `quadrilateral', `spherical',
     `triangle', `tube',
     `vector', and `geomap' (this one defined in package `worldmap').

     See also `draw' and `draw3d'.

     To make use of this object, write first `load(draw)'.


48.2.2 Functions
----------------

 -- Function: draw (<gr2d>, ..., <gr3d>, ..., <options>, ...)
     Plots a series of scenes; its arguments are `gr2d' and/or `gr3d'
     objects, together with some options, or lists of scenes and
     options.  By default, the scenes are put together in one column.

     Function `draw' accepts the following global options: `terminal',
     `columns', `dimensions', `file_name' and `delay'.

     Functions `draw2d' and `draw3d' are short cuts to be used when
     only one scene is required, in two or three dimensions,
     respectively.

     See also `gr2d' and `gr3d'.

     To make use of this function, write first `load(draw)'.

     Example:

          (%i1) load(draw)$
          (%i2) scene1: gr2d(title="Ellipse",
                             nticks=30,
                             parametric(2*cos(t),5*sin(t),t,0,2*%pi))$
          (%i3) scene2: gr2d(title="Triangle",
                             polygon([4,5,7],[6,4,2]))$
          (%i4) draw(scene1, scene2, columns = 2)$

     The two draw sentences are equivalent:
          (%i1) load(draw)$
          (%i2) draw(gr3d(explicit(x^2+y^2,x,-1,1,y,-1,1)));
          (%o2)                          [gr3d(explicit)]
          (%i3) draw3d(explicit(x^2+y^2,x,-1,1,y,-1,1));
          (%o3)                          [gr3d(explicit)]

     An animated gif file:
          (%i1) load(draw)$
          (%i2) draw(
                  delay     = 100,
                  file_name = "zzz",
                  terminal  = 'animated_gif,
                  gr2d(explicit(x^2,x,-1,1)),
                  gr2d(explicit(x^3,x,-1,1)),
                  gr2d(explicit(x^4,x,-1,1)));
          End of animation sequence
          (%o2)          [gr2d(explicit), gr2d(explicit), gr2d(explicit)]

     See also `gr2d', `gr3d', `draw2d' and `draw3d'..


 -- Function: draw2d (<option>, <graphic_object>, ...)
     This function is a short cut for `draw(gr2d(<options>, ...,
     <graphic_object>, ...))'.

     It can be used to plot a unique scene in 2d.

     To make use of this function, write first `load(draw)'.

     See also `draw' and `gr2d'.


 -- Function: draw3d (<option>, <graphic_object>, ...)
     This function is a short cut for `draw(gr3d(<options>, ...,
     <graphic_object>, ...))'.

     It can be used to plot a unique scene in 3d.

     To make use of this function, write first `load(draw)'.

     See also `draw' and `gr3d'.


 -- Function: draw_file (<graphic option>, ..., <graphic object>, ...)
     Saves the current plot into a file. Accepted graphics options are:
     `terminal', `dimensions', `file_name' and `background_color'.

     Example:

          (%i1) load(draw)$
          (%i2) /* screen plot */
                draw(gr3d(explicit(x^2+y^2,x,-1,1,y,-1,1)))$
          (%i3) /* same plot in eps format */
                draw_file(terminal  = eps,
                          dimensions = [5,5]) $


 -- Function: multiplot_mode (<term>)
     This function enables Maxima to work in one-window multiplot mode
     with terminal <term>; accepted arguments for this function are
     `screen', `wxt', `aquaterm' and `none'.

     When multiplot mode is enabled, each call to `draw' sends a new
     plot to the same window, without erasing the previous ones. To
     disable the multiplot mode, write `multiplot_mode(none)'.

     When multiplot mode is enabled, global option `terminal' is
     blocked and you have to disable this working mode before changing
     to another terminal.

     This feature does not work in Windows platforms.

     Example:

          (%i1) load(draw)$
          (%i2) set_draw_defaults(
                   xrange = [-1,1],
                   yrange = [-1,1],
                   grid   = true,
                   title  = "Step by step plot" )$
          (%i3) multiplot_mode(screen)$
          (%i4) draw2d(color=blue,  explicit(x^2,x,-1,1))$
          (%i5) draw2d(color=red,   explicit(x^3,x,-1,1))$
          (%i6) draw2d(color=brown, explicit(x^4,x,-1,1))$
          (%i7) multiplot_mode(none)$


 -- Function: set_draw_defaults (<graphic option>, ..., <graphic
          object>, ...)
     Sets user graphics options. This function is useful for plotting a
     sequence of graphics with common graphics options. Calling this
     function without arguments removes user defaults.

     Example:

          (%i1) load(draw)$
          (%i2) set_draw_defaults(
                   xrange = [-10,10],
                   yrange = [-2, 2],
                   color  = blue,
                   grid   = true)$
          (%i3) /* plot with user defaults */
                draw2d(explicit(((1+x)**2/(1+x*x))-1,x,-10,10))$
          (%i4) set_draw_defaults()$
          (%i5) /* plot with standard defaults */
                draw2d(explicit(((1+x)**2/(1+x*x))-1,x,-10,10))$

     To make use of this function, write first `load(draw)'.


48.2.3 Graphics options
-----------------------

 -- Graphic option: adapt_depth
     Default value: 10

     `adapt_depth' is the maximum number of splittings used by the
     adaptive plotting routine.

     This option is relevant only for 2d `explicit' functions.


 -- Graphic option: allocation
     Default value: `false'

     With option `allocation' it is possible to place a scene in the
     output window at will; this is of interest in multiplots. When
     `false', the scene is placed automatically, depending on the value
     assigned to option `columns'. In any other case, `allocation' must
     be set to a list of two pairs of numbers; the first corresponds to
     the position of the lower left corner of the scene, and the second
     pair gives the width and height of the plot.  All quantities must
     be given in relative coordinates, between 0 and 1.

     Examples:

     In site graphics.

          (%i1) load(draw)$
          (%i2) draw(
                  gr2d(
                    explicit(x^2,x,-1,1)),
                  gr2d(
                    allocation = [[1/4, 1/4],[1/2, 1/2]],
                    explicit(x^3,x,-1,1),
                    grid = true) ) $

     Multiplot with selected dimensions.

          (%i1) load(draw)$
          (%i2) draw(
                  terminal = wxt,
                  gr2d(
                    allocation = [[0, 0],[1, 1/4]],
                    explicit(x^2,x,-1,1)),
                  gr3d(
                    allocation = [[0, 1/4],[1, 3/4]],
                    explicit(x^2+y^2,x,-1,1,y,-1,1) ))$

     See also option `columns'.


 -- Graphic option: axis_3d
     Default value: `true'

     If `axis_3d' is `true', the <x>, <y> and <z> axis are shown in 3d
     scenes.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     Example:

          (%i1) load(draw)$
          (%i2) draw3d(axis_3d = false,
                       explicit(sin(x^2+y^2),x,-2,2,y,-2,2) )$

     See also `axis_bottom',  `axis_left', `axis_top', and `axis_right'
     for axis in 2d.


 -- Graphic option: axis_bottom
     Default value: `true'

     If `axis_bottom' is `true', the bottom axis is shown in 2d scenes.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(axis_bottom = false,
                       explicit(x^3,x,-1,1))$

     See also `axis_left',  `axis_top', `axis_right', and `axis_3d'.


 -- Graphic option: axis_left
     Default value: `true'

     If `axis_left' is `true', the left axis is shown in 2d scenes.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(axis_left = false,
                       explicit(x^3,x,-1,1))$

     See also `axis_bottom',  `axis_top', `axis_right', and `axis_3d'.


 -- Graphic option: axis_right
     Default value: `true'

     If `axis_right' is `true', the right axis is shown in 2d scenes.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(axis_right = false,
                       explicit(x^3,x,-1,1))$

     See also `axis_bottom',  `axis_left', `axis_top', and `axis_3d'.


 -- Graphic option: axis_top
     Default value: `true'

     If `axis_top' is `true', the top axis is shown in 2d scenes.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(axis_top = false,
                       explicit(x^3,x,-1,1))$

     See also `axis_bottom',  `axis_left', `axis_right', and `axis_3d'.


 -- Graphic option: background_color
     Default value: `white'

     Sets the background color for terminals. Default background color
     is white.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     This option das not work with terminals `epslatex' and
     `epslatex_standalone'.

     See also `color'.


 -- Graphic option: border
     Default value: `true'

     If `border' is `true', borders of polygons are painted according
     to `line_type' and `line_width'.

     This option affects the following graphic objects:
        * `gr2d': `polygon', `rectangle', and `ellipse'.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(color       = brown,
                       line_width  = 8,
                       polygon([[3,2],[7,2],[5,5]]),
                       border      = false,
                       fill_color  = blue,
                       polygon([[5,2],[9,2],[7,5]]) )$


 -- Graphic option: cbrange
     Default value: `auto'

     If `cbrange' is `auto', the range for the values which are colored
     when `enhanced3d' is not `false' is computed automatically. Values
     outside of the color range use color of the nearest extreme.

     When `enhanced3d' or `colorbox' is `false', option `cbrange' has
     no effect.

     If the user wants a specific interval for the colored values, it
     must be given as a Maxima list, as in `cbrange=[-2, 3]'.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     Example:

          (%i1) load(draw)$
          (%i2) draw3d (
                  enhanced3d     = true,
                  color          = green,
                  cbrange = [-3,10],
                  explicit(x^2+y^2, x,-2,2,y,-2,2)) $

     See also `enhanced3d', `colorbox' and `cbtics'.


 -- Graphic option: cbtics
     Default value: `auto'

     This graphic option controls the way tic marks are drawn on the
     colorbox when option `enhanced3d' is not `false'.

     When `enhanced3d' or `colorbox' is `false', option `cbtics' has no
     effect.

     See `xtics' for a complete description.

     Example :

          (%i1) load(draw)$
          (%i2) draw3d (
                  enhanced3d = true,
                  color      = green,
                  cbtics  = {["High",10],["Medium",05],["Low",0]},
                  cbrange = [0, 10],
                  explicit(x^2+y^2, x,-2,2,y,-2,2)) $

     See also `enhanced3d', `colorbox' and `cbrange'.


 -- Graphic option: color
     Default value: `blue'

     `color' specifies the color for plotting lines, points, borders of
     polygons and labels.

     Colors can be given as names or in hexadecimal rgb code.

     Available color names are:
     white            black            gray0            grey0
     gray10           grey10           gray20           grey20
     gray30           grey30           gray40           grey40
     gray50           grey50           gray60           grey60
     gray70           grey70           gray80           grey80
     gray90           grey90           gray100          grey100
     gray             grey             light_gray       light_grey
     dark_gray        dark_grey        red              light_red
     dark_red         yellow           light_yellow     dark_yellow
     green            light_green      dark_green       spring_green
     forest_green     sea_green        blue             light_blue
     dark_blue        midnight_blue    navy             medium_blue
     royalblue        skyblue          cyan             light_cyan
     dark_cyan        magenta          light_magenta    dark_magenta
     turquoise        light_turquoise  dark_turquoise   pink
     light_pink       dark_pink        coral            light_coral
     orange_red       salmon           light_salmon     dark_salmon
     aquamarine       khaki            dark_khaki       goldenrod
     light_goldenrod  dark_goldenrod   gold             beige
     brown            orange           dark_orange      violet
     dark_violet      plum             purple

     Cromatic componentes in hexadecimal code are introduced in the
     form `"#rrggbb"'.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(explicit(x^2,x,_1,1), /* default is black */
                       color = red,
                       explicit(0.5 + x^2,x,-1,1),
                       color = blue,
                       explicit(1 + x^2,x,-1,1),
                       color = light_blue,
                       explicit(1.5 + x^2,x,-1,1),
                       color = "#23ab0f",
                       label(["This is a label",0,1.2])  )$

     See also `fill_color'.


 -- Graphic option: colorbox
     Default value: `true'

     If `colorbox' is `true', a color scale without label is drawn
     together with `image' 2D objects, or coloured 3d objects. If
     `colorbox' is `false', no color scale is shown. If `colorbox' is a
     string, a color scale with label is drawn.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     Example:

     Color scale and images.

          (%i1) load(draw)$
          (%i2) im: apply('matrix,
                           makelist(makelist(random(200),i,1,30),i,1,30))$
          (%i3) draw2d(image(im,0,0,30,30))$
          (%i4) draw2d(colorbox = false, image(im,0,0,30,30))$

     Color scale and 3D coloured object.

          (%i1) load(draw)$
          (%i2) draw3d(
                  colorbox   = "Magnitude",
                  enhanced3d = true,
                  explicit(x^2+y^2,x,-1,1,y,-1,1))$

     See also `palette'.


 -- Graphic option: columns
     Default value: 1

     `columns' is the number of columns in multiple plots.

     Since this is a global graphics option, its position in the scene
     description does not matter. It can be also used as an argument of
     function `draw'.

     Example:

          (%i1) load(draw)$
          (%i2) scene1: gr2d(title="Ellipse",
                             nticks=30,
                             parametric(2*cos(t),5*sin(t),t,0,2*%pi))$
          (%i3) scene2: gr2d(title="Triangle",
                             polygon([4,5,7],[6,4,2]))$
          (%i4) draw(scene1, scene2, columns = 2)$


 -- Graphic option: contour
     Default value: `none'

     Option `contour' enables the user to select where to plot contour
     lines.  Possible values are:

        * `none': no contour lines are plotted.

        * `base': contour lines are projected on the xy plane.

        * `surface': contour lines are plotted on the surface.

        * `both': two contour lines are plotted: on the xy plane and on
          the surface.

        * `map': contour lines are projected on the xy plane, and the
          view point is set just in the vertical.


     Since this is a global graphics option, its position in the scene
     description does not matter.

     Example:

          (%i1) load(draw)$
          (%i2) draw3d(explicit(20*exp(-x^2-y^2)-10,x,0,2,y,-3,3),
                       contour_levels = 15,
                       contour        = both,
                       surface_hide   = true) $


 -- Graphic option: contour_levels
     Default value: 5

     This graphic option controls the way contours are drawn.
     `contour_levels' can be set to a positive integer number, a list
     of three numbers or an arbitrary set of numbers:

        * When option `contour_levels' is bounded to positive integer
          <n>, <n> contour lines will be drawn at equal intervals. By
          default, five equally spaced contours are plotted.

        * When option `contour_levels' is bounded to a list of length
          three of the form `[lowest,s,highest]', contour lines are
          plotted from `lowest' to `highest' in steps of `s'.

        * When option `contour_levels' is bounded to a set of numbers
          of the form `{n1, n2, ...}', contour lines are plotted at
          values `n1', `n2', ...

     Since this is a global graphics option, its position in the scene
     description does not matter.

     Examples:

     Ten equally spaced contour lines. The actual number of levels can
     be adjusted to give simple labels.
          (%i1) load(draw)$
          (%i2) draw3d(color = green,
                       explicit(20*exp(-x^2-y^2)-10,x,0,2,y,-3,3),
                       contour_levels = 10,
                       contour        = both,
                       surface_hide   = true) $

     From -8 to 8 in steps of 4.
          (%i1) load(draw)$
          (%i2) draw3d(color = green,
                       explicit(20*exp(-x^2-y^2)-10,x,0,2,y,-3,3),
                       contour_levels = [-8,4,8],
                       contour        = both,
                       surface_hide   = true) $

     Isolines at levels -7, -6, 0.8 and 5.
          (%i1) load(draw)$
          (%i2) draw3d(color = green,
                       explicit(20*exp(-x^2-y^2)-10,x,0,2,y,-3,3),
                       contour_levels = {-7, -6, 0.8, 5},
                       contour        = both,
                       surface_hide   = true) $

     See also `contour'.


 -- Graphic option: data_file_name
     Default value: `"data.gnuplot"'

     This is the name of the file with the numeric data needed by
     Gnuplot to build the requested plot.

     Since this is a global graphics option, its position in the scene
     description does not matter. It can be also used as an argument of
     function `draw'.

     See example in `gnuplot_file_name'.


 -- Graphic option: delay
     Default value: 5

     This is the delay in 1/100 seconds of frames in animated gif files.

     Since this is a global graphics option, its position in the scene
     description does not matter. It can be also used as an argument of
     function `draw'.

     Example:

          (%i1) load(draw)$
          (%i2) draw(
                  delay     = 100,
                  file_name = "zzz",
                  terminal  = 'animated_gif,
                  gr2d(explicit(x^2,x,-1,1)),
                  gr2d(explicit(x^3,x,-1,1)),
                  gr2d(explicit(x^4,x,-1,1)));
          End of animation sequence
          (%o2)          [gr2d(explicit), gr2d(explicit), gr2d(explicit)]

     Option `delay' is only active in animated gif's; it is ignored in
     any other case.

     See also `terminal', `dimensions'.


 -- Graphic option: dimensions
     Default value: `[600,500]'

     Dimensions of the output terminal. Its value is a list formed by
     the width and the height. The meaning of the two numbers depends on
     the terminal you are working with.

     With terminals `gif', `animated_gif', `png', `jpg', `svg',
     `screen', `wxt', and `aquaterm', the integers represent the number
     of points in each direction. If they are not intergers, they are
     rounded.

     With terminals `eps', `eps_color', `pdf', and `pdfcairo', both
     numbers represent hundredths of cm, which means that, by default,
     pictures in these formats are 6 cm in width and 5 cm in height.

     Since this is a global graphics option, its position in the scene
     description does not matter. It can be also used as an argument of
     function `draw'.

     Examples:

     Option `dimensions' applied to file output and to wxt canvas.

          (%i1) load(draw)$
          (%i2) draw2d(
                  dimensions = [300,300],
                  terminal   = 'png,
                  explicit(x^4,x,-1,1)) $
          (%i3) draw2d(
                  dimensions = [300,300],
                  terminal   = 'wxt,
                  explicit(x^4,x,-1,1)) $

     Option `dimensions' applied to eps output.  We want an eps file
     with A4 portrait dimensions.

          (%i1) load(draw)$
          (%i2) A4portrait: 100*[21, 29.7]$
          (%i3) draw3d(
                  dimensions = A4portrait,
                  terminal   = 'eps,
                  explicit(x^2-y^2,x,-2,2,y,-2,2)) $


 -- Graphic option: draw_realpart
     Default value: `true'

     When `true', functions to be drawn are considered as complex
     functions whose real part value should be plotted; when `false',
     nothing will be plotted when the function does not give a real
     value.

     This option affects objects `explicit' and `parametric' in 2D and
     3D, and `parametric_surface'.

     Example:

     Option `draw_realpart' affects objects `explicit' and `parametric'.

          (%i1) load(draw)$
          (%i2) draw2d(
                  draw_realpart = false,
                  explicit(sqrt(x^2  - 4*x) - x, x, -1, 5),
                  color         = red,
                  draw_realpart = true,
                  parametric(x,sqrt(x^2  - 4*x) - x + 1, x, -1, 5) );


 -- Graphic option: enhanced3d
     Default value: `none'

     If `enhanced3d' is `none', surfaces are not colored in 3D plots.
     In order to get a colored surface, a list must be assigned to
     option `enhanced3d', where the first element is an expression and
     the rest are the names of the variables or parameters used in that
     expression. A list such `[f(x,y,z), x, y, z]' means that point
     `[x,y,z]' of the surface is assigned number `f(x,y,z)', which will
     be colored according to the actual `palette'. For those 3D graphic
     objects defined in terms of parameters, it is possible to define
     the color number in terms of the parameters, as in `[f(u), u]', as
     in objects `parametric' and `tube', or `[f(u,v), u, v]', as in
     object `parametric_surface'.  While all 3D objects admit the model
     based on absolute coordinates, `[f(x,y,z), x, y, z]', only two of
     them, namely `explicit' and `elevation_grid', accept also models
     defined on the `[x,y]' coordinates, `[f(x,y), x, y]'. 3D graphic
     object `implicit' accepts only the `[f(x,y,z), x, y, z]' model.
     Object `points' accepts also the `[f(x,y,z), x, y, z]' model, but
     when points have a chronological nature, model `[f(k), k]' is also
     valid, being `k' an ordering parameter.

     When `enhanced3d' is assigned something different to `none',
     options `color' and `surface_hide' are ignored.

     The names of the variables defined in the lists may be different
     to those used in the definitions of the graphic objects.

     In order to maintain back compatibility, `enhanced3d = false' is
     equivalent to `enhanced3d = none', and `enhanced3d = true' is
     equivalent to `enhanced3d = [z, x, y, z]'.  If an expression is
     given to `enhanced3d', its variables must be the same used in the
     surface definition. This is not necessary when using lists.

     See option `palette' to learn how palettes are specified.

     Examples:

     `explicit' object with coloring defined by the `[f(x,y,z), x, y,
     z]' model.

          (%i1) load(draw)$
          (%i2) draw3d(
                   enhanced3d = [x-z/10,x,y,z],
                   palette    = gray,
                   explicit(20*exp(-x^2-y^2)-10,x,-3,3,y,-3,3))$

     `explicit' object with coloring defined by the `[f(x,y), x, y]'
     model.  The names of the variables defined in the lists may be
     different to those used in the definitions of the graphic objects;
     in this case, `r' corresponds to `x', and `s' to `y'.

          (%i1) load(draw)$
          (%i2) draw3d(
                   enhanced3d = [sin(r*s),r,s],
                   explicit(20*exp(-x^2-y^2)-10,x,-3,3,y,-3,3))$

     `parametric' object with coloring defined by the `[f(x,y,z), x, y,
     z]' model.

          (%i1) load(draw)$
          (%i2) draw3d(
                   nticks = 100,
                   line_width = 2,
                   enhanced3d = [if y>= 0 then 1 else 0, x, y, z],
                   parametric(sin(u)^2,cos(u),u,u,0,4*%pi)) $

     `parametric' object with coloring defined by the `[f(u), u]' model.
     In this case, `(u-1)^2' is a shortcut for `[(u-1)^2,u]'.

          (%i1) load(draw)$
          (%i2) draw3d(
                   nticks = 60,
                   line_width = 3,
                   enhanced3d = (u-1)^2,
                   parametric(cos(5*u)^2,sin(7*u),u-2,u,0,2))$

     `elevation_grid' object with coloring defined by the `[f(x,y), x,
     y]' model.

          (%i1) load(draw)$
          (%i2) m: apply(
                     matrix,
                     makelist(makelist(cos(i^2/80-k/30),k,1,30),i,1,20)) $
          (%i3) draw3d(
                   enhanced3d = [cos(x*y*10),x,y],
                   elevation_grid(m,-1,-1,2,2),
                   xlabel = "x",
                   ylabel = "y");

     `tube' object with coloring defined by the `[f(x,y,z), x, y, z]'
     model.

          (%i1) load(draw)$
          (%i2) draw3d(
                   enhanced3d = [cos(x-y),x,y,z],
                   palette = gray,
                   xu_grid = 50,
                   tube(cos(a), a, 0, 1, a, 0, 4*%pi) )$

     `tube' object with coloring defined by the `[f(u), u]' model.
     Here, `enhanced3d = -a' would be the shortcut for `enhanced3d =
     [-foo,foo]'.

          (%i1) load(draw)$
          (%i2) draw3d(
                   tube_extremes = [open, closed],
                   palette = [26,15,-2],
                   enhanced3d = [-foo, foo],
                   tube(a, a, a^2, 1, a, -2, 2) )$

     `implicit' and `points' objects with coloring defined by the
     `[f(x,y,z), x, y, z]' model.

          (%i1) load(draw)$
          (%i2) draw3d(
                   enhanced3d = [x-y,x,y,z],
                   implicit((x^2+y^2+z^2-1)*(x^2+(y-1.5)^2+z^2-0.5)=0.015,
                            x,-1,1,y,-1.2,2.3,z,-1,1)) $
          (%i3) m: makelist([random(1.0),random(1.0),random(1.0)],k,1,2000)$
          (%i4) draw3d(
                   point_type = filled_circle,
                   point_size = 2,
                   enhanced3d = [u+v-w,u,v,w],
                   points(m) ) $

     When points have a chronological nature, model `[f(k), k]' is also
     valid, being `k' an ordering parameter.

          (%i1) load(draw)$
          (%i2) m:makelist([random(1.0), random(1.0), random(1.0)],k,1,5)$
          (%i3) draw3d(
                   enhanced3d = [sin(j), j],
                   point_size = 3,
                   point_type = filled_circle,
                   points_joined = true,
                   points(m)) $


 -- Graphic option: error_type
     Default value: `y'

     Depending on its value, which can be `x', `y', or `xy', graphic
     object `errors' will draw points with horizontal, vertical, or
     both, error bars. When `error_type=boxes', boxes will be drawn
     instead of crosses.

     See also `errors'.

 -- Graphic option: file_name
     Default value: `"maxima_out"'

     This is the name of the file where terminals `png', `jpg', `gif',
     `eps', `eps_color', `pdf', `pdfcairo' and `svg' will save the
     graphic.

     Since this is a global graphics option, its position in the scene
     description does not matter. It can be also used as an argument of
     function `draw'.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(file_name = "myfile",
                       explicit(x^2,x,-1,1),
                       terminal  = 'png)$

     See also `terminal', `dimensions'.


 -- Graphic option: fill_color
     Default value: `"red"'

     `fill_color' specifies the color for filling polygons and 2d
     `explicit' functions.

     See `color' to learn how colors are specified.


 -- Graphic option: fill_density
     Default value: 0

     `fill_density' is a number between 0 and 1 that specifies the
     intensity of the `fill_color' in `bars' objects.

     See `bars' for examples.

 -- Graphic option: filled_func
     Default value: `false'

     Option `filled_func' controls how regions limited by functions
     should be filled. When `filled_func' is `true', the region bounded
     by the function defined with object `explicit' and the bottom of
     the graphic window is filled with `fill_color'. When `filled_func'
     contains a function expression, then the region bounded by this
     function and the function defined with object `explicit' will be
     filled. By default, explicit functions are not filled.

     This option affects only the 2d graphic object `explicit'.

     Example:

     Region bounded by an `explicit' object and the bottom of the
     graphic window.
          (%i1) load(draw)$
          (%i2) draw2d(fill_color  = red,
                       filled_func = true,
                       explicit(sin(x),x,0,10) )$

     Region bounded by an `explicit' object and the function defined by
     option `filled_func'. Note that the variable in `filled_func' must
     be the same as that used in `explicit'.
          (%i1) load(draw)$
          (%i2) draw2d(fill_color  = grey,
                       filled_func = sin(x),
                       explicit(-sin(x),x,0,%pi));

     See also `fill_color' and `explicit'.


 -- Graphic option: font
     Default value: `""' (empty string)

     This option can be used to set the font face to be used by the
     terminal.  Only one font face and size can be used throughout the
     plot.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     See also `font_size'.

     Gnuplot doesn't handle fonts by itself, it leaves this task to the
     support libraries of the different terminals, each one with its own
     philosophy about it. A brief summary follows:

        * x11: Uses the normal x11 font server mechanism.

          Example:
               (%i1) load(draw)$
               (%i2) draw2d(font      = "Arial",
                            font_size = 20,
                            label(["Arial font, size 20",1,1]))$

        * windows: The windows terminal doesn't support changing of
          fonts from inside the plot.  Once the plot has been
          generated, the font can be changed right-clicking on the menu
          of the graph window.

        * png, jpeg, gif: The libgd library uses the font path stored
          in the environment variable `GDFONTPATH'; in this case, it is
          only necessary to set option `font' to the font's name. It is
          also possible to give the complete path to the font file.

          Examples:

          Option `font' can be given the complete path to the font file:
               (%i1) load(draw)$
               (%i2) path: "/usr/share/fonts/truetype/freefont/" $
               (%i3) file: "FreeSerifBoldItalic.ttf" $
               (%i4) draw2d(
                       font      = concat(path, file),
                       font_size = 20,
                       color     = red,
                       label(["FreeSerifBoldItalic font, size 20",1,1]),
                       terminal  = png)$

          If environment variable `GDFONTPATH' is set to the path where
          font files are allocated, it is possible to set graphic
          option `font' to the name of the font.
               (%i1) load(draw)$
               (%i2) draw2d(
                       font      = "FreeSerifBoldItalic",
                       font_size = 20,
                       color     = red,
                       label(["FreeSerifBoldItalic font, size 20",1,1]),
                       terminal  = png)$

        * Postscript: Standard Postscript fonts are:
          `"Times-Roman"', `"Times-Italic"', `"Times-Bold"',
          `"Times-BoldItalic"',
          `"Helvetica"', `"Helvetica-Oblique"', `"Helvetica-Bold"',
          `"Helvetic-BoldOblique"', `"Courier"', `"Courier-Oblique"',
          `"Courier-Bold"',
          and `"Courier-BoldOblique"'.

          Example:
               (%i1) load(draw)$
               (%i2) draw2d(
                       font      = "Courier-Oblique",
                       font_size = 15,
                       label(["Courier-Oblique font, size 15",1,1]),
                       terminal = eps)$

        * pdf: Uses same fonts as Postscript.

        * pdfcairo: Uses same fonts as wxt.

        * wxt: The pango library finds fonts via the `fontconfig'
          utility.

        * aqua: Default is `"Times-Roman"'.

     The gnuplot documentation is an important source of information
     about terminals and fonts.


 -- Graphic option: font_size
     Default value: 10

     This option can be used to set the font size to be used by the
     terminal.  Only one font face and size can be used throughout the
     plot. `font_size' is active only when option `font' is not equal
     to the empty string.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     See also `font'.


 -- Graphic option: gnuplot_file_name
     Default value: `"maxout.gnuplot"'

     This is the name of the file with the necessary commands to be
     processed by Gnuplot.

     Since this is a global graphics option, its position in the scene
     description does not matter. It can be also used as an argument of
     function `draw'.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(
                 file_name = "my_file",
                 gnuplot_file_name = "my_commands_for_gnuplot",
                 data_file_name    = "my_data_for_gnuplot",
                 terminal          = png,
                 explicit(x^2,x,-1,1)) $

     See also `data_file_name'.


 -- Graphic option: grid
     Default value: `false'

     If `grid' is `true', a grid will be drawn on the <xy> plane.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(grid = true,
                       explicit(exp(u),u,-2,2))$


 -- Graphic option: head_angle
     Default value: 45

     `head_angle' indicates the angle, in degrees, between the arrow
     heads and the segment.

     This option is relevant only for `vector' objects.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(xrange      = [0,10],
                       yrange      = [0,9],
                       head_length = 0.7,
                       head_angle  = 10,
                       vector([1,1],[0,6]),
                       head_angle  = 20,
                       vector([2,1],[0,6]),
                       head_angle  = 30,
                       vector([3,1],[0,6]),
                       head_angle  = 40,
                       vector([4,1],[0,6]),
                       head_angle  = 60,
                       vector([5,1],[0,6]),
                       head_angle  = 90,
                       vector([6,1],[0,6]),
                       head_angle  = 120,
                       vector([7,1],[0,6]),
                       head_angle  = 160,
                       vector([8,1],[0,6]),
                       head_angle  = 180,
                       vector([9,1],[0,6]) )$

     See also `head_both', `head_length', and `head_type'.


 -- Graphic option: head_both
     Default value: `false'

     If `head_both' is `true', vectors are plotted with two arrow heads.
     If `false', only one arrow is plotted.

     This option is relevant only for `vector' objects.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(xrange      = [0,8],
                       yrange      = [0,8],
                       head_length = 0.7,
                       vector([1,1],[6,0]),
                       head_both   = true,
                       vector([1,7],[6,0]) )$

     See also `head_length', `head_angle', and `head_type'.


 -- Graphic option: head_length
     Default value: 2

     `head_length' indicates, in <x>-axis units, the length of arrow
     heads.

     This option is relevant only for `vector' objects.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(xrange      = [0,12],
                       yrange      = [0,8],
                       vector([0,1],[5,5]),
                       head_length = 1,
                       vector([2,1],[5,5]),
                       head_length = 0.5,
                       vector([4,1],[5,5]),
                       head_length = 0.25,
                       vector([6,1],[5,5]))$

     See also `head_both', `head_angle', and `head_type'.


 -- Graphic option: head_type
     Default value: `filled'

     `head_type' is used to specify how arrow heads are plotted.
     Possible values are: `filled' (closed and filled arrow heads),
     `empty' (closed but not filled arrow heads), and `nofilled' (open
     arrow heads).

     This option is relevant only for `vector' objects.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(xrange      = [0,12],
                       yrange      = [0,10],
                       head_length = 1,
                       vector([0,1],[5,5]), /* default type */
                       head_type = 'empty,
                       vector([3,1],[5,5]),
                       head_type = 'nofilled,
                       vector([6,1],[5,5]))$

     See also `head_both', `head_angle', and `head_length'.


 -- Graphic option: ip_grid
     Default value: `[50, 50]'

     `ip_grid' sets the grid for the first sampling in implicit plots.

     This option is relevant only for `implicit' objects.


 -- Graphic option: ip_grid_in
     Default value: `[5, 5]'

     `ip_grid_in' sets the grid for the second sampling in implicit
     plots.

     This option is relevant only for `implicit' objects.


 -- Graphic option: key
     Default value: `""' (empty string)

     `key' is the name of a function in the legend. If `key' is an
     empty string, no key is assigned to the function.

     This option affects the following graphic objects:
        * `gr2d': `points', `polygon', `rectangle', `ellipse',
          `vector', `explicit', `implicit', `parametric', and `polar'.

        * `gr3d': `points', `explicit', `parametric', and
          `parametric_surface'.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(key   = "Sinus",
                       explicit(sin(x),x,0,10),
                       key   = "Cosinus",
                       color = red,
                       explicit(cos(x),x,0,10) )$


 -- Graphic option: label_alignment
     Default value: `center'

     `label_alignment' is used to specify where to write labels with
     respect to the given coordinates. Possible values are: `center',
     `left', and `right'.

     This option is relevant only for `label' objects.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(xrange          = [0,10],
                       yrange          = [0,10],
                       points_joined   = true,
                       points([[5,0],[5,10]]),
                       color           = blue,
                       label(["Centered alignment (default)",5,2]),
                       label_alignment = 'left,
                       label(["Left alignment",5,5]),
                       label_alignment = 'right,
                       label(["Right alignment",5,8]))$

     See also `label_orientation', and `color'.


 -- Graphic option: label_orientation
     Default value: `horizontal'

     `label_orientation' is used to specify orientation of labels.
     Possible values are: `horizontal', and `vertical'.

     This option is relevant only for `label' objects.

     Example:

     In this example, a dummy point is added to get an image.  Package
     `draw' needs always data to draw an scene.
          (%i1) load(draw)$
          (%i2) draw2d(xrange     = [0,10],
                       yrange     = [0,10],
                       point_size = 0,
                       points([[5,5]]),
                       color      = navy,
                       label(["Horizontal orientation (default)",5,2]),
                       label_orientation = 'vertical,
                       color             = "#654321",
                       label(["Vertical orientation",1,5]))$

     See also `label_alignment' and `color'.


 -- Graphic option: line_type
     Default value: `solid'

     `line_type' indicates how lines are displayed; possible values are
     `solid' and `dots'.

     This option affects the following graphic objects:
        * `gr2d': `points', `polygon', `rectangle', `ellipse',
          `vector', `explicit', `implicit', `parametric' and `polar'.

        * `gr3d': `points', `explicit', `parametric' and
          `parametric_surface'.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(line_type = dots,
                       explicit(1 + x^2,x,-1,1),
                       line_type = solid, /* default */
                       explicit(2 + x^2,x,-1,1))$

     See also `line_width'.


 -- Graphic option: line_width
     Default value: 1

     `line_width' is the width of plotted lines.  Its value must be a
     positive number.

     This option affects the following graphic objects:
        * `gr2d': `points', `polygon', `rectangle', `ellipse',
          `vector', `explicit', `implicit', `parametric' and `polar'.

        * `gr3d': `points' and `parametric'.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(explicit(x^2,x,-1,1), /* default width */
                       line_width = 5.5,
                       explicit(1 + x^2,x,-1,1),
                       line_width = 10,
                       explicit(2 + x^2,x,-1,1))$

     See also `line_type'.


 -- Graphic option: logcb
     Default value: `false'

     If `logcb' is `true', the tics in the colorbox will be drawn in the
     logarithmic scale.

     When `enhanced3d' or `colorbox' is `false', option `logcb' has no
     effect.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     Example:

          (%i1) load(draw)$
          (%i2) draw3d (
                  enhanced3d = true,
                  color      = green,
                  logcb = true,
                  logz  = true,
                  palette = [-15,24,-9],
                  explicit(exp(x^2-y^2), x,-2,2,y,-2,2)) $

     See also `enhanced3d', `colorbox' and `cbrange'.


 -- Graphic option: logx
     Default value: `false'

     If `logx' is `true', the <x> axis will be drawn in the logarithmic
     scale.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(explicit(log(x),x,0.01,5),
                       logx = true)$

     See also `logy' and `logz'.


 -- Graphic option: logy
     Default value: `false'

     If `logy' is `true', the <y> axis will be drawn in the logarithmic
     scale.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(logy = true,
                       explicit(exp(x),x,0,5))$

     See also `logx' and `logz'.


 -- Graphic option: logz
     Default value: `false'

     If `logz' is `true', the <z> axis will be drawn in the logarithmic
     scale.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     Example:

          (%i1) load(draw)$
          (%i2) draw3d(logz = true,
                       explicit(exp(u^2+v^2),u,-2,2,v,-2,2))$

     See also `logx' and `logy'.


 -- Graphic option: nticks
     Default value: 29

     In 2d, `nticks' gives the initial number of points used by the
     adaptive plotting routine for explicit objects. It is also the
     number of points that will be shown in parametric and polar curves.

     This option affects the following graphic objects:
        * `gr2d': `ellipse', `explicit', `parametric' and `polar'.

        * `gr3d': `parametric'.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(transparent = true,
                       ellipse(0,0,4,2,0,180),
                       nticks = 5,
                       ellipse(0,0,4,2,180,180) )$


 -- Graphic option: palette
     Default value: `color'

     `palette' indicates how to map gray levels onto color components.
     It works together with option `enhanced3d' in 3D graphics, who
     associates every point of a surfaces to a real number or gray
     level.  It also works with gray images. With `palette', levels are
     transformed into colors.

     There are two ways for defining these transformations.

     First, `palette' can be a vector of length three with components
     ranging from -36 to +36; each value is an index for a formula
     mapping the levels onto red, green and blue colors, respectively:
           0: 0               1: 0.5           2: 1
           3: x               4: x^2           5: x^3
           6: x^4             7: sqrt(x)       8: sqrt(sqrt(x))
           9: sin(90x)       10: cos(90x)     11: |x-0.5|
          12: (2x-1)^2       13: sin(180x)    14: |cos(180x)|
          15: sin(360x)      16: cos(360x)    17: |sin(360x)|
          18: |cos(360x)|    19: |sin(720x)|  20: |cos(720x)|
          21: 3x             22: 3x-1         23: 3x-2
          24: |3x-1|         25: |3x-2|       26: (3x-1)/2
          27: (3x-2)/2       28: |(3x-1)/2|   29: |(3x-2)/2|
          30: x/0.32-0.78125 31: 2*x-0.84     32: 4x;1;-2x+1.84;x/0.08-11.5
          33: |2*x - 0.5|    34: 2*x          35: 2*x - 0.5
          36: 2*x - 1
     negative numbers mean negative colour component.  `palette = gray'
     and `palette = color' are short cuts for `palette = [3,3,3]' and
     `palette = [7,5,15]', respectively.

     Second, `palette' can be a user defined lookup table. In this case,
     the format for building a lookup table of length `n' is
     `palette=[color_1, color_2, ..., color_n]', where `color_i' is a
     well formed color (see option `color'), such that `color_1' is
     assigned to the lowest gray level and `color_n' to the highest.
     The rest of colors are interpolated.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     Examples:

     It works together with option `enhanced3d' in 3D graphics.

          (%i1) load(draw)$
          (%i2) draw3d(
                  enhanced3d = [z-x+2*y,x,y,z],
                  palette = [32, -8, 17],
                  explicit(20*exp(-x^2-y^2)-10,x,-3,3,y,-3,3))$

     It also works with gray images.

          (%i1) load(draw)$
          (%i2) im: apply(
                     'matrix,
                      makelist(makelist(random(200),i,1,30),i,1,30))$
          (%i3) /* palette = color, default */
                draw2d(image(im,0,0,30,30))$
          (%i4) draw2d(palette = gray, image(im,0,0,30,30))$
          (%i5) draw2d(palette = [15,20,-4],
                       colorbox=false,
                       image(im,0,0,30,30))$

     `palette' can be a user defined lookup table.  In this example,
     low values of `x' are colored in red, and higher values in yellow.

          (%i1) load(draw)$
          (%i2) draw3d(
                   palette = [red, blue, yellow],
                   enhanced3d = x,
                   explicit(x^2+y^2,x,-1,1,y,-1,1)) $

     See also `colorbox' and `enhanced3d'.


 -- Graphic option: point_size
     Default value: 1

     `point_size' sets the size for plotted points. It must be a non
     negative number.

     This option has no effect when graphic option `point_type' is set
     to `dot'.

     This option affects the following graphic objects:
        * `gr2d': `points'.

        * `gr3d': `points'.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(points(makelist([random(20),random(50)],k,1,10)),
                  point_size = 5,
                  points(makelist(k,k,1,20),makelist(random(30),k,1,20)))$


 -- Graphic option: point_type
     Default value: 1

     `point_type' indicates how isolated points are displayed; the
     value of this option can be any integer index greater or equal
     than -1, or the name of a point style: `$none' (-1), `dot' (0),
     `plus' (1), `multiply' (2), `asterisk' (3), `square' (4),
     `filled_square' (5), `circle' (6), `filled_circle' (7),
     `up_triangle' (8), `filled_up_triangle' (9), `down_triangle' (10),
     `filled_down_triangle' (11), `diamant' (12) and `filled_diamant'
     (13).

     This option affects the following graphic objects:
        * `gr2d': `points'.

        * `gr3d': `points'.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(xrange = [0,10],
                       yrange = [0,10],
                       point_size = 3,
                       point_type = diamant,
                       points([[1,1],[5,1],[9,1]]),
                       point_type = filled_down_triangle,
                       points([[1,2],[5,2],[9,2]]),
                       point_type = asterisk,
                       points([[1,3],[5,3],[9,3]]),
                       point_type = filled_diamant,
                       points([[1,4],[5,4],[9,4]]),
                       point_type = 5,
                       points([[1,5],[5,5],[9,5]]),
                       point_type = 6,
                       points([[1,6],[5,6],[9,6]]),
                       point_type = filled_circle,
                       points([[1,7],[5,7],[9,7]]),
                       point_type = 8,
                       points([[1,8],[5,8],[9,8]]),
                       point_type = filled_diamant,
                       points([[1,9],[5,9],[9,9]]) )$


 -- Graphic option: points_joined
     Default value: `false'

     When `points_joined' is `true', points are joined by lines; when
     `false', isolated points are drawn. A third possible value for
     this graphic option is `impulses'; in such case, vertical segments
     are drawn from points to the x-axis (2D) or to the xy-plane (3D).

     This option affects the following graphic objects:
        * `gr2d': `points'.

        * `gr3d': `points'.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(xrange        = [0,10],
                       yrange        = [0,4],
                       point_size    = 3,
                       point_type    = up_triangle,
                       color         = blue,
                       points([[1,1],[5,1],[9,1]]),
                       points_joined = true,
                       point_type    = square,
                       line_type     = dots,
                       points([[1,2],[5,2],[9,2]]),
                       point_type    = circle,
                       color         = red,
                       line_width    = 7,
                       points([[1,3],[5,3],[9,3]]) )$


 -- Graphic option: proportional_axes
     Default value: `none'

     When `proportional_axes' is equal to `xy' or `xyz', a 2D or 3D
     scene will be drawn with axes proportional to their relative
     lengths.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     This option works with Gnuplot version 4.2.6 or greater.

     Examples:

     Single 2D plot.

          (%i1) load(draw)$
          (%i2) draw2d(
                  ellipse(0,0,1,1,0,360),
                  transparent=true,
                  color = blue,
                  line_width = 4,
                  ellipse(0,0,2,1/2,0,360),
                  proportional_axes = xy) $

     Multiplot.

          (%i1) load(draw)$
          (%i2) draw(
                  terminal = wxt,
                  gr2d(proportional_axes = xy,
                       explicit(x^2,x,0,1)),
                  gr2d(explicit(x^2,x,0,1),
                       xrange = [0,1],
                       yrange = [0,2],
                       proportional_axes=xy),
                  gr2d(explicit(x^2,x,0,1))


 -- Graphic option: surface_hide
     Default value: `false'

     If `surface_hide' is `true', hidden parts are not plotted in 3d
     surfaces.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     Example:

          (%i1) load(draw)$
          (%i2) draw(columns=2,
                     gr3d(explicit(exp(sin(x)+cos(x^2)),x,-3,3,y,-3,3)),
                     gr3d(surface_hide = true,
                          explicit(exp(sin(x)+cos(x^2)),x,-3,3,y,-3,3)) )$


 -- Graphic option: terminal
     Default value: `screen'

     Selects the terminal to be used by Gnuplot; possible values are:
     `screen' (default), `png', `pngcairo', `jpg', `gif', `eps',
     `eps_color', `epslatex', `epslatex_standalone', `svg', `dumb',
     `dumb_file', `pdf', `pdfcairo', `wxt', `animated_gif',
     `multipage_pdfcairo', `multipage_pdf', `multipage_eps',
     `multipage_eps_color', and `aquaterm'.

     Terminals `screen', `wxt' and `aquaterm' can be also defined as a
     list with two elements: the name of the terminal itself and a non
     negative integer number.  In this form, multiple windows can be
     opened at the same time, each with its corresponding number. This
     feature does not work in Windows platforms.

     Since this is a global graphics option, its position in the scene
     description does not matter. It can be also used as an argument of
     function `draw'.

     N.B. pdfcairo requires Gnuplot 4.3 or newer.  `pdf' requires
     Gnuplot to be compiled with the option `--enable-pdf' and libpdf
     must be installed. The pdf library is available from:
     `http://www.pdflib.com/en/download/pdflib-family/pdflib-lite/'

     Examples:

          (%i1) load(draw)$
          (%i2) /* screen terminal (default) */
                draw2d(explicit(x^2,x,-1,1))$
          (%i3) /* png file */
                draw2d(terminal  = 'png,
                       explicit(x^2,x,-1,1))$
          (%i4) /* jpg file */
                draw2d(terminal   = 'jpg,
                       dimensions = [300,300],
                       explicit(x^2,x,-1,1))$
          (%i5) /* eps file */
                draw2d(file_name = "myfile",
                       explicit(x^2,x,-1,1),
                       terminal  = 'eps)$
          (%i6) /* pdf file */
                draw2d(file_name = "mypdf",
                       dimensions = 100*[12.0,8.0],
                       explicit(x^2,x,-1,1),
                       terminal  = 'pdf)$
          (%i7) /* wxwidgets window */
                draw2d(explicit(x^2,x,-1,1),
                       terminal  = 'wxt)$

     Multiple windows.
          (%i1) load(draw)$
          (%i2) draw2d(explicit(x^5,x,-2,2), terminal=[screen, 3])$
          (%i3) draw2d(explicit(x^2,x,-2,2), terminal=[screen, 0])$

     An animated gif file.
          (%i1) load(draw)$
          (%i2) draw(
                  delay     = 100,
                  file_name = "zzz",
                  terminal  = 'animated_gif,
                  gr2d(explicit(x^2,x,-1,1)),
                  gr2d(explicit(x^3,x,-1,1)),
                  gr2d(explicit(x^4,x,-1,1)));
          End of animation sequence
          (%o2)          [gr2d(explicit), gr2d(explicit), gr2d(explicit)]

     Option `delay' is only active in animated gif's; it is ignored in
     any other case.

     Multipage output in eps format.
          (%i1) load(draw)$
          (%i2) draw(
                  file_name = "parabol",
                  terminal  = multipage_eps,
                  dimensions = 100*[10,10],
                  gr2d(explicit(x^2,x,-1,1)),
                  gr3d(explicit(x^2+y^2,x,-1,1,y,-1,1))) $

     See also `file_name', `dimensions' and `delay'.


 -- Graphic option: title
     Default value: `""' (empty string)

     Option `title', a string, is the main title for the scene.  By
     default, no title is written.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(explicit(exp(u),u,-2,2),
                       title = "Exponential function")$


 -- Graphic option: transform
     Default value: `none'

     If `transform' is `none', the space is not transformed and graphic
     objects are drawn as defined. When a space transformation is
     desired, a list must be assigned to option `transform'. In case of
     a 2D scene, the list takes the form `[f1(x,y), f2(x,y), x, y]'.
     In case of a 3D scene, the list is of the form `[f1(x,y,z),
     f2(x,y,z), f3(x,y,z), x, y, z]'.

     The names of the variables defined in the lists may be different
     to those used in the definitions of the graphic objects.

     Examples:

     Rotation in 2D.

          (%i1) load(draw)$
          (%i2) th : %pi / 4$
          (%i3) draw2d(
                  color = "#e245f0",
                  proportional_axes = 'xy,
                  line_width = 8,
                  triangle([3,2],[7,2],[5,5]),
                  border     = false,
                  fill_color = yellow,
                  transform  = [cos(th)*x - sin(th)*y,
                                sin(th)*x + cos(th)*y, x, y],
                  triangle([3,2],[7,2],[5,5]) )$

     Translation in 3D.

          (%i1) load(draw)$
          (%i2) draw3d(
                  color     = "#a02c00",
                  explicit(20*exp(-x^2-y^2)-10,x,-3,3,y,-3,3),
                  transform = [x+10,y+10,z+10,x,y,z],
                  color     = blue,
                  explicit(20*exp(-x^2-y^2)-10,x,-3,3,y,-3,3) )$


 -- Graphic option: transparent
     Default value: `false'

     If `transparent' is `true', interior regions of polygons are
     filled according to `fill_color'.

     This option affects the following graphic objects:
        * `gr2d': `polygon', `rectangle', and `ellipse'.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(polygon([[3,2],[7,2],[5,5]]),
                       transparent = true,
                       color       = blue,
                       polygon([[5,2],[9,2],[7,5]]) )$


 -- Graphic option: tube_extremes
     Default value: `[open, open]'

     A list with two possible elements, `open' and `closed', indicating
     whether the extremes of a graphic object `tube' remain open or
     must be closed. By default, both extremes are left open.

     Example:

          (%i1) load(draw)$
          (%i2) draw3d(
                  tube_extremes = [open, closed],
                  tube(0, 0, a, 1,
                       a, 0, 8) )$


 -- Graphic option: unit_vectors
     Default value: `false'

     If `unit_vectors' is `true', vectors are plotted with module 1.
     This is useful for plotting vector fields. If `unit_vectors' is
     `false', vectors are plotted with its original length.

     This option is relevant only for `vector' objects.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(xrange      = [-1,6],
                       yrange      = [-1,6],
                       head_length = 0.1,
                       vector([0,0],[5,2]),
                       unit_vectors = true,
                       color        = red,
                       vector([0,3],[5,2]))$


 -- Graphic option: user_preamble
     Default value: `""' (empty string)

     Expert Gnuplot users can make use of this option to fine tune
     Gnuplot's behaviour by writing settings to be sent before the
     `plot' or `splot' command.

     The value of this option must be a string or a list of strings
     (one per line).

     Since this is a global graphics option, its position in the scene
     description does not matter.

     Example:

     The dumb terminal is not supported by package `draw', but it is
     possible to set it by making use of option `user_preamble',
          (%i1) load(draw)$
          (%i2) draw2d(explicit(exp(x)-1,x,-1,1),
                       parametric(cos(u),sin(u),u,0,2*%pi),
                       user_preamble="set terminal dumb")$


 -- Graphic option: view
     Default value: `[60,30]'

     A pair of angles, measured in degrees, indicating the view
     direction in a 3D scene. The first angle is the vertical rotation
     around the <x> axis, in the range [0, 360]. The second one is the
     horizontal rotation around the <z> axis, in the range [0, 360].

     Since this is a global graphics option, its position in the scene
     description does not matter.

     Example:

          (%i1) load(draw)$
          (%i2) draw3d(view = [170, 360],
                       explicit(sin(x^2+y^2),x,-2,2,y,-2,2) )$


 -- Graphic option: wired_surface
     Default value: `false'

     Indicates whether 3D surfaces in `enhanced3d' mode show the grid
     joinning the points or not.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     Example:

          (%i1) load(draw)$
          (%i2) draw3d(
                  enhanced3d    = [sin(x),x,y],
                  wired_surface = true,
                  explicit(x^2+y^2,x,-1,1,y,-1,1)) $


 -- Graphic option: x_voxel
     Default value: 10

     `x_voxel' is the number of voxels in the x direction to be used by
     the marching cubes algorithm implemented by the 3d `implicit'
     object. It is also used by graphic object `region'.


 -- Graphic option: xaxis
     Default value: `false'

     If `xaxis' is `true', the <x> axis is drawn.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(explicit(x^3,x,-1,1),
                       xaxis       = true,
                       xaxis_color = blue)$

     See also `xaxis_width', `xaxis_type' and `xaxis_color'.


 -- Graphic option: xaxis_color
     Default value: `"black"'

     `xaxis_color' specifies the color for the <x> axis. See `color' to
     know how colors are defined.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(explicit(x^3,x,-1,1),
                       xaxis       = true,
                       xaxis_color = red)$

     See also `xaxis', `xaxis_width' and `xaxis_type'.


 -- Graphic option: xaxis_secondary
     Default value: `false'

     If `xaxis_secondary' is `true', function values can be plotted with
     respect to the second <x> axis, which will be drawn on top of the
     scene.

     Note that this is a local graphics option which only affects to 2d
     plots.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(
                   key   = "Bottom x-axis",
                   explicit(x+1,x,1,2),
                   color = red,
                   key   = "Above x-axis",
                   xtics_secondary = true,
                   xaxis_secondary = true,
                   explicit(x^2,x,-1,1)) $

     See also `xrange_secondary', `xtics_secondary',
     `xtics_rotate_secondary', `xtics_axis_secondary' and
     `xaxis_secondary'.


 -- Graphic option: xaxis_type
     Default value: `dots'

     `xaxis_type' indicates how the <x> axis is displayed; possible
     values are `solid' and `dots'.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(explicit(x^3,x,-1,1),
                       xaxis       = true,
                       xaxis_type  = solid)$

     See also `xaxis', `xaxis_width' and `xaxis_color'.


 -- Graphic option: xaxis_width
     Default value: 1

     `xaxis_width' is the width of the <x> axis.  Its value must be a
     positive number.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(explicit(x^3,x,-1,1),
                       xaxis       = true,
                       xaxis_width = 3)$

     See also `xaxis', `xaxis_type' and `xaxis_color'.


 -- Graphic option: xlabel
     Default value: `""' (empty string)

     Option `xlabel', a string, is the label for the <x> axis.  By
     default, no label is written.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(xlabel = "Time",
                       explicit(exp(u),u,-2,2),
                       ylabel = "Population")$

     See also `ylabel', and `zlabel'.


 -- Graphic option: xrange
     Default value: `auto'

     If `xrange' is `auto', the range for the <x> coordinate is
     computed automatically.

     If the user wants a specific interval for <x>, it must be given as
     a Maxima list, as in `xrange=[-2, 3]'.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(xrange = [-3,5],
                       explicit(x^2,x,-1,1))$

     See also `yrange' and `zrange'.


 -- Graphic option: xrange_secondary
     Default value: `auto'

     If `xrange_secondary' is `auto', the range for the second <x> axis
     is computed automatically.

     If the user wants a specific interval for the second <x> axis, it
     must be given as a Maxima list, as in `xrange_secondary=[-2, 3]'.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     See also `xrange', `yrange', `zrange' and `yrange_secondary'.


 -- Graphic option: xtics
     Default value: `auto'

     This graphic option controls the way tic marks are drawn on the
     <x> axis.

        * When option `xtics' is bounded to symbol <auto>, tic marks are
          drawn automatically.

        * When option `xtics' is bounded to symbol <none>, tic marks are
          not drawn.

        * When option `xtics' is bounded to a positive number, this is
          the distance between two consecutive tic marks.

        * When option `xtics' is bounded to a list of length three of
          the form `[start,incr,end]', tic marks are plotted from
          `start' to `end' at intervals of length `incr'.

        * When option `xtics' is bounded to a set of numbers of the
          form `{n1, n2, ...}', tic marks are plotted at values `n1',
          `n2', ...

        * When option `xtics' is bounded to a set of pairs of the form
          `{["label1", n1], ["label2", n2], ...}', tic marks
          corresponding to values `n1', `n2', ... are labeled with
          `"label1"', `"label2"', ..., respectively.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     Examples:

     Disable tics.
          (%i1) load(draw)$
          (%i2) draw2d(xtics = 'none,
                       explicit(x^3,x,-1,1)  )$

     Tics every 1/4 units.
          (%i1) load(draw)$
          (%i2) draw2d(xtics = 1/4,
                       explicit(x^3,x,-1,1)  )$

     Tics from -3/4 to 3/4 in steps of 1/8.
          (%i1) load(draw)$
          (%i2) draw2d(xtics = [-3/4,1/8,3/4],
                       explicit(x^3,x,-1,1)  )$

     Tics at points -1/2, -1/4 and 3/4.
          (%i1) load(draw)$
          (%i2) draw2d(xtics = {-1/2,-1/4,3/4},
                       explicit(x^3,x,-1,1)  )$

     Labeled tics.
          (%i1) load(draw)$
          (%i2) draw2d(xtics = {["High",0.75],["Medium",0],["Low",-0.75]},
                       explicit(x^3,x,-1,1)  )$

     See also `ytics', and `ztics'.


 -- Graphic option: xtics_axis
     Default value: `false'

     If `xtics_axis' is `true', tic marks and their labels are plotted
     just along the <x> axis, if it is `false' tics are plotted on the
     border.

     Since this is a global graphics option, its position in the scene
     description does not matter.


 -- Graphic option: xtics_rotate
     Default value: `false'

     If `xtics_rotate' is `true', tic marks on the <x> axis are rotated
     90 degrees.

     Since this is a global graphics option, its position in the scene
     description does not matter.


 -- Graphic option: xtics_rotate_secondary
     Default value: `false'

     If `xtics_rotate_secondary' is `true', tic marks on the secondary
     <x> axis are rotated 90 degrees.

     Since this is a global graphics option, its position in the scene
     description does not matter.


 -- Graphic option: xtics_secondary
     Default value: `auto'

     This graphic option controls the way tic marks are drawn on the
     second <x> axis.

     See `xtics' for a complete description.


 -- Graphic option: xtics_secondary_axis
     Default value: `false'

     If `xtics_secondary_axis' is `true', tic marks and their labels
     are plotted just along the secondary <x> axis, if it is `false'
     tics are plotted on the border.

     Since this is a global graphics option, its position in the scene
     description does not matter.


 -- Graphic option: xu_grid
     Default value: 30

     `xu_grid' is the number of coordinates of the first variable (`x'
     in explicit and `u' in parametric 3d surfaces) to build the grid
     of sample points.

     This option affects the following graphic objects:
        * `gr3d': `explicit' and `parametric_surface'.

     Example:

          (%i1) load(draw)$
          (%i2) draw3d(xu_grid = 10,
                       yv_grid = 50,
                       explicit(x^2+y^2,x,-3,3,y,-3,3) )$

     See also `yv_grid'.


 -- Graphic option: xy_file
     Default value: `""' (empty string)

     `xy_file' is the name of the file where the coordinates will be
     saved after clicking with the mouse button and hitting the 'x'
     key. By default, no coordinates are saved.

     Since this is a global graphics option, its position in the scene
     description does not matter.


 -- Graphic option: xyplane
     Default value: `false'

     Allocates the xy-plane in 3D scenes. When `xyplane' is `false',
     the xy-plane is placed automatically; when it is a real number,
     the xy-plane intersects the z-axis at this level.  This option has
     no effect in 2D scenes.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     Example:

          (%i1) load(draw)$
          (%i2) draw3d(xyplane = %e-2,
                       explicit(x^2+y^2,x,-1,1,y,-1,1))$


 -- Graphic option: y_voxel
     Default value: 10

     `y_voxel' is the number of voxels in the y direction to be used by
     the marching cubes algorithm implemented by the 3d `implicit'
     object. It is also used by graphic object `region'.


 -- Graphic option: yaxis
     Default value: `false'

     If `yaxis' is `true', the <y> axis is drawn.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(explicit(x^3,x,-1,1),
                       yaxis       = true,
                       yaxis_color = blue)$

     See also `yaxis_width', `yaxis_type' and `yaxis_color'.


 -- Graphic option: yaxis_color
     Default value: `"black"'

     `yaxis_color' specifies the color for the <y> axis. See `color' to
     know how colors are defined.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(explicit(x^3,x,-1,1),
                       yaxis       = true,
                       yaxis_color = red)$

     See also `yaxis', `yaxis_width' and `yaxis_type'.


 -- Graphic option: yaxis_secondary
     Default value: `false'

     If `yaxis_secondary' is `true', function values can be plotted with
     respect to the second <y> axis, which will be drawn on the right
     side of the scene.

     Note that this is a local graphics option which only affects to 2d
     plots.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(
                   explicit(sin(x),x,0,10),
                   yaxis_secondary = true,
                   ytics_secondary = true,
                   color = blue,
                   explicit(100*sin(x+0.1)+2,x,0,10));

     See also `yrange_secondary', `ytics_secondary',
     `ytics_rotate_secondary' and `ytics_axis_secondary'.


 -- Graphic option: yaxis_type
     Default value: `dots'

     `yaxis_type' indicates how the <y> axis is displayed; possible
     values are `solid' and `dots'.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(explicit(x^3,x,-1,1),
                       yaxis       = true,
                       yaxis_type  = solid)$

     See also `yaxis', `yaxis_width' and `yaxis_color'.


 -- Graphic option: yaxis_width
     Default value: 1

     `yaxis_width' is the width of the <y> axis.  Its value must be a
     positive number.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(explicit(x^3,x,-1,1),
                       yaxis       = true,
                       yaxis_width = 3)$

     See also `yaxis', `yaxis_type' and `yaxis_color'.


 -- Graphic option: ylabel
     Default value: `""' (empty string)

     Option `ylabel', a string, is the label for the <y> axis.  By
     default, no label is written.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(xlabel = "Time",
                       ylabel = "Population",
                       explicit(exp(u),u,-2,2) )$

     See also `xlabel', and `zlabel'.


 -- Graphic option: yrange
     Default value: `auto'

     If `yrange' is `auto', the range for the <y> coordinate is
     computed automatically.

     If the user wants a specific interval for <y>, it must be given as
     a Maxima list, as in `yrange=[-2, 3]'.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(yrange = [-2,3],
                       explicit(x^2,x,-1,1),
                       xrange = [-3,3])$

     See also `xrange', `yrange_secondary' and `zrange'.


 -- Graphic option: yrange_secondary
     Default value: `auto'

     If `yrange_secondary' is `auto', the range for the second <y> axis
     is computed automatically.

     If the user wants a specific interval for the second <y> axis, it
     must be given as a Maxima list, as in `yrange_secondary=[-2, 3]'.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(
                   explicit(sin(x),x,0,10),
                   yaxis_secondary = true,
                   ytics_secondary = true,
                   yrange = [-3, 3],
                   yrange_secondary = [-20, 20],
                   color = blue,
                   explicit(100*sin(x+0.1)+2,x,0,10)) $

     See also `xrange', `yrange' and `zrange'.


 -- Graphic option: ytics
     Default value: `auto'

     This graphic option controls the way tic marks are drawn on the
     <y> axis.

     See `xtics' for a complete description.


 -- Graphic option: ytics_axis
     Default value: `false'

     If `ytics_axis' is `true', tic marks and their labels are plotted
     just along the <y> axis, if it is `false' tics are plotted on the
     border.

     Since this is a global graphics option, its position in the scene
     description does not matter.


 -- Graphic option: ytics_rotate
     Default value: `false'

     If `ytics_rotate' is `true', tic marks on the <y> axis are rotated
     90 degrees.

     Since this is a global graphics option, its position in the scene
     description does not matter.


 -- Graphic option: ytics_rotate_secondary
     Default value: `false'

     If `ytics_rotate_secondary' is `true', tic marks on the secondary
     <y> axis are rotated 90 degrees.

     Since this is a global graphics option, its position in the scene
     description does not matter.


 -- Graphic option: ytics_secondary
     Default value: `auto'

     This graphic option controls the way tic marks are drawn on the
     second <y> axis.

     See `xtics' for a complete description.


 -- Graphic option: ytics_secondary_axis
     Default value: `false'

     If `ytics_secondary_axis' is `true', tic marks and their labels
     are plotted just along the secondary <y> axis, if it is `false'
     tics are plotted on the border.

     Since this is a global graphics option, its position in the scene
     description does not matter.


 -- Graphic option: yv_grid
     Default value: 30

     `yv_grid' is the number of coordinates of the second variable (`y'
     in explicit and `v' in parametric 3d surfaces) to build the grid
     of sample points.

     This option affects the following graphic objects:
        * `gr3d': `explicit' and `parametric_surface'.

     Example:

          (%i1) load(draw)$
          (%i2) draw3d(xu_grid = 10,
                       yv_grid = 50,
                       explicit(x^2+y^2,x,-3,3,y,-3,3) )$

     See also `xu_grid'.


 -- Graphic option: z_voxel
     Default value: 10

     `z_voxel' is the number of voxels in the z direction to be used by
     the marching cubes algorithm implemented by the 3d `implicit'
     object.


 -- Graphic option: zaxis
     Default value: `false'

     If `zaxis' is `true', the <z> axis is drawn in 3D plots.  This
     option has no effect in 2D scenes.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     Example:

          (%i1) load(draw)$
          (%i2) draw3d(explicit(x^2+y^2,x,-1,1,y,-1,1),
                       zaxis       = true,
                       zaxis_type  = solid,
                       zaxis_color = blue)$

     See also `zaxis_width', `zaxis_type' and `zaxis_color'.


 -- Graphic option: zaxis_color
     Default value: `"black"'

     `zaxis_color' specifies the color for the <z> axis. See `color' to
     know how colors are defined.  This option has no effect in 2D
     scenes.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     Example:

          (%i1) load(draw)$
          (%i2) draw3d(explicit(x^2+y^2,x,-1,1,y,-1,1),
                       zaxis       = true,
                       zaxis_type  = solid,
                       zaxis_color = red)$

     See also `zaxis', `zaxis_width' and `zaxis_type'.


 -- Graphic option: zaxis_type
     Default value: `dots'

     `zaxis_type' indicates how the <z> axis is displayed; possible
     values are `solid' and `dots'.  This option has no effect in 2D
     scenes.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     Example:

          (%i1) load(draw)$
          (%i2) draw3d(explicit(x^2+y^2,x,-1,1,y,-1,1),
                       zaxis       = true,
                       zaxis_type  = solid)$

     See also `zaxis', `zaxis_width' and `zaxis_color'.


 -- Graphic option: zaxis_width
     Default value: 1

     `zaxis_width' is the width of the <z> axis.  Its value must be a
     positive number. This option has no effect in 2D scenes.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     Example:

          (%i1) load(draw)$
          (%i2) draw3d(explicit(x^2+y^2,x,-1,1,y,-1,1),
                       zaxis       = true,
                       zaxis_type  = solid,
                       zaxis_width = 3)$

     See also `zaxis', `zaxis_type' and `zaxis_color'.


 -- Graphic option: zlabel
     Default value: `""' (empty string)

     Option `zlabel', a string, is the label for the <z> axis.  By
     default, no label is written.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     Example:

          (%i1) load(draw)$
          (%i2) draw3d(zlabel = "Z variable",
                       ylabel = "Y variable",
                       explicit(sin(x^2+y^2),x,-2,2,y,-2,2),
                       xlabel = "X variable" )$

     See also `xlabel', and `ylabel'.


 -- Graphic option: zrange
     Default value: `auto'

     If `zrange' is `auto', the range for the <z> coordinate is
     computed automatically.

     If the user wants a specific interval for <z>, it must be given as
     a Maxima list, as in `zrange=[-2, 3]'.

     Since this is a global graphics option, its position in the scene
     description does not matter.

     Example:

          (%i1) load(draw)$
          (%i2) draw3d(yrange = [-3,3],
                       zrange = [-2,5],
                       explicit(x^2+y^2,x,-1,1,y,-1,1),
                       xrange = [-3,3])$

     See also `xrange' and `yrange'.


 -- Graphic option: ztics
     Default value: `auto'

     This graphic option controls the way tic marks are drawn on the
     <z> axis.

     See `xtics' for a complete description.


 -- Graphic option: ztics_axis
     Default value: `false'

     If `ztics_axis' is `true', tic marks and their labels are plotted
     just along the <z> axis, if it is `false' tics are plotted on the
     border.

     Since this is a global graphics option, its position in the scene
     description does not matter.


 -- Graphic option: ztics_rotate
     Default value: `false'

     If `ztics_rotate' is `true', tic marks on the <z> axis are rotated
     90 degrees.

     Since this is a global graphics option, its position in the scene
     description does not matter.


48.2.4 Graphics objects
-----------------------

 -- Graphic object: bars ([<x1>,<h1>,<w1>], [<x2>,<h2>,<w2>, ...])
     Draws vertical bars in 2D.

     2D

     `bars ([<x1>,<h1>,<w1>], [<x2>,<h2>,<w2>, ...])' draws bars
     centered at values <x1>, <x2>, ... with heights <h1>, <h2>, ...
     and widths <w1>, <w2>, ...

     This object is affected by the following graphic options: `key',
     `fill_color', `fill_density' and `line_width'.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(
                 key          = "Group A",
                 fill_color   = blue,
                 fill_density = 0.2,
                 bars([0.8,5,0.4],[1.8,7,0.4],[2.8,-4,0.4]),
                 key          = "Group B",
                 fill_color   = red,
                 fill_density = 0.6,
                 line_width   = 4,
                 bars([1.2,4,0.4],[2.2,-2,0.4],[3.2,5,0.4]),
                 xaxis = true);


 -- Graphic object: cylindrical (<radius>, <z>, <minz>, <maxz>, <azi>,
          <minazi>, <maxazi>)
     Draws 3D functions defined in cylindrical coordinates.

     3D

     `cylindrical(<radius>, <z>, <minz>, <maxz>, <azi>, <minazi>,
     <maxazi>)' plots the function `<radius>(<z>, <azi>)' defined in
     cylindrical coordinates, with variable <z> taking values from
     <minz> to <maxz> and azimuth <azi> taking values from <minazi> to
     <maxazi>.

     This object is affected by the following graphic options:
     `xu_grid', `yv_grid', `line_type', `key', `wired_surface',
     `enhanced3d' and `color'.

     Example:

          (%i1) load(draw)$
          (%i2) draw3d(cylindrical(1,z,-2,2,az,0,2*%pi))$


 -- Graphic object: elevation_grid (<mat>,<x0>,<y0>,<width>,<height>)
     Draws matrix <mat> in 3D space. <z> values are taken from <mat>,
     the abscissas range from <x0> to <x0> + <width> and ordinates from
     <y0> to <y0> + <height>. Element a(1,1) is projected on point
     (x0,y0+height), a(1,n) on (x0+width,y0+height), a(m,1) on (x0,y0),
     and a(m,n) on (x0+width,y0).

     This object is affected by the following graphic options:
     `line_type', `line_width', `key', `wired_surface', `enhanced3d',
     and `color'.

     In older versions of Maxima, `elevation_grid' was called `mesh'.
     See also `mesh'.

     Example:

          (%i1) load(draw)$
          (%i2) m: apply(
                      matrix,
                      makelist(makelist(random(10.0),k,1,30),i,1,20)) $
          (%i3) draw3d(
                   color = blue,
                   elevation_grid(m,0,0,3,2),
                   xlabel = "x",
                   ylabel = "y",
                   surface_hide = true);


 -- Graphic object: ellipse (<xc>, <yc>, <a>, <b>, <ang1>, <ang2>)
     Draws ellipses and circles in 2D.

     2D

     `ellipse (<xc>, <yc>, <a>, <b>, <ang1>, <ang2>)' plots an ellipse
     centered at `[<xc>, <yc>]' with horizontal and vertical semi axis
     <a> and <b>, respectively, starting at angle <ang1> with an
     amplitude equal to angle <ang2>.

     This object is affected by the following graphic options: `nticks',
     `transparent', `fill_color', `border', `line_width', `line_type',
     `key' and `color'.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(transparent = false,
                       fill_color  = red,
                       color       = gray30,
                       transparent = false,
                       line_width  = 5,
                       ellipse(0,6,3,2,270,-270),
                       /* center (x,y), a, b, start & end in degrees */
                       transparent = true,
                       color       = blue,
                       line_width  = 3,
                       ellipse(2.5,6,2,3,30,-90),
                       xrange      = [-3,6],
                       yrange      = [2,9] )$


 -- Graphic object: errors ([<x1>, <x2>, ...], [<y1>, <y2>, ...])
     Draws points with error bars, horizontally, vertically or both,
     depending on the value of option `error_type'.

     2D

     If `error_type = x', arguments to `errors' must be of the form
     `[x, y, xdelta]' or `[x, y, xlow, xhigh]'.  If `error_type = y',
     arguments must be of the form `[x, y, ydelta]' or `[x, y, ylow,
     yhigh]'.  If `error_type = xy' or `error_type = boxes', arguments
     to `errors' must be of the form `[x, y, xdelta, ydelta]' or `[x,
     y, xlow, xhigh, ylow, yhigh]'.

     See also `error_type'.

     This object is affected by the following graphic options:
     `error_type', `points_joined', `line_width', `key', `line_type',
     `color', `fill_density', `xaxis_secondary', and  `yaxis_secondary'.

     Option `fill_density' is only relevant when `error_type=boxes'.

     Examples:

     Horizontal error bars.

          (%i1) load(draw)$
          (%i2) draw2d(
                  error_type = y,
                  errors([[1,2,1], [3,5,3], [10,3,1], [17,6,2]]))$

     Vertical and horizontal error bars.

          (%i1) load(draw)$
          (%i2) draw2d(
                  error_type = xy,
                  points_joined = true,
                  color = blue,
                  errors([[1,2,1,2], [3,5,2,1], [10,3,1,1], [17,6,1/2,2]]));


 -- Graphic object: explicit (<fcn>,<var>,<minval>,<maxval>)
 -- Graphic object: explicit
          (<fcn>,<var1>,<minval1>,<maxval1>,<var2>,<minval2>,<maxval2>)
     Draws explicit functions in 2D and 3D.

     2D

     `explicit(<fcn>,<var>,<minval>,<maxval>)' plots explicit function
     <fcn>, with variable <var> taking values from <minval> to <maxval>.

     This object is affected by the following graphic options: `nticks',
     `adapt_depth', `draw_realpart', `line_width', `line_type', `key',
     `filled_func', `fill_color' and `color'.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(line_width = 3,
                       color      = blue,
                       explicit(x^2,x,-3,3) )$
          (%i3) draw2d(fill_color  = brown,
                       filled_func = true,
                       explicit(x^2,x,-3,3) )$

     3D

     `explicit(<fcn>, <var1>, <minval1>, <maxval1>, <var2>, <minval2>,
     <maxval2>)' plots the explicit function <fcn>, with variable
     <var1> taking values from <minval1> to <maxval1> and variable
     <var2> taking values from <minval2> to <maxval2>.

     This object is affected by the following graphic options:
     `draw_realpart', `xu_grid', `yv_grid', `line_type', `line_width',
     `key', `wired_surface', `enhanced3d', and `color'.

     Example:

          (%i1) load(draw)$
          (%i2) draw3d(key   = "Gauss",
                       color = "#a02c00",
                       explicit(20*exp(-x^2-y^2)-10,x,-3,3,y,-3,3),
                       yv_grid     = 10,
                       color = blue,
                       key   = "Plane",
                       explicit(x+y,x,-5,5,y,-5,5),
                       surface_hide = true)$

     See also `filled_func' for filled functions.


 -- Graphic object: image (<im>,<x0>,<y0>,<width>,<height>)
     Renders images in 2D.

     2D

     `image (<im>,<x0>,<y0>,<width>,<height>)' plots image <im> in the
     rectangular region from vertex `(<x0>,<y0>)' to
     `(x0+<width>,y0+<height>)' on the real plane. Argument <im> must
     be a matrix of real numbers, a matrix of vectors of length three
     or a <picture> object.

     If <im> is a matrix of real numbers or a <levels picture> object,
     pixel values are interpreted according to graphic option `palette',
     which is a vector of length three with components ranging from -36
     to +36; each value is an index for a formula mapping the levels
     onto red, green and blue colors, respectively:
           0: 0               1: 0.5           2: 1
           3: x               4: x^2           5: x^3
           6: x^4             7: sqrt(x)       8: sqrt(sqrt(x))
           9: sin(90x)       10: cos(90x)     11: |x-0.5|
          12: (2x-1)^2       13: sin(180x)    14: |cos(180x)|
          15: sin(360x)      16: cos(360x)    17: |sin(360x)|
          18: |cos(360x)|    19: |sin(720x)|  20: |cos(720x)|
          21: 3x             22: 3x-1         23: 3x-2
          24: |3x-1|         25: |3x-2|       26: (3x-1)/2
          27: (3x-2)/2       28: |(3x-1)/2|   29: |(3x-2)/2|
          30: x/0.32-0.78125                  31: 2*x-0.84
          32: 4x;1;-2x+1.84;x/0.08-11.5
          33: |2*x - 0.5|    34: 2*x          35: 2*x - 0.5
          36: 2*x - 1
     negative numbers mean negative colour component.

     `palette = gray' and `palette = color' are short cuts for `palette
     = [3,3,3]' and `palette = [7,5,15]', respectively.

     If <im> is a matrix of vectors of length three or an <rgb picture>
     object, they are interpreted as red, green and blue color
     components.

     Examples:

     If <im> is a matrix of real numbers, pixel values are interpreted
     according to graphic option `palette'.
          (%i1) load(draw)$
          (%i2) im: apply(
                     'matrix,
                      makelist(makelist(random(200),i,1,30),i,1,30))$
          (%i3) /* palette = color, default */
                draw2d(image(im,0,0,30,30))$
          (%i4) draw2d(palette = gray, image(im,0,0,30,30))$
          (%i5) draw2d(palette = [15,20,-4],
                       colorbox=false,
                       image(im,0,0,30,30))$

     See also `colorbox'.

     If <im> is a matrix of vectors of length three, they are
     interpreted as red, green and blue color components.
          (%i1) load(draw)$
          (%i2) im: apply(
                      'matrix,
                       makelist(
                         makelist([random(300),
                                   random(300),
                                   random(300)],i,1,30),i,1,30))$
          (%i3) draw2d(image(im,0,0,30,30))$

     Package `draw' automatically loads package `picture'. In this
     example, a level picture object is built by hand and then rendered.
          (%i1) load(draw)$
          (%i2) im: make_level_picture([45,87,2,134,204,16],3,2);
          (%o2)       picture(level, 3, 2, {Array:  #(45 87 2 134 204 16)})
          (%i3) /* default color palette */
                draw2d(image(im,0,0,30,30))$
          (%i4) /* gray palette */
                draw2d(palette = gray,
                       image(im,0,0,30,30))$

     An xpm file is read and then rendered.
          (%i1) load(draw)$
          (%i2) im: read_xpm("myfile.xpm")$
          (%i3) draw2d(image(im,0,0,10,7))$

     See also `make_level_picture', `make_rgb_picture' and `read_xpm'.

     `http://www.telefonica.net/web2/biomates/maxima/gpdraw/image'
     contains more elaborated examples.


 -- Graphic object: implicit (<fcn>,<x>,<xmin>,<xmax>,<y>,<ymin>,<ymax>)
 -- Graphic object: implicit
          (<fcn>,<x>,<xmin>,<xmax>,<y>,<ymin>,<ymax>,<z>,<zmin>,<zmax>)
     Draws implicit functions in 2D and 3D.

     2D

     `implicit(<fcn>,<x>,<xmin>,<xmax>,<y>,<ymin>,<ymax>)' plots the
     implicit function defined by <fcn>, with variable <x> taking values
     from <xmin> to <xmax>, and variable <y> taking values from <ymin>
     to <ymax>.

     This object is affected by the following graphic options:
     `ip_grid', `ip_grid_in', `line_width', `line_type', `key' and
     `color'.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(terminal  = eps,
                       grid      = true,
                       line_type = solid,
                       key       = "y^2=x^3-2*x+1",
                       implicit(y^2=x^3-2*x+1, x, -4,4, y, -4,4),
                       line_type = dots,
                       key       = "x^3+y^3 = 3*x*y^2-x-1",
                       implicit(x^3+y^3 = 3*x*y^2-x-1, x,-4,4, y,-4,4),
                       title     = "Two implicit functions" )$

     3D

     `implicit (<fcn>,<x>,<xmin>,<xmax>, <y>,<ymin>,<ymax>,
     <z>,<zmin>,<zmax>)' plots the implicit surface defined by <fcn>,
     with variable <x> taking values from <xmin> to <xmax>, variable
     <y> taking values from <ymin> to <ymax> and variable <z> taking
     values from <zmin> to <zmax>. This object implements the marching
     cubes algorithm.

     This object is affected by the following graphic options:
     `x_voxel', `y_voxel', `z_voxel', `line_width', `line_type', `key',
     `wired_surface', `enhanced3d',and `color'.

     Example:

          (%i1) load(draw)$
          (%i2) draw3d(
                  color=blue,
                  implicit((x^2+y^2+z^2-1)*(x^2+(y-1.5)^2+z^2-0.5)=0.015,
                           x,-1,1,y,-1.2,2.3,z,-1,1),
                  surface_hide=true);


 -- Graphic object: label ([<string>,<x>,<y>],...)
 -- Graphic object: label ([<string>,<x>,<y>,<z>],...)
     Writes labels in 2D and 3D.

     Colored labels work only with Gnuplot 4.3. This is a known bug in
     package `draw'.

     This object is affected by the following graphic options:
     `label_alignment', `label_orientation' and `color'.

     2D

     `label([<string>,<x>,<y>])' writes the <string> at point
     `[<x>,<y>]'.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(yrange = [0.1,1.4],
                       color = red,
                       label(["Label in red",0,0.3]),
                       color = "#0000ff",
                       label(["Label in blue",0,0.6]),
                       color = light_blue,
                       label(["Label in light-blue",0,0.9],
                             ["Another light-blue",0,1.2])  )$

     3D

     `label([<string>,<x>,<y>,<z>])' writes the <string> at point
     `[<x>,<y>,<z>]'.

     Example:

          (%i1) load(draw)$
          (%i2) draw3d(explicit(exp(sin(x)+cos(x^2)),x,-3,3,y,-3,3),
                       color = red,
                       label(["UP 1",-2,0,3], ["UP 2",1.5,0,4]),
                       color = blue,
                       label(["DOWN 1",2,0,-3]) )$


 -- Graphic object: mesh (<row_1>,<row_2>,...)
     Draws a quadrangular mesh in 3D.

     3D

     Argument <row_i> is a list of <n> 3D points of the form
     `[[x_i1,y_i1,z_i1], ...,[x_in,y_in,z_in]]', and all rows are of
     equal length. All these points define an arbitrary surface in 3D
     and in some sense it's a generalization of the `elevation_grid'
     object.

     This object is affected by the following graphic options:
     `line_type', `line_width', `color', `key', `wired_surface',
     `enhanced3d', and `transform'.

     Examples:

     A simple example.

          (%i1) load(draw)$
          (%i2) draw3d(
                   mesh([[1,1,3],   [7,3,1],[12,-2,4],[15,0,5]],
                        [[2,7,8],   [4,3,1],[10,5,8], [12,7,1]],
                        [[-2,11,10],[6,9,5],[6,15,1], [20,15,2]])) $

     Plotting a triangle in 3D.

          (%i1) load(draw)$
          (%i2) draw3d(
                  line_width = 2,
                  mesh([[1,0,0],[0,1,0]],
                       [[0,0,1],[0,0,1]])) $

     Two quadrilaterals.

          (%i1) load(draw)$
          (%i2) draw3d(
                  surface_hide = true,
                  line_width   = 3,
                  color = red,
                  mesh([[0,0,0], [0,1,0]],
                       [[2,0,2], [2,2,2]]),
                  color = blue,
                  mesh([[0,0,2], [0,1,2]],
                       [[2,0,4], [2,2,4]])) $


 -- Graphic object: parametric (<xfun>,<yfun>,<par>,<parmin>,<parmax>)
 -- Graphic object: parametric
          (<xfun>,<yfun>,<zfun>,<par>,<parmin>,<parmax>)
     Draws parametric functions in 2D and 3D.

     This object is affected by the following graphic options: `nticks',
     `line_width', `line_type', `key', `color' and `enhanced3d'.

     2D

     The command `parametric(<xfun>, <yfun>, <par>, <parmin>,
     <parmax>)' plots the parametric function `[<xfun>, <yfun>]', with
     parameter <par> taking values from <parmin> to <parmax>.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(explicit(exp(x),x,-1,3),
                       color = red,
                       key   = "This is the parametric one!!",
                       parametric(2*cos(rrr),rrr^2,rrr,0,2*%pi))$

     3D

     `parametric(<xfun>, <yfun>, <zfun>, <par>, <parmin>, <parmax>)'
     plots the parametric curve `[<xfun>, <yfun>, <zfun>]', with
     parameter <par> taking values from <parmin> to <parmax>.

     Example:

          (%i1) load(draw)$
          (%i2) draw3d(explicit(exp(sin(x)+cos(x^2)),x,-3,3,y,-3,3),
                       color = royalblue,
                       parametric(cos(5*u)^2,sin(7*u),u-2,u,0,2),
                       color      = turquoise,
                       line_width = 2,
                       parametric(t^2,sin(t),2+t,t,0,2),
                       surface_hide = true,
                       title = "Surface & curves" )$


 -- Graphic object: parametric_surface (<xfun>, <yfun>, <zfun>, <par1>,
          <par1min>, <par1max>, <par2>, <par2min>, <par2max>)
     Draws parametric surfaces in 3D.

     3D

     The command `parametric_surface(<xfun>, <yfun>, <zfun>, <par1>,
     <par1min>, <par1max>, <par2>, <par2min>, <par2max>)' plots the
     parametric surface `[<xfun>, <yfun>, <zfun>]', with parameter
     <par1> taking values from <par1min> to <par1max> and parameter
     <par2> taking values from <par2min> to <par2max>.

     This object is affected by the following graphic options:
     `draw_realpart', `xu_grid', `yv_grid', `line_type', `line_width',
     `key', `wired_surface', `enhanced3d',  and `color'.

     Example:

          (%i1) load(draw)$
          (%i2) draw3d(title          = "Sea shell",
                       xu_grid        = 100,
                       yv_grid        = 25,
                       view           = [100,20],
                       surface_hide   = true,
                       parametric_surface(0.5*u*cos(u)*(cos(v)+1),
                                     0.5*u*sin(u)*(cos(v)+1),
                                     u*sin(v) - ((u+3)/8*%pi)^2 - 20,
                                     u, 0, 13*%pi, v, -%pi, %pi) )$


 -- Graphic object: points ([[<x1>,<y1>], [<x2>,<y2>],...])
 -- Graphic object: points ([<x1>,<x2>,...], [<y1>,<y2>,...])
 -- Graphic object: points ([<y1>,<y2>,...])
 -- Graphic object: points ([[<x1>,<y1>,<z1>], [<x2>,<y2>,<z2>],...])
 -- Graphic object: points ([<x1>,<x2>,...], [<y1>,<y2>,...],
          [<z1>,<z2>,...])
 -- Graphic object: points (<matrix>)
 -- Graphic object: points (<1d_y_array>)
 -- Graphic object: points (<1d_x_array>, <1d_y_array>)
 -- Graphic object: points (<1d_x_array>, <1d_y_array>, <1d_z_array>)
 -- Graphic object: points (<2d_xy_array>)
 -- Graphic object: points (<2d_xyz_array>)
     Draws points in 2D and 3D.

     This object is affected by the following graphic options:
     `point_size', `point_type', `points_joined', `line_width', `key',
     `line_type' and `color'. In 3D mode, it is also affected by
     `enhanced3d'.

     2D

     `points ([[<x1>,<y1>], [<x2>,<y2>],...])' or `points
     ([<x1>,<x2>,...], [<y1>,<y2>,...])' plots points `[x1,y1]',
     `[x2,y2]', etc. If abscissas are not given, they are set to
     consecutive positive integers, so that `points ([<y1>,<y2>,...])'
     draws points `[1,<y1>]', `[2,<y2>]', etc.  If <matrix> is a
     two-column or two-row matrix, `points (<matrix>)' draws the
     associated points. If <matrix> is a one-column or one-row matrix,
     abscissas are assigned automatically.

     If <1d_y_array> is a 1D lisp array of numbers, `points
     (<1d_y_array>)' plots them setting abscissas to consecutive
     positive integers. `points (<1d_x_array>, <1d_y_array>)' plots
     points with their coordinates taken from the two arrays passed as
     arguments. If <2d_xy_array> is a 2D array with two columns, or
     with two rows, `points (<2d_xy_array>)' plots the corresponding
     points on the plane.

     Examples:

     Two types of arguments for `points', a list of pairs and two lists
     of separate coordinates.
          (%i1) load(draw)$
          (%i2) draw2d(
                  key = "Small points",
                  points(makelist([random(20),random(50)],k,1,10)),
                  point_type    = circle,
                  point_size    = 3,
                  points_joined = true,
                  key           = "Great points",
                  points(makelist(k,k,1,20),makelist(random(30),k,1,20)),
                  point_type    = filled_down_triangle,
                  key           = "Automatic abscissas",
                  color         = red,
                  points([2,12,8]))$

     Drawing impulses.
          (%i1) load(draw)$
          (%i2) draw2d(
                  points_joined = impulses,
                  line_width    = 2,
                  color         = red,
                  points(makelist([random(20),random(50)],k,1,10)))$

     Array with ordinates.
          (%i1) load(draw)$
          (%i2) a: make_array (flonum, 100) $
          (%i3) for i:0 thru 99 do a[i]: random(1.0) $
          (%i4) draw2d(points(a)) $

     Two arrays with separate coordinates.
          (%i1) load(draw)$
          (%i2) x: make_array (flonum, 100) $
          (%i3) y: make_array (fixnum, 100) $
          (%i4) for i:0 thru 99 do (
                  x[i]: float(i/100),
                  y[i]: random(10) ) $
          (%i5) draw2d(points(x, y)) $

     A two-column 2D array.
          (%i1) load(draw)$
          (%i2) xy: make_array(flonum, 100, 2) $
          (%i3) for i:0 thru 99 do (
                  xy[i, 0]: float(i/100),
                  xy[i, 1]: random(10) ) $
          (%i4) draw2d(points(xy)) $

     Drawing an array filled with function `read_array'.
          (%i1) load(draw)$
          (%i2) a: make_array(flonum,100) $
          (%i3) read_array (file_search ("pidigits.data"), a) $
          (%i4) draw2d(points(a)) $

     3D

     `points([[<x1>, <y1>, <z1>], [<x2>, <y2>, <z2>], ...])' or
     `points([<x1>, <x2>, ...], [<y1>, <y2>, ...], [<z1>, <z2>,...])'
     plots points `[<x1>, <y1>, <z1>]', `[<x2>, <y2>, <z2>]', etc.  If
     <matrix> is a three-column or three-row matrix, `points
     (<matrix>)' draws the associated points.

     When arguments are lisp arrays, `points (<1d_x_array>,
     <1d_y_array>, <1d_z_array>)' takes coordinates from the three 1D
     arrays.  If <2d_xyz_array> is a 2D array with three columns, or
     with three rows, `points (<2d_xyz_array>)' plots the corresponding
     points.

     Examples:

     One tridimensional sample,
          (%i1) load(draw)$
          (%i2) load (numericalio)$
          (%i3) s2 : read_matrix (file_search ("wind.data"))$
          (%i4) draw3d(title = "Daily average wind speeds",
                       point_size = 2,
                       points(args(submatrix (s2, 4, 5))) )$

     Two tridimensional samples,
          (%i1) load(draw)$
          (%i2) load (numericalio)$
          (%i3) s2 : read_matrix (file_search ("wind.data"))$
          (%i4) draw3d(
                   title = "Daily average wind speeds. Two data sets",
                   point_size = 2,
                   key        = "Sample from stations 1, 2 and 3",
                   points(args(submatrix (s2, 4, 5))),
                   point_type = 4,
                   key        = "Sample from stations 1, 4 and 5",
                   points(args(submatrix (s2, 2, 3))) )$

     Unidimensional arrays,
          (%i1) load(draw)$
          (%i2) x: make_array (fixnum, 10) $
          (%i3) y: make_array (fixnum, 10) $
          (%i4) z: make_array (fixnum, 10) $
          (%i5) for i:0 thru 9 do (
                  x[i]: random(10),
                  y[i]: random(10),
                  z[i]: random(10) ) $
          (%i6) draw3d(points(x,y,z)) $

     Bidimensional colored array,
          (%i1) load(draw)$
          (%i2) xyz: make_array(fixnum, 10, 3) $
          (%i3) for i:0 thru 9 do (
                  xyz[i, 0]: random(10),
                  xyz[i, 1]: random(10),
                  xyz[i, 2]: random(10) ) $
          (%i4) draw3d(
                   enhanced3d = true,
                   points_joined = true,
                   points(xyz)) $

     Color numbers explicitly specified by the user.
          (%i1) load(draw)$
          (%i2) pts: makelist([t,t^2,cos(t)], t, 0, 15)$
          (%i3) col_num: makelist(k, k, 1, length(pts))$
          (%i4) draw3d(
                  enhanced3d = ['part(col_num,k),k],
                  point_size = 3,
                  point_type = filled_circle,
                  points(pts))$


 -- Graphic object: polar (<radius>,<ang>,<minang>,<maxang>)
     Draws 2D functions defined in polar coordinates.

     2D

     `polar (<radius>,<ang>,<minang>,<maxang>)' plots function
     `<radius>(<ang>)' defined in polar coordinates, with variable
     <ang> taking values from <minang> to <maxang>.

     This object is affected by the following graphic options: `nticks',
     `line_width', `line_type', `key' and `color'.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(user_preamble = "set grid polar",
                       nticks        = 200,
                       xrange        = [-5,5],
                       yrange        = [-5,5],
                       color         = blue,
                       line_width    = 3,
                       title         = "Hyperbolic Spiral",
                       polar(10/theta,theta,1,10*%pi) )$


 -- Graphic object: polygon ([[<x1>, <y1>], [<x2>, <y2>], ...])
 -- Graphic object: polygon ([<x1>, <x2>, ...], [<y1>, <y2>, ...])
     Draws polygons in 2D.

     2D

     The commands `polygon([[<x1>, <y1>], [<x2>, <y2>], ...])' or
     `polygon([<x1>, <x2>, ...], [<y1>, <y2>, ...])' plot on the plane
     a polygon with vertices `[<x1>, <y1>]', `[<x2>, <y2>]', etc.

     This object is affected by the following graphic options:
     `transparent', `fill_color', `border', `line_width', `key',
     `line_type' and `color'.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(color      = "#e245f0",
                       line_width = 8,
                       polygon([[3,2],[7,2],[5,5]]),
                       border      = false,
                       fill_color  = yellow,
                       polygon([[5,2],[9,2],[7,5]]) )$


 -- Graphic object: quadrilateral (<point_1>, <point_2>, <point_3>,
          <point_4>)
     Draws a quadrilateral.

     2D

     `quadrilateral([<x1>, <y1>], [<x2>, <y2>], [<x3>, <y3>], [<x4>,
     <y4>])' draws a quadrilateral with vertices `[<x1>, <y1>]',
     `[<x2>, <y2>]', `[<x3>, <y3>]', and `[<x4>, <y4>]'.

     This object is affected by the following graphic options:
     `transparent', `fill_color', `border', `line_width', `key',
     `xaxis_secondary', `yaxis_secondary', `line_type', `transform' and
     `color'.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(
                  quadrilateral([1,1],[2,2],[3,-1],[2,-2]))$

     3D

     `quadrilateral([<x1>, <y1>, <z1>], [<x2>, <y2>, <z2>], [<x3>,
     <y3>, <z3>], [<x4>, <y4>, <z4>])' draws a quadrilateral with
     vertices `[<x1>, <y1>, <z1>]', `[<x2>, <y2>, <z2>]', `[<x3>, <y3>,
     <z3>]', and `[<x4>, <y4>, <z4>]'.

     This object is affected by the following graphic options:
     `line_type', `line_width', `color', `key', `enhanced3d', and
     `transform'.


 -- Graphic object: rectangle ([<x1>,<y1>], [<x2>,<y2>])
     Draws rectangles in 2D.

     2D

     `rectangle ([<x1>,<y1>], [<x2>,<y2>])' draws a rectangle with
     opposite vertices `[<x1>,<y1>]' and `[<x2>,<y2>]'.

     This object is affected by the following graphic options:
     `transparent', `fill_color', `border', `line_width', `key',
     `line_type' and `color'.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(fill_color  = red,
                       line_width  = 6,
                       line_type   = dots,
                       transparent = false,
                       fill_color  = blue,
                       rectangle([-2,-2],[8,-1]), /* opposite vertices */
                       transparent = true,
                       line_type   = solid,
                       line_width  = 1,
                       rectangle([9,4],[2,-1.5]),
                       xrange      = [-3,10],
                       yrange      = [-3,4.5] )$


 -- Graphic object: region
          (<expr>,<var1>,<minval1>,<maxval1>,<var2>,<minval2>,<maxval2>)
     Plots a region on the plane defined by inequalities.

     2D <expr> is an expression formed by inequalities and boolean
     operators `and', `or', and `not'. The region is bounded by the
     rectangle defined by [<minval1>, <maxval1>] and [<minval2>,
     <maxval2>].

     This object is affected by the following graphic options:
     `fill_color', `key', `x_voxel', and `y_voxel'.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(
                  x_voxel = 30,
                  y_voxel = 30,
                  region(x^2+y^2<1 and x^2+y^2 > 1/2,
                         x, -1.5, 1.5, y, -1.5, 1.5));

 -- Graphic object: spherical (<radius>, <azi>, <minazi>, <maxazi>,
          <zen>, <minzen>, <maxzen>)
     Draws 3D functions defined in spherical coordinates.

     3D

     `spherical(<radius>, <azi>, <minazi>, <maxazi>, <zen>, <minzen>,
     <maxzen>)' plots the function `<radius>(<azi>, <zen>)' defined in
     spherical coordinates, with azimuth <azi> taking values from
     <minazi> to <maxazi> and zenith <zen> taking values from <minzen>
     to <maxzen>.

     This object is affected by the following graphic options:
     `xu_grid', `yv_grid', `line_type', `key', `wired_surface',
     `enhanced3d' and `color'.

     Example:

          (%i1) load(draw)$
          (%i2) draw3d(spherical(1,a,0,2*%pi,z,0,%pi))$


 -- Graphic object: triangle (<point_1>, <point_2>, <point_3>)
     Draws a triangle.

     2D

     `triangle ([<x1>,<y1>], [<x2>,<y2>], [<x3>,<y3>])' draws a
     triangle with vertices `[<x1>,<y1>]', `[<x2>,<y2>]', and
     `[<x3>,<y3>]'.

     This object is affected by the following graphic options:
     `transparent', `fill_color', `border', `line_width', `key',
     `xaxis_secondary', `yaxis_secondary', `line_type', `transform',
     and `color'.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(
                  triangle([1,1],[2,2],[3,-1]))$

     3D

     `triangle ([<x1>,<y1>,<z1>], [<x2>,<y2>,<z2>], [<x3>,<y3>,<z3>])'
     draws a triangle with vertices `[<x1>,<y1>,<z1>]',
     `[<x2>,<y2>,<z2>]', and `[<x3>,<y3>,<z3>]'.

     This object is affected by the following graphic options:
     `line_type', `line_width', `color', `key', `enhanced3d', and
     `transform'.


 -- Graphic object: tube (<xfun>,<yfun>,<zfun>,<rfun>,<p>,<pmin>,<pmax>)
     Draws a tube in 3D with varying diameter.

     3D

     `[<xfun>,<yfun>,<zfun>]' is the parametric curve with parameter
     <p> taking values from <pmin> to <pmax>. Circles of radius <rfun>
     are placed with their centers on the parametric curve and
     perpendicular to it.

     This object is affected by the following graphic options:
     `xu_grid', `yv_grid', `line_type', `line_width', `key',
     `wired_surface', `enhanced3d', `color', and `tube_extremes'.

     Example:

          (%i1) load(draw)$
          (%i2) draw3d(
                  enhanced3d = true,
                  xu_grid = 50,
                  tube(cos(a), a, 0, cos(a/10)^2,
                       a, 0, 4*%pi) )$


 -- Graphic object: vector ([<x>,<y>], [<dx>,<dy>])
 -- Graphic object: vector ([<x>,<y>,<z>], [<dx>,<dy>,<dz>])
     Draws vectors in 2D and 3D.

     This object is affected by the following graphic options:
     `head_both', `head_length', `head_angle', `head_type',
     `line_width', `line_type', `key' and `color'.

     2D

     `vector([<x>,<y>], [<dx>,<dy>])' plots vector `[<dx>,<dy>]' with
     origin in `[<x>,<y>]'.

     Example:

          (%i1) load(draw)$
          (%i2) draw2d(xrange      = [0,12],
                       yrange      = [0,10],
                       head_length = 1,
                       vector([0,1],[5,5]), /* default type */
                       head_type = 'empty,
                       vector([3,1],[5,5]),
                       head_both = true,
                       head_type = 'nofilled,
                       line_type = dots,
                       vector([6,1],[5,5]))$

     3D

     `vector([<x>,<y>,<z>], [<dx>,<dy>,<dz>])' plots vector
     `[<dx>,<dy>,<dz>]' with origin in `[<x>,<y>,<z>]'.

     Example:

          (%i1) load(draw)$
          (%i2) draw3d(color = cyan,
                       vector([0,0,0],[1,1,1]/sqrt(3)),
                       vector([0,0,0],[1,-1,0]/sqrt(2)),
                       vector([0,0,0],[1,1,-2]/sqrt(6)) )$



File: maxima.info,  Node: Functions and Variables for pictures,  Next: Functions and Variables for worldmap,  Prev: Functions and Variables for draw,  Up: draw

48.3 Functions and Variables for pictures
=========================================

 -- Function: get_pixel (<pic>,<x>,<y>)
     Returns pixel from picture. Coordinates <x> and <y> range from 0 to
     `width-1' and `height-1', respectively.


 -- Function: make_level_picture (<data>)
 -- Function: make_level_picture (<data>,<width>,<height>)
     Returns a levels <picture> object. `make_level_picture (<data>)'
     builds the <picture> object from matrix <data>.
     `make_level_picture (<data>,<width>,<height>)' builds the object
     from a list of numbers; in this case, both the <width> and the
     <height> must be given.

     The returned <picture> object contains the following four parts:

       1. symbol `level'

       2. image width

       3. image height

       4. an integer array with pixel data ranging from 0 to 255.
          Argument <data> must contain only numbers ranged from 0 to
          255; negative numbers are substituted by 0, and those which
          are greater than 255 are set to 255.

     Example:

     Level picture from matrix.
          (%i1) load(draw)$
          (%i2) make_level_picture(matrix([3,2,5],[7,-9,3000]));
          (%o2)         picture(level, 3, 2, {Array:  #(3 2 5 7 0 255)})

     Level picture from numeric list.
          (%i1) load(draw)$
          (%i2) make_level_picture([-2,0,54,%pi],2,2);
          (%o2)            picture(level, 2, 2, {Array:  #(0 0 54 3)})


 -- Function: make_rgb_picture (<redlevel>,<greenlevel>,<bluelevel>)
     Returns an rgb-coloured <picture> object. All three arguments must
     be levels picture; with red, green and blue levels.

     The returned <picture> object contains the following four parts:

       1. symbol `rgb'

       2. image width

       3. image height

       4. an integer array of length <3*width*height> with pixel data
          ranging from 0 to 255. Each pixel is represented by three
          consecutive numbers (red, green, blue).

     Example:

          (%i1) load(draw)$
          (%i2) red: make_level_picture(matrix([3,2],[7,260]));
          (%o2)           picture(level, 2, 2, {Array:  #(3 2 7 255)})
          (%i3) green: make_level_picture(matrix([54,23],[73,-9]));
          (%o3)           picture(level, 2, 2, {Array:  #(54 23 73 0)})
          (%i4) blue: make_level_picture(matrix([123,82],[45,32.5698]));
          (%o4)          picture(level, 2, 2, {Array:  #(123 82 45 33)})
          (%i5) make_rgb_picture(red,green,blue);
          (%o5) picture(rgb, 2, 2,
                        {Array:  #(3 54 123 2 23 82 7 73 45 255 0 33)})


 -- Function: negative_picture (<pic>)
     Returns the negative of a (<level> or <rgb>) picture.


 -- Function: picture_equalp (<x>,<y>)
     Returns `true' in case of equal pictures, and `false' otherwise.


 -- Function: picturep (<x>)
     Returns `true' if the argument is a well formed image, and `false'
     otherwise.


 -- Function: read_xpm (<xpm_file>)
     Reads a file in xpm and returns a picture object.


 -- Function: rgb2level (<pic>)
     Transforms an <rgb> picture into a <level> one by averaging the
     red, green and blue channels.


 -- Function: take_channel (<im>,<color>)
     If argument <color> is `red', `green' or `blue', function
     `take_channel' returns the corresponding color channel of picture
     <im>.  Example:

          (%i1) load(draw)$
          (%i2) red: make_level_picture(matrix([3,2],[7,260]));
          (%o2)           picture(level, 2, 2, {Array:  #(3 2 7 255)})
          (%i3) green: make_level_picture(matrix([54,23],[73,-9]));
          (%o3)           picture(level, 2, 2, {Array:  #(54 23 73 0)})
          (%i4) blue: make_level_picture(matrix([123,82],[45,32.5698]));
          (%o4)          picture(level, 2, 2, {Array:  #(123 82 45 33)})
          (%i5) make_rgb_picture(red,green,blue);
          (%o5) picture(rgb, 2, 2,
                        {Array:  #(3 54 123 2 23 82 7 73 45 255 0 33)})
          (%i6) take_channel(%,'green);  /* simple quote!!! */
          (%o6)           picture(level, 2, 2, {Array:  #(54 23 73 0)})



File: maxima.info,  Node: Functions and Variables for worldmap,  Prev: Functions and Variables for pictures,  Up: draw

48.4 Functions and Variables for worldmap
=========================================

This package automatically loads package `draw'.

48.4.1 Variables and Functions
------------------------------

 -- Global variable: boundaries_array
     Default value: `false'

     `boundaries_array' is where the graphic object `geomap' looks for
     boundaries coordinates.

     Each component of `boundaries_array' is an array of floating point
     quantities, the coordinates of a polygonal segment or map boundary.

     See also `geomap'.


 -- Function: numbered_boundaries (<nlist>)
     Draws a list of polygonal segments (boundaries), labeled by its
     numbers (`boundaries_array' coordinates). This is of great help
     when building new geographical entities.

     Example:

     Map of Europe labeling borders with their component number in
     `boundaries_array'.
          (%i1) load(worldmap)$
          (%i2) european_borders:
                     region_boundaries(-31.81,74.92,49.84,32.06)$
          (%i3) numbered_boundaries(european_borders)$


 -- Function: make_poly_continent (<continent_name>)
 -- Function: make_poly_continent (<country_list>)
     Makes the necessary polygons to draw a colored continent or a list
     of countries.

     Example:

          (%i1) load(worldmap)$
          (%i2) /* A continent */
                make_poly_continent(Africa)$
          (%i3) apply(draw2d, %)$
          (%i4) /* A list of countries */
                make_poly_continent([Germany,Denmark,Poland])$
          (%i5) apply(draw2d, %)$


 -- Function: make_poly_country (<country_name>)
     Makes the necessary polygons to draw a colored country.  If
     islands exist, one country can be defined with more than just one
     polygon.

     Example:

          (%i1) load(worldmap)$
          (%i2) make_poly_country(India)$
          (%i3) apply(draw2d, %)$


 -- Function: make_polygon (<nlist>)
     Returns a `polygon' object from boundary indices. Argument <nlist>
     is a list of components of `boundaries_array'.

     Example:

     Bhutan is defined by boundary numbers 171, 173 and 1143, so that
     `make_polygon([171,173,1143])' appends arrays of coordinates
     `boundaries_array[171]', `boundaries_array[173]' and
     `boundaries_array[1143]' and returns a `polygon' object suited to
     be plotted by `draw'. To avoid an error message, arrays must be
     compatible in the sense that any two consecutive arrays have two
     coordinates in the extremes in common. In this example, the two
     first components of `boundaries_array[171]' are equal to the last
     two coordinates of `boundaries_array[173]', and the two first of
     `boundaries_array[173]' are equal to the two first of
     `boundaries_array[1143]'; in conclussion, boundary numbers 171,
     173 and 1143 (in this order) are compatible and the colored
     polygon can be drawn.
          (%i1) load(worldmap)$
          (%i2) Bhutan;
          (%o2)                        [[171, 173, 1143]]
          (%i3) boundaries_array[171];
          (%o3) {Array:
                 #(88.750549 27.14727 88.806351 27.25305 88.901367 27.282221
                   88.917877 27.321039)}
          (%i4) boundaries_array[173];
          (%o4) {Array:
                 #(91.659554 27.76511 91.6008 27.66666 91.598022 27.62499
                   91.631348 27.536381 91.765533 27.45694 91.775253 27.4161
                   92.007751 27.471939 92.11441 27.28583 92.015259 27.168051
                   92.015533 27.08083 92.083313 27.02277 92.112183 26.920271
                   92.069977 26.86194 91.997192 26.85194 91.915253 26.893881
                   91.916924 26.85416 91.8358 26.863331 91.712479 26.799999
                   91.542191 26.80444 91.492188 26.87472 91.418854 26.873329
                   91.371353 26.800831 91.307457 26.778049 90.682457 26.77417
                   90.392197 26.903601 90.344131 26.894159 90.143044 26.75333
                   89.98996 26.73583 89.841919 26.70138 89.618301 26.72694
                   89.636093 26.771111 89.360786 26.859989 89.22081 26.81472
                   89.110237 26.829161 88.921631 26.98777 88.873016 26.95499
                   88.867737 27.080549 88.843307 27.108601 88.750549
                   27.14727)}
          (%i5) boundaries_array[1143];
          (%o5) {Array:
                 #(91.659554 27.76511 91.666924 27.88888 91.65831 27.94805
                   91.338028 28.05249 91.314972 28.096661 91.108856 27.971109
                   91.015808 27.97777 90.896927 28.05055 90.382462 28.07972
                   90.396088 28.23555 90.366074 28.257771 89.996353 28.32333
                   89.83165 28.24888 89.58609 28.139999 89.35997 27.87166
                   89.225517 27.795 89.125793 27.56749 88.971077 27.47361
                   88.917877 27.321039)}
          (%i6) Bhutan_polygon: make_polygon([171,173,1143])$
          (%i7) draw2d(Bhutan_polygon)$


 -- Function: region_boundaries (<x1>,<y1>,<x2>,<y2>)
     Detects polygonal segments of global variable `boundaries_array'
     fully contained in the rectangle with vertices (<x1>,<y1>) -upper
     left- and (<x2>,<y2>) -bottom right-.

     Example:

     Returns segment numbers for plotting southern Italy.
          (%i1) load(worldmap)$
          (%i2) region_boundaries(10.4,41.5,20.7,35.4);
          (%o2)                [1846, 1863, 1864, 1881, 1888, 1894]
          (%i3) draw2d(geomap(%))$


 -- Function: region_boundaries_plus (<x1>,<y1>,<x2>,<y2>)
     Detects polygonal segments of global variable `boundaries_array'
     containing at least one vertex in the rectangle defined by
     vertices (<x1>,<y1>) -upper left- and (<x2>,<y2>) -bottom right-.

     Example:

          (%i1) load(worldmap)$
          (%i2) region_boundaries_plus(10.4,41.5,20.7,35.4);
          (%o2) [1060, 1062, 1076, 1835, 1839, 1844, 1846, 1858,
                 1861, 1863, 1864, 1871, 1881, 1888, 1894, 1897]
          (%i3) draw2d(geomap(%))$


48.4.2 Graphic objects
----------------------

 -- Graphic object: geomap (<numlist>)
 -- Graphic object: geomap (<numlist>,<3Dprojection>)
     Draws cartographic maps in 2D and 3D.

     2D

     This function works together with global variable
     `boundaries_array'.

     Argument <numlist> is a list containing numbers or lists of
     numbers.  All these numbers must be integers greater or equal than
     zero, representing the components of global array
     `boundaries_array'.

     Each component of `boundaries_array' is an array of floating point
     quantities, the coordinates of a polygonal segment or map boundary.

     `geomap (<numlist>)' flattens its arguments and draws the
     associated boundaries in `boundaries_array'.

     This object is affected by the following graphic options:
     `line_width', `line_type' and `color'.

     Examples:

     A simple map defined by hand:
          (%i1) load(worldmap)$
          (%i2) /* Vertices of boundary #0: {(1,1),(2,5),(4,3)} */
             ( bnd0: make_array(flonum,6),
               bnd0[0]:1.0, bnd0[1]:1.0, bnd0[2]:2.0,
               bnd0[3]:5.0, bnd0[4]:4.0, bnd0[5]:3.0 )$
          (%i3) /* Vertices of boundary #1: {(4,3),(5,4),(6,4),(5,1)} */
             ( bnd1: make_array(flonum,8),
               bnd1[0]:4.0, bnd1[1]:3.0, bnd1[2]:5.0, bnd1[3]:4.0,
               bnd1[4]:6.0, bnd1[5]:4.0, bnd1[6]:5.0, bnd1[7]:1.0)$
          (%i4) /* Vertices of boundary #2: {(5,1), (3,0), (1,1)} */
             ( bnd2: make_array(flonum,6),
               bnd2[0]:5.0, bnd2[1]:1.0, bnd2[2]:3.0,
               bnd2[3]:0.0, bnd2[4]:1.0, bnd2[5]:1.0 )$
          (%i5) /* Vertices of boundary #3: {(1,1), (4,3)} */
             ( bnd3: make_array(flonum,4),
               bnd3[0]:1.0, bnd3[1]:1.0, bnd3[2]:4.0, bnd3[3]:3.0)$
          (%i6) /* Vertices of boundary #4: {(4,3), (5,1)} */
             ( bnd4: make_array(flonum,4),
               bnd4[0]:4.0, bnd4[1]:3.0, bnd4[2]:5.0, bnd4[3]:1.0)$
          (%i7) /* Pack all together in boundaries_array */
             ( boundaries_array: make_array(any,5),
               boundaries_array[0]: bnd0, boundaries_array[1]: bnd1,
               boundaries_array[2]: bnd2, boundaries_array[3]: bnd3,
               boundaries_array[4]: bnd4 )$
          (%i8) draw2d(geomap([0,1,2,3,4]))$

     The auxiliary package `worldmap' sets the global variable
     `boundaries_array' to real world boundaries in (longitude,
     latitude) coordinates. These data are in the public domain and
     come from `http://www-cger.nies.go.jp/grid-e/gridtxt/grid19.html'.
     Package `worldmap' defines also boundaries for countries,
     continents and coastlines as lists with the necessary components of
     `boundaries_array' (see file `share/draw/worldmap.mac' for more
     information). Package `worldmap' automatically loads package
     `worldmap'.
          (%i1) load(worldmap)$
          (%i2) c1: gr2d(geomap(Canada,United_States,
                                Mexico,Cuba))$
          (%i3) c2: gr2d(geomap(Africa))$
          (%i4) c3: gr2d(geomap(Oceania,China,Japan))$
          (%i5) c4: gr2d(geomap(France,Portugal,Spain,
                                Morocco,Western_Sahara))$
          (%i6) draw(columns  = 2,
                     c1,c2,c3,c4)$

     Package `worldmap' is also useful for plotting countries as
     polygons. In this case, graphic object `geomap' is no longer
     necessary and the `polygon' object is used instead. Since lists
     are now used and not arrays, maps rendering will be slower. See
     also `make_poly_country' and `make_poly_continent' to understand
     the following code.
          (%i1) load(worldmap)$
          (%i2) mymap: append(
             [color      = white],  /* borders are white */
             [fill_color = red],             make_poly_country(Bolivia),
             [fill_color = cyan],            make_poly_country(Paraguay),
             [fill_color = green],           make_poly_country(Colombia),
             [fill_color = blue],            make_poly_country(Chile),
             [fill_color = "#23ab0f"],       make_poly_country(Brazil),
             [fill_color = goldenrod],       make_poly_country(Argentina),
             [fill_color = "midnight-blue"], make_poly_country(Uruguay))$
          (%i3) apply(draw2d, mymap)$

     3D

     `geomap (<numlist>)' projects map boundaries on the sphere of
     radius 1 centered at (0,0,0). It is possible to change the sphere
     or the projection type by using `geomap
     (<numlist>,<3Dprojection>)'.

     Available 3D projections:

        * `[spherical_projection,<x>,<y>,<z>,<r>]': projects map
          boundaries on the sphere of radius <r> centered at
          (<x>,<y>,<z>).
               (%i1) load(worldmap)$
               (%i2) draw3d(geomap(Australia), /* default projection */
                            geomap(Australia,
                                   [spherical_projection,2,2,2,3]))$

        * `[cylindrical_projection,<x>,<y>,<z>,<r>,<rc>]': re-projects
          spherical map boundaries on the cylinder of radius <rc> and
          axis passing through the poles of the globe of radius <r>
          centered at (<x>,<y>,<z>).
               (%i1) load(worldmap)$
               (%i2) draw3d(geomap([America_coastlines,Eurasia_coastlines],
                                   [cylindrical_projection,2,2,2,3,4]))$

        * `[conic_projection,<x>,<y>,<z>,<r>,<alpha>]': re-projects
          spherical map boundaries on the cones of angle <alpha>, with
          axis passing through the poles of the globe of radius <r>
          centered at (<x>,<y>,<z>). Both the northern and southern
          cones are tangent to sphere.
               (%i1) load(worldmap)$
               (%i2) draw3d(geomap(World_coastlines,
                                   [conic_projection,0,0,0,1,90]))$

     See also
     `http://www.telefonica.net/web2/biomates/maxima/gpdraw/geomap' for
     more elaborated examples.



File: maxima.info,  Node: drawdf,  Next: dynamics,  Prev: draw,  Up: Top

49 drawdf
*********

* Menu:

* Introduction to drawdf::
* Functions and Variables for drawdf::


File: maxima.info,  Node: Introduction to drawdf,  Next: Functions and Variables for drawdf,  Prev: drawdf,  Up: drawdf

49.1 Introduction to drawdf
===========================

The function `drawdf' draws the direction field of a first-order
Ordinary Differential Equation (ODE) or a system of two autonomous
first-order ODE's.

   Since this is an additional package, in order to use it you must
first load it with `load(drawdf)'.  Drawdf is built upon the `draw'
package, which requires Gnuplot 4.2.

   To plot the direction field of a single ODE, the ODE must be written
in the form:
            dy
            -- = F(x,y)
            dx

   and the function <F> should be given as the argument for `drawdf'.
If the independent and dependent variables are not <x>, and <y>, as in
the equation above, then those two variables should be named explicitly
in a list given as an argument to the drawdf command (see the examples).

   To plot the direction field of a set of two autonomous ODE's, they
must be written in the form
            dx             dy
            -- = G(x,y)    -- = F(x,y)
            dt             dt

   and the argument for `drawdf' should be a list with the two
functions <G> and <F>, in that order; namely, the first expression in
the list will be taken to be the time derivative of the variable
represented on the horizontal axis, and the second expression will be
the time derivative of the variable represented on the vertical axis.
Those two variables do not have to be <x> and <y>, but if they are not,
then the second argument given to drawdf must be another list naming
the two variables, first the one on the horizontal axis and then the
one on the vertical axis.

   If only one ODE is given, `drawdf' will implicitly admit `x=t', and
`G(x,y)=1', transforming the non-autonomous equation into a system of
two autonomous equations.


File: maxima.info,  Node: Functions and Variables for drawdf,  Prev: Introduction to drawdf,  Up: drawdf

49.2 Functions and Variables for drawdf
=======================================

49.2.1 Functions
----------------

 -- Function: drawdf (<dydx>, ...options and objects...)
 -- Function: drawdf (<dvdu>, `['<u>,<v>`]', ...options and objects...)
 -- Function: drawdf (<dvdu>, `['<u>,<umin>,<umax>`]',
          `['<v>,<vmin>,<vmax>`]', ...options and objects...)
 -- Function: drawdf (`['<dxdt>,<dydt>`]', ...options and objects...)
 -- Function: drawdf (`['<dudt>,<dvdt>`]', `['<u>,<v>`]', ...options
          and objects...)
 -- Function: drawdf (`['<dudt>,<dvdt>`]', `['<u>,<umin>,<umax>`]',
          `['<v>,<vmin>,<vmax>`]', ...options and objects...)
     Function `drawdf' draws a 2D direction field with optional
     solution curves and other graphics using the `draw' package.

     The first argument specifies the derivative(s), and must be either
     an expression or a list of two expressions.  <dydx>, <dxdt> and
     <dydt> are expressions that depend on <x> and <y>.  <dvdu>, <dudt>
     and <dvdt> are expressions that depend on <u> and <v>.

     If the independent and dependent variables are not <x> and <y>,
     then their names must be specified immediately following the
     derivative(s), either as a list of two names `['<u>,<v>`]', or as
     two lists of the form `['<u>,<umin>,<umax>`]' and
     `['<v>,<vmin>,<vmax>`]'.

     The remaining arguments are graphic options, graphic objects, or
     lists containing graphic options and objects, nested to arbitrary
     depth.  The set of graphic options and objects supported by
     `drawdf' is a superset of those supported by `draw2d' and `gr2d'
     from the `draw' package.

     The arguments are interpreted sequentially: graphic options affect
     all following graphic objects.  Furthermore, graphic objects are
     drawn on the canvas in order specified, and may obscure graphics
     drawn earlier.  Some graphic options affect the global appearence
     of the scene.

     The additional graphic objects supported by `drawdf' include:
     `solns_at', `points_at', `saddles_at', `soln_at', `point_at', and
     `saddle_at'.

     The additional graphic options supported by `drawdf' include:
     `field_degree', `soln_arrows', `field_arrows', `field_grid',
     `field_color', `show_field', `tstep', `nsteps', `duration',
     `direction', `field_tstep', `field_nsteps', and `field_duration'.

     Commonly used graphic objects inherited from the `draw' package
     include: `explicit', `implicit', `parametric', `polygon',
     `points', `vector', `label', and all others supported by `draw2d'
     and `gr2d'.

     Commonly used graphic options inherited from the `draw' package
     include:
     `points_joined', `color', `point_type', `point_size', `line_width',
     `line_type', `key', `title', `xlabel', `ylabel', `user_preamble',
     `terminal', `dimensions', `file_name', and all others supported by
     `draw2d' and `gr2d'.

     See also `draw2d'.

     Users of wxMaxima or Imaxima may optionally use `wxdrawdf', which
     is identical to `drawdf' except that the graphics are drawn within
     the notebook using `wxdraw'.

     To make use of this function, write first `load(drawdf)'.

     Examples:

          (%i1) load(drawdf)$
          (%i2) drawdf(exp(-x)+y)$        /* default vars: x,y */
          (%i3) drawdf(exp(-t)+y, [t,y])$ /* default range: [-10,10] */
          (%i4) drawdf([y,-9*sin(x)-y/5], [x,1,5], [y,-2,2])$

     For backward compatibility, `drawdf' accepts most of the
     parameters supported by plotdf.

          (%i5) drawdf(2*cos(t)-1+y, [t,y], [t,-5,10], [y,-4,9],
                       [trajectory_at,0,0])$

     `soln_at' and `solns_at' draw solution curves passing through the
     specified points, using a slightly enhanced 4th-order Runge Kutta
     numerical integrator.

          (%i6) drawdf(2*cos(t)-1+y, [t,-5,10], [y,-4,9],
                       solns_at([0,0.1],[0,-0.1]),
                       color=blue, soln_at(0,0))$

     `field_degree=2' causes the field to be composed of quadratic
     splines, based on the first and second derivatives at each grid
     point.  `field_grid=['<COLS>,<ROWS>`]' specifies the number of
     columns and rows in the grid.

          (%i7) drawdf(2*cos(t)-1+y, [t,-5,10], [y,-4,9],
                       field_degree=2, field_grid=[20,15],
                       solns_at([0,0.1],[0,-0.1]),
                       color=blue, soln_at(0,0))$

     `soln_arrows=true' adds arrows to the solution curves, and (by
     default) removes them from the direction field.  It also changes
     the default colors to emphasize the solution curves.

          (%i8) drawdf(2*cos(t)-1+y, [t,-5,10], [y,-4,9],
                       soln_arrows=true,
                       solns_at([0,0.1],[0,-0.1],[0,0]))$

     `duration=40' specifies the time duration of numerical integration
     (default 10).  Integration will also stop automatically if the
     solution moves too far away from the plotted region, or if the
     derivative becomes complex or infinite.  Here we also specify
     `field_degree=2' to plot quadratic splines.  The equations below
     model a predator-prey system.

          (%i9) drawdf([x*(1-x-y), y*(3/4-y-x/2)], [x,0,1.1], [y,0,1],
                       field_degree=2, duration=40,
                       soln_arrows=true, point_at(1/2,1/2),
                       solns_at([0.1,0.2], [0.2,0.1], [1,0.8], [0.8,1],
                                [0.1,0.1], [0.6,0.05], [0.05,0.4],
                                [1,0.01], [0.01,0.75]))$

     `field_degree='solns' causes the field to be composed of many
     small solution curves computed by 4th-order Runge Kutta, with
     better results in this case.

          (%i10) drawdf([x*(1-x-y), y*(3/4-y-x/2)], [x,0,1.1], [y,0,1],
                        field_degree='solns, duration=40,
                        soln_arrows=true, point_at(1/2,1/2),
                        solns_at([0.1,0.2], [0.2,0.1], [1,0.8],
                                 [0.8,1], [0.1,0.1], [0.6,0.05],
                                 [0.05,0.4], [1,0.01], [0.01,0.75]))$

     `saddles_at' attempts to automatically linearize the equation at
     each saddle, and to plot a numerical solution corresponding to each
     eigenvector, including the separatrices.  `tstep=0.05' specifies
     the maximum time step for the numerical integrator (the default is
     0.1).  Note that smaller time steps will sometimes be used in
     order to keep the x and y steps small.  The equations below model
     a damped pendulum.

          (%i11) drawdf([y,-9*sin(x)-y/5], tstep=0.05,
                        soln_arrows=true, point_size=0.5,
                        points_at([0,0], [2*%pi,0], [-2*%pi,0]),
                        field_degree='solns,
                        saddles_at([%pi,0], [-%pi,0]))$

     `show_field=false' suppresses the field entirely.

          (%i12) drawdf([y,-9*sin(x)-y/5], tstep=0.05,
                        show_field=false, soln_arrows=true,
                        point_size=0.5,
                        points_at([0,0], [2*%pi,0], [-2*%pi,0]),
                        saddles_at([3*%pi,0], [-3*%pi,0],
                                   [%pi,0], [-%pi,0]))$

     `drawdf' passes all unrecognized parameters to `draw2d' or `gr2d',
     allowing you to combine the full power of the `draw' package with
     `drawdf'.

          (%i13) drawdf(x^2+y^2, [x,-2,2], [y,-2,2], field_color=gray,
                        key="soln 1", color=black, soln_at(0,0),
                        key="soln 2", color=red, soln_at(0,1),
                        key="isocline", color=green, line_width=2,
                        nticks=100, parametric(cos(t),sin(t),t,0,2*%pi))$

     `drawdf' accepts nested lists of graphic options and objects,
     allowing convenient use of makelist and other function calls to
     generate graphics.

          (%i14) colors : ['red,'blue,'purple,'orange,'green]$
          (%i15) drawdf([x-x*y/2, (x*y - 3*y)/4],
                        [x,2.5,3.5], [y,1.5,2.5],
                        field_color = gray,
                        makelist([ key   = concat("soln",k),
                                   color = colors[k],
                                   soln_at(3, 2 + k/20) ],
                                 k,1,5))$



File: maxima.info,  Node: dynamics,  Next: ezunits,  Prev: drawdf,  Up: Top

50 dynamics
***********

* Menu:

* Introduction to dynamics::
* Functions and Variables for dynamics::


File: maxima.info,  Node: Introduction to dynamics,  Next: Functions and Variables for dynamics,  Prev: dynamics,  Up: dynamics

50.1 Introduction to dynamics
=============================

The additional package `dynamics' includes several functions to create
various graphical representations of discrete dynamical systems and
fractals, and an implementation of the Runge-Kutta 4th-order numerical
method for solving systems of differential equations.

   To use the functions in this package you must first load it with
`load("dynamics")'.

   Changes introduced in Maxima 5.12

   Starting with Maxima 5.12, the dynamics package now uses the function
`plot2d' to do the graphs. The commands that produce graphics (with the
exception of `julia' and `mandelbrot') now accept any options of
`plot2d', including the option to change among the various graphical
interfaces, using different plot styles and colors, and representing
one or both axes in a logarithmic scale. The old options <domain>,
<pointsize>, <xcenter>, <xradius>, <ycenter>, <yradius>, <xaxislabel>
and <yaxislabel> are not accepted in this new version.

   All programs will now accept any variables names, and not just <x>
and <y> as in the older versions. Two required parameters have changes
in two of the programs: `evolution2d' now requires a list naming
explicitely the two independent variables, and the horizontal range for
`orbits' no longer requires a step size; the range should only specify
the variable name, and the minimum and maximum values; the number of
steps can now be changed with the option <nticks>.


File: maxima.info,  Node: Functions and Variables for dynamics,  Prev: Introduction to dynamics,  Up: dynamics

50.2 Functions and Variables for dynamics
=========================================

 -- Function: chaosgame (`[['<x1>, <y1>`]'...`['<xm>, <ym>`]]',
          `['<x0>, <y0>`]', <b>, <n>, ..., options, ...);
     Implements the so-called chaos game: the initial point (<x0>,
     <y0>) is plotted and then one of the <m> points `['<x1>,
     <y1>`]'...`['<xm>, <ym>`]' will be selected at random. The next
     point plotted will be on the segment from the previous point
     plotted to the point chosen randomly, at a distance from the
     random point which will be <b> times that segment's length. The
     procedure is repeated <n> times.


 -- Function: evolution (<F>, <y0>, <n>, ..., options, ...);
     Draws <n+1> points in a two-dimensional graph, where the horizontal
     coordinates of the points are the integers 0, 1, 2, ..., <n>, and
     the vertical coordinates are the corresponding values <y(n)> of the
     sequence defined by the recurrence relation
                  y(n+1) = F(y(n))

     With initial value <y(0)> equal to <y0>. <F> must be an expression
     that depends only on one variable (in the example, it depend on
     <y>, but any other variable can be used), <y0> must be a real
     number and <n> must be a positive integer.


 -- Function: evolution2d (`['<F>, <G>`]', `['<u>, <v>`]', `['<u0>,
          <y0>`]', <n>, ..., options, ...);
     Shows, in a two-dimensional plot, the first <n+1> points in the
     sequence of points defined by the two-dimensional discrete
     dynamical system with recurrence relations
                  u(n+1) = F(u(n), v(n))    v(n+1) = G(u(n), v(n))

     With initial values <u0> and <v0>. <F> and <G> must be two
     expressions that depend only on two variables, <u> and <v>, which
     must be named explicitely in a list.


 -- Function: ifs (`['<r1>, ..., <rm>`]', `['<A1>, ..., <Am>`]',
          `[['<x1>, <y1>`]', ..., `['<xm>, <ym>`]]', `['<x0>, <y0>`]',
          <n>, ..., options, ...);
     Implements the Iterated Function System method. This method is
     similar to the method described in the function `chaosgame', but
     instead of shrinking the segment from the current point to the
     randomly chosen point, the 2 components of that segment will be
     multiplied by the 2 by 2 matrix <Ai> that corresponds to the point
     chosen randomly.

     The random choice of one of the <m> attractive points can be made
     with a non-uniform probability distribution defined by the weights
     <r1>,...,<rm>. Those weights are given in cumulative form; for
     instance if there are 3 points with probabilities 0.2, 0.5 and
     0.3, the weights <r1>, <r2> and <r3> could be 2, 7 and 10.


 -- Function: julia (<x>, <y>, ...<options>...)
     Creates a graphics file with the representation of the Julia set
     for the complex number (<x> + i <y>). The parameters <x> and <y>
     must be real. The file is created in the current directory or in
     the user's directory, using the XPM graphics format. The program
     may take several seconds to run and after it is finished, a
     message will be printed with the name of the file created.

     The points which do not belong to the Julia set are assigned
     different colors, according to the number of iterations it takes
     the sequence starting at that point to move out of the convergence
     circle of radius 2. The maximum number of iterations is set with
     the option <levels>; after that number of iterations, if the
     sequence is still inside the convergence circle, the point will be
     painted with the color defined by the option <color>.

     All the colors used for the points that do not belong to the Julia
     set will have the same <saturation> and <value>, but with different
     hue angles distributed uniformly between <hue> and (<hue> +
     <huerange>).

     <options> is an optional sequence of options. The list of accepted
     options is given in a section below.


 -- Function: mandelbrot (<options>)
     Creates a graphics file with the representation of the Mandelbrot
     set. The file is created in the current directory or in the user's
     directory, using the XPM graphics format. The program may take
     several seconds to run and after it is finished, a message will be
     printed with the name of the file created.

     The points which do not belong to the Mandelbrot set are assigned
     different colors, according to the number of iterations it takes
     the sequence generated with that point to move out of the
     convergence circle o radius 2. The maximum number of iterations is
     set with the option <levels>; after that number of iterations, if
     the sequence is still inside the convergence circle, the point
     will be painted with the color defined by the option <color>.

     All the colors used for the points that do not belong to the
     Mandelbrot set will have the same <saturation> and <value>, but
     with different hue angles distributed uniformly between <hue> and
     (<hue> + <huerange>).

     <options> is an optional sequence of options. The list of accepted
     options is given in a section below.


 -- Function: orbits (<F>, <y0>, <n1>, <n2>, [<x>, <x0>, <xf>,
          <xstep>], ...options...);
     Draws the orbits diagram for a family of one-dimensional discrete
     dynamical systems, with one parameter <x>; that kind of diagram is
     used to study the bifurcations of a one-dimensional discrete
     system.

     The function <F(y)> defines a sequence with a starting value of
     <y0>, as in the case of the function `evolution', but in this case
     that function will also depend on a parameter <x> that will take
     values in the interval from <x0> to <xf> with increments of
     <xstep>. Each value used for the parameter <x> is shown on the
     horizontal axis. The vertical axis will show the <n2> values of
     the sequence <y(n1+1)>,..., <y(n1+n2+1)> obtained after letting
     the sequence evolve <n1> iterations.


 -- Function: staircase (<F>, <y0>, <n>, ...options...);
     Draws a staircase diagram for the sequence defined by the
     recurrence relation
                  y(n+1) = F(y(n))

     The interpretation and allowed values of the input parameters is
     the same as for the function `evolution'. A staircase diagram
     consists of a plot of the function <F(y)>, together with the line
     <G(y)> `=' <y>. A vertical segment is drawn from the point (<y0>,
     <y0>) on that line until the point where it intersects the
     function <F>. From that point a horizontal segment is drawn until
     it reaches the point (<y1>, <y1>) on the line, and the procedure
     is repeated <n> times until the point (<yn>, <yn>) is reached.


   Options

   Each option is a list of two or more items. The first item is the
name of the option, and the remainder comprises the arguments for the
option.

   The options accepted by the functions `evolution', `evolution2d',
`staircase', `orbits', `ifs' and `chaosgame' are the same as the
options for `plot2d'. In addition to those options, `orbits' accepts and
extra option <pixels> that sets up the maximum number of different
points that will be represented in the vertical direction.

   The following options are accepted by the functions `julia' and
`mandelbrot':

   * "size" takes either one or two arguments. If only one argument is
     given, the width and height of the graphic file created will be
     equal to that value, in pixels. If two arguments are given, they
     will define the width and height. The default value is 400 pixels
     for both the width and height. If the two values are not equal,
     the set will appear distorted.

   * "levels" defines the maximum number of iterations, which is also
     equal to the number of colors used for points not belonging to the
     set. The default value is 12; larger values mean much longer
     processing times.

   * "huerange" defines the range of hue angles used for the hue of
     points not belonging to the set. The default value is 360, which
     means that the colors will expand all the range of hues. Values
     bigger than 360, will mean repeated ranges of the hue, and negative
     values can be used to make the hue angle decrease as the number of
     iterations increases.

   * "hue" sets the hue, in degrees, of the first color used for the
     points which do not belong to the set. Its default value is 300
     degrees, which corresponds to magenta; the values for other
     standard colors are 0 for red, 45 for orange, 60 for yellow, 120
     for green, 180 for cyan and 240 for blue. See also option
     <huerange>.

   * "saturation" sets the value of the saturation used for points not
     belonging to the set. It must be between 0 and 1. The default is
     0.46.

   * "value" sets the value of the colors used for points not belonging
     to the set. It must be between 0 and 1; the higher the value, the
     brighter the colors. The default is 0.96

   * "color" must be followed by three parameters that define the hue,
     saturation and value, for the color used to represent the points
     of the set. The default value is 0 for the three parameters, which
     corresponds to black. For an explanation of the range of allowed
     values, see options <hue>, <saturation> and <value>.

   * "center" must be followed by two real parameters, which give the
     coordinates, on the complex plane, of the point in the center of
     the region shown. The default value is 0 for both coordinates (the
     origin).

   * "radius" sets the radius of the biggest circle inside the square
     region that will be displayed. The default value is 2.

   * "filename" gives the name of the file where the resulting graph
     will be saved. The extension .xpm will be added to that name. If
     the file already exists, it will be replaced by the file generated
     by the function. The default values are julia for the Julia set,
     and mandelbrot for the Mandelbrot set.


   Examples

   Graphical representation and staircase diagram for the sequence: 2,
cos(2), cos(cos(2)),...

     (%i1) load("dynamics")$

     (%i2) evolution(cos(y), 2, 11);

     (%i3) staircase(cos(y), 1, 11, [y, 0, 1.2]);

   If your system is slow, you'll have to reduce the number of
iterations in the following examples. And if the dots appear too small
in your monitor, you might want to try a different style, such as
`['<style>,`['<points>,0.8`]]'.

   Orbits diagram for the quadratic map, with a parameter <a>.
             x(n+1) = a + x(n)^2

     (%i4) orbits(x^2+a, 0, 50, 200, [a, -2, 0.25], [style, dots]);

   To enlarge the region around the lower bifurcation near x `=' -1.25
use:
     (%i5) orbits(x^2+a, 0, 100, 400, [a,-1,-1.53], [x,-1.6,-0.8],
                  [nticks, 400], [style,dots]);

   Evolution of a two-dimensional system that leads to a fractal:

     (%i6) f: 0.6*x*(1+2*x)+0.8*y*(x-1)-y^2-0.9$

     (%i7) g: 0.1*x*(1-6*x+4*y)+0.1*y*(1+9*y)-0.4$

     (%i8) evolution2d([f,g], [x,y], [-0.5,0], 50000, [style,dots]);

   And an enlargement of a small region in that fractal:

     (%i9) evolution2d([f,g], [x,y], [-0.5,0], 300000, [x,-0.8,-0.6],
                       [y,-0.4,-0.2], [style, dots]);

   A plot of Sierpinsky's triangle, obtained with the chaos game:

     (%i9) chaosgame([[0, 0], [1, 0], [0.5, sqrt(3)/2]], [0.1, 0.1], 1/2,
                      30000, [style, dots]);

   Barnsley's fern, obtained with an Iterated Function System:

     (%i10) a1: matrix([0.85,0.04],[-0.04,0.85])$

     (%i11) a2: matrix([0.2,-0.26],[0.23,0.22])$

     (%i12) a3: matrix([-0.15,0.28],[0.26,0.24])$

     (%i13) a4: matrix([0,0],[0,0.16])$

     (%i14) p1: [0,1.6]$

     (%i15) p2: [0,1.6]$

     (%i16) p3: [0,0.44]$

     (%i17) p4: [0,0]$

     (%i18) w: [85,92,99,100]$

     (%i19) ifs(w, [a1,a2,a3,a4], [p1,p2,p3,p4], [5,0], 50000, [style,dots]);

   To create a file named _dynamics9.xpm_ with a graphical
representation of the Mandelbrot set, with 12 colors, use:

     mandelbrot([filename,"dynamics9"])$

   and the Julia set for the number (-0.55 + i 0.6) can be obtained
with:
     julia(-0.55, 0.6, [levels, 36], [center, 0, 0.6], [radius, 0.3],
           [hue, 240], [huerange, -180], [filename, "dynamics10"])$

   the graph will be saved in the file _dynamics10.xpm_ and will show
the region from -0.3 to 0.3 in the x direction, and from 0.3 to 0.9 in
the y direction. 36 colors will be used, starting with blue and ending
with yellow.


File: maxima.info,  Node: ezunits,  Next: f90,  Prev: dynamics,  Up: Top

51 ezunits
**********

* Menu:

* Introduction to ezunits::
* Introduction to physical_constants::
* Functions and Variables for ezunits::


File: maxima.info,  Node: Introduction to ezunits,  Next: Introduction to physical_constants,  Prev: ezunits,  Up: ezunits

51.1 Introduction to ezunits
============================

`ezunits' is a package for working with dimensional quantities,
including some functions for dimensional analysis.  `ezunits' can carry
out arithmetic operations on dimensional quantities and unit
conversions.  The built-in units include Systeme Internationale (SI)
and US customary units, and other units can be declared.  See also
`physical_constants', a collection of physical constants.

   `load(ezunits)' loads this package.  `demo(ezunits)' displays
several examples.  The convenience function `known_units' returns a
list of the built-in and user-declared units, while
`display_known_unit_conversions' displays the set of known conversions
in an easy-to-read format.

   An expression a ` b represents a dimensional quantity, with `a'
indicating a nondimensional quantity and `b' indicating the dimensional
units.  A symbol can be used as a unit without declaring it as such;
unit symbols need not have any special properties.  The quantity and
unit of an expression a ` b can be extracted by the `qty' and `units'
functions, respectively.

   A symbol may be declared to be a dimensional quantity, with
specified quantity or specified units or both.

   An expression a ` b `` c converts from unit `b' to unit `c'.
`ezunits' has built-in conversions for SI base units, SI derived units,
and some non-SI units.  Unit conversions not already known to `ezunits'
can be declared.  The unit conversions known to `ezunits' are specified
by the global variable `known_unit_conversions', which comprises
built-in and user-defined conversions.  Conversions for products,
quotients, and powers of units are derived from the set of known unit
conversions.

   As Maxima generally prefers exact numbers (integers or rationals) to
inexact (float or bigfloat), so `ezunits' preserves exact numbers when
they appear in dimensional quantities.  All built-in unit conversions
are expressed in terms of exact numbers; inexact numbers in declared
conversions are coerced to exact.

   There is no preferred system for display of units; input units are
not converted to other units unless conversion is explicitly indicated.
`ezunits' recognizes the prefixes m-, k-, M, and G- (for milli-, kilo-,
mega-, and giga-) as applied to SI base units and SI derived units, but
such prefixes are applied only when indicated by an explicit conversion.

   Arithmetic operations on dimensional quantities are carried out by
conventional rules for such operations.

   * (x ` a) * (y ` b) is equal to (x * y) ` (a * b).

   * (x ` a) + (y ` a) is equal to (x + y) ` a.

   * (x ` a)^y is equal to x^y ` a^y when `y' is nondimensional.

   `ezunits' does not require that units in a sum have the same
dimensions; such terms are not added together, and no error is reported.

   `ezunits' includes functions for elementary dimensional analysis,
namely the fundamental dimensions and fundamental units of a
dimensional quantity, and computation of dimensionless quantities and
natural units.  The functions for dimensional analysis were adapted
from similar functions in another package, written by Barton Willis.

   For the purpose of dimensional analysis, a list of fundamental
dimensions and an associated list of fundamental units are maintained;
by default the fundamental dimensions are length, mass, time, charge,
temperature, and quantity, and the fundamental units are the associated
SI units, but other fundamental dimensions and units can be declared.


File: maxima.info,  Node: Introduction to physical_constants,  Next: Functions and Variables for ezunits,  Prev: Introduction to ezunits,  Up: ezunits

51.2 Introduction to physical_constants
=======================================

`physical_constants' is a collection of physical constants, copied from
CODATA 2006 recommended values. [1] `load(physical_constants)' loads
this package, and loads `ezunits' also, if it is not already loaded.

   A physical constant is represented as a symbol which has a property
which is the constant value.  The constant value is a dimensional
quantity, as represented by `ezunits'.  The function `constvalue'
fetches the constant value; the constant value is not the ordinary
value of the symbol, so symbols of physical constants persist in
evaluated expressions until their values are fetched by `constvalue'.

   `physical_constants' includes some auxilliary information, namely, a
description string for each constant, an estimate of the error of its
numerical value, and a property for TeX display.  To identify physical
constants, each symbol has the `physical_constant' property;
`propvars(physical_constant)' therefore shows the list of all such
symbols.

   `physical_constants' comprises the following constants.

`%c'
     speed of light in vacuum

`%mu_0'
     magnetic constant

`%e_0'
     electric constant

`%Z_0'
     characteristic impedance of vacuum

`%G'
     Newtonian constant of gravitation

`%h'
     Planck constant

`%h_bar'
     Planck constant

`%m_P'
     Planck mass

`%T_P'
     Planck temperature

`%l_P'
     Planck length

`%t_P'
     Planck time

`%%e'
     elementary charge

`%Phi_0'
     magnetic flux quantum

`%G_0'
     conductance quantum

`%K_J'
     Josephson constant

`%R_K'
     von Klitzing constant

`%mu_B'
     Bohr magneton

`%mu_N'
     nuclear magneton

`%alpha'
     fine-structure constant

`%R_inf'
     Rydberg constant

`%a_0'
     Bohr radius

`%E_h'
     Hartree energy

`%ratio_h_me'
     quantum of circulation

`%m_e'
     electron mass

`%N_A'
     Avogadro constant

`%m_u'
     atomic mass constant

`%F'
     Faraday constant

`%R'
     molar gas constant

`%%k'
     Boltzmann constant

`%V_m'
     molar volume of ideal gas

`%n_0'
     Loschmidt constant

`%ratio_S0_R'
     Sackur-Tetrode constant (absolute entropy constant)

`%sigma'
     Stefan-Boltzmann constant

`%c_1'
     first radiation constant

`%c_1L'
     first radiation constant for spectral radiance

`%c_2'
     second radiation constant

`%b'
     Wien displacement law constant

`%b_prime'
     Wien displacement law constant

   References:

   [1] `http://physics.nist.gov/constants'

   Examples:

   The list of all symbols which have the `physical_constant' property.

     (%i1) load (physical_constants)$
     (%i2) propvars (physical_constant);
     (%o2) [%c, %mu_0, %e_0, %Z_0, %G, %h, %h_bar, %m_P, %T_P, %l_P,
     %t_P, %%e, %Phi_0, %G_0, %K_J, %R_K, %mu_B, %mu_N, %alpha,
     %R_inf, %a_0, %E_h, %ratio_h_me, %m_e, %N_A, %m_u, %F, %R, %%k,
     %V_m, %n_0, %ratio_S0_R, %sigma, %c_1, %c_1L, %c_2, %b, %b_prime]

   Properties of the physical constant `%c'.

     (%i1) load (physical_constants)$
     (%i2) constantp (%c);
     (%o2)                         true
     (%i3) get (%c, description);
     (%o3)               speed of light in vacuum
     (%i4) constvalue (%c);
                                           m
     (%o4)                     299792458 ` -
                                           s
     (%i5) get (%c, RSU);
     (%o5)                           0
     (%i6) tex (%c);
     $$c$$
     (%o6)                         false

   The energy equivalent of 1 pound-mass.  The symbol `%c' persists
until its value is fetched by `constvalue'.

     (%i1) load (physical_constants)$
     (%i2) m * %c^2;
                                     2
     (%o2)                         %c  m
     (%i3) %, m = 1 ` lbm;
                                   2
     (%o3)                       %c  ` lbm
     (%i4) constvalue (%);
                                                 2
                                            lbm m
     (%o4)              89875517873681764 ` ------
                                               2
                                              s
     (%i5) E : % `` J;
     Computing conversions to base units; may take a moment.
                          366838848464007200
     (%o5)                ------------------ ` J
                                  9
     (%i6) E `` GJ;
                           458548560580009
     (%o6)                 --------------- ` GJ
                              11250000
     (%i7) float (%);
     (%o7)              4.0759872051556356e+7 ` GJ


File: maxima.info,  Node: Functions and Variables for ezunits,  Prev: Introduction to physical_constants,  Up: ezunits

51.3 Functions and Variables for ezunits
========================================

 -- Operator: `
     The dimensional quantity operator.  An expression a ` b represents
     a dimensional quantity, with `a' indicating a nondimensional
     quantity and `b' indicating the dimensional units.  A symbol can
     be used as a unit without declaring it as such; unit symbols need
     not have any special properties.  The quantity and unit of an
     expression a ` b can be extracted by the `qty' and `units'
     functions, respectively.

     Arithmetic operations on dimensional quantities are carried out by
     conventional rules for such operations.

        * (x ` a) * (y ` b) is equal to (x * y) ` (a * b).

        * (x ` a) + (y ` a) is equal to (x + y) ` a.

        * (x ` a)^y is equal to x^y ` a^y when `y' is nondimensional.

     `ezunits' does not require that units in a sum have the same
     dimensions; such terms are not added together, and no error is
     reported.

     `load(ezunits)' enables this operator.

     Examples:

     SI (Systeme Internationale) units.

          (%i1) load (ezunits)$
          (%i2) foo : 10 ` m;
          (%o2)                        10 ` m
          (%i3) qty (foo);
          (%o3)                          10
          (%i4) units (foo);
          (%o4)                           m
          (%i5) dimensions (foo);
          (%o5)                        length

     "Customary" units.

          (%i1) load (ezunits)$
          (%i2) bar : x ` acre;
          (%o2)                       x ` acre
          (%i3) dimensions (bar);
                                             2
          (%o3)                        length
          (%i4) fundamental_units (bar);
                                          2
          (%o4)                          m

     Units ad hoc.

          (%i1) load (ezunits)$
          (%i2) baz : 3 ` sheep + 8 ` goat + 1 ` horse;
          (%o2)           8 ` goat + 3 ` sheep + 1 ` horse
          (%i3) subst ([sheep = 3*goat, horse = 10*goat], baz);
          (%o3)                       27 ` goat
          (%i4) baz2 : 1000`gallon/fortnight;
                                          gallon
          (%o4)                   1000 ` ---------
                                         fortnight
          (%i5) subst (fortnight = 14*day, baz2);
                                    500   gallon
          (%o5)                     --- ` ------
                                     7     day

     Arithmetic operations on dimensional quantities.

          (%i1) load (ezunits)$
          (%i2) 100 ` kg + 200 ` kg;
          (%o2)                       300 ` kg
          (%i3) 100 ` m^3 - 100 ` m^3;
                                            3
          (%o3)                        0 ` m
          (%i4) (10 ` kg) * (17 ` m/s^2);
                                           kg m
          (%o4)                      170 ` ----
                                             2
                                            s
          (%i5) (x ` m) / (y ` s);
                                        x   m
          (%o5)                         - ` -
                                        y   s
          (%i6) (a ` m)^2;
                                        2    2
          (%o6)                        a  ` m


 -- Operator: ``
     The unit conversion operator.  An expression a ` b `` c converts
     from unit `b' to unit `c'.  `ezunits' has built-in conversions for
     SI base units, SI derived units, and some non-SI units.  Unit
     conversions not already known to `ezunits' can be declared.  The
     unit conversions known to `ezunits' are specified by the global
     variable `known_unit_conversions', which comprises built-in and
     user-defined conversions.  Conversions for products, quotients,
     and powers of units are derived from the set of known unit
     conversions.

     There is no preferred system for display of units; input units are
     not converted to other units unless conversion is explicitly
     indicated.  `ezunits' does not attempt to simplify units by
     prefixes (milli-, centi-, deci-, etc) unless such conversion is
     explicitly indicated.

     `load(ezunits)' enables this operator.

     Examples:

     The set of known unit conversions.

          (%i1) load (ezunits)$
          (%i2) display2d : false$
          (%i3) known_unit_conversions;
          (%o3) {acre = 4840*yard^2,Btu = 1055*J,cfm = feet^3/minute,
                 cm = m/100,day = 86400*s,feet = 381*m/1250,ft = feet,
                 g = kg/1000,gallon = 757*l/200,GHz = 1000000000*Hz,
                 GOhm = 1000000000*Ohm,GPa = 1000000000*Pa,
                 GWb = 1000000000*Wb,Gg = 1000000*kg,Gm = 1000000000*m,
                 Gmol = 1000000*mol,Gs = 1000000000*s,ha = hectare,
                 hectare = 100*m^2,hour = 3600*s,Hz = 1/s,inch = feet/12,
                 km = 1000*m,kmol = 1000*mol,ks = 1000*s,l = liter,
                 lbf = pound_force,lbm = pound_mass,liter = m^3/1000,
                 metric_ton = Mg,mg = kg/1000000,MHz = 1000000*Hz,
                 microgram = kg/1000000000,micrometer = m/1000000,
                 micron = micrometer,microsecond = s/1000000,
                 mile = 5280*feet,minute = 60*s,mm = m/1000,
                 mmol = mol/1000,month = 2629800*s,MOhm = 1000000*Ohm,
                 MPa = 1000000*Pa,ms = s/1000,MWb = 1000000*Wb,
                 Mg = 1000*kg,Mm = 1000000*m,Mmol = 1000000000*mol,
                 Ms = 1000000*s,ns = s/1000000000,ounce = pound_mass/16,
                 oz = ounce,Ohm = s*J/C^2,
                 pound_force = 32*ft*pound_mass/s^2,
                 pound_mass = 200*kg/441,psi = pound_force/inch^2,
                 Pa = N/m^2,week = 604800*s,Wb = J/A,yard = 3*feet,
                 year = 31557600*s,C = s*A,F = C^2/J,GA = 1000000000*A,
                 GC = 1000000000*C,GF = 1000000000*F,GH = 1000000000*H,
                 GJ = 1000000000*J,GK = 1000000000*K,GN = 1000000000*N,
                 GS = 1000000000*S,GT = 1000000000*T,GV = 1000000000*V,
                 GW = 1000000000*W,H = J/A^2,J = m*N,kA = 1000*A,
                 kC = 1000*C,kF = 1000*F,kH = 1000*H,kHz = 1000*Hz,
                 kJ = 1000*J,kK = 1000*K,kN = 1000*N,kOhm = 1000*Ohm,
                 kPa = 1000*Pa,kS = 1000*S,kT = 1000*T,kV = 1000*V,
                 kW = 1000*W,kWb = 1000*Wb,mA = A/1000,mC = C/1000,
                 mF = F/1000,mH = H/1000,mHz = Hz/1000,mJ = J/1000,
                 mK = K/1000,mN = N/1000,mOhm = Ohm/1000,mPa = Pa/1000,
                 mS = S/1000,mT = T/1000,mV = V/1000,mW = W/1000,
                 mWb = Wb/1000,MA = 1000000*A,MC = 1000000*C,
                 MF = 1000000*F,MH = 1000000*H,MJ = 1000000*J,
                 MK = 1000000*K,MN = 1000000*N,MS = 1000000*S,
                 MT = 1000000*T,MV = 1000000*V,MW = 1000000*W,
                 N = kg*m/s^2,R = 5*K/9,S = 1/Ohm,T = J/(m^2*A),V = J/C,
                 W = J/s}

     Elementary unit conversions.

          (%i1) load (ezunits)$
          (%i2) 1 ` ft `` m;
          Computing conversions to base units; may take a moment.
                                      381
          (%o2)                       ---- ` m
                                      1250
          (%i3) %, numer;
          (%o3)                      0.3048 ` m
          (%i4) 1 ` kg `` lbm;
                                      441
          (%o4)                       --- ` lbm
                                      200
          (%i5) %, numer;
          (%o5)                      2.205 ` lbm
          (%i6) 1 ` W `` Btu/hour;
                                     720   Btu
          (%o6)                      --- ` ----
                                     211   hour
          (%i7) %, numer;
                                                  Btu
          (%o7)               3.412322274881517 ` ----
                                                  hour
          (%i8) 100 ` degC `` degF;
          (%o8)                      212 ` degF
          (%i9) -40 ` degF `` degC;
          (%o9)                     (- 40) ` degC
          (%i10) 1 ` acre*ft `` m^3;
                                  60228605349    3
          (%o10)                  ----------- ` m
                                   48828125
          (%i11) %, numer;
                                                    3
          (%o11)                1233.48183754752 ` m

     Coercing quantities in feet and meters to one or the other.

          (%i1) load (ezunits)$
          (%i2) 100 ` m + 100 ` ft;
          (%o2)                  100 ` m + 100 ` ft
          (%i3) (100 ` m + 100 ` ft) `` ft;
          Computing conversions to base units; may take a moment.
                                     163100
          (%o3)                      ------ ` ft
                                      381
          (%i4) %, numer;
          (%o4)                428.0839895013123 ` ft
          (%i5) (100 ` m + 100 ` ft) `` m;
                                      3262
          (%o5)                       ---- ` m
                                       25
          (%i6) %, numer;
          (%o6)                      130.48 ` m

     Dimensional analysis to find fundamental dimensions and
     fundamental units.

          (%i1) load (ezunits)$
          (%i2) foo : 1 ` acre * ft;
          (%o2)                      1 ` acre ft
          (%i3) dimensions (foo);
                                             3
          (%o3)                        length
          (%i4) fundamental_units (foo);
                                          3
          (%o4)                          m
          (%i5) foo `` m^3;
          Computing conversions to base units; may take a moment.
                                  60228605349    3
          (%o5)                   ----------- ` m
                                   48828125
          (%i6) %, numer;
                                                    3
          (%o6)                 1233.48183754752 ` m

     Declared unit conversions.

          (%i1) load (ezunits)$
          (%i2) declare_unit_conversion (MMBtu = 10^6*Btu, kW = 1000*W);
          (%o2)                         done
          (%i3) declare_unit_conversion (kWh = kW*hour, MWh = 1000*kWh,
                                         bell = 1800*s);
          (%o3)                         done
          (%i4) 1 ` kW*s `` MWh;
          Computing conversions to base units; may take a moment.
                                       1
          (%o4)                     ------- ` MWh
                                    3600000
          (%i5) 1 ` kW/m^2 `` MMBtu/bell/ft^2;
                                 1306449      MMBtu
          (%o5)                 ---------- ` --------
                                8242187500          2
                                             bell ft


 -- Function: constvalue (<x>)
 -- Function: declare_constvalue (<a>, <x>)
 -- Function: remove_constvalue (<a>)
     Returns the declared constant value of a symbol, or value of an
     expression with declared constant values substituted for symbols.

     Constant values are declared by `declare_constvalue'.  Note that
     constant values as recognized by `constvalue' are separate from
     values declared by `numerval' and recognized by `constantp'.

     The `physical_units' package declares constant values for a number
     of physical constants.

     `remove_constvalue' reverts the effect of `declare_constvalue'.

     `load(ezunits)' loads these functions.

     Examples:

     Constant value of a physical constant.

          (%i1) load (physical_constants)$
          (%i2) constvalue (%G);
                                               3
                                              m
          (%o2)                    6.67428 ` -----
                                                 2
                                             kg s
          (%i3) get ('%G, 'description);
          (%o3)           Newtonian constant of gravitation

     Declaring a new constant.

          (%i1) load (ezunits)$
          (%i2) declare_constvalue (FOO, 100 ` lbm / acre);
                                           lbm
          (%o2)                      100 ` ----
                                           acre
          (%i3) FOO * (50 ` acre);
          (%o3)                     50 FOO ` acre
          (%i4) constvalue (%);
          (%o4)                      5000 ` lbm


 -- Function: units (<x>)
 -- Function: declare_units (<a>, <u>)
     Returns the units of a dimensional quantity <x>, or returns 1 if
     <x> is nondimensional.

     <x> may be a literal dimensional expression a ` b, a symbol with
     declared units via `declare_units', or an expression containing
     either or both of those.

     `declare_units' declares that `units(<a>)' should return <u>,
     where <u> is an expression.

     `load(ezunits)' loads these functions.

     Examples:

     `units' applied to literal dimensional expressions.

          (%i1) load (ezunits)$
          (%i2) foo : 100 ` kg;
          (%o2)                       100 ` kg
          (%i3) bar : x ` m/s;
                                            m
          (%o3)                         x ` -
                                            s
          (%i4) units (foo);
          (%o4)                          kg
          (%i5) units (bar);
                                          m
          (%o5)                           -
                                          s
          (%i6) units (foo * bar);
                                        kg m
          (%o6)                         ----
                                         s
          (%i7) units (foo / bar);
                                        kg s
          (%o7)                         ----
                                         m
          (%i8) units (foo^2);
                                           2
          (%o8)                          kg

     `units' applied to symbols with declared units.

          (%i1) load (ezunits)$
          (%i2) units (aa);
          (%o2)                           1
          (%i3) declare_units (aa, J);
          (%o3)                           J
          (%i4) units (aa);
          (%o4)                           J
          (%i5) units (aa^2);
                                          2
          (%o5)                          J
          (%i6) foo : 100 ` kg;
          (%o6)                       100 ` kg
          (%i7) units (aa * foo);
          (%o7)                         kg J


 -- Function: qty (<x>)
 -- Function: declare_qty (<a>, <x>)
     `qty' returns the nondimensional part of a dimensional quantity
     <x>, or returns <x> if <x> is nondimensional.  <x> may be a
     literal dimensional expression a ` b, a symbol with declared
     quantity, or an expression containing either or both of those.

     `declare_qty' declares that `qty(<a>)' should return <x>, where
     <x> is a nondimensional quantity.

     `load(ezunits)' loads these functions.

     Examples:

     `qty' applied to literal dimensional expressions.

          (%i1) load (ezunits)$
          (%i2) foo : 100 ` kg;
          (%o2)                       100 ` kg
          (%i3) qty (foo);
          (%o3)                          100
          (%i4) bar : v ` m/s;
                                            m
          (%o4)                         v ` -
                                            s
          (%i5) foo * bar;
                                            kg m
          (%o5)                     100 v ` ----
                                             s
          (%i6) qty (foo * bar);
          (%o6)                         100 v

     `qty' applied to symbols with declared quantity.

          (%i1) load (ezunits)$
          (%i2) declare_qty (aa, xx);
          (%o2)                          xx
          (%i3) qty (aa);
          (%o3)                          xx
          (%i4) qty (aa^2);
                                           2
          (%o4)                          xx
          (%i5) foo : 100 ` kg;
          (%o5)                       100 ` kg
          (%i6) qty (aa * foo);
          (%o6)                        100 xx


 -- Function: unitp (<x>)
     Returns `true' if <x> is a literal dimensional expression, a
     symbol declared dimensional, or an expression in which the main
     operator is declared dimensional.  `unitp' returns `false'
     otherwise.

     `load(ezunits)' loads this function.

     Examples:

     `unitp' applied to a literal dimensional expression.

          (%i1) load (ezunits)$
          (%i2) unitp (100 ` kg);
          (%o2)                         true

     `unitp' applied to a symbol declared dimensional.

          (%i1) load (ezunits)$
          (%i2) unitp (foo);
          (%o2)                         false
          (%i3) declare (foo, dimensional);
          (%o3)                         done
          (%i4) unitp (foo);
          (%o4)                         true

     `unitp' applied to an expression in which the main operator is
     declared dimensional.

          (%i1) load (ezunits)$
          (%i2) unitp (bar (x, y, z));
          (%o2)                         false
          (%i3) declare (bar, dimensional);
          (%o3)                         done
          (%i4) unitp (bar (x, y, z));
          (%o4)                         true


 -- Function: declare_unit_conversion (<u> = <v>, ...)
     Appends equations <u> = <v>, ... to the list of unit conversions
     known to the unit conversion operator ``.  <u> and <v> are both
     multiplicative terms, in which any variables are units, or both
     literal dimensional expressions.

     At present, it is necessary to express conversions such that the
     left-hand side of each equation is a simple unit (not a
     multiplicative expression) or a literal dimensional expression
     with the quantity equal to 1 and the unit being a simple unit.
     This limitation might be relaxed in future versions.

     `known_unit_conversions' is the list of known unit conversions.

     `load(ezunits)' loads this function.

     Examples:

     Unit conversions expressed by equations of multiplicative terms.

          (%i1) load (ezunits)$
          (%i2) declare_unit_conversion (nautical_mile = 1852 * m,
                                         fortnight = 14 * day);
          (%o2)                         done
          (%i3) 100 ` nautical_mile / fortnight `` m/s;
          Computing conversions to base units; may take a moment.
                                      463    m
          (%o3)                       ---- ` -
                                      3024   s

     Unit conversions expressed by equations of literal dimensional
     expressions.

          (%i1) load (ezunits)$
          (%i2) declare_unit_conversion (1 ` fluid_ounce = 2 ` tablespoon);
          (%o2)                         done
          (%i3) declare_unit_conversion (1 ` tablespoon = 3 ` teaspoon);
          (%o3)                         done
          (%i4) 15 ` fluid_ounce `` teaspoon;
          Computing conversions to base units; may take a moment.
          (%o4)                     90 ` teaspoon


 -- Function: declare_dimensions (<a_1>, <d_1>, ..., <a_n>, <d_n>)
 -- Function: remove_dimensions (<a_1>, ..., <a_n>)
     `declare_dimensions' declares <a_1>, ..., <a_n> to have dimensions
     <d_1>, ..., <d_n>, respectively.

     Each <a_k> is a symbol or a list of symbols.  If it is a list,
     then every symbol in <a_k> is declared to have dimension <d_k>.

     `remove_dimensions' reverts the effect of `declare_dimensions'.

     `load(ezunits)' loads these functions.

     Examples:

          (%i1) load (ezunits) $
          (%i2) declare_dimensions ([x, y, z], length, [t, u], time);
          (%o2)                         done
          (%i3) dimensions (y^2/u);
                                             2
                                       length
          (%o3)                        -------
                                        time
          (%i4) fundamental_units (y^2/u);
          0 errors, 0 warnings
                                          2
                                         m
          (%o4)                          --
                                         s


 -- Function: declare_fundamental_dimensions (<d_1>, <d_2>, <d_3>, ...)
 -- Function: remove_fundamental_dimensions (<d_1>, <d_2>, <d_3>, ...)
 -- Global variable: fundamental_dimensions
     `declare_fundamental_dimensions' declares fundamental dimensions.
     Symbols <d_1>, <d_2>, <d_3>, ... are appended to the list of
     fundamental dimensions, if they are not already on the list.

     `remove_fundamental_dimensions' reverts the effect of
     `declare_fundamental_dimensions'.

     `fundamental_dimensions' is the list of fundamental dimensions.
     By default, the list comprises several physical dimensions.

     `load(ezunits)' loads these functions.

     Examples:

          (%i1) load (ezunits) $
          (%i2) fundamental_dimensions;
          (%o2) [length, mass, time, current, temperature, quantity]
          (%i3) declare_fundamental_dimensions (money, cattle, happiness);
          (%o3)                         done
          (%i4) fundamental_dimensions;
          (%o4) [length, mass, time, current, temperature, quantity,
                                                  money, cattle, happiness]
          (%i5) remove_fundamental_dimensions (cattle, happiness);
          (%o5)                         done
          (%i6) fundamental_dimensions;
          (%o6) [length, mass, time, current, temperature, quantity, money]


 -- Function: declare_fundamental_units (<u_1>, <d_1>, ..., <u_n>,
          <d_n>)
 -- Function: remove_fundamental_units (<u_1>, ..., <u_n>)
     `declare_fundamental_units' declares <u_1>, ..., <u_n> to have
     dimensions <d_1>, ..., <d_n>, respectively.  All arguments must be
     symbols.

     After calling `declare_fundamental_units', `dimensions(<u_k>)'
     returns <d_k> for each argument <u_1>, ..., <u_n>, and
     `fundamental_units(<d_k>)' returns <u_k> for each argument <d_1>,
     ..., <d_n>.

     `remove_fundamental_units' reverts the effect of
     `declare_fundamental_units'.

     `load(ezunits)' loads these functions.

     Examples:

          (%i1) load (ezunits) $
          (%i2) declare_fundamental_dimensions (money, cattle, happiness);
          (%o2)                         done
          (%i3) declare_fundamental_units (dollar, money, goat, cattle,
                                           smile, happiness);
          (%o3)                 [dollar, goat, smile]
          (%i4) dimensions (100 ` dollar/goat/km^2);
                                       money
          (%o4)                    --------------
                                                2
                                   cattle length
          (%i5) dimensions (x ` smile/kg);
                                      happiness
          (%o5)                       ---------
                                        mass
          (%i6) fundamental_units (money*cattle/happiness);
          0 errors, 0 warnings
                                     dollar goat
          (%o6)                      -----------
                                        smile


 -- Function: dimensions (<x>)
 -- Function: dimensions_as_list (<x>)
     `dimensions' returns the dimensions of the dimensional quantity <x>
     as an expression comprising products and powers of base dimensions.

     `dimensions_as_list' returns the dimensions of the dimensional
     quantity <x> as a list, in which each element is an integer which
     indicates the power of the corresponding base dimension in the
     dimensions of <x>.

     `load(ezunits)' loads these functions.

     Examples:

          (%i1) load (ezunits)$
          (%i2) dimensions (1000 ` kg*m^2/s^3);
                                          2
                                    length  mass
          (%o2)                     ------------
                                           3
                                       time
          (%i3) declare_units (foo, acre*ft/hour);
                                       acre ft
          (%o3)                        -------
                                        hour
          (%i4) dimensions (foo);
                                             3
                                       length
          (%o4)                        -------
                                        time

          (%i1) load (ezunits)$
          (%i2) fundamental_dimensions;
          (%o2)  [length, mass, time, charge, temperature, quantity]
          (%i3) dimensions_as_list (1000 ` kg*m^2/s^3);
          (%o3)                 [2, 1, - 3, 0, 0, 0]
          (%i4) declare_units (foo, acre*ft/hour);
                                       acre ft
          (%o4)                        -------
                                        hour
          (%i5) dimensions_as_list (foo);
          (%o5)                 [3, 0, - 1, 0, 0, 0]


 -- Function: fundamental_units (<x>)
 -- Function: fundamental_units ()
     `fundamental_units(<x>)' returns the units associated with the
     fundamental dimensions of <x>.  as determined by `dimensions(<x>)'.

     <x> may be a literal dimensional expression a ` b, a symbol with
     declared units via `declare_units', or an expression containing
     either or both of those.

     `fundamental_units()' returns the list of all known fundamental
     units, as declared by `declare_fundamental_units'.

     `load(ezunits)' loads this function.

     Examples:

          (%i1) load (ezunits)$
          (%i2) fundamental_units ();
          (%o2)                 [m, kg, s, A, K, mol]
          (%i3) fundamental_units (100 ` mile/hour);
                                          m
          (%o3)                           -
                                          s
          (%i4) declare_units (aa, g/foot^2);
                                          g
          (%o4)                         -----
                                            2
                                        foot
          (%i5) fundamental_units (aa);
                                         kg
          (%o5)                          --
                                          2
                                         m


 -- Function: dimensionless (<L>)
     Returns a basis for the dimensionless quantities which can be
     formed from a list <L> of dimensional quantities.

     `load(ezunits)' loads this function.

     Examples:

          (%i1) load (ezunits) $
          (%i2) dimensionless ([x ` m, y ` m/s, z ` s]);
          0 errors, 0 warnings
          0 errors, 0 warnings
                                         y z
          (%o2)                         [---]
                                          x

     Dimensionless quantities derived from fundamental physical
     quantities.  Note that the first element on the list is
     proportional to the fine-structure constant.

          (%i1) load (ezunits) $
          (%i2) load (physical_constants) $
          (%i3) dimensionless([%h_bar, %m_e, %m_P, %%e, %c, %e_0]);
          0 errors, 0 warnings
          0 errors, 0 warnings
                                        2
                                     %%e        %m_e
          (%o3)                [--------------, ----]
                                %c %e_0 %h_bar  %m_P


 -- Function: natural_unit (<expr>, [<v_1>, ..., <v_n>])
     Finds exponents <e_1>, ..., <e_n> such that `dimension(<expr>) =
     dimension(<v_1>^<e_1> ... <v_n>^<e_n>)'.

     `load(ezunits)' loads this function.

     Examples:




File: maxima.info,  Node: f90,  Next: finance,  Prev: ezunits,  Up: Top

52 f90
******

* Menu:

* Functions and Variables for f90::


File: maxima.info,  Node: Functions and Variables for f90,  Prev: f90,  Up: f90

52.1 Functions and Variables for f90
====================================

 -- Function: f90 (<expr_1>, ..., <expr_n>)
     Prints one or more expressions <expr_1>, ..., <expr_n> as a
     Fortran 90 program.  Output is printed to the standard output.

     `f90' prints output in the so-called "free form" input format for
     Fortran 90: there is no special attention to column positions.
     Long lines are split at a fixed width with the ampersand `&'
     continuation character.

     `load(f90)' loads this function.  See also the function `fortran'.

     Examples:

          (%i1) load (f90)$
          (%i2) foo : expand ((xxx + yyy + 7)^4);
                   4            3         3        2    2             2
          (%o2) yyy  + 4 xxx yyy  + 28 yyy  + 6 xxx  yyy  + 84 xxx yyy
                    2        3             2
           + 294 yyy  + 4 xxx  yyy + 84 xxx  yyy + 588 xxx yyy + 1372 yyy
                4         3          2
           + xxx  + 28 xxx  + 294 xxx  + 1372 xxx + 2401
          (%i3) f90 ('foo = foo);
          foo = yyy**4+4*xxx*yyy**3+28*yyy**3+6*xxx**2*yyy**2+84*xxx*yyy**2&
          +294*yyy**2+4*xxx**3*yyy+84*xxx**2*yyy+588*xxx*yyy+1372*yyy+xxx**&
          4+28*xxx**3+294*xxx**2+1372*xxx+2401
          (%o3)                         false

     Multiple expressions.  Capture standard output into a file via the
     `with_stdout'  function.

          (%i1) load (f90)$
          (%i2) foo : sin (3*x + 1) - cos (7*x - 2);
          (%o2)              sin(3 x + 1) - cos(7 x - 2)
          (%i3) with_stdout ("foo.f90",
                             f90 (x=0.25, y=0.625, 'foo=foo, 'stop, 'end));
          (%o3)                         false
          (%i4) printfile ("foo.f90");
          x = 0.25
          y = 0.625
          foo = sin(3*x+1)-cos(7*x-2)
          stop
          end
          (%o4)                        foo.f90



File: maxima.info,  Node: finance,  Next: fractals,  Prev: f90,  Up: Top

53 finance
**********

* Menu:

* Introduction to finance::
* Functions and Variables for finance::


File: maxima.info,  Node: Introduction to finance,  Next: Functions and Variables for finance,  Prev: finance,  Up: finance

53.1 Introduction to finance
============================

This is the Finance Package (Ver 0.1).

   In all the functions, <rate> is the compound interest rate, <num> is
the number of periods and must be postivive and <flow> refers to cash
flow so if you have an Output the flow is negative and positive for
Inputs.

   Note that before using the functions defined in this package, you
have to load it writing `load(finance)$'.

   Author: Nicolas Guarin Zapata.


File: maxima.info,  Node: Functions and Variables for finance,  Prev: Introduction to finance,  Up: finance

53.2 Functions and Variables for finance
========================================

 -- Function: days360 (<year1>,<month1>,<day1>,<year2>,<month2>,<day2>)
     Calculates the distance between 2 dates, assuming 360 days years,
     30 days months.

     Example:

          (%i1) load(finance)$
          (%i2) days360(2008,12,16,2007,3,25);
          (%o2)                      - 621


 -- Function: fv (<rate>,<PV>,<num>)
     We can calculate the future value of a Present one given a certain
     interest rate.  <rate> is the interest rate, <PV> is the present
     value and <num> is the number of periods.

     Example:

          (%i1) load(finance)$
          (%i2) fv(0.12,1000,3);
          (%o2)                     1404.928


 -- Function: pv (<rate>,<FV>,<num>)
     We can calculate the present value of a Future one given a certain
     interest rate.  <rate> is the interest rate, <FV> is the future
     value and <num> is the number of periods.

     Example:

          (%i1) load(finance)$
          (%i2) pv(0.12,1000,3);
          (%o2)                711.7802478134108


 -- Function: graph_flow (<val>)
     Plots the money flow in a time line, the positive values are in
     blue and upside; the negative ones are in red and downside.  The
     direction of the flow is given by the sign of the value.  <val> is
     a list of flow values.

     Example:

          (%i1) load(finance)$
          (%i2) graph_flow([-5000,-3000,800,1300,1500,2000])$


 -- Function: annuity_pv (<rate>,<PV>,<num>)
     We can calculate the annuity knowing the present value (like an
     ammount), it is a constant and periodic payment. <rate> is the
     interest rate, <PV> is the present value and <num> is the number
     of periods.

     Example:

          (%i1) load(finance)$
          (%i2) annuity_pv(0.12,5000,10);
          (%o2)                884.9208207992202


 -- Function: annuity_fv (<rate>,<FV>,<num>)
     We can calculate the annuity knowing the desired value (future
     value), it is a constant and periodic payment. <rate> is the
     interest rate, <FV> is the future value and <num> is the number of
     periods.

     Example:

          (%i1) load(finance)$
          (%i2) annuity_fv(0.12,65000,10);
          (%o2)                3703.970670389863


 -- Function: geo_annuity_pv (<rate>,<growing_rate>,<PV>,<num>)
     We can calculate the annuity knowing the present value (like an
     ammount), in a growing periodic payment. <rate> is the interest
     rate, <growing_rate> is the growing rate, <PV> is the present
     value and <num> is the number of periods.

     Example:

          (%i1) load(finance)$
          (%i2) geo_annuity_pv(0.14,0.05,5000,10);
          (%o2)                802.6888176505123


 -- Function: geo_annuity_fv (<rate>,<growing_rate>,<FV>,<num>)
     We can calculate the annuity knowing the desired value (future
     value), in a growing periodic payment. <rate> is the interest
     rate, <growing_rate> is the growing rate, <FV> is the future value
     and <num> is the number of periods.

     Example:

          (%i1) load(finance)$
          (%i2) geo_annuity_fv(0.14,0.05,5000,10);
          (%o2)                216.5203395312695


 -- Function: amortization (<rate>,<ammount>,<num>)
     Amortization table determinated by a specific rate.  <rate> is the
     interest rate, <ammount> is the ammount value, and <num> is the
     number of periods.

     Example:

          (%i1) load(finance)$
          (%i2) amortization(0.05,56000,12)$
                "n"    "Balance"     "Interest"   "Amortization"  "Payment"
               0.000     56000.000         0.000         0.000         0.000
               1.000     52481.777      2800.000      3518.223      6318.223
               2.000     48787.643      2624.089      3694.134      6318.223
               3.000     44908.802      2439.382      3878.841      6318.223
               4.000     40836.019      2245.440      4072.783      6318.223
               5.000     36559.597      2041.801      4276.422      6318.223
               6.000     32069.354      1827.980      4490.243      6318.223
               7.000     27354.599      1603.468      4714.755      6318.223
               8.000     22404.106      1367.730      4950.493      6318.223
               9.000     17206.088      1120.205      5198.018      6318.223
              10.000     11748.170       860.304      5457.919      6318.223
              11.000      6017.355       587.408      5730.814      6318.223
              12.000         0.000       300.868      6017.355      6318.223


 -- Function: arit_amortization (<rate>,<increment>,<ammount>,<num>)
     The amortization table determinated by a specific rate and with
     growing payment can be claculated by `arit_amortization'.  Notice
     that the payment is not constant, it presents an arithmetic
     growing, increment is then the difference between two consecutive
     rows in the "Payment" column.  <rate> is the interest rate,
     <increment> is the increment, <ammount> is the ammount value, and
     <num> is the number of periods.

     Example:

          (%i1) load(finance)$
          (%i2) arit_amortization(0.05,1000,56000,12)$
                "n"    "Balance"     "Interest"   "Amortization"  "Payment"
               0.000     56000.000         0.000         0.000         0.000
               1.000     57403.679      2800.000     -1403.679      1396.321
               2.000     57877.541      2870.184      -473.863      2396.321
               3.000     57375.097      2893.877       502.444      3396.321
               4.000     55847.530      2868.755      1527.567      4396.321
               5.000     53243.586      2792.377      2603.945      5396.321
               6.000     49509.443      2662.179      3734.142      6396.321
               7.000     44588.594      2475.472      4920.849      7396.321
               8.000     38421.703      2229.430      6166.892      8396.321
               9.000     30946.466      1921.085      7475.236      9396.321
              10.000     22097.468      1547.323      8848.998     10396.321
              11.000     11806.020      1104.873     10291.448     11396.321
              12.000        -0.000       590.301     11806.020     12396.321


 -- Function: geo_amortization (<rate>,<growing_rate>,<ammount>,<num>)
     The amortization table determinated by rate, ammount, and number
     of periods can be found by `geo_amortization'.  Notice that the
     payment is not constant, it presents a geometric growing,
     <growing_rate> is then the quotient between two consecutive rows
     in the "Payment" column.  <rate> is the interest rate, <ammount>
     is the ammount value, and <num> is the number of periods.

     Example:

          (%i1) load(finance)$
          (%i2) geo_amortization(0.05,0.03,56000,12)$
                "n"    "Balance"     "Interest"   "Amortization"  "Payment"
               0.000     56000.000         0.000         0.000         0.000
               1.000     53365.296      2800.000      2634.704      5434.704
               2.000     50435.816      2668.265      2929.480      5597.745
               3.000     47191.930      2521.791      3243.886      5765.677
               4.000     43612.879      2359.596      3579.051      5938.648
               5.000     39676.716      2180.644      3936.163      6116.807
               6.000     35360.240      1983.836      4316.475      6300.311
               7.000     30638.932      1768.012      4721.309      6489.321
               8.000     25486.878      1531.947      5152.054      6684.000
               9.000     19876.702      1274.344      5610.176      6884.520
              10.000     13779.481       993.835      6097.221      7091.056
              11.000      7164.668       688.974      6614.813      7303.787
              12.000         0.000       358.233      7164.668      7522.901


 -- Function: saving (<rate>,<ammount>,<num>)
     The table that represents the values in a constant and periodic
     saving can be found by `saving'.  <ammount> represents the desired
     quantity and num the number of periods to save.

     Example:

          (%i1) load(finance)$
          (%i2) saving(0.15,12000,15)$
                "n"    "Balance"     "Interest"   "Payment"
               0.000         0.000         0.000         0.000
               1.000       252.205         0.000       252.205
               2.000       542.240        37.831       252.205
               3.000       875.781        81.336       252.205
               4.000      1259.352       131.367       252.205
               5.000      1700.460       188.903       252.205
               6.000      2207.733       255.069       252.205
               7.000      2791.098       331.160       252.205
               8.000      3461.967       418.665       252.205
               9.000      4233.467       519.295       252.205
              10.000      5120.692       635.020       252.205
              11.000      6141.000       768.104       252.205
              12.000      7314.355       921.150       252.205
              13.000      8663.713      1097.153       252.205
              14.000     10215.474      1299.557       252.205
              15.000     12000.000      1532.321       252.205


 -- Function: npv (<rate>,<val>)
     Calculates de present value of a value series to evaluate the
     viability in a project.  <flowValues> es una lista con los valores
     para cada periodo.

     Example:

          (%i1) load(finance)$
          (%i2) npv(0.25,[100,500,323,124,300]);
          (%o2)                714.4703999999999


 -- Function: irr (<val>,<IO>)
     IRR (Internal Rate of Return) is the value of rate which makes Net
     Present Value zero.  <flowValues> los valores para cada periodo
     (para periodos mayores a 0) y <I0> el valor para el periodo cero.

     Example:

          (%i1) load(finance)$
          (%i2) res:irr([-5000,0,800,1300,1500,2000],0)$
          (%i3) rhs(res[1][1]);
          (%o3)                .03009250374237132


 -- Function: benefit_cost (<rate>,<input>,<output>)
     Calculates the ratio Benefit/Cost. Benefit is the Net Present
     Value (NPV) of the inputs, and Cost is the Net Present Value (NPV)
     of the outputs.  Notice that if there is not an input or output
     value in a specific period, the input/output would be a zero for
     that period.  <rate> is the interest rate, <input> is a list of
     input values, and <output> is a list of output values.

     Example:

          (%i1) load(finance)$
          (%i2) benefit_cost(0.24,[0,300,500,150],[100,320,0,180]);
          (%o2)               1.427249324905784



File: maxima.info,  Node: fractals,  Next: ggf,  Prev: finance,  Up: Top

54 fractals
***********

* Menu:

* Introduction to fractals::
* Definitions for IFS fractals::
* Definitions for complex fractals::
* Definitions for Koch snowflakes::
* Definitions for Peano maps::


File: maxima.info,  Node: Introduction to fractals,  Next: Definitions for IFS fractals,  Prev: fractals,  Up: fractals

54.1 Introduction to fractals
=============================

This package defines some well known fractals:

   - with random IFS (Iterated Function System): the Sierpinsky
triangle, a Tree and a Fern

   - Complex Fractals: the  Mandelbrot and Julia Sets

   - the Koch snowflake sets

   - Peano maps: the Sierpinski and Hilbert maps

   Author: Jose' Rami'rez Labrador.

   For questions, suggestions and  bugs, please feel free to contact me
at

   pepe DOT ramirez AAATTT uca DOT es


File: maxima.info,  Node: Definitions for IFS fractals,  Next: Definitions for complex fractals,  Prev: Introduction to fractals,  Up: fractals

54.2 Definitions for IFS fractals
=================================

Some fractals can be generated by iterative applications of contractive
affine transformations in a random way; see

   Hoggar S. G., "Mathematics for computer graphics", Cambridge
University Press 1994.

   We define a list with several contractive affine transformations,
and  we randomly select the transformation in a recursive way.  The
probability of the choice of a transformation must be related with the
contraction ratio.

   You can change the transformations and find another fractal

 -- Function: sierpinskiale (<n>)
     Sierpinski Triangle: 3 contractive maps; .5 contraction constant
     and translations; all maps have the same contraction ratio.
     Argument <n> must be great enougth, 10000 or greater.

     Example:

          (%i1) load(fractals)$
          (%i2) n: 10000$
          (%i3) plot2d([discrete,sierpinskiale(n)], [style,dots])$


 -- Function: treefale (<n>)
     3 contractive maps all with the same contraction ratio.  Argument
     <n> must be great enougth, 10000 or greater.

     Example:

          (%i1) load(fractals)$
          (%i2) n: 10000$
          (%i3) plot2d([discrete,treefale(n)], [style,dots])$


 -- Function: fernfale (<n>)
     4 contractive maps, the probability to choice a transformation
     must be related with the contraction ratio. Argument <n> must be
     great enougth, 10000 or greater.

     Example:

          (%i1) load(fractals)$
          (%i2) n: 10000$
          (%i3) plot2d([discrete,fernfale(n)], [style,dots])$



File: maxima.info,  Node: Definitions for complex fractals,  Next: Definitions for Koch snowflakes,  Prev: Definitions for IFS fractals,  Up: Top

54.3 Definitions for complex fractals
=====================================

 -- Function: mandelbrot_set (<x>, <y>)
     Mandelbrot set.

     Example:

     This program is time consuming because it must make a lot of
     operations; the computing time is also related with the number of
     grid points.

          (%i1) load(fractals)$
          (%i2) plot3d (mandelbrot_set, [x, -2.5, 1], [y, -1.5, 1.5],
                          [gnuplot_preamble, "set view map"],
                          [gnuplot_pm3d, true],
                          [grid, 150, 150])$


 -- Function: julia_set (<x>, <y>)
     Julia sets.

     This program is time consuming because it must make a lot of
     operations; the computing time is also related with the number of
     grid points.

     Example:

          (%i1) load(fractals)$
          (%i2) plot3d (julia_set, [x, -2, 1], [y, -1.5, 1.5],
                          [gnuplot_preamble, "set view map"],
                          [gnuplot_pm3d, true],
                          [grid, 150, 150])$

     See also `julia_parameter'.


 -- Optional variable: julia_parameter
     Default value: `%i'

     Complex parameter for Julia fractals.  Its default value is `%i';
     we  suggest the  values `-.745+%i*.113002', `-.39054-%i*.58679',
     `-.15652+%i*1.03225', `-.194+%i*.6557' and `.011031-%i*.67037'.


 -- Function: julia_sin (<x>, <y>)
     While function `julia_set' implements the transformation
     `julia_parameter+z^2', function `julia_sin' implements
     `julia_parameter*sin(z)'. See source code for more details.

     This program runs slowly  because it calculates a lot of sines.

     Example:

     This program is time consuming because it must make a lot of
     operations; the computing time is also related with the number of
     grid points.

          (%i1) load(fractals)$
          (%i2) julia_parameter:1+.1*%i$
          (%i3) plot3d (julia_sin, [x, -2, 2], [y, -3, 3],
                          [gnuplot_preamble, "set view map"],
                          [gnuplot_pm3d, true],
                          [grid, 150, 150])$

     See also `julia_parameter'.



File: maxima.info,  Node: Definitions for Koch snowflakes,  Next: Definitions for Peano maps,  Prev: Definitions for complex fractals,  Up: Top

54.4 Definitions for Koch snowflakes
====================================

 -- Function: snowmap (<ent>, <nn>)
     Koch snowflake sets. Function `snowmap' plots the snow Koch map
     over the vertex of an initial closed polygonal, in the complex
     plane. Here the orientation of the polygon is important. Argument
     <nn> is the number of recursive applications of Koch
     transformation; <nn> must be small (5 or 6).

     Examples:

          (%i1) load(fractals)$
          (%i2) plot2d([discrete,
                        snowmap([1,exp(%i*%pi*2/3),exp(-%i*%pi*2/3),1],4)])$
          (%i3) plot2d([discrete,
                        snowmap([1,exp(-%i*%pi*2/3),exp(%i*%pi*2/3),1],4)])$
          (%i4) plot2d([discrete, snowmap([0,1,1+%i,%i,0],4)])$
          (%i5) plot2d([discrete, snowmap([0,%i,1+%i,1,0],4)])$



File: maxima.info,  Node: Definitions for Peano maps,  Prev: Definitions for Koch snowflakes,  Up: fractals

54.5 Definitions for Peano maps
===============================

Continuous curves that cover an area. Warning: the number of points
exponentially grows with <n>.

 -- Function: hilbertmap (<nn>)
     Hilbert map. Argument <nn> must be small (5, for example).  Maxima
     can crash if <nn> is 7 or greater.

     Example:

          (%i1) load(fractals)$
          (%i2) plot2d([discrete,hilbertmap(6)])$


 -- Function: sierpinskimap (<nn>)
     Sierpinski map. Argument <nn> must be small (5, for example).
     Maxima can crash if <nn> is 7 or greater.

     Example:

          (%i1) load(fractals)$
          (%i2) plot2d([discrete,sierpinskimap(6)])$



File: maxima.info,  Node: ggf,  Next: graphs,  Prev: fractals,  Up: Top

55 ggf
******

* Menu:

* Functions and Variables for ggf::


File: maxima.info,  Node: Functions and Variables for ggf,  Prev: ggf,  Up: ggf

55.1 Functions and Variables for ggf
====================================

 -- Option variable: GGFINFINITY
     Default value: 3

     This is an option variable for function `ggf'.

     When computing the continued fraction of the generating function,
     a partial quotient having a degree (strictly) greater than
     <GGFINFINITY> will be discarded and the current convergent will be
     considered as the exact value of the generating function; most
     often the degree of all partial quotients will be 0 or 1; if you
     use a greater value, then you should give enough terms in order to
     make the computation accurate enough.

     See also `ggf'.


 -- Option variable: GGFCFMAX
     Default value: 3

     This is an option variable for function `ggf'.

     When computing the continued fraction of the generating function,
     if no good result has been found (see the <GGFINFINITY> flag)
     after having computed <GGFCFMAX> partial quotients, the generating
     function will be considered as not being a fraction of two
     polynomials and the function will exit. Put freely a greater value
     for more complicated generating functions.

     See also `ggf'.


 -- Function: ggf (<l>)
     Compute the generating function (if it is a fraction of two
     polynomials) of a sequence, its first terms being given. <l> is a
     list of numbers.

     The solution is returned as a fraction of two polynomials.  If no
     solution has been found, it returns with `done'.

     This function is controlled by global variables <GGFINFINITY> and
     <GGFCFMAX>. See also <GGFINFINITY> and <GGFCFMAX>.

     To use this function write first `load("ggf")'.



File: maxima.info,  Node: graphs,  Next: grobner,  Prev: ggf,  Up: Top

56 graphs
*********

* Menu:

* Introduction to graphs::
* Functions and Variables for graphs::


File: maxima.info,  Node: Introduction to graphs,  Next: Functions and Variables for graphs,  Prev: graphs,  Up: graphs

56.1 Introduction to graphs
===========================

The `graphs' package provides graph and digraph data structure for
Maxima. Graphs and digraphs are simple (have no multiple edges nor
loops), although digraphs can have a directed edge from <u> to <v> and
a directed edge from <v> to <u>.

   Internally graphs are represented by adjacency lists and implemented
as a lisp structures. Vertices are identified by their ids (an id is an
integer). Edges/arcs are represented by lists of length 2. Labels can be
assigned to vertices of graphs/digraphs and weights can be assigned to
edges/arcs of graphs/digraphs.

   There is a `draw_graph' function for drawing graphs. Graphs are
drawn using a force based vertex positioning algorithm. `draw_graph'
can also use graphviz programs available from
`http://www.graphviz.org'. `draw_graph' is based on the maxima `draw'
package.

   To use the `graphs' package, first load it with `load(graphs)'.


File: maxima.info,  Node: Functions and Variables for graphs,  Prev: Introduction to graphs,  Up: graphs

56.2 Functions and Variables for graphs
=======================================

56.2.1 Building graphs
----------------------

 -- Function: create_graph (<v_list>, <e_list>)
 -- Function: create_graph (<n>, <e_list>)
 -- Function: create_graph (<v_list>, <e_list>, <directed>)
     Creates a new graph on the set of vertices <v_list> and with edges
     <e_list>.

     <v_list> is a list of vertices (`[v1, v2,..., vn]') or a list of
     vertices together with vertex labels (`[[v1,l1], [v2,l2],...,
     [vn,ln]]').

     <n> is the number of vertices. Vertices will be identified by
     integers from 0 to n-1.

     <e_list> is a list of edges (`[e1, e2,..., em]') or a list of
     edges together with edge-weights (`[[e1, w1], ..., [em, wm]]').

     If <directed> is not `false', a directed graph will be returned.

     Example 1: create a cycle on 3 vertices:
          (%i1) load (graphs)$
          (%i2) g : create_graph([1,2,3], [[1,2], [2,3], [1,3]])$
          (%i3) print_graph(g)$
          Graph on 3 vertices with 3 edges.
          Adjacencies:
            3 :  1  2
            2 :  3  1
            1 :  3  2

     Example 2: create a cycle on 3 vertices with edge weights:
          (%i1) load (graphs)$
          (%i2) g : create_graph([1,2,3], [[[1,2], 1.0], [[2,3], 2.0],
                                    [[1,3], 3.0]])$
          (%i3) print_graph(g)$
          Graph on 3 vertices with 3 edges.
          Adjacencies:
            3 :  1  2
            2 :  3  1
            1 :  3  2

     Example 3: create a directed graph:
          (%i1) load (graphs)$
          (%i2) d : create_graph(
                  [1,2,3,4],
                  [
                   [1,3], [1,4],
                   [2,3], [2,4]
                  ],
                  'directed = true)$
          (%i3) print_graph(d)$
          Digraph on 4 vertices with 4 arcs.
          Adjacencies:
            4 :
            3 :
            2 :  4  3
            1 :  4  3


 -- Function: copy_graph (<g>)
     Returns a copy of the graph <g>.


 -- Function: circulant_graph (<n>, <d>)
     Returns the circulant graph with parameters <n> and <d>.

     Example:
          (%i1) load (graphs)$
          (%i2) g : circulant_graph(10, [1,3])$
          (%i3) print_graph(g)$
          Graph on 10 vertices with 20 edges.
          Adjacencies:
            9 :  2  6  0  8
            8 :  1  5  9  7
            7 :  0  4  8  6
            6 :  9  3  7  5
            5 :  8  2  6  4
            4 :  7  1  5  3
            3 :  6  0  4  2
            2 :  9  5  3  1
            1 :  8  4  2  0
            0 :  7  3  9  1


 -- Function: clebsch_graph ()
     Returns the Clebsch graph.


 -- Function: complement_graph (<g>)
     Returns the complement of the graph <g>.


 -- Function: complete_bipartite_graph (<n>, <m>)
     Returns the complete bipartite graph on <n+m> vertices.


 -- Function: complete_graph (<n>)
     Returns the complete graph on <n> vertices.


 -- Function: cycle_digraph (<n>)
     Returns the directed cycle on <n> vertices.


 -- Function: cycle_graph (<n>)
     Returns the cycle on <n> vertices.


 -- Function: cuboctahedron_graph (<n>)
     Returns the cuboctahedron graph.


 -- Function: cube_graph (<n>)
     Returns the <n>-dimensional cube.


 -- Function: dodecahedron_graph ()
     Returns the dodecahedron graph.


 -- Function: empty_graph (<n>)
     Returns the empty graph on <n> vertices.


 -- Function: flower_snark (<n>)
     Returns the flower graph on <4n> vertices.

     Example:
          (%i1) load (graphs)$
          (%i2) f5 : flower_snark(5)$
          (%i3) chromatic_index(f5);
          (%o3)                           4


 -- Function: from_adjacency_matrix (<A>)
     Returns the graph represented by its adjacency matrix <A>.


 -- Function: frucht_graph ()
     Returns the Frucht graph.


 -- Function: graph_product (<g1>, <g1>)
     Returns the direct product of graphs <g1> and <g2>.

     Example:
          (%i1) load (graphs)$
          (%i2) grid : graph_product(path_graph(3), path_graph(4))$
          (%i3) draw_graph(grid)$


 -- Function: graph_union (<g1>, <g1>)
     Returns the union (sum) of graphs <g1> and <g2>.


 -- Function: grid_graph (<n>, <m>)
     Returns the <n x m> grid.


 -- Function: great_rhombicosidodecahedron_graph ()
     Returns the great rhombicosidodecahedron graph.


 -- Function: great_rhombicuboctahedron_graph ()
     Returns the great rhombicuboctahedron graph.


 -- Function: grotzch_graph ()
     Returns the Grotzch graph.


 -- Function: heawood_graph ()
     Returns the Heawood graph.


 -- Function: icosahedron_graph ()
     Returns the icosahedron graph.


 -- Function: icosidodecahedron_graph ()
     Returns the icosidodecahedron graph.


 -- Function: induced_subgraph (<V>, <g>)
     Returns the graph induced on the subset <V> of vertices of the
     graph <g>.

     Example:
          (%i1) load (graphs)$
          (%i2) p : petersen_graph()$
          (%i3) V : [0,1,2,3,4]$
          (%i4) g : induced_subgraph(V, p)$
          (%i5) print_graph(g)$
          Graph on 5 vertices with 5 edges.
          Adjacencies:
            4 :  3  0
            3 :  2  4
            2 :  1  3
            1 :  0  2
            0 :  1  4


 -- Function: line_graph (<g>)
     Returns the line graph of the graph <g>.


 -- Function: make_graph (<vrt>, <f>)
 -- Function: make_graph (<vrt>, <f>, <oriented>)
     Creates a graph using a predicate function <f>.

     <vrt> is a list/set of vertices or an integer. If <vrt> is an
     integer, then vertices of the graph will be integers from 1 to
     <vrt>.

     <f> is a predicate function. Two vertices <a> and <b> will be
     connected if `f(a,b)=true'.

     If <directed> is not <false>, then the graph will be directed.

     Example 1:
          (%i1) load(graphs)$
          (%i2) g : make_graph(powerset({1,2,3,4,5}, 2), disjointp)$
          (%i3) is_isomorphic(g, petersen_graph());
          (%o3)                         true
          (%i4) get_vertex_label(1, g);
          (%o4)                        {1, 2}

     Example 2:
          (%i1) load(graphs)$
          (%i2) f(i, j) := is (mod(j, i)=0)$
          (%i3) g : make_graph(20, f, directed=true)$
          (%i4) out_neighbors(4, g);
          (%o4)                    [8, 12, 16, 20]
          (%i5) in_neighbors(18, g);
          (%o5)                    [1, 2, 3, 6, 9]


 -- Function: mycielski_graph (<g>)
     Returns the mycielskian graph of the graph <g>.


 -- Function: new_graph ()
     Returns the graph with no vertices and no edges.


 -- Function: path_digraph (<n>)
     Returns the directed path on <n> vertices.


 -- Function: path_graph (<n>)
     Returns the path on <n> vertices.


 -- Function: petersen_graph ()
 -- Function: petersen_graph (<n>, <d>)
     Returns the petersen graph <P_{n,d}>. The default values for <n>
     and <d> are `n=5' and `d=2'.


 -- Function: random_bipartite_graph (<a>, <b>, <p>)
     Returns a random bipartite graph on `a+b' vertices. Each edge is
     present with probability <p>.


 -- Function: random_digraph (<n>, <p>)
     Returns a random directed graph on <n> vertices. Each arc is
     present with probability <p>.


 -- Function: random_regular_graph (<n>)
 -- Function: random_regular_graph (<n>, <d>)
     Returns a random <d>-regular graph on <n> vertices. The default
     value for <d> is `d=3'.


 -- Function: random_graph (<n>, <p>)
     Returns a random graph on <n> vertices. Each edge is present with
     probability <p>.


 -- Function: random_graph1 (<n>, <m>)
     Returns a random graph on <n> vertices and random <m> edges.


 -- Function: random_network (<n>, <p>, <w>)
     Returns a random network on <n> vertices. Each arc is present with
     probability <p> and has a weight in the range `[0,w]'. The
     function returns a list `[network, source, sink]'.

     Example:
          (%i1) load (graphs)$
          (%i2) [net, s, t] : random_network(50, 0.2, 10.0);
          (%o2)                   [DIGRAPH, 50, 51]
          (%i3) max_flow(net, s, t)$
          (%i4) first(%);
          (%o4)                   27.65981397932507


 -- Function: random_tournament (<n>)
     Returns a random tournament on <n> vertices.


 -- Function: random_tree (<n>)
     Returns a random tree on <n> vertices.


 -- Function: small_rhombicosidodecahedron_graph ()
     Returns the small rhombicosidodecahedron graph.


 -- Function: small_rhombicuboctahedron_graph ()
     Returns the small rhombicuboctahedron graph.


 -- Function: snub_cube_graph ()
     Returns the snub cube graph.


 -- Function: snub_dodecahedron_graph ()
     Returns the snub dodecahedron graph.


 -- Function: truncated_cube_graph ()
     Returns the truncated cube graph.


 -- Function: truncated_dodecahedron_graph ()
     Returns the truncated dodecahedron graph.


 -- Function: truncated_icosahedron_graph ()
     Returns the truncated icosahedron graph.


 -- Function: truncated_tetrahedron_graph ()
     Returns the truncated tetrahedron graph.


 -- Function: tutte_graph ()
     Returns the Tutte graph.


 -- Function: underlying_graph (<g>)
     Returns the underlying graph of the directed graph <g>.


 -- Function: wheel_graph (<n>)
     Returns the wheel graph on <n+1> vertices.


56.2.2 Graph properties
-----------------------

 -- Function: adjacency_matrix (<gr>)
     Returns the adjacency matrix of the graph <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) c5 : cycle_graph(4)$
          (%i3) adjacency_matrix(c5);
                                   [ 0  1  0  1 ]
                                   [            ]
                                   [ 1  0  1  0 ]
          (%o3)                    [            ]
                                   [ 0  1  0  1 ]
                                   [            ]
                                   [ 1  0  1  0 ]


 -- Function: average_degree (<gr>)
     Returns the average degree of vertices in the graph <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) average_degree(grotzch_graph());
                                         40
          (%o2)                          --
                                         11


 -- Function: biconnected_components (<gr>)
     Returns the (vertex sets of) 2-connected components of the graph
     <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) g : create_graph(
                      [1,2,3,4,5,6,7],
                      [
                       [1,2],[2,3],[2,4],[3,4],
                       [4,5],[5,6],[4,6],[6,7]
                      ])$
          (%i3) biconnected_components(g);
          (%o3)        [[6, 7], [4, 5, 6], [1, 2], [2, 3, 4]]


 -- Function: bipartition (<gr>)
     Returns a bipartition of the vertices of the graph <gr> or an empty
     list if <gr> is not bipartite.

     Example:

          (%i1) load (graphs)$
          (%i2) h : heawood_graph()$
          (%i3) [A,B]:bipartition(h);
          (%o3)  [[8, 12, 6, 10, 0, 2, 4], [13, 5, 11, 7, 9, 1, 3]]
          (%i4) draw_graph(h, show_vertices=A, program=circular)$


 -- Function: chromatic_index (<gr>)
     Returns the chromatic index of the graph <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) p : petersen_graph()$
          (%i3) chromatic_index(p);
          (%o3)                           4


 -- Function: chromatic_number (<gr>)
     Returns the chromatic number of the graph <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) chromatic_number(cycle_graph(5));
          (%o2)                           3
          (%i3) chromatic_number(cycle_graph(6));
          (%o3)                           2


 -- Function: clear_edge_weight (<e>, <gr>)
     Removes the weight of the edge  <e> in the graph <gr>.

     Example:

          (%i1) load (graphs)$
          (%i2) g : create_graph(3, [[[0,1], 1.5], [[1,2], 1.3]])$
          (%i3) get_edge_weight([0,1], g);
          (%o3)                          1.5
          (%i4) clear_edge_weight([0,1], g)$
          (%i5) get_edge_weight([0,1], g);
          (%o5)                           1


 -- Function: clear_vertex_label (<v>, <gr>)
     Removes the label of the vertex <v> in the graph <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) g : create_graph([[0,"Zero"], [1, "One"]], [[0,1]])$
          (%i3) get_vertex_label(0, g);
          (%o3)                         Zero
          (%i4) clear_vertex_label(0, g);
          (%o4)                         done
          (%i5) get_vertex_label(0, g);
          (%o5)                         false


 -- Function: connected_components (<gr>)
     Returns the (vertex sets of) connected components of the graph
     <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) g: graph_union(cycle_graph(5), path_graph(4))$
          (%i3) connected_components(g);
          (%o3)            [[1, 2, 3, 4, 0], [8, 7, 6, 5]]


 -- Function: diameter (<gr>)
     Returns the diameter of the graph <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) diameter(dodecahedron_graph());
          (%o2)                           5


 -- Function: edge_coloring (<gr>)
     Returns an optimal coloring of the edges of the graph <gr>.

     The function returns the chromatic index and a list representing
     the coloring of the edges of <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) p : petersen_graph()$
          (%i3) [ch_index, col] : edge_coloring(p);
          (%o3) [4, [[[0, 5], 3], [[5, 7], 1], [[0, 1], 1], [[1, 6], 2],
          [[6, 8], 1], [[1, 2], 3], [[2, 7], 4], [[7, 9], 2], [[2, 3], 2],
          [[3, 8], 3], [[5, 8], 2], [[3, 4], 1], [[4, 9], 4], [[6, 9], 3],
          [[0, 4], 2]]]
          (%i4) assoc([0,1], col);
          (%o4)                           1
          (%i5) assoc([0,5], col);
          (%o5)                           3


 -- Function: degree_sequence (<gr>)
     Returns the list of vertex degrees of the graph <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) degree_sequence(random_graph(10, 0.4));
          (%o2)            [2, 2, 2, 2, 2, 2, 3, 3, 3, 3]


 -- Function: edge_connectivity (<gr>)
     Returns the edge-connectivity of the graph <gr>.

     See also `min_edge_cut'.


 -- Function: edges (<gr>)
     Returns the list of edges (arcs) in a (directed) graph <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) edges(complete_graph(4));
          (%o2)   [[2, 3], [1, 3], [1, 2], [0, 3], [0, 2], [0, 1]]


 -- Function: get_edge_weight (<e>, <gr>)
 -- Function: get_edge_weight (<e>, <gr>, <ifnot>)
     Returns the weight of the edge <e> in the graph <gr>.

     If there is no weight assigned to the edge, the function returns
     1. If the edge is not present in the graph, the function signals
     an error or returns the optional argument <ifnot>.

     Example:
          (%i1) load (graphs)$
          (%i2) c5 : cycle_graph(5)$
          (%i3) get_edge_weight([1,2], c5);
          (%o3)                           1
          (%i4) set_edge_weight([1,2], 2.0, c5);
          (%o4)                         done
          (%i5) get_edge_weight([1,2], c5);
          (%o5)                          2.0


 -- Function: get_vertex_label (<v>, <gr>)
     Returns the label of the vertex <v> in the graph <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) g : create_graph([[0,"Zero"], [1, "One"]], [[0,1]])$
          (%i3) get_vertex_label(0, g);
          (%o3)                         Zero


 -- Function: graph_charpoly (<gr>, <x>)
     Returns the characteristic polynomial (in variable <x>) of the
     graph <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) p : petersen_graph()$
          (%i3) graph_charpoly(p, x), factor;
                                             5        4
          (%o3)               (x - 3) (x - 1)  (x + 2)


 -- Function: graph_center (<gr>)
     Returns the center of the graph <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) g : grid_graph(5,5)$
          (%i3) graph_center(g);
          (%o3)                         [12]


 -- Function: graph_eigenvalues (<gr>)
     Returns the eigenvalues of the graph <gr>. The function returns
     eigenvalues in the same format as maxima `eigenvalue' function.

     Example:
          (%i1) load (graphs)$
          (%i2) p : petersen_graph()$
          (%i3) graph_eigenvalues(p);
          (%o3)               [[3, - 2, 1], [1, 4, 5]]


 -- Function: graph_periphery (<gr>)
     Returns the periphery of the graph <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) g : grid_graph(5,5)$
          (%i3) graph_periphery(g);
          (%o3)                    [24, 20, 4, 0]


 -- Function: graph_size (<gr>)
     Returns the number of edges in the graph <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) p : petersen_graph()$
          (%i3) graph_size(p);
          (%o3)                          15


 -- Function: graph_order (<gr>)
     Returns the number of vertices in the graph <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) p : petersen_graph()$
          (%i3) graph_order(p);
          (%o3)                          10


 -- Function: girth (<gr>)
     Returns the length of the shortest cycle in <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) g : heawood_graph()$
          (%i3) girth(g);
          (%o3)                           6


 -- Function: hamilton_cycle (<gr>)
     Returns the Hamilton cycle of the graph <gr> or an empty list if
     <gr> is not hamiltonian.

     Example:
          (%i1) load (graphs)$
          (%i2) c : cube_graph(3)$
          (%i3) hc : hamilton_cycle(c);
          (%o3)              [7, 3, 2, 6, 4, 0, 1, 5, 7]
          (%i4) draw_graph(c, show_edges=vertices_to_cycle(hc))$


 -- Function: hamilton_path (<gr>)
     Returns the Hamilton path of the graph <gr> or an empty list if
     <gr> does not have a Hamilton path.

     Example:
          (%i1) load (graphs)$
          (%i2) p : petersen_graph()$
          (%i3) hp : hamilton_path(p);
          (%o3)            [0, 5, 7, 2, 1, 6, 8, 3, 4, 9]
          (%i4) draw_graph(p, show_edges=vertices_to_path(hp))$


 -- Function: isomorphism (<gr1>, <gr2>)
     Returns a an isomorphism between graphs/digraphs <gr1> and <gr2>.
     If <gr1> and <gr2> are not isomorphic, it returns an empty list.

     Example:
          (%i1) load (graphs)$
          (%i2) clk5:complement_graph(line_graph(complete_graph(5)))$
          (%i3) isomorphism(clk5, petersen_graph());
          (%o3) [9 -> 0, 2 -> 1, 6 -> 2, 5 -> 3, 0 -> 4, 1 -> 5, 3 -> 6,
                                                    4 -> 7, 7 -> 8, 8 -> 9]


 -- Function: in_neighbors (<v>, <gr>)
     Returns the list of in-neighbors of the vertex <v> in the directed
     graph <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) p : path_digraph(3)$
          (%i3) in_neighbors(2, p);
          (%o3)                          [1]
          (%i4) out_neighbors(2, p);
          (%o4)                          []


 -- Function: is_biconnected (<gr>)
     Returns `true' if <gr> is 2-connected and `false' otherwise.

     Example:
          (%i1) load (graphs)$
          (%i2) is_biconnected(cycle_graph(5));
          (%o2)                         true
          (%i3) is_biconnected(path_graph(5));
          (%o3)                         false


 -- Function: is_bipartite (<gr>)
     Returns `true' if <gr> is bipartite (2-colorable) and `false'
     otherwise.

     Example:
          (%i1) load (graphs)$
          (%i2) is_bipartite(petersen_graph());
          (%o2)                         false
          (%i3) is_bipartite(heawood_graph());
          (%o3)                         true


 -- Function: is_connected (<gr>)
     Returns `true' if the graph <gr> is connected and `false'
     otherwise.

     Example:
          (%i1) load (graphs)$
          (%i2) is_connected(graph_union(cycle_graph(4), path_graph(3)));
          (%o2)                         false


 -- Function: is_digraph (<gr>)
     Returns `true' if <gr> is a directed graph and `false' otherwise.

     Example:
          (%i1) load (graphs)$
          (%i2) is_digraph(path_graph(5));
          (%o2)                         false
          (%i3) is_digraph(path_digraph(5));
          (%o3)                         true


 -- Function: is_edge_in_graph (<e>, <gr>)
     Returns `true' if <e> is an edge (arc) in the (directed) graph <g>
     and `false' otherwise.

     Example:
          (%i1) load (graphs)$
          (%i2) c4 : cycle_graph(4)$
          (%i3) is_edge_in_graph([2,3], c4);
          (%o3)                         true
          (%i4) is_edge_in_graph([3,2], c4);
          (%o4)                         true
          (%i5) is_edge_in_graph([2,4], c4);
          (%o5)                         false
          (%i6) is_edge_in_graph([3,2], cycle_digraph(4));
          (%o6)                         false


 -- Function: is_graph (<gr>)
     Returns `true' if <gr> is a graph and `false' otherwise.

     Example:
          (%i1) load (graphs)$
          (%i2) is_graph(path_graph(5));
          (%o2)                         true
          (%i3) is_graph(path_digraph(5));
          (%o3)                         false


 -- Function: is_graph_or_digraph (<gr>)
     Returns `true' if <gr> is a graph or a directed graph and `false'
     otherwise.

     Example:
          (%i1) load (graphs)$
          (%i2) is_graph_or_digraph(path_graph(5));
          (%o2)                         true
          (%i3) is_graph_or_digraph(path_digraph(5));
          (%o3)                         true


 -- Function: is_isomorphic (<gr1>, <gr2>)
     Returns `true' if graphs/digraphs <gr1> and <gr2> are isomorphic
     and `false' otherwise.

     See also `isomorphism'.

     Example:
          (%i1) load (graphs)$
          (%i2) clk5:complement_graph(line_graph(complete_graph(5)))$
          (%i3) is_isomorphic(clk5, petersen_graph());
          (%o3)                         true


 -- Function: is_planar (<gr>)
     Returns `true' if <gr> is a planar graph and `false' otherwise.

     The algorithm used is the Demoucron's algorithm, which is a
     quadratic time algorithm.

     Example:
          (%i1) load (graphs)$
          (%i2) is_planar(dodecahedron_graph());
          (%o2)                         true
          (%i3) is_planar(petersen_graph());
          (%o3)                         false
          (%i4) is_planar(petersen_graph(10,2));
          (%o4)                         true


 -- Function: is_sconnected (<gr>)
     Returns `true' if the directed graph <gr> is strongly connected and
     `false' otherwise.

     Example:
          (%i1) load (graphs)$
          (%i2) is_sconnected(cycle_digraph(5));
          (%o2)                         true
          (%i3) is_sconnected(path_digraph(5));
          (%o3)                         false


 -- Function: is_vertex_in_graph (<v>, <gr>)
     Returns `true' if <v> is a vertex in the graph <g> and `false'
     otherwise.

     Example:
          (%i1) load (graphs)$
          (%i2) c4 : cycle_graph(4)$
          (%i3) is_vertex_in_graph(0, c4);
          (%o3)                         true
          (%i4) is_vertex_in_graph(6, c4);
          (%o4)                         false


 -- Function: is_tree (<gr>)
     Returns `true' if <gr> is a tree and `false'  otherwise.

     Example:
          (%i1) load (graphs)$
          (%i2) is_tree(random_tree(4));
          (%o2)                         true
          (%i3) is_tree(graph_union(random_tree(4), random_tree(5)));
          (%o3)                         false


 -- Function: laplacian_matrix (<gr>)
     Returns the laplacian matrix of the graph <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) laplacian_matrix(cycle_graph(5));
                             [  2   - 1   0    0   - 1 ]
                             [                         ]
                             [ - 1   2   - 1   0    0  ]
                             [                         ]
          (%o2)              [  0   - 1   2   - 1   0  ]
                             [                         ]
                             [  0    0   - 1   2   - 1 ]
                             [                         ]
                             [ - 1   0    0   - 1   2  ]


 -- Function: max_clique (<gr>)
     Returns a maximum clique of the graph <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) g : random_graph(100, 0.5)$
          (%i3) max_clique(g);
          (%o3)          [6, 12, 31, 36, 52, 59, 62, 63, 80]


 -- Function: max_degree (<gr>)
     Returns the maximal degree of vertices of the graph <gr> and a
     vertex of maximal degree.

     Example:
          (%i1) load (graphs)$
          (%i2) g : random_graph(100, 0.02)$
          (%i3) max_degree(g);
          (%o3)                        [6, 79]
          (%i4) vertex_degree(95, g);
          (%o4)                           2


 -- Function: max_flow (<net>, <s>, <t>)
     Returns a maximum flow through the network <net> with the source
     <s> and the sink <t>.

     The function returns the value of the maximal flow and a list
     representing the weights of the arcs in the optimal flow.

     Example:
          (%i1) load (graphs)$
          (%i2) net : create_graph(
            [1,2,3,4,5,6],
            [[[1,2], 1.0],
             [[1,3], 0.3],
             [[2,4], 0.2],
             [[2,5], 0.3],
             [[3,4], 0.1],
             [[3,5], 0.1],
             [[4,6], 1.0],
             [[5,6], 1.0]],
            directed=true)$
          (%i3) [flow_value, flow] : max_flow(net, 1, 6);
          (%o3) [0.7, [[[1, 2], 0.5], [[1, 3], 0.2], [[2, 4], 0.2],
          [[2, 5], 0.3], [[3, 4], 0.1], [[3, 5], 0.1], [[4, 6], 0.3],
          [[5, 6], 0.4]]]
          (%i4) fl : 0$
          (%i5) for u in out_neighbors(1, net)
               do fl : fl + assoc([1, u], flow)$
          (%i6) fl;
          (%o6)                          0.7


 -- Function: max_independent_set (<gr>)
     Returns a maximum independent set of the graph <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) d : dodecahedron_graph()$
          (%i3) mi : max_independent_set(d);
          (%o3)             [0, 3, 5, 9, 10, 11, 18, 19]
          (%i4) draw_graph(d, show_vertices=mi)$


 -- Function: max_matching (<gr>)
     Returns a maximum matching of the graph <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) d : dodecahedron_graph()$
          (%i3) m : max_matching(d);
          (%o3) [[5, 7], [8, 9], [6, 10], [14, 19], [13, 18], [12, 17],
                                         [11, 16], [0, 15], [3, 4], [1, 2]]
          (%i4) draw_graph(d, show_edges=m)$


 -- Function: min_degree (<gr>)
     Returns the minimum degree of vertices of the graph <gr> and a
     vertex of minimum degree.

     Example:
          (%i1) load (graphs)$
          (%i2) g : random_graph(100, 0.1)$
          (%i3) min_degree(g);
          (%o3)                        [3, 49]
          (%i4) vertex_degree(21, g);
          (%o4)                           9


 -- Function: min_edge_cut (<gr>)
     Returns the minimum edge cut in the graph <gr>.

     See also `edge_connectivity'.


 -- Function: min_vertex_cover (<gr>)
     Returns the minimum vertex cover of the graph <gr>.


 -- Function: min_vertex_cut (<gr>)
     Returns the minimum vertex cut in the graph <gr>.

     See also `vertex_connectivity'.


 -- Function: minimum_spanning_tree (<gr>)
     Returns the minimum spanning tree of the graph <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) g : graph_product(path_graph(10), path_graph(10))$
          (%i3) t : minimum_spanning_tree(g)$
          (%i4) draw_graph(g, show_edges=edges(t))$


 -- Function: neighbors (<v>, <gr>)
     Returns the list of neighbors of the vertex <v> in the graph <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) p : petersen_graph()$
          (%i3) neighbors(3, p);
          (%o3)                       [4, 8, 2]


 -- Function: odd_girth (<gr>)
     Returns the length of the shortest odd cycle in the graph <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) g : graph_product(cycle_graph(4), cycle_graph(7))$
          (%i3) girth(g);
          (%o3)                           4
          (%i4) odd_girth(g);
          (%o4)                           7


 -- Function: out_neighbors (<v>, <gr>)
     Returns the list of out-neighbors of the vertex <v> in the directed
     graph <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) p : path_digraph(3)$
          (%i3) in_neighbors(2, p);
          (%o3)                          [1]
          (%i4) out_neighbors(2, p);
          (%o4)                          []


 -- Function: planar_embedding (<gr>)
     Returns the list of facial walks in a planar embedding of <gr> and
     `false' if <gr> is not a planar graph.

     The graph <gr> must be biconnected.

     The algorithm used is the Demoucron's algorithm, which is a
     quadratic time algorithm.

     Example:
          (%i1) load (graphs)$
          (%i2) planar_embedding(grid_graph(3,3));
          (%o2) [[3, 6, 7, 8, 5, 2, 1, 0], [4, 3, 0, 1], [3, 4, 7, 6],
                                                [8, 7, 4, 5], [1, 2, 5, 4]]


 -- Function: print_graph (<gr>)
     Prints some information about the graph <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) c5 : cycle_graph(5)$
          (%i3) print_graph(c5)$
          Graph on 5 vertices with 5 edges.
          Adjacencies:
            4 :  0  3
            3 :  4  2
            2 :  3  1
            1 :  2  0
            0 :  4  1
          (%i4) dc5 : cycle_digraph(5)$
          (%i5) print_graph(dc5)$
          Digraph on 5 vertices with 5 arcs.
          Adjacencies:
            4 :  0
            3 :  4
            2 :  3
            1 :  2
            0 :  1
          (%i6) out_neighbors(0, dc5);
          (%o6)                          [1]


 -- Function: radius (<gr>)
     Returns the radius of the graph <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) radius(dodecahedron_graph());
          (%o2)                           5


 -- Function: set_edge_weight (<e>, <w>, <gr>)
     Assigns the weight <w> to the edge <e> in the graph <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) g : create_graph([1, 2], [[[1,2], 1.2]])$
          (%i3) get_edge_weight([1,2], g);
          (%o3)                          1.2
          (%i4) set_edge_weight([1,2], 2.1, g);
          (%o4)                         done
          (%i5) get_edge_weight([1,2], g);
          (%o5)                          2.1


 -- Function: set_vertex_label (<v>, <l>, <gr>)
     Assigns the label <l> to the vertex <v> in the graph <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) g : create_graph([[1, "One"], [2, "Two"]], [[1,2]])$
          (%i3) get_vertex_label(1, g);
          (%o3)                          One
          (%i4) set_vertex_label(1, "oNE", g);
          (%o4)                         done
          (%i5) get_vertex_label(1, g);
          (%o5)                          oNE


 -- Function: shortest_path (<u>, <v>, <gr>)
     Returns the shortest path from <u> to <v> in the graph <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) d : dodecahedron_graph()$
          (%i3) path : shortest_path(0, 7, d);
          (%o3)                   [0, 1, 19, 13, 7]
          (%i4) draw_graph(d, show_edges=vertices_to_path(path))$


 -- Function: shortest_weighted_path (<u>, <v>, <gr>)
     Returns the length of the shortest weighted path and the shortest
     weighted path from <u> to <v> in the graph <gr>.

     The length of a weighted path is the sum of edge weights of edges
     in the path. If an edge has no weight, then it has a default
     weight 1.

     Example:

          (%i1) load (graphs)$
          (%i2) g: petersen_graph(20, 2)$
          (%i3) for e in edges(g) do set_edge_weight(e, random(1.0), g)$
          (%i4) shortest_weighted_path(0, 10, g);
          (%o4) [2.575143920268482, [0, 20, 38, 36, 34, 32, 30, 10]]


 -- Function: strong_components (<gr>)
     Returns the strong components of a directed graph <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) t : random_tournament(4)$
          (%i3) strong_components(t);
          (%o3)                 [[1], [0], [2], [3]]
          (%i4) vertex_out_degree(3, t);
          (%o4)                           3


 -- Function: topological_sort (<dag>)
     Returns a topological sorting of the vertices of a directed graph
     <dag> or an empty list if <dag> is not a directed acyclic graph.

     Example:
          (%i1) load (graphs)$
          (%i2) g:create_graph(
                   [1,2,3,4,5],
                   [
                    [1,2], [2,5], [5,3],
                    [5,4], [3,4], [1,3]
                   ],
                   directed=true)$
          (%i3) topological_sort(g);
          (%o3)                    [1, 2, 5, 3, 4]


 -- Function: vertex_connectivity (<g>)
     Returns the vertex connectivity of the graph <g>.

     See also `min_vertex_cut'.


 -- Function: vertex_degree (<v>, <gr>)
     Returns the degree of the vertex <v> in the graph <gr>.


 -- Function: vertex_distance (<u>, <v>, <gr>)
     Returns the length of the shortest path between <u> and <v> in the
     (directed) graph <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) d : dodecahedron_graph()$
          (%i3) vertex_distance(0, 7, d);
          (%o3)                           4
          (%i4) shortest_path(0, 7, d);
          (%o4)                   [0, 1, 19, 13, 7]


 -- Function: vertex_eccentricity (<v>, <gr>)
     Returns the eccentricity of the vertex <v> in the graph <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) g:cycle_graph(7)$
          (%i3) vertex_eccentricity(0, g);
          (%o3)                           3


 -- Function: vertex_in_degree (<v>, <gr>)
     Returns the in-degree of the vertex <v> in the directed graph <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) p5 : path_digraph(5)$
          (%i3) print_graph(p5)$
          Digraph on 5 vertices with 4 arcs.
          Adjacencies:
            4 :
            3 :  4
            2 :  3
            1 :  2
            0 :  1
          (%i4) vertex_in_degree(4, p5);
          (%o4)                           1
          (%i5) in_neighbors(4, p5);
          (%o5)                          [3]


 -- Function: vertex_out_degree (<v>, <gr>)
     Returns the out-degree of the vertex <v> in the directed graph
     <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) t : random_tournament(10)$
          (%i3) vertex_out_degree(0, t);
          (%o3)                           2
          (%i4) out_neighbors(0, t);
          (%o4)                        [7, 1]


 -- Function: vertices (<gr>)
     Returns the list of vertices in the graph <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) vertices(complete_graph(4));
          (%o2)                     [3, 2, 1, 0]


 -- Function: vertex_coloring (<gr>)
     Returns an optimal coloring of the vertices of the graph <gr>.

     The function returns the chromatic number and a list representing
     the coloring of the vertices of <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) p:petersen_graph()$
          (%i3) vertex_coloring(p);
          (%o3) [3, [[0, 2], [1, 3], [2, 2], [3, 3], [4, 1], [5, 3],
                                           [6, 1], [7, 1], [8, 2], [9, 2]]]


 -- Function: wiener_index (<gr>)
     Returns the Wiener index of the graph <gr>.

     Example:
          (%i2) wiener_index(dodecahedron_graph());
          (%o2)                          500


56.2.3 Modifying graphs
-----------------------

 -- Function: add_edge (<e>, <gr>)
     Adds the edge <e> to the graph <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) p : path_graph(4)$
          (%i3) neighbors(0, p);
          (%o3)                          [1]
          (%i4) add_edge([0,3], p);
          (%o4)                         done
          (%i5) neighbors(0, p);
          (%o5)                        [3, 1]


 -- Function: add_edges (<e_list>, <gr>)
     Adds all edges in the list <e_list> to the graph <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) g : empty_graph(3)$
          (%i3) add_edges([[0,1],[1,2]], g)$
          (%i4) print_graph(g)$
          Graph on 3 vertices with 2 edges.
          Adjacencies:
            2 :  1
            1 :  2  0
            0 :  1


 -- Function: add_vertex (<v>, <gr>)
     Adds the vertex <v> to the graph <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) g : path_graph(2)$
          (%i3) add_vertex(2, g)$
          (%i4) print_graph(g)$
          Graph on 3 vertices with 1 edges.
          Adjacencies:
            2 :
            1 :  0
            0 :  1


 -- Function: add_vertices (<v_list>, <gr>)
     Adds all vertices in the list <v_list> to the graph <gr>.


 -- Function: connect_vertices (<v_list>, <u_list>, <gr>)
     Connects all vertices from the list <v_list> with the vertices in
     the list <u_list> in the graph <gr>.

     <v_list> and <u_list> can be single vertices or lists of vertices.

     Example:
          (%i1) load (graphs)$
          (%i2) g : empty_graph(4)$
          (%i3) connect_vertices(0, [1,2,3], g)$
          (%i4) print_graph(g)$
          Graph on 4 vertices with 3 edges.
          Adjacencies:
            3 :  0
            2 :  0
            1 :  0
            0 :  3  2  1


 -- Function: contract_edge (<e>, <gr>)
     Contracts the edge <e> in the graph <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) g: create_graph(
                8, [[0,3],[1,3],[2,3],[3,4],[4,5],[4,6],[4,7]])$
          (%i3) print_graph(g)$
          Graph on 8 vertices with 7 edges.
          Adjacencies:
            7 :  4
            6 :  4
            5 :  4
            4 :  7  6  5  3
            3 :  4  2  1  0
            2 :  3
            1 :  3
            0 :  3
          (%i4) contract_edge([3,4], g)$
          (%i5) print_graph(g)$
          Graph on 7 vertices with 6 edges.
          Adjacencies:
            7 :  3
            6 :  3
            5 :  3
            3 :  5  6  7  2  1  0
            2 :  3
            1 :  3
            0 :  3


 -- Function: remove_edge (<e>, <gr>)
     Removes the edge <e> from the graph <gr>.

     Example:
          (%i1) load (graphs)$
          (%i2) c3 : cycle_graph(3)$
          (%i3) remove_edge([0,1], c3)$
          (%i4) print_graph(c3)$
          Graph on 3 vertices with 2 edges.
          Adjacencies:
            2 :  0  1
            1 :  2
            0 :  2


 -- Function: remove_vertex (<v>, <gr>)
     Removes the vertex <v> from the graph <gr>.


56.2.4 Reading and writing to files
-----------------------------------

 -- Function: dimacs_export (<gr>, <fl>)
 -- Function: dimacs_export (<gr>, <fl>, <comment1>, ..., <commentn>)
     Exports the graph into the file <fl> in the DIMACS format. Optional
     comments will be added to the top of the file.


 -- Function: dimacs_import (<fl>)
     Returns the graph from file <fl> in the DIMACS format.


 -- Function: graph6_decode (<str>)
     Returns the graph encoded in the graph6 format in the string <str>.


 -- Function: graph6_encode (<gr>)
     Returns a string which encodes the graph <gr> in the graph6 format.


 -- Function: graph6_export (<gr_list>, <fl>)
     Exports graphs in the list <gr_list> to the file <fl> in the
     graph6 format.


 -- Function: graph6_import (<fl>)
     Returns a list of graphs from the file <fl> in the graph6 format.


 -- Function: sparse6_decode (<str>)
     Returns the graph encoded in the sparse6 format in the string
     <str>.


 -- Function: sparse6_encode (<gr>)
     Returns a string which encodes the graph <gr> in the sparse6
     format.


 -- Function: sparse6_export (<gr_list>, <fl>)
     Exports graphs in the list <gr_list> to the file <fl> in the
     sparse6 format.


 -- Function: sparse6_import (<fl>)
     Returns a list of graphs from the file <fl> in the sparse6 format.


56.2.5 Visualization
--------------------

 -- Function: draw_graph (<graph>)
 -- Function: draw_graph (<graph>, <option1>, ..., <optionk>)
     Draws the graph using the `draw' package.

     The algorithm used to position vertices is specified by the
     optional argument <program>. The default value is
     `program=spring_embedding'. <draw_graph> can also use the graphviz
     programs for positioning vertices, but graphviz must be installed
     separately.

     Example 1:

          (%i1) load (graphs)$
          (%i2) g:grid_graph(10,10)$
          (%i3) m:max_matching(g)$
          (%i4) draw_graph(g,
             spring_embedding_depth=100,
             show_edges=m, edge_type=dots,
             vertex_size=0)$

     Example 2:

          (%i1) load (graphs)$
          (%i2) g:create_graph(16,
              [
               [0,1],[1,3],[2,3],[0,2],[3,4],[2,4],
               [5,6],[6,4],[4,7],[6,7],[7,8],[7,10],[7,11],
               [8,10],[11,10],[8,9],[11,12],[9,15],[12,13],
               [10,14],[15,14],[13,14]
              ])$
          (%i3) t:minimum_spanning_tree(g)$
          (%i4) draw_graph(
              g,
              show_edges=edges(t),
              show_edge_width=4,
              show_edge_color=green,
              vertex_type=filled_square,
              vertex_size=2
              )$

     Example 3:

          (%i1) load (graphs)$
          (%i2) g:create_graph(16,
              [
               [0,1],[1,3],[2,3],[0,2],[3,4],[2,4],
               [5,6],[6,4],[4,7],[6,7],[7,8],[7,10],[7,11],
               [8,10],[11,10],[8,9],[11,12],[9,15],[12,13],
               [10,14],[15,14],[13,14]
              ])$
          (%i3) mi : max_independent_set(g)$
          (%i4) draw_graph(
              g,
              show_vertices=mi,
              show_vertex_type=filled_up_triangle,
              show_vertex_size=2,
              edge_color=cyan,
              edge_width=3,
              show_id=true,
              text_color=brown
              )$

     Example 4:

          (%i1) load (graphs)$
          (%i2) net : create_graph(
              [0,1,2,3,4,5],
              [
               [[0,1], 3], [[0,2], 2],
               [[1,3], 1], [[1,4], 3],
               [[2,3], 2], [[2,4], 2],
               [[4,5], 2], [[3,5], 2]
              ],
              directed=true
              )$
          (%i3) draw_graph(
              net,
              show_weight=true,
              vertex_size=0,
              show_vertices=[0,5],
              show_vertex_type=filled_square,
              head_length=0.2,
              head_angle=10,
              edge_color="dark-green",
              text_color=blue
              )$

     Example 5:

          (%i1) load(graphs)$
          (%i2) g: petersen_graph(20, 2);
          (%o2)                         GRAPH
          (%i3) draw_graph(g, redraw=true, program=planar_embedding);
          (%o3)                         done

     Example 6:

          (%i1) load(graphs)$
          (%i2) t: tutte_graph();
          (%o2)                         GRAPH
          (%i3) draw_graph(t, redraw=true,
                              fixed_vertices=[1,2,3,4,5,6,7,8,9]);
          (%o3)                         done


 -- Option variable: draw_graph_program
     Default value: <spring_embedding>

     The default value for the program used to position vertices in
     `draw_graph' program.


 -- draw_graph option: show_id
     Default value: <false>

     If <true> then ids of the vertices are displayed.


 -- draw_graph option: show_label
     Default value: <false>

     If <true> then labels of the vertices are displayed.


 -- draw_graph option: label_alignment
     Default value: <center>

     Determines how to align the labels/ids of the vertices. Can be
     `left', `center' or `right'.


 -- draw_graph option: show_weight
     Default value: <false>

     If <true> then weights of the edges are displayed.


 -- draw_graph option: vertex_type
     Default value: <circle>

     Defines how vertices are displayed. See the <point_type> option for
     the `draw' package for possible values.


 -- draw_graph option: vertex_size
     The size of vertices.


 -- draw_graph option: vertex_color
     The color used for displaying vertices.


 -- draw_graph option: show_vertices
     Default value: []

     Display selected vertices in the using a different color.


 -- draw_graph option: show_vertex_type
     Defines how vertices specified in <show_vertices> are displayed.
     See the <point_type> option for the `draw' package for possible
     values.


 -- draw_graph option: show_vertex_size
     The size of vertices in <show_vertices>.


 -- draw_graph option: show_vertex_color
     The color used for displaying vertices in the <show_vertices> list.


 -- draw_graph option: vertex_partition
     Default value: []

     A partition `[[v1,v2,...],...,[vk,...,vn]]' of the vertices of the
     graph. The vertices of each list in the partition will be drawn in
     a different color.


 -- draw_graph option: vertex_coloring
     Specifies coloring of the vertices. The coloring <col> must be
     specified in the format as returned by <vertex_coloring>.


 -- draw_graph option: edge_color
     The color used for displaying edges.


 -- draw_graph option: edge_width
     The width of edges.


 -- draw_graph option: edge_type
     Defines how edges are displayed. See the <line_type> option for the
     `draw' package.


 -- draw_graph option: show_edges
     Display edges specified in the list <e_list> using a different
     color.


 -- draw_graph option: show_edge_color
     The color used for displaying edges in the <show_edges> list.


 -- draw_graph option: show_edge_width
     The width of edges in <show_edges>.


 -- draw_graph option: show_edge_type
     Defines how edges in <show_edges> are displayed. See the
     <line_type> option for the `draw' package.


 -- draw_graph option: edge_partition
     A partition `[[e1,e2,...],...,[ek,...,em]]' of edges of the graph.
     The edges of each list in the partition will be drawn using a
     different color.


 -- draw_graph option: edge_coloring
     The coloring of edges. The coloring must be specified in the
     format as returned by the function <edge_coloring>.


 -- draw_graph option: redraw
     Default value: <false>

     If `true', vertex positions are recomputed even if the positions
     have been saved from a previous drawing of the graph.


 -- draw_graph option: head_angle
     Default value: 15

     The angle for the arrows displayed on arcs (in directed graphs).


 -- draw_graph option: head_length
     Default value: 0.1

     The length for the arrows displayed on arcs (in directed graphs).


 -- draw_graph option: spring_embedding_depth
     Default value: 50

     The number of iterations in the spring embedding graph drawing
     algorithm.


 -- draw_graph option: terminal
     The terminal used for drawing (see the <terminal> option in the
     `draw' package).


 -- draw_graph option: file_name
     The filename of the drawing if terminal is not screen.


 -- draw_graph option: program
     Defines the program used for positioning vertices of the graph.
     Can be one of the graphviz programs (dot, neato, twopi, circ, fdp),
     <circular>, <spring_embedding> or <planar_embedding>.
     <planar_embedding> is only available for 2-connected planar
     graphs. When `program=spring_embedding', a set of vertices with
     fixed position can be specified with the <fixed_vertices> option.


 -- draw_graph option: fixed_vertices
     Specifies a list of vertices which will have positions fixed along
     a regular polygon.  Can be used when `program=spring_embedding'.


 -- Function: vertices_to_path (<v_list>)
     Converts a list <v_list> of vertices to a list of edges of the path
     defined by <v_list>.


 -- Function: vertices_to_cycle (<v_list>)
     Converts a list <v_list> of vertices to a list of edges of the
     cycle defined by <v_list>.



File: maxima.info,  Node: grobner,  Next: impdiff,  Prev: graphs,  Up: Top

57 grobner
**********

* Menu:

* Introduction to grobner ::
* Functions and Variables for grobner ::


File: maxima.info,  Node: Introduction to grobner,  Next: Functions and Variables for grobner,  Prev: Top,  Up: Top

57.1 Introduction to grobner
============================

`grobner' is a package for working with Groebner bases in Maxima.

To use the following functions you must load the `grobner.lisp' package.

     load(grobner);

A demo can be started by
     demo("grobner.demo");

or
     batch("grobner.demo")

Some of the calculation in the demo will take a lot of time therefore
the output `grobner-demo.output' of the demo can be found in the same
directory as the demo file.

57.1.1 Notes on the grobner package
-----------------------------------

The package was written by

Marek Rychlik

`http://alamos.math.arizona.edu'

and is released 2002-05-24 under the terms of the General Public
License(GPL) (see file `grobner.lisp'.  This documentation was
extracted from the files
`README', `grobner.lisp', `grobner.demo', `grobner-demo.output'

by Gu"nter Nowak. Suggestions for improvement of the documentation can
be discussed at the _maxima_-mailing-list <maxima@math.utexas.edu>.
The code is a little bit out of date now. Modern implementation use the
fast _F4_ algorithm described in
A new efficient algorithm for computing Gro"bner bases (F4)
Jean-Charles Fauge`re
LIP6/CNRS Universite' Paris VI
January 20, 1999

57.1.2 Implementations of admissible monomial orders in grobner
---------------------------------------------------------------

   * `lex'

     pure lexicographic, default order for monomial comparisons

   * `grlex'

     total degree order, ties broken by lexicographic

   * `grevlex'

     total degree, ties broken by reverse lexicographic

   * `invlex'

     inverse lexicographic order



File: maxima.info,  Node: Functions and Variables for grobner,  Prev: Introduction to grobner,  Up: Top

57.2 Functions and Variables for grobner
========================================

57.2.1 Global switches for grobner
----------------------------------

 -- Option variable: poly_monomial_order
     Default value: `lex'

     This global switch controls which monomial order is used in
     polynomial and Groebner Bases calculations. If not set, `lex' will
     be used.


 -- Option variable: poly_coefficient_ring
     Default value: `expression_ring'

     This switch indicates the coefficient ring of the polynomials that
     will be used in grobner calculations. If not set, _maxima's_
     general expression ring will be used. This variable may be set to
     `ring_of_integers' if desired.


 -- Option variable: poly_primary_elimination_order
     Default value: `false'

     Name of the default order for eliminated variables in
     elimination-based functions. If not set, `lex' will be used.


 -- Option variable: poly_secondary_elimination_order
     Default value: `false'

     Name of the default order for kept variables in elimination-based
     functions. If not set, `lex' will be used.


 -- Option variable: poly_elimination_order
     Default value: `false'

     Name of the default elimination order used in elimination
     calculations. If set, it overrides the settings in variables
     `poly_primary_elimination_order' and
     `poly_secondary_elimination_order'.  The user must ensure that
     this is a true elimination order valid for the number of
     eliminated variables.


 -- Option variable: poly_return_term_list
     Default value: `false'

     If set to `true', all functions in this package will return each
     polynomial as a list of terms in the current monomial order rather
     than a _maxima_ general expression.


 -- Option variable: poly_grobner_debug
     Default value: `false'

     If set to `true', produce debugging and tracing output.


 -- Option variable: poly_grobner_algorithm
     Default value: `buchberger'

     Possible values:
        * `buchberger'

        * `parallel_buchberger'

        * `gebauer_moeller'

     The name of the algorithm used to find the Groebner Bases.


 -- Option variable: poly_top_reduction_only
     Default value: `false'

     If not `false', use top reduction only whenever possible. Top
     reduction means that division algorithm stops after the first
     reduction.


57.2.2 Simple operators in grobner
----------------------------------

`poly_add', `poly_subtract', `poly_multiply' and `poly_expt' are the
arithmetical operations on polynomials.  These are performed using the
internal representation, but the results are converted back to the
_maxima_ general form.

 -- Function: poly_add (<poly1>, <poly2>, <varlist>)
     Adds two polynomials <poly1> and <poly2>.

          (%i1) poly_add(z+x^2*y,x-z,[x,y,z]);
                                              2
          (%o1)                              x  y + x


 -- Function: poly_subtract (<poly1>, <poly2>, <varlist>)
     Subtracts a polynomial <poly2> from <poly1>.

          (%i1) poly_subtract(z+x^2*y,x-z,[x,y,z]);
                                                2
          (%o1)                          2 z + x  y - x


 -- Function: poly_multiply (<poly1>, <poly2>, <varlist>)
     Returns the product of polynomials <poly1> and <poly2>.

          (%i2) poly_multiply(z+x^2*y,x-z,[x,y,z])-(z+x^2*y)*(x-z),expand;
          (%o1)                                  0


 -- Function: poly_s_polynomial (<poly1>, <poly2>, <varlist>)
     Returns the _syzygy polynomial_ (_S-polynomial_) of two
     polynomials <poly1> and <poly2>.


 -- Function: poly_primitive_part (<poly1>, <varlist>)
     Returns the polynomial <poly> divided by the GCD of its
     coefficients.

          (%i1) poly_primitive_part(35*y+21*x,[x,y]);
          (%o1)                              5 y + 3 x


 -- Function: poly_normalize (<poly>, <varlist>)
     Returns the polynomial <poly> divided by the leading coefficient.
     It assumes that the division is possible, which may not always be
     the case in rings which are not fields.


57.2.3 Other functions in grobner
---------------------------------

 -- Function: poly_expand (<poly>, <varlist>)
     This function parses polynomials to internal form and back. It is
     equivalent to `expand(<poly>)' if <poly> parses correctly to a
     polynomial. If the representation is not compatible with a
     polynomial in variables <varlist>, the result is an error.  It can
     be used to test whether an expression correctly parses to the
     internal representation. The following examples illustrate that
     indexed and transcendental function variables are allowed.

          (%i1) poly_expand((x-y)*(y+x),[x,y]);
                                               2    2
          (%o1)                               x  - y
          (%i2) poly_expand((y+x)^2,[x,y]);
                                          2            2
          (%o2)                          y  + 2 x y + x
          (%i3) poly_expand((y+x)^5,[x,y]);
                            5      4         2  3       3  2      4      5
          (%o3)            y  + 5 x y  + 10 x  y  + 10 x  y  + 5 x  y + x
          (%i4) poly_expand(-1-x*exp(y)+x^2/sqrt(y),[x]);
                                                    2
                                            y      x
          (%o4)                       - x %e  + ------- - 1
                                                 sqrt(y)

          (%i5) poly_expand(-1-sin(x)^2+sin(x),[sin(x)]);
                                          2
          (%o5)                      - sin (x) + sin(x) - 1


 -- Function: poly_expt (<poly>, <number>, <varlist>)
     exponentitates <poly> by a positive integer <number>. If <number>
     is not a positive integer number an error will be raised.

          (%i1) poly_expt(x-y,3,[x,y])-(x-y)^3,expand;
          (%o1)                                  0


 -- Function: poly_content (<poly>. <varlist>)
     `poly_content' extracts the GCD of its coefficients

          (%i1) poly_content(35*y+21*x,[x,y]);
          (%o1)                                  7


 -- Function: poly_pseudo_divide (<poly>, <polylist>, <varlist>)
     Pseudo-divide a polynomial <poly> by the list of n polynomials
     <polylist>. Return multiple values. The first value is a list of
     quotients a. The second value is the remainder r. The third
     argument is a scalar coefficient c, such that c*poly can be
     divided by <polylist> within the ring of coefficients, which is
     not necessarily a field. Finally, the fourth value is an integer
     count of the number of reductions performed. The resulting objects
     satisfy the equation:

     c*poly=sum(a[i]*polylist[i],i=1...n)+r.


 -- Function: poly_exact_divide (<poly1>, <poly2>, <varlist>)
     Divide a polynomial <poly1> by another polynomial <poly2>. Assumes
     that exact division with no remainder is possible. Returns the
     quotient.


 -- Function: poly_normal_form (<poly>, <polylist>, <varlist>)
     `poly_normal_form' finds the normal form of a polynomial <poly>
     with respect to a set of polynomials <polylist>.


 -- Function: poly_buchberger_criterion (<polylist>, <varlist>)
     Returns `true' if <polylist> is a Groebner basis with respect to
     the current term order, by using the Buchberger criterion: for
     every two polynomials h1 and h2 in <polylist> the S-polynomial
     S(h1,h2) reduces to 0 modulo <polylist>.


 -- Function: poly_buchberger (<polylist_fl> <varlist>)
     `poly_buchberger' performs the Buchberger algorithm on a list of
     polynomials and returns the resulting Groebner basis.


57.2.4 Standard postprocessing of Groebner Bases
------------------------------------------------

The _k-th elimination Ideal_ I_k of an Ideal I over K[ x[1],...,x[n] ]
is the ideal intersect(I, K[ x[k+1],...,x[n] ]).
The _colon ideal_ I:J is the ideal {h|for all w in J: w*h in I}.
The ideal I:p^inf is the ideal {h| there is a n in N: p^n*h in I}.
The ideal I:J^inf is the ideal {h| there is a n in N and a p in J:
p^n*h in I}.
The _radical ideal_ sqrt(I) is the ideal {h| there is a n in N : h^n in
I }.



 -- Function: poly_reduction (<polylist>, <varlist>)
     `poly_reduction' reduces a list of polynomials <polylist>, so that
     each polynomial is fully reduced with respect to the other
     polynomials.


 -- Function: poly_minimization (<polylist>, <varlist>)
     Returns a sublist of the polynomial list <polylist> spanning the
     same monomial ideal as <polylist> but minimal, i.e. no leading
     monomial of a polynomial in the sublist divides the leading
     monomial of another polynomial.


 -- Function: poly_normalize_list (<polylist>, <varlist>)
     `poly_normalize_list' applies `poly_normalize' to each polynomial
     in the list.  That means it divides every polynomial in a list
     <polylist> by its leading coefficient.


 -- Function: poly_grobner (<polylist>, <varlist>)
     Returns a Groebner basis of the ideal span by the polynomials
     <polylist>. Affected by the global flags.


 -- Function: poly_reduced_grobner (<polylist>, <varlist>)
     Returns a reduced Groebner basis of the ideal span by the
     polynomials <polylist>. Affected by the global flags.


 -- Function: poly_depends_p (<poly>, <var>, <varlist>)
     `poly_depends' tests whether a polynomial depends on a variable
     <var>.


 -- Function: poly_elimination_ideal (<polylist>, <number>, <varlist>)
     `poly_elimination_ideal' returns the grobner basis of the
     number-th elimination ideal of an ideal specified as a list of
     generating polynomials (not necessarily Groebner basis).


 -- Function: poly_colon_ideal (<polylist1>, <polylist2>, <varlist>)
     Returns the reduced Groebner basis of the colon ideal

     I(polylist1):I(polylist2)

     where polylist1 and polylist2 are two lists of polynomials.


 -- Function: poly_ideal_intersection (<polylist1>, <polylist2>,
          <varlist>)
     `poly_ideal_intersection' returns the intersection of two ideals.


 -- Function: poly_lcm (<poly1>, <poly2>, <varlist>)
     Returns the lowest common multiple of <poly1> and <poly2>.


 -- Function: poly_gcd (<poly1>, <poly2>, <varlist>)
     Returns the greatest common divisor of <poly1> and <poly2>.

     See also `ezgcd',  `gcd',  `gcdex',  and `gcdivide'.

     Example:

          (%i1) p1:6*x^3+19*x^2+19*x+6;
                                  3       2
          (%o1)                6 x  + 19 x  + 19 x + 6
          (%i2) p2:6*x^5+13*x^4+12*x^3+13*x^2+6*x;
                            5       4       3       2
          (%o2)          6 x  + 13 x  + 12 x  + 13 x  + 6 x
          (%i3) poly_gcd(p1, p2, [x]);
                                      2
          (%o3)                    6 x  + 13 x + 6


 -- Function: poly_grobner_equal (<polylist1>, <polylist2>, <varlist>)
     `poly_grobner_equal' tests whether two Groebner Bases generate the
     same ideal.  Returns `true' if two lists of polynomials
     <polylist1> and <polylist2>, assumed to be Groebner Bases,
     generate the same ideal, and `false' otherwise.  This is
     equivalent to checking that every polynomial of the first basis
     reduces to 0 modulo the second basis and vice versa. Note that in
     the example below the first list is not a Groebner basis, and thus
     the result is `false'.

          (%i1) poly_grobner_equal([y+x,x-y],[x,y],[x,y]);
          (%o1)                         false


 -- Function: poly_grobner_subsetp (<polylist1>, <polylist2>, <varlist>)
     `poly_grobner_subsetp' tests whether an ideal generated by
     <polylist1> is contained in the ideal generated by <polylist2>.
     For this test to always succeed, <polylist2> must be a Groebner
     basis.


 -- Function: poly_grobner_member (<poly>, <polylist>, <varlist>)
     Returns `true' if a polynomial <poly> belongs to the ideal
     generated by the polynomial list <polylist>, which is assumed to
     be a Groebner basis. Returns `false' otherwise.

     `poly_grobner_member' tests whether a polynomial belongs to an
     ideal generated by a list of polynomials, which is assumed to be a
     Groebner basis. Equivalent to `normal_form' being 0.


 -- Function: poly_ideal_saturation1 (<polylist>, <poly>, <varlist>)
     Returns the reduced Groebner basis of the saturation of the ideal

     I(polylist):poly^inf

     Geometrically, over an algebraically closed field, this is the set
     of polynomials in the ideal generated by <polylist> which do not
     identically vanish on the variety of <poly>.


 -- Function: poly_ideal_saturation (<polylist1>, <polylist2>,
          <varlist>)
     Returns the reduced Groebner basis of the saturation of the ideal

     I(polylist1):I(polylist2)^inf

     Geometrically, over an algebraically closed field, this is the set
     of polynomials in the ideal generated by <polylist1> which do not
     identically vanish on the variety of <polylist2>.


 -- Function: poly_ideal_polysaturation1 (<polylist1>, <polylist2>,
          <varlist>)
     <polylist2> ist a list of n polynomials `[poly1,...,polyn]'.
     Returns the reduced Groebner basis of the ideal

     I(polylist):poly1^inf:...:polyn^inf

     obtained by a sequence of successive saturations in the polynomials
     of the polynomial list <polylist2> of the ideal generated by the
     polynomial list <polylist1>.


 -- Function: poly_ideal_polysaturation (<polylist>, <polylistlist>,
          <varlist>)
     <polylistlist> is a list of n list of polynomials
     `[polylist1,...,polylistn]'.  Returns the reduced Groebner basis
     of the saturation of the ideal

     I(polylist):I(polylist_1)^inf:...:I(polylist_n)^inf


 -- Function: poly_saturation_extension (<poly>, <polylist>,
          <varlist1>, <varlist2>)
     `poly_saturation_extension' implements the famous Rabinowitz trick.


 -- Function: poly_polysaturation_extension (<poly>, <polylist>,
          <varlist1>, <varlist2>)


File: maxima.info,  Node: impdiff,  Next: interpol,  Prev: grobner,  Up: Top

58 impdiff
**********

* Menu:

* Functions and Variables for impdiff::


File: maxima.info,  Node: Functions and Variables for impdiff,  Prev: impdiff,  Up: impdiff

58.1 Functions and Variables for impdiff
========================================

 -- Function: implicit_derivative
          (<f>,<indvarlist>,<orderlist>,<depvar>)
     This subroutine computes implicit derivatives of multivariable
     functions.  <f> is an array function, the indexes are the
     derivative degree in the <indvarlist> order; <indvarlist> is the
     independent variable list; <orderlist> is the order desired; and
     <depvar> is the dependent variable.

     To use this function write first `load("impdiff")'.



File: maxima.info,  Node: interpol,  Next: lapack,  Prev: impdiff,  Up: Top

59 interpol
***********

* Menu:

* Introduction to interpol::
* Functions and Variables for interpol::


File: maxima.info,  Node: Introduction to interpol,  Next: Functions and Variables for interpol,  Prev: interpol,  Up: interpol

59.1 Introduction to interpol
=============================

Package `interpol' defines the Lagrangian, the linear and the cubic
splines methods for polynomial interpolation.

   For comments, bugs or suggestions, please contact me at <'mario AT
edu DOT xunta DOT es'>.


File: maxima.info,  Node: Functions and Variables for interpol,  Prev: Introduction to interpol,  Up: interpol

59.2 Functions and Variables for interpol
=========================================

 -- Function: lagrange (<points>)
 -- Function: lagrange (<points>, <option>)
     Computes the polynomial interpolation by the Lagrangian method.
     Argument <points> must be either:

        * a two column matrix, `p:matrix([2,4],[5,6],[9,3])',

        * a list of pairs, `p: [[2,4],[5,6],[9,3]]',

        * a list of numbers, `p: [4,6,3]', in which case the abscissas
          will be assigned automatically to 1, 2, 3, etc.

     In the first two cases the pairs are ordered with respect to the
     first coordinate before making computations.

     With the <option> argument it is possible to select the name for
     the independent variable, which is `'x' by default; to define
     another one, write something like `varname='z'.

     Note that when working with high degree polynomials, floating
     point evaluations are unstable.

     See also `linearinterpol', `cspline', and `ratinterpol'.

     Examples:

          (%i1) load(interpol)$
          (%i2) p:[[7,2],[8,2],[1,5],[3,2],[6,7]]$
          (%i3) lagrange(p);
                 (x - 7) (x - 6) (x - 3) (x - 1)
          (%o3)  -------------------------------
                               35
             (x - 8) (x - 6) (x - 3) (x - 1)
           - -------------------------------
                           12
             7 (x - 8) (x - 7) (x - 3) (x - 1)
           + ---------------------------------
                            30
             (x - 8) (x - 7) (x - 6) (x - 1)
           - -------------------------------
                           60
             (x - 8) (x - 7) (x - 6) (x - 3)
           + -------------------------------
                           84
          (%i4) f(x):=''%;
                         (x - 7) (x - 6) (x - 3) (x - 1)
          (%o4)  f(x) := -------------------------------
                                       35
             (x - 8) (x - 6) (x - 3) (x - 1)
           - -------------------------------
                           12
             7 (x - 8) (x - 7) (x - 3) (x - 1)
           + ---------------------------------
                            30
             (x - 8) (x - 7) (x - 6) (x - 1)
           - -------------------------------
                           60
             (x - 8) (x - 7) (x - 6) (x - 3)
           + -------------------------------
                           84
          (%i5) /* Evaluate the polynomial at some points */
                expand(map(f,[2.3,5/7,%pi]));
                                            4          3           2
                              919062  73 %pi    701 %pi    8957 %pi
          (%o5)  [- 1.567535, ------, ------- - -------- + ---------
                              84035     420       210         420
                                                       5288 %pi   186
                                                     - -------- + ---]
                                                         105       5
          (%i6) %,numer;
          (%o6) [- 1.567535, 10.9366573451538, 2.89319655125692]
          (%i7) load(draw)$  /* load draw package */
          (%i8) /* Plot the polynomial together with points */
                draw2d(
                  color      = red,
                  key        = "Lagrange polynomial",
                  explicit(f(x),x,0,10),
                  point_size = 3,
                  color      = blue,
                  key        = "Sample points",
                  points(p))$
          (%i9) /* Change variable name */
                lagrange(p, varname=w);
                 (w - 7) (w - 6) (w - 3) (w - 1)
          (%o9)  -------------------------------
                               35
             (w - 8) (w - 6) (w - 3) (w - 1)
           - -------------------------------
                           12
             7 (w - 8) (w - 7) (w - 3) (w - 1)
           + ---------------------------------
                            30
             (w - 8) (w - 7) (w - 6) (w - 1)
           - -------------------------------
                           60
             (w - 8) (w - 7) (w - 6) (w - 3)
           + -------------------------------
                           84


 -- Function: charfun2 (<x>, <a>, <b>)
     Returns `true' if number <x> belongs to the interval [a, b), and
     `false' otherwise.


 -- Function: linearinterpol (<points>)
 -- Function: linearinterpol (<points>, <option>)
     Computes the polynomial interpolation by the linear method.
     Argument <points> must be either:

        * a two column matrix, `p:matrix([2,4],[5,6],[9,3])',

        * a list of pairs, `p: [[2,4],[5,6],[9,3]]',

        * a list of numbers, `p: [4,6,3]', in which case the abscissas
          will be assigned automatically to 1, 2, 3, etc.

     In the first two cases the pairs are ordered with respect to the
     first coordinate before making computations.

     With the <option> argument it is possible to select the name for
     the independent variable, which is `'x' by default; to define
     another one, write something like `varname='z'.

     See also `lagrange', `cspline', and `ratinterpol'.

     Examples:

          (%i1) load(interpol)$
          (%i2) p: matrix([7,2],[8,3],[1,5],[3,2],[6,7])$
          (%i3) linearinterpol(p);
                  13   3 x
          (%o3)  (-- - ---) charfun2(x, minf, 3)
                  2     2
           + (x - 5) charfun2(x, 7, inf) + (37 - 5 x) charfun2(x, 6, 7)
              5 x
           + (--- - 3) charfun2(x, 3, 6)
               3

          (%i4) f(x):=''%;
                          13   3 x
          (%o4)  f(x) := (-- - ---) charfun2(x, minf, 3)
                          2     2
           + (x - 5) charfun2(x, 7, inf) + (37 - 5 x) charfun2(x, 6, 7)
              5 x
           + (--- - 3) charfun2(x, 3, 6)
               3
          (%i5)  /* Evaluate the polynomial at some points */
                 map(f,[7.3,25/7,%pi]);
                                      62  5 %pi
          (%o5)                 [2.3, --, ----- - 3]
                                      21    3
          (%i6) %,numer;
          (%o6)  [2.3, 2.952380952380953, 2.235987755982989]
          (%i7) load(draw)$  /* load draw package */
          (%i8)  /* Plot the polynomial together with points */
                 draw2d(
                   color      = red,
                   key        = "Linear interpolator",
                   explicit(f(x),x,-5,20),
                   point_size = 3,
                   color      = blue,
                   key        = "Sample points",
                   points(args(p)))$
          (%i9)  /* Change variable name */
                 linearinterpol(p, varname='s);
                 13   3 s
          (%o9) (-- - ---) charfun2(s, minf, 3)
                 2     2
           + (s - 5) charfun2(s, 7, inf) + (37 - 5 s) charfun2(s, 6, 7)
              5 s
           + (--- - 3) charfun2(s, 3, 6)
               3


 -- Function: cspline (<points>)
 -- Function: cspline (<points>, <option1>, <option2>, ...)
     Computes the polynomial interpolation by the cubic splines method.
     Argument <points> must be either:

        * a two column matrix, `p:matrix([2,4],[5,6],[9,3])',

        * a list of pairs, `p: [[2,4],[5,6],[9,3]]',

        * a list of numbers, `p: [4,6,3]', in which case the abscissas
          will be assigned automatically to 1, 2, 3, etc.

     In the first two cases the pairs are ordered with respect to the
     first coordinate before making computations.

     There are three options to fit specific needs:
        * `'d1', default `'unknown', is the first derivative at x_1; if
          it is `'unknown', the second derivative at x_1 is made equal
          to 0 (natural cubic spline); if it is equal to a number, the
          second derivative is calculated based on this number.

        * `'dn', default `'unknown', is the first derivative at x_n; if
          it is `'unknown', the second derivative at x_n is made equal
          to 0 (natural cubic spline); if it is equal to a number, the
          second derivative is calculated based on this number.

        * `'varname', default `'x', is the name of the independent
          variable.

     See also `lagrange', `linearinterpol', and `ratinterpol'.

     Examples:
          (%i1) load(interpol)$
          (%i2) p:[[7,2],[8,2],[1,5],[3,2],[6,7]]$
          (%i3) /* Unknown first derivatives at the extremes
                   is equivalent to natural cubic splines */
                cspline(p);
                        3         2
                  1159 x    1159 x    6091 x   8283
          (%o3)  (------- - ------- - ------ + ----) charfun2(x, minf, 3)
                   3288      1096      3288    1096
                      3         2
                2587 x    5174 x    494117 x   108928
           + (- ------- + ------- - -------- + ------) charfun2(x, 7, inf)
                 1644       137       1644      137
                    3          2
              4715 x    15209 x    579277 x   199575
           + (------- - -------- + -------- - ------) charfun2(x, 6, 7)
               1644       274        1644      274
                      3         2
                3287 x    2223 x    48275 x   9609
           + (- ------- + ------- - ------- + ----) charfun2(x, 3, 6)
                 4932       274      1644     274

          (%i4) f(x):=''%$
          (%i5) /* Some evaluations */
                map(f,[2.3,5/7,%pi]), numer;
          (%o5) [1.991460766423356, 5.823200187269903, 2.227405312429507]
          (%i6) load(draw)$  /* load draw package */
          (%i7) /* Plotting interpolating function */
                draw2d(
                  color      = red,
                  key        = "Cubic splines",
                  explicit(f(x),x,0,10),
                  point_size = 3,
                  color      = blue,
                  key        = "Sample points",
                  points(p))$
          (%i8) /* New call, but giving values at the derivatives */
                cspline(p,d1=0,dn=0);
                        3          2
                  1949 x    11437 x    17027 x   1247
          (%o8)  (------- - -------- + ------- + ----) charfun2(x, minf, 3)
                   2256       2256      2256     752
                      3          2
                1547 x    35581 x    68068 x   173546
           + (- ------- + -------- - ------- + ------) charfun2(x, 7, inf)
                  564       564        141      141
                   3          2
              607 x    35147 x    55706 x   38420
           + (------ - -------- + ------- - -----) charfun2(x, 6, 7)
               188       564        141      47
                      3         2
                3895 x    1807 x    5146 x   2148
           + (- ------- + ------- - ------ + ----) charfun2(x, 3, 6)
                 5076       188      141      47
          (%i8) /* Defining new interpolating function */
                g(x):=''%$
          (%i9) /* Plotting both functions together */
                draw2d(
                  color      = black,
                  key        = "Cubic splines (default)",
                  explicit(f(x),x,0,10),
                  color      = red,
                  key        = "Cubic splines (d1=0,dn=0)",
                  explicit(g(x),x,0,10),
                  point_size = 3,
                  color      = blue,
                  key        = "Sample points",
                  points(p))$


 -- Function: ratinterpol (<points>, <numdeg>)
 -- Function: ratinterpol (<points>, <numdeg>, <option1>)
     Generates a rational interpolator for data given by <points> and
     the degree of the numerator being equal to <numdeg>; the degree of
     the denominator is calculated automatically. Argument <points>
     must be either:

        * a two column matrix, `p:matrix([2,4],[5,6],[9,3])',

        * a list of pairs, `p: [[2,4],[5,6],[9,3]]',

        * a list of numbers, `p: [4,6,3]', in which case the abscissas
          will be assigned automatically to 1, 2, 3, etc.

     In the first two cases the pairs are ordered with respect to the
     first coordinate before making computations.

     There is one option to fit specific needs:
        * `'varname', default `'x', is the name of the independent
          variable.

     See also `lagrange', `linearinterpol', `cspline',
     `minpack_lsquares', and `lbfgs'.

     Examples:

          (%i1) load(interpol)$
          (%i2) load(draw)$
          (%i3) p:[[7.2,2.5],[8.5,2.1],[1.6,5.1],[3.4,2.4],[6.7,7.9]]$
          (%i4) for k:0 thru length(p)-1 do
                  draw2d(
                    explicit(ratinterpol(p,k),x,0,9),
                    point_size = 3,
                    points(p),
                    title = concat("Degree of numerator = ",k),
                    yrange=[0,10])$



File: maxima.info,  Node: lapack,  Next: lbfgs,  Prev: interpol,  Up: Top

60 lapack
*********

* Menu:

* Introduction to lapack::
* Functions and Variables for lapack::


File: maxima.info,  Node: Introduction to lapack,  Next: Functions and Variables for lapack,  Prev: lapack,  Up: lapack

60.1 Introduction to lapack
===========================

`lapack' is a Common Lisp translation (via the program `f2c') of the
Fortran library LAPACK, as obtained from the SLATEC project.


File: maxima.info,  Node: Functions and Variables for lapack,  Prev: Introduction to lapack,  Up: lapack

60.2 Functions and Variables for lapack
=======================================

 -- Function: dgeev (<A>)
 -- Function: dgeev (<A>, <right_p>, <left_p>)
     Computes the eigenvalues and, optionally, the eigenvectors of a
     matrix <A>.  All elements of <A> must be integer or floating point
     numbers.  <A> must be square (same number of rows and columns).
     <A> might or might not be symmetric.

     `dgeev(<A>)' computes only the eigenvalues of <A>.  `dgeev(<A>,
     <right_p>, <left_p>)' computes the eigenvalues of <A> and the
     right eigenvectors when <right_p> = `true' and the left
     eigenvectors when <left_p> = `true'.

     A list of three items is returned.  The first item is a list of
     the eigenvalues.  The second item is `false' or the matrix of
     right eigenvectors.  The third item is `false' or the matrix of
     left eigenvectors.

     The right eigenvector v(j) (the j-th column of the right
     eigenvector matrix) satisfies

     A . v(j) = lambda(j) . v(j)

     where lambda(j) is the corresponding eigenvalue.  The left
     eigenvector u(j) (the j-th column of the left eigenvector matrix)
     satisfies

     u(j)**H . A = lambda(j) . u(j)**H

     where u(j)**H denotes the conjugate transpose of u(j).  The Maxima
     function `ctranspose' computes the conjugate transpose.

     The computed eigenvectors are normalized to have Euclidean norm
     equal to 1, and largest component has imaginary part equal to zero.

     Example:

          (%i1) load (lapack)$
          (%i2) fpprintprec : 6;
          (%o2)                           6
          (%i3) M : matrix ([9.5, 1.75], [3.25, 10.45]);
                                   [ 9.5   1.75  ]
          (%o3)                    [             ]
                                   [ 3.25  10.45 ]
          (%i4) dgeev (M);
          (%o4)          [[7.54331, 12.4067], false, false]
          (%i5) [L, v, u] : dgeev (M, true, true);
                                     [ - .666642  - .515792 ]
          (%o5) [[7.54331, 12.4067], [                      ],
                                     [  .745378   - .856714 ]
                                                  [ - .856714  - .745378 ]
                                                  [                      ]]
                                                  [  .515792   - .666642 ]
          (%i6) D : apply (diag_matrix, L);
                                [ 7.54331     0    ]
          (%o6)                 [                  ]
                                [    0     12.4067 ]
          (%i7) M . v - v . D;
                          [      0.0       - 8.88178E-16 ]
          (%o7)           [                              ]
                          [ - 8.88178E-16       0.0      ]
          (%i8) transpose (u) . M - D . transpose (u);
                               [ 0.0  - 4.44089E-16 ]
          (%o8)                [                    ]
                               [ 0.0       0.0      ]


 -- Function: dgeqrf (<A>)
     Computes the QR decomposition of the matrix <A>.  All elements of
     <A> must be integer or floating point numbers.  <A> may or may not
     have the same number of rows and columns.

     A list of two items is returned.  The first item is the matrix
     <Q>, which is a square, orthonormal matrix which has the same
     number of rows as <A>.  The second item is the matrix <R>, which
     is the same size as <A>, and which has all elements equal to zero
     below the diagonal.  The product `<Q> . <R>', where "." is the
     noncommutative multiplication operator, is equal to <A> (ignoring
     floating point round-off errors).

          (%i1) load (lapack) $
          (%i2) fpprintprec : 6 $
          (%i3) M : matrix ([1, -3.2, 8], [-11, 2.7, 5.9]) $
          (%i4) [q, r] : dgeqrf (M);
                 [ - .0905357  .995893  ]
          (%o4) [[                      ],
                 [  .995893    .0905357 ]
                                         [ - 11.0454   2.97863   5.15148 ]
                                         [                               ]]
                                         [     0      - 2.94241  8.50131 ]
          (%i5) q . r - M;
                   [ - 7.77156E-16   1.77636E-15   - 8.88178E-16 ]
          (%o5)    [                                             ]
                   [      0.0       - 1.33227E-15   8.88178E-16  ]
          (%i6) mat_norm (%, 1);
          (%o6)                      3.10862E-15


 -- Function: dgesv (<A>, <b>)
     Computes the solution <x> of the linear equation <A> <x> = <b>,
     where <A> is a square matrix, and <b> is a matrix of the same
     number of rows as <A> and any number of columns.  The return value
     <x> is the same size as <b>.

     The elements of <A> and <b> must evaluate to real floating point
     numbers via `float'; thus elements may be any numeric type,
     symbolic numerical constants, or expressions which evaluate to
     floats.  The elements of <x> are always floating point numbers.
     All arithmetic is carried out as floating point operations.

     `dgesv' computes the solution via the LU decomposition of <A>.

     Examples:

     `dgesv' computes the solution of the linear equation <A> <x> = <b>.

          (%i1) A : matrix ([1, -2.5], [0.375, 5]);
                                         [   1    - 2.5 ]
          (%o1)                          [              ]
                                         [ 0.375    5   ]
          (%i2) b : matrix ([1.75], [-0.625]);
                                            [  1.75   ]
          (%o2)                             [         ]
                                            [ - 0.625 ]
          (%i3) x : dgesv (A, b);
                                      [  1.210526315789474  ]
          (%o3)                       [                     ]
                                      [ - 0.215789473684211 ]
          (%i4) dlange (inf_norm, b - A.x);
          (%o4)                                 0.0

     <b> is a matrix with the same number of rows as <A> and any number
     of columns.  <x> is the same size as <b>.

          (%i1) A : matrix ([1, -0.15], [1.82, 2]);
                                         [  1    - 0.15 ]
          (%o1)                          [              ]
                                         [ 1.82    2    ]
          (%i2) b : matrix ([3.7, 1, 8], [-2.3, 5, -3.9]);
                                        [  3.7   1    8   ]
          (%o2)                         [                 ]
                                        [ - 2.3  5  - 3.9 ]
          (%i3) x : dgesv (A, b);
                [  3.103827540695117  1.20985481742191    6.781786185657722 ]
          (%o3) [                                                           ]
                [ -3.974483062032557  1.399032116146062  -8.121425428948527 ]
          (%i4) dlange (inf_norm, b - A . x);
          (%o4)                       1.1102230246251565E-15

     The elements of <A> and <b> must evaluate to real floating point
     numbers.

          (%i1) A : matrix ([5, -%pi], [1b0, 11/17]);
                                         [   5    - %pi ]
                                         [              ]
          (%o1)                          [         11   ]
                                         [ 1.0b0   --   ]
                                         [         17   ]
          (%i2) b : matrix ([%e], [sin(1)]);
                                            [   %e   ]
          (%o2)                             [        ]
                                            [ sin(1) ]
          (%i3) x : dgesv (A, b);
                                       [ 0.690375643155986 ]
          (%o3)                        [                   ]
                                       [ 0.233510982552952 ]
          (%i4) dlange (inf_norm, b - A . x);
          (%o4)                        2.220446049250313E-16


 -- Function: dgesvd (<A>)
 -- Function: dgesvd (<A>, <left_p>, <right_p>)
     Computes the singular value decomposition (SVD) of a matrix <A>,
     comprising the singular values and, optionally, the left and right
     singular vectors.  All elements of <A> must be integer or floating
     point numbers.  <A> might or might not be square (same number of
     rows and columns).

     Let m be the number of rows, and n the number of columns of <A>.
     The singular value decomposition of <A> comprises three matrices,
     <U>, <Sigma>, and <V^T>, such that

     <A> = <U> . <Sigma> . <V>^T

     where <U> is an m-by-m unitary matrix, <Sigma> is an m-by-n
     diagonal matrix, and <V^T> is an n-by-n unitary matrix.

     Let sigma[i] be a diagonal element of Sigma, that is, <Sigma>[i,
     i] = <sigma>[i].  The elements sigma[i] are the so-called singular
     values of <A>; these are real and nonnegative, and returned in
     descending order.  The first min(m, n) columns of <U> and <V> are
     the left and right singular vectors of <A>.  Note that `dgesvd'
     returns the transpose of <V>, not <V> itself.

     `dgesvd(<A>)' computes only the singular values of <A>.
     `dgesvd(<A>, <left_p>, <right_p>)' computes the singular values of
     <A> and the left singular vectors when <left_p> = `true' and the
     right singular vectors when <right_p> = `true'.

     A list of three items is returned.  The first item is a list of
     the singular values.  The second item is `false' or the matrix of
     left singular vectors.  The third item is `false' or the matrix of
     right singular vectors.

     Example:

          (%i1) load (lapack)$
          (%i2) fpprintprec : 6;
          (%o2)                           6
          (%i3) M: matrix([1, 2, 3], [3.5, 0.5, 8], [-1, 2, -3], [4, 9, 7]);
                                  [  1    2    3  ]
                                  [               ]
                                  [ 3.5  0.5   8  ]
          (%o3)                   [               ]
                                  [ - 1   2   - 3 ]
                                  [               ]
                                  [  4    9    7  ]
          (%i4) dgesvd (M);
          (%o4)      [[14.4744, 6.38637, .452547], false, false]
          (%i5) [sigma, U, VT] : dgesvd (M, true, true);
          (%o5) [[14.4744, 6.38637, .452547],
          [ - .256731  .00816168   .959029    - .119523 ]
          [                                             ]
          [ - .526456   .672116   - .206236   - .478091 ]
          [                                             ],
          [  .107997   - .532278  - .0708315  - 0.83666 ]
          [                                             ]
          [ - .803287  - .514659  - .180867    .239046  ]
          [ - .374486  - .538209  - .755044 ]
          [                                 ]
          [  .130623   - .836799   0.5317   ]]
          [                                 ]
          [ - .917986   .100488    .383672  ]
          (%i6) m : length (U);
          (%o6)                           4
          (%i7) n : length (VT);
          (%o7)                           3
          (%i8) Sigma:
                  genmatrix(lambda ([i, j], if i=j then sigma[i] else 0),
                            m, n);
                            [ 14.4744     0        0    ]
                            [                           ]
                            [    0     6.38637     0    ]
          (%o8)             [                           ]
                            [    0        0     .452547 ]
                            [                           ]
                            [    0        0        0    ]
          (%i9) U . Sigma . VT - M;
                    [  1.11022E-15        0.0       1.77636E-15 ]
                    [                                           ]
                    [  1.33227E-15    1.66533E-15       0.0     ]
          (%o9)     [                                           ]
                    [ - 4.44089E-16  - 8.88178E-16  4.44089E-16 ]
                    [                                           ]
                    [  8.88178E-16    1.77636E-15   8.88178E-16 ]
          (%i10) transpose (U) . U;
                 [     1.0      5.55112E-17    2.498E-16     2.77556E-17  ]
                 [                                                        ]
                 [ 5.55112E-17      1.0       5.55112E-17    4.16334E-17  ]
          (%o10) [                                                        ]
                 [  2.498E-16   5.55112E-17       1.0       - 2.08167E-16 ]
                 [                                                        ]
                 [ 2.77556E-17  4.16334E-17  - 2.08167E-16       1.0      ]
          (%i11) VT . transpose (VT);
                    [      1.0           0.0      - 5.55112E-17 ]
                    [                                           ]
          (%o11)    [      0.0           1.0       5.55112E-17  ]
                    [                                           ]
                    [ - 5.55112E-17  5.55112E-17       1.0      ]


 -- Function: dlange (<norm>, <A>)
 -- Function: zlange (<norm>, <A>)
     Computes a norm or norm-like function of the matrix <A>.

    `max'
          Compute max(abs(A(i, j))) where i and j range over the rows
          and columns, respectively, of <A>.  Note that this function
          is not a proper matrix norm.

    `one_norm'
          Compute the L[1] norm of <A>, that is, the maximum of the sum
          of the absolute value of elements in each column.

    `inf_norm'
          Compute the L[inf] norm of <A>, that is, the maximum of the
          sum of the absolute value of elements in each row.

    `frobenius'
          Compute the Frobenius norm of <A>, that is, the square root
          of the sum of squares of the matrix elements.


 -- Function: dgemm (<A>, <B>)
 -- Function: dgemm (<A>, <B>, <options>)
     Compute the product of two matrices and optionally add the product
     to a third matrix.

     In the simplest form, `dgemm(<A>, <B>)' computes the product of
     the two real matrices, <A> and <B>.

     In the second form, `dgemm' computes the <alpha> * <A> * <B> +
     <beta> * <C> where <A>, <B>, <C> are real matrices of the
     appropriate sizes and <alpha> and <beta> are real numbers.
     Optionally, <A> and/or <B> can be transposed before computing the
     product.  The extra parameters are specifed by optional keyword
     arguments: The keyword arguments are optional and may be specified
     in any order.  They all take the form `key=val'.  The keyword
     arguments are:

    <C>
          The matrix <C> that should be added.  The default is `false',
          which means no matrix is added.

    <alpha>
          The product of <A> and <B> is multiplied by this value.  The
          default is 1.

    <beta>
          If a matrix <C> is given, this value multiplies <C> before it
          is added.  The default value is 0, which implies that <C> is
          not added, even if <C> is given.  Hence, be sure to specify a
          non-zero value for <beta>.

    <transpose_a>
          If `true', the transpose of <A> is used instead of <A> for
          the product.  The default is `false'.

    <transpose_b>
          If `true', the transpose of <B> is used instead of <B> for
          the product.  The default is `false'.

          (%i1) load (lapack)$
          (%i2) A : matrix([1,2,3],[4,5,6],[7,8,9]);
                                            [ 1  2  3 ]
                                            [         ]
          (%o2)                             [ 4  5  6 ]
                                            [         ]
                                            [ 7  8  9 ]
          (%i3) B : matrix([-1,-2,-3],[-4,-5,-6],[-7,-8,-9]);
                                         [ - 1  - 2  - 3 ]
                                         [               ]
          (%o3)                          [ - 4  - 5  - 6 ]
                                         [               ]
                                         [ - 7  - 8  - 9 ]
          (%i4) C : matrix([3,2,1],[6,5,4],[9,8,7]);
                                            [ 3  2  1 ]
                                            [         ]
          (%o4)                             [ 6  5  4 ]
                                            [         ]
                                            [ 9  8  7 ]
          (%i5) dgemm(A,B);
                                   [ - 30.0   - 36.0   - 42.0  ]
                                   [                           ]
          (%o5)                    [ - 66.0   - 81.0   - 96.0  ]
                                   [                           ]
                                   [ - 102.0  - 126.0  - 150.0 ]
          (%i6) A . B;
                                      [ - 30   - 36   - 42  ]
                                      [                     ]
          (%o6)                       [ - 66   - 81   - 96  ]
                                      [                     ]
                                      [ - 102  - 126  - 150 ]
          (%i7) dgemm(A,B,transpose_a=true);
                                   [ - 66.0  - 78.0   - 90.0  ]
                                   [                          ]
          (%o7)                    [ - 78.0  - 93.0   - 108.0 ]
                                   [                          ]
                                   [ - 90.0  - 108.0  - 126.0 ]
          (%i8) transpose(A) . B;
                                     [ - 66  - 78   - 90  ]
                                     [                    ]
          (%o8)                      [ - 78  - 93   - 108 ]
                                     [                    ]
                                     [ - 90  - 108  - 126 ]
          (%i9) dgemm(A,B,c=C,beta=1);
                                   [ - 27.0  - 34.0   - 41.0  ]
                                   [                          ]
          (%o9)                    [ - 60.0  - 76.0   - 92.0  ]
                                   [                          ]
                                   [ - 93.0  - 118.0  - 143.0 ]
          (%i10) A . B + C;
                                      [ - 27  - 34   - 41  ]
                                      [                    ]
          (%o10)                      [ - 60  - 76   - 92  ]
                                      [                    ]
                                      [ - 93  - 118  - 143 ]
          (%i11) dgemm(A,B,c=C,beta=1, alpha=-1);
                                      [ 33.0   38.0   43.0  ]
                                      [                     ]
          (%o11)                      [ 72.0   86.0   100.0 ]
                                      [                     ]
                                      [ 111.0  134.0  157.0 ]
          (%i12) -A . B + C;
                                         [ 33   38   43  ]
                                         [               ]
          (%o12)                         [ 72   86   100 ]
                                         [               ]
                                         [ 111  134  157 ]



File: maxima.info,  Node: lbfgs,  Next: lindstedt,  Prev: lapack,  Up: Top

61 lbfgs
********

* Menu:

* Introduction to lbfgs::
* Functions and Variables for lbfgs::


File: maxima.info,  Node: Introduction to lbfgs,  Next: Functions and Variables for lbfgs,  Prev: Top,  Up: Top

61.1 Introduction to lbfgs
==========================

`lbfgs' is an implementation of the L-BFGS algorithm [1] to solve
unconstrained minimization problems via a limited-memory quasi-Newton
(BFGS) algorithm.  It is called a limited-memory method because a
low-rank approximation of the Hessian matrix inverse is stored instead
of the entire Hessian inverse.  The program was originally written in
Fortran [2] by Jorge Nocedal, incorporating some functions originally
written by Jorge J. More' and David J. Thuente, and translated into
Lisp automatically via the program `f2cl'.  The Maxima package `lbfgs'
comprises the translated code plus an interface function which manages
some details.

   References:

   [1] D. Liu and J. Nocedal. "On the limited memory BFGS method for
large scale optimization". Mathematical Programming B 45:503-528 (1989)

   [2] `http://netlib.org/opt/lbfgs_um.shar'


File: maxima.info,  Node: Functions and Variables for lbfgs,  Prev: Introduction to lbfgs,  Up: Top

61.2 Functions and Variables for lbfgs
======================================

 -- Function: lbfgs (<FOM>, <X>, <X0>, <epsilon>, <iprint>)
 -- Function: lbfgs ([<FOM>, <grad>] <X>, <X0>, <epsilon>, <iprint>)
     Finds an approximate solution of the unconstrained minimization of
     the figure of merit <FOM> over the list of variables <X>, starting
     from initial estimates <X0>, such that norm(grad(FOM)) <
     epsilon*max(1, norm(X)).

     <grad>, if present, is the gradient of <FOM> with respect to the
     variables <X>.  <grad> is a list, with one element for each
     element of <X>.  If not present, the gradient is computed
     automatically by symbolic differentiation.

     The algorithm applied is a limited-memory quasi-Newton (BFGS)
     algorithm [1].  It is called a limited-memory method because a
     low-rank approximation of the Hessian matrix inverse is stored
     instead of the entire Hessian inverse.  Each iteration of the
     algorithm is a line search, that is, a search along a ray in the
     variables <X>, with the search direction computed from the
     approximate Hessian inverse.  The FOM is always decreased by a
     successful line search.  Usually (but not always) the norm of the
     gradient of FOM also decreases.

     <iprint> controls progress messages printed by `lbfgs'.

    `iprint[1]'
          `<iprint>[1]' controls the frequency of progress messages.
         `iprint[1] < 0'
               No progress messages.

         `iprint[1] = 0'
               Messages at the first and last iterations.

         `iprint[1] > 0'
               Print a message every `<iprint>[1]' iterations.

    `iprint[2]'
          `<iprint>[2]' controls the verbosity of progress messages.
         `iprint[2] = 0'
               Print out iteration count, number of evaluations of
               <FOM>, value of <FOM>, norm of the gradient of <FOM>,
               and step length.

         `iprint[2] = 1'
               Same as `<iprint>[2] = 0', plus <X0> and the gradient of
               <FOM> evaluated at <X0>.

         `iprint[2] = 2'
               Same as `<iprint>[2] = 1', plus values of <X> at each
               iteration.

         `iprint[2] = 3'
               Same as `<iprint>[2] = 2', plus the gradient of <FOM> at
               each iteration.

     The columns printed by `lbfgs' are the following.

    `I'
          Number of iterations. It is incremented for each line search.

    `NFN'
          Number of evaluations of the figure of merit.

    `FUNC'
          Value of the figure of merit at the end of the most recent
          line search.

    `GNORM'
          Norm of the gradient of the figure of merit at the end of the
          most recent line search.

    `STEPLENGTH'
          An internal parameter of the search algorithm.

     Additional information concerning details of the algorithm are
     found in the comments of the original Fortran code [2].

     See also `lbfgs_nfeval_max' and `lbfgs_ncorrections'.

     References:

     [1] D. Liu and J. Nocedal. "On the limited memory BFGS method for
     large scale optimization". Mathematical Programming B 45:503-528
     (1989)

     [2] `http://netlib.org/opt/lbfgs_um.shar'

     Examples:

     The same FOM as computed by FGCOMPUTE in the program sdrive.f in
     the LBFGS package from Netlib.  Note that the variables in
     question are subscripted variables.  The FOM has an exact minimum
     equal to zero at u[k] = 1 for k = 1, ..., 8.

          (%i1) load (lbfgs);
          (%o1)   /usr/share/maxima/5.10.0cvs/share/lbfgs/lbfgs.mac
          (%i2) t1[j] := 1 - u[j];
          (%o2)                     t1  := 1 - u
                                      j         j
          (%i3) t2[j] := 10*(u[j + 1] - u[j]^2);
                                                    2
          (%o3)                t2  := 10 (u      - u )
                                 j         j + 1    j
          (%i4) n : 8;
          (%o4)                           8
          (%i5) FOM : sum (t1[2*j - 1]^2 + t2[2*j - 1]^2, j, 1, n/2);
                           2 2           2              2 2           2
          (%o5) 100 (u  - u )  + (1 - u )  + 100 (u  - u )  + (1 - u )
                      8    7           7           6    5           5
                               2 2           2              2 2           2
                  + 100 (u  - u )  + (1 - u )  + 100 (u  - u )  + (1 - u )
                          4    3           3           2    1           1
          (%i6) lbfgs (FOM, '[u[1],u[2],u[3],u[4],u[5],u[6],u[7],u[8]],
                 [-1.2, 1, -1.2, 1, -1.2, 1, -1.2, 1], 1e-3, [1, 0]);
          *************************************************
            N=    8   NUMBER OF CORRECTIONS=25
                 INITIAL VALUES
           F=  9.680000000000000D+01   GNORM=  4.657353755084532D+02
          *************************************************

           I NFN   FUNC                    GNORM                   STEPLENGTH

           1   3   1.651479526340304D+01   4.324359291335977D+00   7.926153934390631D-04
           2   4   1.650209316638371D+01   3.575788161060007D+00   1.000000000000000D+00
           3   5   1.645461701312851D+01   6.230869903601577D+00   1.000000000000000D+00
           4   6   1.636867301275588D+01   1.177589920974980D+01   1.000000000000000D+00
           5   7   1.612153014409201D+01   2.292797147151288D+01   1.000000000000000D+00
           6   8   1.569118407390628D+01   3.687447158775571D+01   1.000000000000000D+00
           7   9   1.510361958398942D+01   4.501931728123680D+01   1.000000000000000D+00
           8  10   1.391077875774294D+01   4.526061463810632D+01   1.000000000000000D+00
           9  11   1.165625686278198D+01   2.748348965356917D+01   1.000000000000000D+00
          10  12   9.859422687859137D+00   2.111494974231644D+01   1.000000000000000D+00
          11  13   7.815442521732281D+00   6.110762325766556D+00   1.000000000000000D+00
          12  15   7.346380905773160D+00   2.165281166714631D+01   1.285316401779533D-01
          13  16   6.330460634066370D+00   1.401220851762050D+01   1.000000000000000D+00
          14  17   5.238763939851439D+00   1.702473787613255D+01   1.000000000000000D+00
          15  18   3.754016790406701D+00   7.981845727704576D+00   1.000000000000000D+00
          16  20   3.001238402309352D+00   3.925482944716691D+00   2.333129631296807D-01
          17  22   2.794390709718290D+00   8.243329982546473D+00   2.503577283782332D-01
          18  23   2.563783562918759D+00   1.035413426521790D+01   1.000000000000000D+00
          19  24   2.019429976377856D+00   1.065187312346769D+01   1.000000000000000D+00
          20  25   1.428003167670903D+00   2.475962450826961D+00   1.000000000000000D+00
          21  27   1.197874264861340D+00   8.441707983493810D+00   4.303451060808756D-01
          22  28   9.023848941942773D-01   1.113189216635162D+01   1.000000000000000D+00
          23  29   5.508226405863770D-01   2.380830600326308D+00   1.000000000000000D+00
          24  31   3.902893258815567D-01   5.625595816584421D+00   4.834988416524465D-01
          25  32   3.207542206990315D-01   1.149444645416472D+01   1.000000000000000D+00
          26  33   1.874468266362791D-01   3.632482152880997D+00   1.000000000000000D+00
          27  34   9.575763380706598D-02   4.816497446154354D+00   1.000000000000000D+00
          28  35   4.085145107543406D-02   2.087009350166495D+00   1.000000000000000D+00
          29  36   1.931106001379290D-02   3.886818608498966D+00   1.000000000000000D+00
          30  37   6.894000721499670D-03   3.198505796342214D+00   1.000000000000000D+00
          31  38   1.443296033051864D-03   1.590265471025043D+00   1.000000000000000D+00
          32  39   1.571766603154336D-04   3.098257063980634D-01   1.000000000000000D+00
          33  40   1.288011776581970D-05   1.207784183577257D-02   1.000000000000000D+00
          34  41   1.806140173752971D-06   4.587890233385193D-02   1.000000000000000D+00
          35  42   1.769004645459358D-07   1.790537375052208D-02   1.000000000000000D+00
          36  43   3.312164100763217D-10   6.782068426119681D-04   1.000000000000000D+00


           THE MINIMIZATION TERMINATED WITHOUT DETECTING ERRORS.
           IFLAG = 0
          (%o6) [u  = 1.000005339815974, u  = 1.000009942839805,
                  1                       2
          u  = 1.000005339815974, u  = 1.000009942839805,
           3                       4
          u  = 1.000005339815974, u  = 1.000009942839805,
           5                       6
          u  = 1.000005339815974, u  = 1.000009942839805]
           7                       8

     A regression problem.  The FOM is the mean square difference
     between the predicted value F(X[i]) and the observed value Y[i].
     The function F is a bounded monotone function (a so-called
     "sigmoidal" function).  In this example, `lbfgs' computes
     approximate values for the parameters of F and `plot2d' displays a
     comparison of F with the observed data.

          (%i1) load (lbfgs);
          (%o1)   /usr/share/maxima/5.10.0cvs/share/lbfgs/lbfgs.mac
          (%i2) FOM : '((1/length(X))*sum((F(X[i]) - Y[i])^2, i, 1,
                                                          length(X)));
                                         2
                         sum((F(X ) - Y ) , i, 1, length(X))
                                 i     i
          (%o2)          -----------------------------------
                                      length(X)
          (%i3) X : [1, 2, 3, 4, 5];
          (%o3)                    [1, 2, 3, 4, 5]
          (%i4) Y : [0, 0.5, 1, 1.25, 1.5];
          (%o4)                [0, 0.5, 1, 1.25, 1.5]
          (%i5) F(x) := A/(1 + exp(-B*(x - C)));
                                             A
          (%o5)            F(x) := ----------------------
                                   1 + exp((- B) (x - C))
          (%i6) ''FOM;
                          A               2            A                2
          (%o6) ((----------------- - 1.5)  + (----------------- - 1.25)
                    - B (5 - C)                  - B (4 - C)
                  %e            + 1            %e            + 1
                      A             2            A               2
           + (----------------- - 1)  + (----------------- - 0.5)
                - B (3 - C)                - B (2 - C)
              %e            + 1          %e            + 1
                       2
                      A
           + --------------------)/5
                - B (1 - C)     2
             (%e            + 1)
          (%i7) estimates : lbfgs (FOM, '[A, B, C], [1, 1, 1], 1e-4, [1, 0]);
          *************************************************
            N=    3   NUMBER OF CORRECTIONS=25
                 INITIAL VALUES
           F=  1.348738534246918D-01   GNORM=  2.000215531936760D-01
          *************************************************

          I  NFN  FUNC                    GNORM                   STEPLENGTH
          1    3  1.177820636622582D-01   9.893138394953992D-02   8.554435968992371D-01
          2    6  2.302653892214013D-02   1.180098521565904D-01   2.100000000000000D+01
          3    8  1.496348495303005D-02   9.611201567691633D-02   5.257340567840707D-01
          4    9  7.900460841091139D-03   1.325041647391314D-02   1.000000000000000D+00
          5   10  7.314495451266917D-03   1.510670810312237D-02   1.000000000000000D+00
          6   11  6.750147275936680D-03   1.914964958023047D-02   1.000000000000000D+00
          7   12  5.850716021108205D-03   1.028089194579363D-02   1.000000000000000D+00
          8   13  5.778664230657791D-03   3.676866074530332D-04   1.000000000000000D+00
          9   14  5.777818823650782D-03   3.010740179797255D-04   1.000000000000000D+00


           THE MINIMIZATION TERMINATED WITHOUT DETECTING ERRORS.
           IFLAG = 0
          (%o7) [A = 1.461933911464101, B = 1.601593973254802,
                                                     C = 2.528933072164854]
          (%i8) plot2d ([F(x), [discrete, X, Y]], [x, -1, 6]), ''estimates;
          (%o8)

     Gradient of FOM is specified (instead of computing it
     automatically).

          (%i1) load (lbfgs)$
          (%i2) F(a, b, c) := (a - 5)^2 + (b - 3)^4 + (c - 2)^6;
                                         2          4          6
          (%o2)     F(a, b, c) := (a - 5)  + (b - 3)  + (c - 2)
          (%i3) F_grad : map (lambda ([x], diff (F(a, b, c), x)), [a, b, c]);
                                              3           5
          (%o3)          [2 (a - 5), 4 (b - 3) , 6 (c - 2) ]
          (%i4) estimates : lbfgs ([F(a, b, c), F_grad],
                                   [a, b, c], [0, 0, 0], 1e-4, [1, 0]);
          *************************************************
            N=    3   NUMBER OF CORRECTIONS=25
                 INITIAL VALUES
           F=  1.700000000000000D+02   GNORM=  2.205175729958953D+02
          *************************************************

             I  NFN     FUNC                    GNORM                   STEPLENGTH

             1    2     6.632967565917638D+01   6.498411132518770D+01   4.534785987412505D-03
             2    3     4.368890936228036D+01   3.784147651974131D+01   1.000000000000000D+00
             3    4     2.685298972775190D+01   1.640262125898521D+01   1.000000000000000D+00
             4    5     1.909064767659852D+01   9.733664001790506D+00   1.000000000000000D+00
             5    6     1.006493272061515D+01   6.344808151880209D+00   1.000000000000000D+00
             6    7     1.215263596054294D+00   2.204727876126879D+00   1.000000000000000D+00
             7    8     1.080252896385334D-02   1.431637116951849D-01   1.000000000000000D+00
             8    9     8.407195124830908D-03   1.126344579730013D-01   1.000000000000000D+00
             9   10     5.022091686198527D-03   7.750731829225274D-02   1.000000000000000D+00
            10   11     2.277152808939775D-03   5.032810859286795D-02   1.000000000000000D+00
            11   12     6.489384688303218D-04   1.932007150271008D-02   1.000000000000000D+00
            12   13     2.075791943844548D-04   6.964319310814364D-03   1.000000000000000D+00
            13   14     7.349472666162257D-05   4.017449067849554D-03   1.000000000000000D+00
            14   15     2.293617477985237D-05   1.334590390856715D-03   1.000000000000000D+00
            15   16     7.683645404048675D-06   6.011057038099201D-04   1.000000000000000D+00


           THE MINIMIZATION TERMINATED WITHOUT DETECTING ERRORS.
           IFLAG = 0
          (%o4) [a = 5.000086823042934, b = 3.05239542970518,
                                                     c = 1.927980629919583]


 -- Variable: lbfgs_nfeval_max
     Default value: 100

     `lbfgs_nfeval_max' is the maximum number of evaluations of the
     figure of merit (FOM) in `lbfgs'.  When `lbfgs_nfeval_max' is
     reached, `lbfgs' returns the result of the last successful line
     search.


 -- Variable: lbfgs_ncorrections
     Default value: 25

     `lbfgs_ncorrections' is the number of corrections applied to the
     approximate inverse Hessian matrix which is maintained by `lbfgs'.



File: maxima.info,  Node: lindstedt,  Next: linearalgebra,  Prev: lbfgs,  Up: Top

62 lindstedt
************

* Menu:

* Functions and Variables for lindstedt::


File: maxima.info,  Node: Functions and Variables for lindstedt,  Prev: lindstedt,  Up: lindstedt

62.1 Functions and Variables for lindstedt
==========================================

 -- Function: Lindstedt (<eq>,<pvar>,<torder>,<ic>)
     This is a first pass at a Lindstedt code.  It can solve problems
     with initial conditions entered, which can be arbitrary constants,
     (just not <%k1> and <%k2>) where the initial conditions on the
     perturbation equations are z[i]=0, z'[i]=0 for i>0. <ic> is the
     list of initial conditions.

     Problems occur when initial conditions are not given, as the
     constants in the perturbation equations are the same as the zero
     order equation solution.  Also, problems occur when the initial
     conditions for the perturbation equations are not z[i]=0, z'[i]=0
     for i>0, such as the Van der Pol equation.

     Example:
          (%i1) load("makeOrders")$

          (%i2) load("lindstedt")$

          (%i3) Lindstedt('diff(x,t,2)+x-(e*x^3)/6,e,2,[1,0]);
                    2
                   e  (cos(5 T) - 24 cos(3 T) + 23 cos(T))
          (%o3) [[[---------------------------------------
                                    36864
             e (cos(3 T) - cos(T))
           - --------------------- + cos(T)],
                      192
                    2
                 7 e    e
          T = (- ---- - -- + 1) t]]
                 3072   16

     To use this function write first `load("makeOrders")' and
     `load("lindstedt")'.



File: maxima.info,  Node: linearalgebra,  Next: lsquares,  Prev: lindstedt,  Up: Top

63 linearalgebra
****************

* Menu:

* Introduction to linearalgebra::
* Functions and Variables for linearalgebra::


File: maxima.info,  Node: Introduction to linearalgebra,  Next: Functions and Variables for linearalgebra,  Prev: linearalgebra,  Up: linearalgebra

63.1 Introduction to linearalgebra
==================================

`linearalgebra' is a collection of functions for linear algebra.

   Example:

     (%i1) M : matrix ([1, 2], [1, 2]);
                                 [ 1  2 ]
     (%o1)                       [      ]
                                 [ 1  2 ]
     (%i2) nullspace (M);
                                    [  1  ]
                                    [     ]
     (%o2)                     span([   1 ])
                                    [ - - ]
                                    [   2 ]
     (%i3) columnspace (M);
                                     [ 1 ]
     (%o3)                      span([   ])
                                     [ 1 ]
     (%i4) ptriangularize (M - z*ident(2), z);
                              [ 1   2 - z   ]
     (%o4)                    [             ]
                              [           2 ]
                              [ 0  3 z - z  ]
     (%i5) M : matrix ([1, 2, 3], [4, 5, 6], [7, 8, 9]) - z*ident(3);
                          [ 1 - z    2      3   ]
                          [                     ]
     (%o5)                [   4    5 - z    6   ]
                          [                     ]
                          [   7      8    9 - z ]
     (%i6) MM : ptriangularize (M, z);
                   [ 4  5 - z            6            ]
                   [                                  ]
                   [                2                 ]
                   [     66        z    102 z   132   ]
                   [ 0   --      - -- + ----- + ---   ]
     (%o6)         [     49        7     49     49    ]
                   [                                  ]
                   [               3        2         ]
                   [           49 z    245 z    147 z ]
                   [ 0    0    ----- - ------ - ----- ]
                   [            264      88      44   ]
     (%i7) algebraic : true;
     (%o7)                         true
     (%i8) tellrat (MM [3, 3]);
                              3       2
     (%o8)                  [z  - 15 z  - 18 z]
     (%i9) MM : ratsimp (MM);
                    [ 4  5 - z           6           ]
                    [                                ]
                    [                2               ]
     (%o9)          [     66      7 z  - 102 z - 132 ]
                    [ 0   --    - ------------------ ]
                    [     49              49         ]
                    [                                ]
                    [ 0    0             0           ]
     (%i10) nullspace (MM);
                             [        1         ]
                             [                  ]
                             [   2              ]
                             [  z  - 14 z - 16  ]
                             [  --------------  ]
     (%o10)             span([        8         ])
                             [                  ]
                             [    2             ]
                             [   z  - 18 z - 12 ]
                             [ - -------------- ]
                             [         12       ]
     (%i11) M : matrix ([1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12],
                        [13, 14, 15, 16]);
                            [ 1   2   3   4  ]
                            [                ]
                            [ 5   6   7   8  ]
     (%o11)                 [                ]
                            [ 9   10  11  12 ]
                            [                ]
                            [ 13  14  15  16 ]
     (%i12) columnspace (M);
                                [ 1  ]  [ 2  ]
                                [    ]  [    ]
                                [ 5  ]  [ 6  ]
     (%o12)                span([    ], [    ])
                                [ 9  ]  [ 10 ]
                                [    ]  [    ]
                                [ 13 ]  [ 14 ]
     (%i13) apply ('orthogonal_complement, args (nullspace (transpose (M))));
                                [ 0 ]  [  1  ]
                                [   ]  [     ]
                                [ 1 ]  [  0  ]
     (%o13)                span([   ], [     ])
                                [ 2 ]  [ - 1 ]
                                [   ]  [     ]
                                [ 3 ]  [ - 2 ]


File: maxima.info,  Node: Functions and Variables for linearalgebra,  Prev: Introduction to linearalgebra,  Up: linearalgebra

63.2 Functions and Variables for linearalgebra
==============================================

 -- Function: addmatrices (<f>, <M_1>, ..., <M_n>)
     Using the function <f> as the addition function, return the sum of
     the matrices <M_1>, ..., <M_n>.  The function <f> must accept any
     number of arguments (a Maxima nary function).

     Examples:

          (%i1) m1 : matrix([1,2],[3,4])$
          (%i2) m2 : matrix([7,8],[9,10])$
          (%i3) addmatrices('max,m1,m2);
          (%o3) matrix([7,8],[9,10])
          (%i4) addmatrices('max,m1,m2,5*m1);
          (%o4) matrix([7,10],[15,20])


 -- Function: blockmatrixp (<M>)
     Return true if and only if <M> is a matrix and every entry of <M>
     is a matrix.


 -- Function: columnop (<M>, <i>, <j>, <theta>)
     If <M> is a matrix, return the matrix that results from doing the
     column operation `C_i <- C_i - <theta> * C_j'. If <M> doesn't have
     a row <i> or <j>, signal an error.


 -- Function: columnswap (<M>, <i>, <j>)
     If <M> is a matrix, swap columns <i> and <j>.  If <M> doesn't have
     a column <i> or <j>, signal an error.


 -- Function: columnspace (<M>)
     If <M> is a matrix, return `span (v_1, ..., v_n)', where the set
     `{v_1, ..., v_n}' is a basis for the column space of <M>.  The span
     of the empty set is `{0}'.  Thus, when the column space has only
     one member, return `span ()'.


 -- Function: copy (<e>)
     Return a copy of the Maxima expression <e>.  Although <e> can be
     any Maxima expression, the copy function is the most useful when
     <e> is either a list or a matrix; consider:

          (%i1) m : [1,[2,3]]$
          (%i2) mm : m$
          (%i3) mm[2][1] : x$
          (%i4) m;
          (%o4)                      [1,[x,3]]
          (%i5) mm;
          (%o5)                      [1,[x,3]]

     Let's try the same experiment, but this time let <mm> be a copy of
     <m>

          (%i6) m : [1,[2,3]]$
          (%i7) mm : copy(m)$
          (%i8) mm[2][1] : x$
          (%i9) m;
          (%o9)                     [1,[2,3]]
          (%i10) mm;
          (%o10)                    [1,[x,3]]

     This time, the assignment to <mm> does not change the value of <m>.


 -- Function: cholesky (<M>)
 -- Function: cholesky (<M>, <field>)
     Return the Cholesky factorization of the matrix selfadjoint (or
     hermitian) matrix <M>.  The second argument defaults to
     'generalring.' For a description of the possible values for
     <field>, see `lu_factor'.


 -- Function: ctranspose (<M>)
     Return the complex conjugate transpose of the matrix <M>.  The
     function `ctranspose' uses `matrix_element_transpose' to transpose
     each matrix element.


 -- Function: diag_matrix (<d_1>, <d_2>, ..., <d_n>)
     Return a diagonal matrix with diagonal entries <d_1>, <d_2>, ...,
     <d_n>.  When the diagonal entries are matrices, the zero entries
     of the returned matrix are zero matrices of the appropriate size;
     for example:

          (%i1) diag_matrix(diag_matrix(1,2),diag_matrix(3,4));

                                      [ [ 1  0 ]  [ 0  0 ] ]
                                      [ [      ]  [      ] ]
                                      [ [ 0  2 ]  [ 0  0 ] ]
          (%o1)                       [                    ]
                                      [ [ 0  0 ]  [ 3  0 ] ]
                                      [ [      ]  [      ] ]
                                      [ [ 0  0 ]  [ 0  4 ] ]
          (%i2) diag_matrix(p,q);

                                             [ p  0 ]
          (%o2)                              [      ]
                                             [ 0  q ]


 -- Function: dotproduct (<u>, <v>)
     Return the dotproduct of vectors <u> and <v>.  This is the same as
     `conjugate (transpose (<u>)) .  <v>'.  The arguments <u> and <v>
     must be column vectors.


 -- Function: eigens_by_jacobi (<A>)
 -- Function: eigens_by_jacobi (<A>, <field_type>)
     Computes the eigenvalues and eigenvectors of <A> by the method of
     Jacobi rotations.  <A> must be a symmetric matrix (but it need not
     be positive definite nor positive semidefinite).  <field_type>
     indicates the computational field, either `floatfield' or
     `bigfloatfield'.  If <field_type> is not specified, it defaults to
     `floatfield'.

     The elements of <A> must be numbers or expressions which evaluate
     to numbers via `float' or `bfloat' (depending on <field_type>).

     Examples:

          (%i1) S: matrix([1/sqrt(2), 1/sqrt(2)],[-1/sqrt(2), 1/sqrt(2)]);
                               [     1         1    ]
                               [  -------   ------- ]
                               [  sqrt(2)   sqrt(2) ]
          (%o1)                [                    ]
                               [      1        1    ]
                               [ - -------  ------- ]
                               [   sqrt(2)  sqrt(2) ]
          (%i2) L : matrix ([sqrt(3), 0], [0, sqrt(5)]);
                                [ sqrt(3)     0    ]
          (%o2)                 [                  ]
                                [    0     sqrt(5) ]
          (%i3) M : S . L . transpose (S);
                      [ sqrt(5)   sqrt(3)  sqrt(5)   sqrt(3) ]
                      [ ------- + -------  ------- - ------- ]
                      [    2         2        2         2    ]
          (%o3)       [                                      ]
                      [ sqrt(5)   sqrt(3)  sqrt(5)   sqrt(3) ]
                      [ ------- - -------  ------- + ------- ]
                      [    2         2        2         2    ]
          (%i4) eigens_by_jacobi (M);
          The largest percent change was 0.1454972243679
          The largest percent change was 0.0
          number of sweeps: 2
          number of rotations: 1
          (%o4) [[1.732050807568877, 2.23606797749979],
                                  [  0.70710678118655   0.70710678118655 ]
                                  [                                      ]]
                                  [ - 0.70710678118655  0.70710678118655 ]
          (%i5) float ([[sqrt(3), sqrt(5)], S]);
          (%o5) [[1.732050807568877, 2.23606797749979],
                                  [  0.70710678118655   0.70710678118655 ]
                                  [                                      ]]
                                  [ - 0.70710678118655  0.70710678118655 ]
          (%i6) eigens_by_jacobi (M, bigfloatfield);
          The largest percent change was 1.454972243679028b-1
          The largest percent change was 0.0b0
          number of sweeps: 2
          number of rotations: 1
          (%o6) [[1.732050807568877b0, 2.23606797749979b0],
                          [  7.071067811865475b-1   7.071067811865475b-1 ]
                          [                                              ]]
                          [ - 7.071067811865475b-1  7.071067811865475b-1 ]


 -- Function: get_lu_factors (<x>)
     When `<x> = lu_factor (<A>)', then `get_lu_factors' returns a list
     of the form `[P, L, U]', where <P> is a permutation matrix, <L> is
     lower triangular with ones on the diagonal, and <U> is upper
     triangular, and `<A> = <P> <L> <U>'.


 -- Function: hankel (<col>)
 -- Function: hankel (<col>, <row>)
     Return a Hankel matrix <H>.  The first column of <H> is <col>;
     except for the first entry, the last row of <H> is <row>.  The
     default for <row> is the zero vector with the same length as <col>.


 -- Function: hessian (<f>, <x>)
     Returns the Hessian matrix of <f> with respect to the list of
     variables <x>.  The `(i, j)'-th element of the Hessian matrix is
     `diff(<f>, <x>[i], 1, <x>[j], 1)'.

     Examples:

          (%i1) hessian (x * sin (y), [x, y]);
                               [   0       cos(y)   ]
          (%o1)                [                    ]
                               [ cos(y)  - x sin(y) ]
          (%i2) depends (F, [a, b]);
          (%o2)                       [F(a, b)]
          (%i3) hessian (F, [a, b]);
                                  [   2      2   ]
                                  [  d F    d F  ]
                                  [  ---   ----- ]
                                  [    2   da db ]
                                  [  da          ]
          (%o3)                   [              ]
                                  [   2      2   ]
                                  [  d F    d F  ]
                                  [ -----   ---  ]
                                  [ da db     2  ]
                                  [         db   ]


 -- Function: hilbert_matrix (<n>)
     Return the <n> by <n> Hilbert matrix.  When <n> isn't a positive
     integer, signal an error.


 -- Function: identfor (<M>)
 -- Function: identfor (<M>, <fld>)
     Return an identity matrix that has the same shape as the matrix
     <M>.  The diagonal entries of the identity matrix are the
     multiplicative identity of the field <fld>; the default for <fld>
     is <generalring>.

     The first argument <M> should be a square matrix or a non-matrix.
     When <M> is a matrix, each entry of <M> can be a square matrix -
     thus <M> can be a blocked Maxima matrix.  The matrix can be
     blocked to any (finite) depth.

     See also `zerofor'


 -- Function: invert_by_lu (<M>, <(rng generalring)>)
     Invert a matrix <M> by using the LU factorization.  The LU
     factorization is done using the ring <rng>.


 -- Function: jacobian (<f>, <x>)
     Returns the Jacobian matrix of the list of functions <f> with
     respect to the list of variables <x>.  The `(i, j)'-th element of
     the Jacobian matrix is `diff(<f>[i], <x>[j])'.

     Examples:

          (%i1) jacobian ([sin (u - v), sin (u * v)], [u, v]);
                            [ cos(v - u)  - cos(v - u) ]
          (%o1)             [                          ]
                            [ v cos(u v)   u cos(u v)  ]
          (%i2) depends ([F, G], [y, z]);
          (%o2)                  [F(y, z), G(y, z)]
          (%i3) jacobian ([F, G], [y, z]);
                                     [ dF  dF ]
                                     [ --  -- ]
                                     [ dy  dz ]
          (%o3)                      [        ]
                                     [ dG  dG ]
                                     [ --  -- ]
                                     [ dy  dz ]


 -- Function: kronecker_product (<A>, <B>)
     Return the Kronecker product of the matrices <A> and <B>.


 -- Function: listp (<e>, <p>)
 -- Function: listp (<e>)
     Given an optional argument <p>, return `true' if <e> is a Maxima
     list and <p> evaluates to `true' for every list element.  When
     `listp' is not given the optional argument, return `true' if <e>
     is a Maxima list.  In all other cases, return `false'.


 -- Function: locate_matrix_entry (<M>, <r_1>, <c_1>, <r_2>, <c_2>,
          <f>, <rel>)
     The first argument must be a matrix; the arguments <r_1> through
     <c_2> determine a sub-matrix of <M> that consists of rows <r_1>
     through <r_2> and columns <c_1> through <c_2>.

     Find a entry in the sub-matrix <M> that satisfies some property.
     Three cases:

     (1) `<rel> = 'bool' and <f> a predicate:

     Scan the sub-matrix from left to right then top to bottom, and
     return the index of the first entry that satisfies the predicate
     <f>.  If no matrix entry satisfies <f>, return `false'.

     (2) `<rel> = 'max' and <f> real-valued:

     Scan the sub-matrix looking for an entry that maximizes <f>.
     Return the index of a maximizing entry.

     (3) `<rel> = 'min' and <f> real-valued:

     Scan the sub-matrix looking for an entry that minimizes <f>.
     Return the index of a minimizing entry.


 -- Function: lu_backsub (<M>, <b>)
     When `<M> = lu_factor (<A>, <field>)', then `lu_backsub (<M>,
     <b>)' solves the linear system `<A> <x> = <b>'.


 -- Function: lu_factor (<M>, <field>)
     Return a list of the form `[<LU>, <perm>, <fld>]', or `[<LU>,
     <perm>, <fld>, <lower-cnd> <upper-cnd>]', where

     (1) The matrix <LU> contains the factorization of <M> in a packed
     form.      Packed form means three things: First, the rows of <LU>
     are permuted     according to the list <perm>.  If, for example,
     <perm> is the list     `[3,2,1]', the actual first row of the <LU>
     factorization is the     third row of the matrix <LU>.  Second,
     the lower triangular factor of     m is the lower triangular part
     of <LU> with the diagonal entries     replaced by all ones.
     Third, the upper triangular factor of <M> is the     upper
     triangular part of <LU>.

     (2) When the field is either `floatfield' or `complexfield', the
      numbers <lower-cnd> and <upper-cnd> are lower and upper bounds
     for     the infinity norm condition number of <M>.  For all
     fields, the     condition number might not be estimated; for such
     fields, `lu_factor'     returns a two item list.  Both the lower
     and upper bounds can differ from     their true values by
     arbitrarily large factors.  (See also `mat_cond'.)

     The argument <M> must be a square matrix.

     The optional argument <fld> must be a symbol that determines a
     ring or   field.  The pre-defined fields and rings are:

     (a) `generalring'      - the ring of Maxima expressions,

     (b) `floatfield'       - the field of floating point numbers of the
                                     type double,

     (c) `complexfield'     - the field of complex floating point
     numbers of                                  the type double,

     (d) `crering'          - the ring of Maxima CRE expressions,

     (e) `rationalfield'    - the field of rational numbers,

     (f) `runningerror'     - track the all floating point rounding
     errors,

     (g) `noncommutingring' - the ring of Maxima expressions where
                                multiplication is the non-commutative
     dot                                  operator.

     When the field is `floatfield', `complexfield', or `runningerror',
     the algorithm uses partial pivoting; for all other fields, rows
     are switched only when needed to avoid a zero pivot.

     Floating point addition arithmetic isn't associative, so the
     meaning of 'field' differs from the mathematical definition.

     A member of the field `runningerror' is a two member Maxima list
     of the form `[x,n]',where <x> is a floating point number and `n'
     is an integer.  The relative difference between the 'true' value
     of `x' and `x' is approximately bounded by the machine epsilon
     times `n'.  The running error bound drops some terms that of the
     order the square of the machine epsilon.

     There is no user-interface for defining a new field.  A user that
     is familiar with Common Lisp should be able to define a new field.
     To do this, a user must define functions for the arithmetic
     operations and functions for converting from the field
     representation to Maxima and back.  Additionally, for ordered
     fields (where partial pivoting will be used), a user must define
     functions for the magnitude and for comparing field members.
     After that all that remains is to define a Common Lisp structure
     `mring'.  The file `mring' has many examples.

     To compute the factorization, the first task is to convert each
     matrix entry to a member of the indicated field.  When conversion
     isn't possible, the factorization halts with an error message.
     Members of the field needn't be Maxima expressions.  Members of the
     `complexfield', for example, are Common Lisp complex numbers.  Thus
     after computing the factorization, the matrix entries must be
     converted to Maxima expressions.

     See also  `get_lu_factors'.

     Examples:

          (%i1) w[i,j] := random (1.0) + %i * random (1.0);
          (%o1)          w     := random(1.) + %i random(1.)
                          i, j
          (%i2) showtime : true$
          Evaluation took 0.00 seconds (0.00 elapsed)
          (%i3) M : genmatrix (w, 100, 100)$
          Evaluation took 7.40 seconds (8.23 elapsed)
          (%i4) lu_factor (M, complexfield)$
          Evaluation took 28.71 seconds (35.00 elapsed)
          (%i5) lu_factor (M, generalring)$
          Evaluation took 109.24 seconds (152.10 elapsed)
          (%i6) showtime : false$

          (%i7) M : matrix ([1 - z, 3], [3, 8 - z]);
                                  [ 1 - z    3   ]
          (%o7)                   [              ]
                                  [   3    8 - z ]
          (%i8) lu_factor (M, generalring);
                    [ 1 - z         3        ]
                    [                        ]
          (%o8)    [[   3            9       ], [1, 2], generalring]
                    [ -----  - z - ----- + 8 ]
                    [ 1 - z        1 - z     ]
          (%i9) get_lu_factors (%);
                            [   1    0 ]  [ 1 - z         3        ]
                  [ 1  0 ]  [          ]  [                        ]
          (%o9)  [[      ], [   3      ], [                9       ]]
                  [ 0  1 ]  [ -----  1 ]  [   0    - z - ----- + 8 ]
                            [ 1 - z    ]  [              1 - z     ]
          (%i10) %[1] . %[2] . %[3];
                                  [ 1 - z    3   ]
          (%o10)                  [              ]
                                  [   3    8 - z ]


 -- Function: mat_cond (<M>, 1)
 -- Function: mat_cond (<M>, inf)
     Return the <p>-norm matrix condition number of the matrix <m>.
     The allowed values for <p> are 1 and <inf>.  This function uses
     the LU factorization to invert the matrix <m>.  Thus the running
     time for `mat_cond' is proportional to the cube of the matrix
     size; `lu_factor' determines lower and upper bounds for the
     infinity norm condition number in time proportional to the square
     of the matrix size.


 -- Function: mat_norm (<M>, 1)
 -- Function: mat_norm (<M>, inf)
 -- Function: mat_norm (<M>, frobenius)
     Return the matrix <p>-norm of the matrix <M>.  The allowed values
     for <p> are 1, `inf', and `frobenius' (the Frobenius matrix norm).
     The matrix <M> should be an unblocked matrix.


 -- Function: matrixp (<e>, <p>)
 -- Function: matrixp (<e>)
     Given an optional argument <p>, return `true' if <e> is a matrix
     and <p> evaluates to `true' for every matrix element.  When
     `matrixp' is not given an optional argument, return `true' if `e'
     is a matrix.  In all other cases, return `false'.

     See also `blockmatrixp'


 -- Function: matrix_size (<M>)
     Return a two member list that gives the number of rows and
     columns, respectively of the matrix <M>.


 -- Function: mat_fullunblocker (<M>)
     If <M> is a block matrix, unblock the matrix to all levels.  If
     <M> is a matrix, return <M>; otherwise, signal an error.


 -- Function: mat_trace (<M>)
     Return the trace of the matrix <M>.  If <M> isn't a matrix, return
     a noun form.  When <M> is a block matrix, `mat_trace(M)' returns
     the same value as does `mat_trace(mat_unblocker(m))'.


 -- Function: mat_unblocker (<M>)
     If <M> is a block matrix, unblock <M> one level.  If <M> is a
     matrix, `mat_unblocker (M)' returns <M>; otherwise, signal an
     error.

     Thus if each entry of <M> is matrix, `mat_unblocker (M)' returns an
     unblocked matrix, but if each entry of <M> is a block matrix,
     `mat_unblocker (M)' returns a block matrix with one less level of
     blocking.

     If you use block matrices, most likely you'll want to set
     `matrix_element_mult' to `"."' and `matrix_element_transpose' to
     `'transpose'.  See also `mat_fullunblocker'.

     Example:

          (%i1) A : matrix ([1, 2], [3, 4]);
                                      [ 1  2 ]
          (%o1)                       [      ]
                                      [ 3  4 ]
          (%i2) B : matrix ([7, 8], [9, 10]);
                                      [ 7  8  ]
          (%o2)                       [       ]
                                      [ 9  10 ]
          (%i3) matrix ([A, B]);
                               [ [ 1  2 ]  [ 7  8  ] ]
          (%o3)                [ [      ]  [       ] ]
                               [ [ 3  4 ]  [ 9  10 ] ]
          (%i4) mat_unblocker (%);
                                   [ 1  2  7  8  ]
          (%o4)                    [             ]
                                   [ 3  4  9  10 ]


 -- Function: nullspace (<M>)
     If <M> is a matrix, return `span (v_1, ..., v_n)', where the set
     `{v_1, ..., v_n}' is a basis for the nullspace of <M>.  The span of
     the empty set is `{0}'.  Thus, when the nullspace has only one
     member, return `span ()'.


 -- Function: nullity (<M>)
     If <M> is a matrix, return the dimension of the nullspace of <M>.


 -- Function: orthogonal_complement (<v_1>, ..., <v_n>)
     Return `span (u_1, ..., u_m)', where the set `{u_1, ..., u_m}' is a
     basis for the orthogonal complement of the set `(v_1, ..., v_n)'.

     Each vector <v_1> through <v_n> must be a column vector.


 -- Function: polynomialp (<p>, <L>, <coeffp>, <exponp>)
 -- Function: polynomialp (<p>, <L>, <coeffp>)
 -- Function: polynomialp (<p>, <L>)
     Return `true' if <p> is a polynomial in the variables in the list
     <L>.  The predicate <coeffp> must evaluate to `true' for each
     coefficient, and the predicate <exponp> must evaluate to `true'
     for all exponents of the variables in <L>.  If you want to use a
     non-default value for <exponp>, you must supply <coeffp> with a
     value even if you want to use the default for <coeffp>.

     The command `polynomialp (<p>, <L>, <coeffp>)' is equivalent to
     `polynomialp (<p>, <L>, <coeffp>, 'nonnegintegerp)' and the
     command `polynomialp (<p>, <L>)' is equivalent to `polynomialp
     (<p>, L<,> 'constantp, 'nonnegintegerp)'.

     The polynomial needn't be expanded:

          (%i1) polynomialp ((x + 1)*(x + 2), [x]);
          (%o1)                         true
          (%i2) polynomialp ((x + 1)*(x + 2)^a, [x]);
          (%o2)                         false

     An example using non-default values for coeffp and exponp:

          (%i1) polynomialp ((x + 1)*(x + 2)^(3/2), [x], numberp, numberp);
          (%o1)                         true
          (%i2) polynomialp ((x^(1/2) + 1)*(x + 2)^(3/2), [x], numberp,
                                                                  numberp);
          (%o2)                         true

     Polynomials with two variables:

          (%i1) polynomialp (x^2 + 5*x*y + y^2, [x]);
          (%o1)                         false
          (%i2) polynomialp (x^2 + 5*x*y + y^2, [x, y]);
          (%o2)                         true


 -- Function: polytocompanion (<p>, <x>)
     If <p> is a polynomial in <x>, return the companion matrix of <p>.
     For a monic polynomial <p> of degree <n>, we have `<p> = (-1)^<n>
     charpoly (polytocompanion (<p>, <x>))'.

     When <p> isn't a polynomial in <x>, signal an error.


 -- Function: ptriangularize (<M>, <v>)
     If <M> is a matrix with each entry a polynomial in <v>, return a
     matrix <M2> such that

     (1) <M2> is upper triangular,

     (2) `<M2> = <E_n> ... <E_1> <M>', where <E_1> through <E_n> are
     elementary matrices whose entries are polynomials in <v>,

     (3) `|det (<M>)| = |det (<M2>)|',

     Note: This function doesn't check that every entry is a polynomial
     in <v>.


 -- Function: rowop (<M>, <i>, <j>, <theta>)
     If <M> is a matrix, return the matrix that results from doing the
     row operation `R_i <- R_i - theta * R_j'.  If <M> doesn't have a
     row <i> or <j>, signal an error.


 -- Function: rank (<M>)
     Return the rank of that matrix <M>.  The rank is the dimension of
     the column space.  Example:

          (%i1) rank(matrix([1,2],[2,4]));
          (%o1)                                  1
          (%i2) rank(matrix([1,b],[c,d]));
          Proviso:  {d - b c # 0}
          (%o2)                                  2


 -- Function: rowswap (<M>, <i>, <j>)
     If <M> is a matrix, swap rows <i> and <j>.  If <M> doesn't have a
     row <i> or <j>, signal an error.


 -- Function: toeplitz (<col>)
 -- Function: toeplitz (<col>, <row>)
     Return a Toeplitz matrix <T>.  The first first column of <T> is
     <col>; except for the first entry, the first row of <T> is <row>.
     The default for <row> is complex conjugate of <col>.  Example:

          (%i1)  toeplitz([1,2,3],[x,y,z]);
                                            [ 1  y  z ]
                                            [         ]
          (%o1)                             [ 2  1  y ]
                                            [         ]
                                            [ 3  2  1 ]
          (%i2)  toeplitz([1,1+%i]);

                                        [   1     1 - %I ]
          (%o2)                         [                ]
                                        [ %I + 1    1    ]


 -- Function: vandermonde_matrix ([<x_1>, ..., <x_n>])
     Return a <n> by <n> matrix whose <i>-th row is `[1, <x_i>,
     <x_i>^2, ... <x_i>^(<n>-1)]'.


 -- Function: zerofor (<M>)
 -- Function: zerofor (<M>, <fld>)
     Return a zero  matrix that has the same shape as the matrix <M>.
     Every entry of the zero matrix is the additive identity of the
     field <fld>; the default for <fld> is <generalring>.

     The first argument <M> should be a square matrix or a non-matrix.
     When <M> is a matrix, each entry of <M> can be a square matrix -
     thus <M> can be a blocked Maxima matrix.  The matrix can be
     blocked to any (finite) depth.

     See also `identfor'


 -- Function: zeromatrixp (<M>)
     If <M> is not a block matrix, return `true' if `is (equal (<e>,
     0))' is true for each element <e> of the matrix <M>.  If <M> is a
     block matrix, return `true' if `zeromatrixp' evaluates to `true'
     for each element of <e>.



File: maxima.info,  Node: lsquares,  Next: minpack,  Prev: linearalgebra,  Up: Top

64 lsquares
***********

* Menu:

* Introduction to lsquares::
* Functions and Variables for lsquares::


File: maxima.info,  Node: Introduction to lsquares,  Next: Functions and Variables for lsquares,  Prev: lsquares,  Up: lsquares

64.1 Introduction to lsquares
=============================

`lsquares' is a collection of functions to implement the method of
least squares to estimate parameters for a model from numerical data.


File: maxima.info,  Node: Functions and Variables for lsquares,  Prev: Introduction to lsquares,  Up: lsquares

64.2 Functions and Variables for lsquares
=========================================

 -- Function: lsquares_estimates (<D>, <x>, <e>, <a>)
 -- Function: lsquares_estimates (<D>, <x>, <e>, <a>, initial = <L>,
          tol = <t>)
     Estimate parameters <a> to best fit the equation <e> in the
     variables <x> and <a> to the data <D>, as determined by the method
     of least squares.  `lsquares_estimates' first seeks an exact
     solution, and if that fails, then seeks an approximate solution.

     The return value is a list of lists of equations of the form `[a =
     ..., b = ..., c = ...]'.  Each element of the list is a distinct,
     equivalent minimum of the mean square error.

     The data <D> must be a matrix.  Each row is one datum (which may
     be called a `record' or `case' in some contexts), and each column
     contains the values of one variable across all data.  The list of
     variables <x> gives a name for each column of <D>, even the
     columns which do not enter the analysis.  The list of parameters
     <a> gives the names of the parameters for which estimates are
     sought.  The equation <e> is an expression or equation in the
     variables <x> and <a>; if <e> is not an equation, it is treated
     the same as `<e> = 0'.

     Additional arguments to `lsquares_estimates' are specified as
     equations and passed on verbatim to the function `lbfgs' which is
     called to find estimates by a numerical method when an exact
     result is not found.

     If some exact solution can be found (via `solve'), the data <D>
     may contain non-numeric values.  However, if no exact solution is
     found, each element of <D> must have a numeric value.  This
     includes numeric constants such as `%pi' and `%e' as well as
     literal numbers (integers, rationals, ordinary floats, and
     bigfloats).  Numerical calculations are carried out with ordinary
     floating-point arithmetic, so all other kinds of numbers are
     converted to ordinary floats for calculations.

     `load(lsquares)' loads this function.

     See also `lsquares_estimates_exact',
     `lsquares_estimates_approximate',
     `lsquares_mse', `lsquares_residuals', and `lsquares_residual_mse'.

     Examples:

     A problem for which an exact solution is found.

          (%i1) load (lsquares)$
          (%i2) M : matrix (
                  [1,1,1], [3/2,1,2], [9/4,2,1], [3,2,2], [2,2,1]);
                                            [ 1  1  1 ]
                                            [         ]
                                            [ 3       ]
                                            [ -  1  2 ]
                                            [ 2       ]
                                            [         ]
          (%o2)                             [ 9       ]
                                            [ -  2  1 ]
                                            [ 4       ]
                                            [         ]
                                            [ 3  2  2 ]
                                            [         ]
                                            [ 2  2  1 ]
          (%i3) lsquares_estimates (
                   M, [z,x,y], (z+D)^2 = A*x+B*y+C, [A,B,C,D]);
                                   59        27      10921        107
          (%o3)            [[A = - --, B = - --, C = -----, D = - ---]]
                                   16        16      1024         32

     A problem for which no exact solution is found, so
     `lsquares_estimates' resorts to numerical approximation.

          (%i1) load (lsquares)$
          (%i2) M : matrix ([1, 1], [2, 7/4], [3, 11/4], [4, 13/4]);
                                             [ 1  1  ]
                                             [       ]
                                             [    7  ]
                                             [ 2  -  ]
                                             [    4  ]
                                             [       ]
          (%o2)                              [    11 ]
                                             [ 3  -- ]
                                             [    4  ]
                                             [       ]
                                             [    13 ]
                                             [ 4  -- ]
                                             [    4  ]
          (%i3) lsquares_estimates (
            M, [x,y], y=a*x^b+c, [a,b,c], initial=[3,3,3], iprint=[-1,0]);
          (%o3) [[a = 1.387365874920637, b = .7110956639593767,
                                                  c = - .4142705622439105]]


 -- Function: lsquares_estimates_exact (<MSE>, <a>)
     Estimate parameters <a> to minimize the mean square error <MSE>,
     by constructing a system of equations and attempting to solve them
     symbolically via `solve'.  The mean square error is an expression
     in the parameters <a>, such as that returned by `lsquares_mse'.

     The return value is a list of lists of equations of the form `[a =
     ..., b = ..., c = ...]'.  The return value may contain zero, one,
     or two or more elements.  If two or more elements are returned,
     each represents a distinct, equivalent minimum of the mean square
     error.

     See also `lsquares_estimates', `lsquares_estimates_approximate',
     `lsquares_mse', `lsquares_residuals', and `lsquares_residual_mse'.

     Example:

          (%i1) load (lsquares)$
          (%i2) M : matrix (
                   [1,1,1], [3/2,1,2], [9/4,2,1], [3,2,2], [2,2,1]);
                                     [ 1  1  1 ]
                                     [         ]
                                     [ 3       ]
                                     [ -  1  2 ]
                                     [ 2       ]
                                     [         ]
          (%o2)                      [ 9       ]
                                     [ -  2  1 ]
                                     [ 4       ]
                                     [         ]
                                     [ 3  2  2 ]
                                     [         ]
                                     [ 2  2  1 ]
          (%i3) mse : lsquares_mse (M, [z, x, y], (z + D)^2 = A*x + B*y + C);
                     5
                    ====
                    \                 2                         2
                     >    ((D + M    )  - C - M     B - M     A)
                    /            i, 1          i, 3      i, 2
                    ====
                    i = 1
          (%o3)     ---------------------------------------------
                                          5
          (%i4) lsquares_estimates_exact (mse, [A, B, C, D]);
                            59        27      10921        107
          (%o4)     [[A = - --, B = - --, C = -----, D = - ---]]
                            16        16      1024         32


 -- Function: lsquares_estimates_approximate (<MSE>, <a>, initial =
          <L>, tol = <t>)
     Estimate parameters <a> to minimize the mean square error <MSE>,
     via the numerical minimization function `lbfgs'.  The mean square
     error is an expression in the parameters <a>, such as that
     returned by `lsquares_mse'.

     The solution returned by `lsquares_estimates_approximate' is a
     local (perhaps global) minimum of the mean square error.  For
     consistency with `lsquares_estimates_exact', the return value is a
     nested list which contains one element, namely a list of equations
     of the form `[a = ..., b = ..., c = ...]'.

     Additional arguments to `lsquares_estimates_approximate' are
     specified as equations and passed on verbatim to the function
     `lbfgs'.

     <MSE> must evaluate to a number when the parameters are assigned
     numeric values.  This requires that the data from which <MSE> was
     constructed comprise only numeric constants such as `%pi' and `%e'
     and literal numbers (integers, rationals, ordinary floats, and
     bigfloats).  Numerical calculations are carried out with ordinary
     floating-point arithmetic, so all other kinds of numbers are
     converted to ordinary floats for calculations.

     `load(lsquares)' loads this function.

     See also `lsquares_estimates', `lsquares_estimates_exact',
     `lsquares_mse',
     `lsquares_residuals', and `lsquares_residual_mse'.

     Example:

          (%i1) load (lsquares)$
          (%i2) M : matrix (
                   [1,1,1], [3/2,1,2], [9/4,2,1], [3,2,2], [2,2,1]);
                                     [ 1  1  1 ]
                                     [         ]
                                     [ 3       ]
                                     [ -  1  2 ]
                                     [ 2       ]
                                     [         ]
          (%o2)                      [ 9       ]
                                     [ -  2  1 ]
                                     [ 4       ]
                                     [         ]
                                     [ 3  2  2 ]
                                     [         ]
                                     [ 2  2  1 ]
          (%i3) mse : lsquares_mse (M, [z, x, y], (z + D)^2 = A*x + B*y + C);
                     5
                    ====
                    \                 2                         2
                     >    ((D + M    )  - C - M     B - M     A)
                    /            i, 1          i, 3      i, 2
                    ====
                    i = 1
          (%o3)     ---------------------------------------------
                                          5
          (%i4) lsquares_estimates_approximate (
                        mse, [A, B, C, D], iprint = [-1, 0]);
          (%o4) [[A = - 3.67850494740174, B = - 1.683070351177813,
                           C = 10.63469950148635, D = - 3.340357993175206]]


 -- Function: lsquares_mse (<D>, <x>, <e>)
     Returns the mean square error (MSE), a summation expression, for
     the equation <e> in the variables <x>, with data <D>.

     The MSE is defined as:

                              n
                             ====
                         1   \                        2
                         -    >    (lhs(e ) - rhs(e ))
                         n   /           i         i
                             ====
                             i = 1

     where <n> is the number of data and `<e>[i]' is the equation <e>
     evaluated with the variables in <x> assigned values from the
     `i'-th datum, `<D>[i]'.

     `load(lsquares)' loads this function.

     Example:

          (%i1) load (lsquares)$
          (%i2) M : matrix (
                   [1,1,1], [3/2,1,2], [9/4,2,1], [3,2,2], [2,2,1]);
                                     [ 1  1  1 ]
                                     [         ]
                                     [ 3       ]
                                     [ -  1  2 ]
                                     [ 2       ]
                                     [         ]
          (%o2)                      [ 9       ]
                                     [ -  2  1 ]
                                     [ 4       ]
                                     [         ]
                                     [ 3  2  2 ]
                                     [         ]
                                     [ 2  2  1 ]

          (%i3) mse : lsquares_mse (M, [z, x, y], (z + D)^2 = A*x + B*y + C);
                     5
                    ====
                    \                 2                         2
                     >    ((D + M    )  - C - M     B - M     A)
                    /            i, 1          i, 3      i, 2
                    ====
                    i = 1
          (%o3)     ---------------------------------------------
                                          5

          (%i4) diff (mse, D);
                   5
                  ====
                  \                             2
                4  >    (D + M    ) ((D + M    )  - C - M     B - M     A)
                  /           i, 1         i, 1          i, 3      i, 2
                  ====
                  i = 1
          (%o4) ----------------------------------------------------------
                                            5

          (%i5) ''mse, nouns;
                         2                 2         9 2               2
          (%o5) (((D + 3)  - C - 2 B - 2 A)  + ((D + -)  - C - B - 2 A)
                                                     4
                     2               2         3 2               2
           + ((D + 2)  - C - B - 2 A)  + ((D + -)  - C - 2 B - A)
                                               2
                     2             2
           + ((D + 1)  - C - B - A) )/5


 -- Function: lsquares_residuals (<D>, <x>, <e>, <a>)
     Returns the residuals for the equation <e> with specified
     parameters <a> and data <D>.

     <D> is a matrix, <x> is a list of variables, <e> is an equation or
     general expression; if not an equation, <e> is treated as if it
     were `<e> = 0'.  <a> is a list of equations which specify values
     for any free parameters in <e> aside from <x>.

     The residuals are defined as:

                                  lhs(e ) - rhs(e )
                                       i         i

     where `<e>[i]' is the equation <e> evaluated with the variables in
     <x> assigned values from the `i'-th datum, `<D>[i]', and assigning
     any remaining free variables from <a>.

     `load(lsquares)' loads this function.

     Example:

          (%i1) load (lsquares)$
          (%i2) M : matrix (
                   [1,1,1], [3/2,1,2], [9/4,2,1], [3,2,2], [2,2,1]);
                                            [ 1  1  1 ]
                                            [         ]
                                            [ 3       ]
                                            [ -  1  2 ]
                                            [ 2       ]
                                            [         ]
          (%o2)                             [ 9       ]
                                            [ -  2  1 ]
                                            [ 4       ]
                                            [         ]
                                            [ 3  2  2 ]
                                            [         ]
                                            [ 2  2  1 ]
          (%i3) a : lsquares_estimates (
                    M, [z,x,y], (z+D)^2 = A*x+B*y+C, [A,B,C,D]);
                                   59        27      10921        107
          (%o3)            [[A = - --, B = - --, C = -----, D = - ---]]
                                   16        16      1024         32
          (%i4) lsquares_residuals (
                    M, [z,x,y], (z+D)^2 = A*x+B*y+C, first(a));
                                      13    13    13  13  13
          (%o4)                      [--, - --, - --, --, --]
                                      64    64    32  64  64


 -- Function: lsquares_residual_mse (<D>, <x>, <e>, <a>)
     Returns the residual mean square error (MSE) for the equation <e>
     with specified parameters <a> and data <D>.

     The residual MSE is defined as:

                              n
                             ====
                         1   \                        2
                         -    >    (lhs(e ) - rhs(e ))
                         n   /           i         i
                             ====
                             i = 1

     where `<e>[i]' is the equation <e> evaluated with the variables in
     <x> assigned values from the `i'-th datum, `<D>[i]', and assigning
     any remaining free variables from <a>.

     `load(lsquares)' loads this function.

     Example:

          (%i1) load (lsquares)$
          (%i2) M : matrix (
                   [1,1,1], [3/2,1,2], [9/4,2,1], [3,2,2], [2,2,1]);
                                     [ 1  1  1 ]
                                     [         ]
                                     [ 3       ]
                                     [ -  1  2 ]
                                     [ 2       ]
                                     [         ]
          (%o2)                      [ 9       ]
                                     [ -  2  1 ]
                                     [ 4       ]
                                     [         ]
                                     [ 3  2  2 ]
                                     [         ]
                                     [ 2  2  1 ]
          (%i3) a : lsquares_estimates (
                       M, [z,x,y], (z+D)^2 = A*x+B*y+C, [A,B,C,D]);

                            59        27      10921        107
          (%o3)     [[A = - --, B = - --, C = -----, D = - ---]]
                            16        16      1024         32
          (%i4) lsquares_residual_mse (
                       M, [z,x,y], (z + D)^2 = A*x + B*y + C, first (a));
                                        169
          (%o4)                         ----
                                        2560


 -- Function: plsquares (<Mat>,<VarList>,<depvars>)
 -- Function: plsquares (<Mat>,<VarList>,<depvars>,<maxexpon>)
 -- Function: plsquares
          (<Mat>,<VarList>,<depvars>,<maxexpon>,<maxdegree>)
     Multivariable polynomial adjustment of a data table by the "least
     squares" method. <Mat> is a matrix containing the data, <VarList>
     is a list of variable names (one for each Mat column, but use "-"
     instead of varnames to ignore Mat columns), <depvars> is the name
     of a dependent variable or a list with one or more names of
     dependent variables (which names should be in <VarList>),
     <maxexpon> is the optional maximum exponent for each independent
     variable (1 by default), and <maxdegree> is the optional maximum
     polynomial degree (<maxexpon> by default); note that the sum of
     exponents of each term must be equal or smaller than <maxdegree>,
     and if `maxdgree = 0' then no limit is applied.

     If <depvars> is the name of a dependent variable (not in a list),
     `plsquares' returns the adjusted polynomial. If <depvars> is a
     list of one or more dependent variables, `plsquares' returns a
     list with the adjusted polynomial(s). The Coefficients of
     Determination  are displayed in order to inform about the goodness
     of fit, which ranges from 0 (no correlation) to 1 (exact
     correlation). These values are also stored in the global variable
     <DETCOEF> (a list if <depvars> is a list).

     A simple example of multivariable linear adjustment:
          (%i1) load("plsquares")$

          (%i2) plsquares(matrix([1,2,0],[3,5,4],[4,7,9],[5,8,10]),
                          [x,y,z],z);
               Determination Coefficient for z = .9897039897039897
                                 11 y - 9 x - 14
          (%o2)              z = ---------------
                                        3

     The same example without degree restrictions:
          (%i3) plsquares(matrix([1,2,0],[3,5,4],[4,7,9],[5,8,10]),
                          [x,y,z],z,1,0);
               Determination Coefficient for z = 1.0
                              x y + 23 y - 29 x - 19
          (%o3)           z = ----------------------
                                        6

     How many diagonals does a N-sides polygon have? What polynomial
     degree should be used?
          (%i4) plsquares(matrix([3,0],[4,2],[5,5],[6,9],[7,14],[8,20]),
                          [N,diagonals],diagonals,5);
               Determination Coefficient for diagonals = 1.0
                                          2
                                         N  - 3 N
          (%o4)              diagonals = --------
                                            2
          (%i5) ev(%, N=9);   /* Testing for a 9 sides polygon */
          (%o5)                 diagonals = 27

     How many ways do we have to put two queens without they are
     threatened into a n x n chessboard?
          (%i6) plsquares(matrix([0,0],[1,0],[2,0],[3,8],[4,44]),
                          [n,positions],[positions],4);
               Determination Coefficient for [positions] = [1.0]
                                   4       3      2
                                3 n  - 10 n  + 9 n  - 2 n
          (%o6)    [positions = -------------------------]
                                            6
          (%i7) ev(%[1], n=8); /* Testing for a (8 x 8) chessboard */
          (%o7)                positions = 1288

     An example with six dependent variables:
          (%i8) mtrx:matrix([0,0,0,0,0,1,1,1],[0,1,0,1,1,1,0,0],
                            [1,0,0,1,1,1,0,0],[1,1,1,1,0,0,0,1])$
          (%i8) plsquares(mtrx,[a,b,_And,_Or,_Xor,_Nand,_Nor,_Nxor],
                               [_And,_Or,_Xor,_Nand,_Nor,_Nxor],1,0);
                Determination Coefficient for
          [_And, _Or, _Xor, _Nand, _Nor, _Nxor] =
          [1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
          (%o2) [_And = a b, _Or = - a b + b + a,
          _Xor = - 2 a b + b + a, _Nand = 1 - a b,
          _Nor = a b - b - a + 1, _Nxor = 2 a b - b - a + 1]

     To use this function write first `load("lsquares")'.



File: maxima.info,  Node: minpack,  Next: makeOrders,  Prev: lsquares,  Up: Top

65 minpack
**********

* Menu:

* Introduction to minpack::
* Functions and Variables for minpack::


File: maxima.info,  Node: Introduction to minpack,  Next: Functions and Variables for minpack,  Up: minpack

65.1 Introduction to minpack
============================

`Minpack' is a Common Lisp translation (via `f2cl') of the Fortran
library MINPACK, as obtained from Netlib.


File: maxima.info,  Node: Functions and Variables for minpack,  Prev: Introduction to minpack,  Up: minpack

65.2 Functions and Variables for minpack
========================================

 -- Function: minpack_lsquares (<flist>, <varlist>, <guess> [,
          <tolerance>, <jacobian>])
     Compute the point that minimizes the sum of the squares of the
     functions in the list <flist>.  The variables are in the list
     <varlist>.  An initial guess of the optimum point must be provided
     in <guess>.

     The optional keyword arguments, <tolerance> and <jacobian> provide
     some control over the algorithm.  <tolerance> is the estimated
     relative error desired in the sum of squares.  <jacobian> can be
     used to specify the Jacobian.  If <jacobian> is not given or is
     `true' (the default), the Jacobian is computed from <flist>.  If
     <jacobian> is `false', a numerical approximation is used.

     `minpack_lsquares' returns a list.  The first item is the
     estimated solution; the second is the sum of squares, and the third
     indicates the success of the algorithm.  The possible values are

    `0'
          improper input parameters.

    `1'
          algorithm estimates that the relative error in the sum of
          squares is at most `tolerance'.

    `2'
          algorithm estimates that the relative error between x and the
          solution is at most `tolerance'.

    `3'
          conditions for info = 1 and info = 2 both hold.

    `4'
          fvec is orthogonal to the columns of the jacobian to machine
          precision.

    `5'
          number of calls to fcn with iflag = 1 has reached 100*(n+1).

    `6'
          tol is too small. no further reduction in the sum of squares
          is possible.

    `7'
          tol is too small. no further improvement in the approximate
          solution x is possible.

          /* Problem 6: Powell singular function */
          (%i1) powell(x1,x2,x3,x4) :=
                   [x1+10*x2, sqrt(5)*(x3-x4), (x2-2*x3)^2,
                        sqrt(10)*(x1-x4)^2]$
          (%i2) minpack_lsquares(powell(x1,x2,x3,x4), [x1,x2,x3,x4],
                                 [3,-1,0,1]);
          (%o2) [[1.652117596168394e-17, - 1.652117596168393e-18,
                  2.643388153869468e-18, 2.643388153869468e-18],
                 6.109327859207777e-34, 4]

          /* Same problem but use numerical approximation to Jacobian */
          (%i3) minpack_lsquares(powell(x1,x2,x3,x4), [x1,x2,x3,x4],
                                 [3,-1,0,1], jacobian = false);
          (%o3) [[5.060282149485331e-11, - 5.060282149491206e-12,
                  2.179447843547218e-11, 2.179447843547218e-11],
                 3.534491794847031e-21, 5]


 -- Function: minpack_solve (<flist>, <varlist>, <guess> [,
          <tolerance>, <jacobian>])
     Solve a system of `n' equations in `n' unknowns.  The `n'
     equations are given in the list <flist>, and the unknowns are in
     <varlist>.  An initial guess of the solution must be provided in
     <guess>.

     The optional keyword arguments, <tolerance> and <jacobian> provide
     some control over the algorithm.  <tolerance> is the estimated
     relative error desired in the sum of squares.  <jacobian> can be
     used to specify the Jacobian.  If <jacobian> is not given or is
     `true' (the default), the Jacobian is computed from <flist>.  If
     <jacobian> is `false', a numerical approximation is used.

     `minpack_solve' returns a list.  The first item is the estimated
     solution; the second is the sum of squares, and the third
     indicates the success of the algorithm.  The possible values are

    `0'
          improper input parameters.

    `1'
          algorithm estimates that the relative error in the solution is
          at most `tolerance'.

    `2'
          number of calls to fcn with iflag = 1 has reached 100*(n+1).

    `3'
          tol is too small. no further reduction in the sum of squares
          is possible.

    `4'
          Iteration is not making good progress.




File: maxima.info,  Node: makeOrders,  Next: mnewton,  Prev: minpack,  Up: Top

66 makeOrders
*************

* Menu:

* Functions and Variables for makeOrders::


File: maxima.info,  Node: Functions and Variables for makeOrders,  Prev: makeOrders,  Up: makeOrders

66.1 Functions and Variables for makeOrders
===========================================

 -- Function: makeOrders (<indvarlist>,<orderlist>)
     Returns a list of all powers for a polynomial up to and including
     the arguments.

          (%i1) load("makeOrders")$

          (%i2) makeOrders([a,b],[2,3]);
          (%o2) [[0, 0], [0, 1], [0, 2], [0, 3], [1, 0], [1, 1],
                      [1, 2], [1, 3], [2, 0], [2, 1], [2, 2], [2, 3]]
          (%i3) expand((1+a+a^2)*(1+b+b^2+b^3));
                 2  3      3    3    2  2      2    2    2
          (%o3) a  b  + a b  + b  + a  b  + a b  + b  + a  b + a b
                                                            2
                                                     + b + a  + a + 1
     where `[0, 1]' is associated with the term b and `[2, 3]' with a^2
     b^3.

     To use this function write first `load("makeOrders")'.



File: maxima.info,  Node: mnewton,  Next: numericalio,  Prev: makeOrders,  Up: Top

67 mnewton
**********

* Menu:

* Introduction to mnewton::
* Functions and Variables for mnewton::


File: maxima.info,  Node: Introduction to mnewton,  Next: Functions and Variables for mnewton,  Prev: mnewton,  Up: mnewton

67.1 Introduction to mnewton
============================

`mnewton' is an implementation of Newton's method for solving nonlinear
equations in one or more variables.


File: maxima.info,  Node: Functions and Variables for mnewton,  Prev: Introduction to mnewton,  Up: mnewton

67.2 Functions and Variables for mnewton
========================================

 -- Option variable: newtonepsilon
     Default value: `10.0^(-fpprec/2)'

     Precision to determine when the `mnewton' function has converged
     towards the solution.  If `newtonepsilon' is a bigfloat, then
     `mnewton' computations are done with bigfloats.  See also
     `mnewton'.


 -- Option variable: newtonmaxiter
     Default value: `50'

     Maximum number of iterations to stop the `mnewton' function if it
     does not converge or if it converges too slowly.

     See also `mnewton'.


 -- Function: mnewton (<FuncList>,<VarList>,<GuessList>)
     Multiple nonlinear functions solution using the Newton method.
     <FuncList> is the list of functions to solve, <VarList> is the
     list of variable names, and <GuessList> is the list of initial
     approximations.

     The solution is returned in the same format that `solve()' returns.
     If the solution is not found, `[]' is returned.

     This function is controlled by global variables `newtonepsilon' and
     `newtonmaxiter'.

          (%i1) load("mnewton")$

          (%i2) mnewton([x1+3*log(x1)-x2^2, 2*x1^2-x1*x2-5*x1+1],
                        [x1, x2], [5, 5]);
          (%o2) [[x1 = 3.756834008012769, x2 = 2.779849592817897]]
          (%i3) mnewton([2*a^a-5],[a],[1]);
          (%o3)             [[a = 1.70927556786144]]
          (%i4) mnewton([2*3^u-v/u-5, u+2^v-4], [u, v], [2, 2]);
          (%o4) [[u = 1.066618389595407, v = 1.552564766841786]]

     The variable `newtonepsilon' controls the precision of the
     approximations.  It also controls if computations are performed
     with floats or bigfloats.

          (%i1) load(mnewton)$

          (%i2) (fpprec : 25, newtonepsilon : bfloat(10^(-fpprec+5)))$

          (%i3) mnewton([2*3^u-v/u-5, u+2^v-4], [u, v], [2, 2]);
          (%o3) [[u = 1.066618389595406772591173b0,
                                         v = 1.552564766841786450100418b0]]

     To use this function write first `load("mnewton")'.  See also
     `newtonepsilon' and `newtonmaxiter'.



File: maxima.info,  Node: numericalio,  Next: opsubst,  Prev: mnewton,  Up: Top

68 numericalio
**************

* Menu:

* Introduction to numericalio::
* Functions and Variables for plain-text input and output::
* Functions and Variables for binary input and output::


File: maxima.info,  Node: Introduction to numericalio,  Next: Functions and Variables for plain-text input and output,  Prev: numericalio,  Up: numericalio

68.1 Introduction to numericalio
================================

`numericalio' is a collection of functions to read and write files and
streams.  Functions for plain-text input and output can read and write
numbers (integer, float, or bigfloat), symbols, and strings.  Functions
for binary input and output can read and write only floating-point
numbers.

   If there already exists a list, matrix, or array object to store
input data, `numericalio' input functions can write data into that
object.  Otherwise, `numericalio' can guess, to some degree, the
structure of an object to store the data, and return that object.

68.1.1 Plain-text input and output
----------------------------------

In plain-text input and output, it is assumed that each item to read or
write is an atom: an integer, float, bigfloat, string, or symbol, and
not a rational or complex number or any other kind of nonatomic
expression.  The `numericalio' functions may attempt to do something
sensible faced with nonatomic expressions, but the results are not
specified here and subject to change.

   Atoms in both input and output files have the same format as in
Maxima batch files or the interactive console.  In particular, strings
are enclosed in double quotes, backslash `\' prevents any special
interpretation of the next character, and the question mark `?' is
recognized at the beginning of a symbol to mean a Lisp symbol (as
opposed to a Maxima symbol).  No continuation character (to join broken
lines) is recognized.

68.1.2 Separator flag values for input
--------------------------------------

The functions for plain-text input and output take an optional argument,
<separator_flag>, that tells what character separates data.

   For plain-text input, these values of <separator_flag> are
recognized: `comma' for comma separated values, `pipe' for values
separated by the vertical bar character `|', `semicolon' for values
separated by semicolon `;', and `space' for values separated by space
or tab characters.  If the file name ends in `.csv' and
<separator_flag> is not specified, `comma' is assumed.  If the file
name ends in something other than `.csv' and `separator_flag' is not
specified, `space' is assumed.

   In plain-text input, multiple successive space and tab characters
count as a single separator.  However, multiple comma, pipe, or
semicolon characters are significant.  Successive comma, pipe, or
semicolon characters (with or without intervening spaces or tabs) are
considered to have `false' between the separators.  For example,
`1234,,Foo' is treated the same as `1234,false,Foo'.

68.1.3 Separator flag values for output
---------------------------------------

For plain-text output, `tab', for values separated by the tab character,
is recognized as a value of <separator_flag>, as well as `comma',
`pipe', `semicolon', and `space'.

   In plain-text output, `false' atoms are written as such; a list
`[1234, false, Foo]' is written `1234,false,Foo', and there is no
attempt to collapse the output to `1234,,Foo'.

68.1.4 Binary floating-point input and output
---------------------------------------------

`numericalio' functions can read and write 8-byte IEEE 754
floating-point numbers.  These numbers can be stored either least
significant byte first or most significant byte first, according to the
global flag set by `assume_external_byte_order'.  If not specified,
`numericalio' assumes the external byte order is most-significant byte
first.

   Other kinds of numbers are coerced to 8-byte floats; `numericalio'
cannot read or write binary non-numeric data.

   Some Lisp implementations do not recognize IEEE 754 special values
(positive and negative infinity, not-a-number values, denormalized
values).  The effect of reading such values with `numericalio' is
undefined.

   `numericalio' includes functions to open a stream for reading or
writing a stream of bytes.


File: maxima.info,  Node: Functions and Variables for plain-text input and output,  Next: Functions and Variables for binary input and output,  Prev: Introduction to numericalio,  Up: numericalio

68.2 Functions and Variables for plain-text input and output
============================================================

 -- Function: read_matrix (<S>)
 -- Function: read_matrix (<S>, <M>)
 -- Function: read_matrix (<S>, <separator_flag>)
 -- Function: read_matrix (<S>, <M>, <separator_flag>)
     `read_matrix(<S>)' reads the source <S> and returns its entire
     content as a matrix.  The size of the matrix is inferred from the
     input data; each line of the file becomes one row of the matrix.
     If some lines have different lengths, `read_matrix' complains.

     `read_matrix(<S>, <M>)' read the source <S> into the matrix <M>,
     until <M> is full or the source is exhausted.  Input data are read
     into the matrix in row-major order; the input need not have the
     same number of rows and columns as <M>.

     The source <S> may be a file name or a stream.

     The recognized values of <separator_flag> are `comma', `pipe',
     `semicolon', and `space'.  If <separator_flag> is not specified,
     the file is assumed space-delimited.


 -- Function: read_array (<S>, <A>)
 -- Function: read_array (<S>, <A>, <separator_flag>)
     Reads the source <S> into the array <A>, until <A> is full or the
     source is exhausted.  Input data are read into the array in
     row-major order; the input need not conform to the dimensions of
     <A>.

     The source <S> may be a file name or a stream.

     The recognized values of <separator_flag> are `comma', `pipe',
     `semicolon', and `space'.  If <separator_flag> is not specified,
     the file is assumed space-delimited.


 -- Function: read_hashed_array (<S>, <A>)
 -- Function: read_hashed_array (<S>, <A>, <separator_flag>)
     Reads the source <S> and returns its entire content as a hashed
     array.  The source <S> may be a file name or a stream.

     `read_hashed_array' treats the first item on each line as a hash
     key, and associates the remainder of the line (as a list) with the
     key.  For example, the line `567 12 17 32 55' is equivalent to
     `A[567]: [12, 17, 32, 55]$'.  Lines need not have the same numbers
     of elements.

     The recognized values of <separator_flag> are `comma', `pipe',
     `semicolon', and `space'.  If <separator_flag> is not specified,
     the file is assumed space-delimited.


 -- Function: read_nested_list (<S>)
 -- Function: read_nested_list (<S>, <separator_flag>)
     Reads the source <S> and returns its entire content as a nested
     list.  The source <S> may be a file name or a stream.

     `read_nested_list' returns a list which has a sublist for each
     line of input. Lines need not have the same numbers of elements.
     Empty lines are not ignored: an empty line yields an empty sublist.

     The recognized values of <separator_flag> are `comma', `pipe',
     `semicolon', and `space'.  If <separator_flag> is not specified,
     the file is assumed space-delimited.


 -- Function: read_list (<S>)
 -- Function: read_list (<S>, <L>)
 -- Function: read_list (<S>, <separator_flag>)
 -- Function: read_list (<S>, <L>, <separator_flag>)
     `read_list(<S>)' reads the source <S> and returns its entire
     content as a flat list.

     `read_list(<S>, <L>)' reads the source <S> into the list <L>,
     until <L> is full or the source is exhausted.

     The source <S> may be a file name or a stream.

     The recognized values of <separator_flag> are `comma', `pipe',
     `semicolon', and `space'.  If <separator_flag> is not specified,
     the file is assumed space-delimited.


 -- Function: write_data (<X>, <D>)
 -- Function: write_data (<X>, <D>, <separator_flag>)
     Writes the object <X> to the destination <D>.

     `write_data' writes a matrix in row-major order, with one line per
     row.

     `write_data' writes an array created by `array' or `make_array' in
     row-major order, with a new line at the end of every slab.
     Higher-dimensional slabs are separated by additional new lines.

     `write_data' writes a hashed array with each key followed by its
     associated list on one line.

     `write_data' writes a nested list with each sublist on one line.

     `write_data' writes a flat list all on one line.

     The destination <D> may be a file name or a stream.  When the
     destination is a file name, the global variable
     `file_output_append' governs whether the output file is appended
     or truncated.  When the destination is a stream, no special action
     is taken by `write_data' after all the data are written; in
     particular, the stream remains open.

     The recognized values of <separator_flag> are `comma', `pipe',
     `semicolon', `space', and `tab'.  If <separator_flag> is not
     specified, the file is assumed space-delimited.



File: maxima.info,  Node: Functions and Variables for binary input and output,  Prev: Functions and Variables for plain-text input and output,  Up: numericalio

68.3 Functions and Variables for binary input and output
========================================================

 -- Function: assume_external_byte_order (<byte_order_flag>)
     Tells `numericalio' the byte order for reading and writing binary
     data.  Two values of <byte_order_flag> are recognized: `lsb' which
     indicates least-significant byte first, also called little-endian
     byte order; and `msb' which indicates most-significant byte first,
     also called big-endian byte order.

     If not specified, `numericalio' assumes the external byte order is
     most-significant byte first.


 -- Function: openr_binary (<file_name>)
     Returns an input stream of 8-bit unsigned bytes to read the file
     named by <file_name>.


 -- Function: openw_binary (<file_name>)
     Returns an output stream of 8-bit unsigned bytes to write the file
     named by <file_name>.


 -- Function: opena_binary (<file_name>)
     Returns an output stream of 8-bit unsigned bytes to append the
     file named by <file_name>.


 -- Function: read_binary_matrix (<S>, <M>)
     Reads binary 8-byte floating point numbers from the source <S>
     into the matrix <M> until <M> is full, or the source is exhausted.
     Elements of <M> are read in row-major order.

     The source <S> may be a file name or a stream.

     The byte order in elements of the source is specified by
     `assume_external_byte_order'.


 -- Function: read_binary_array (<S>, <A>)
     Reads binary 8-byte floating point numbers from the source <S>
     into the array <A> until <A> is full, or the source is exhausted.
     <A> must be an array created by `array' or `make_array'.  Elements
     of <A> are read in row-major order.

     The source <S> may be a file name or a stream.

     The byte order in elements of the source is specified by
     `assume_external_byte_order'.


 -- Function: read_binary_list (<S>)
 -- Function: read_binary_list (<S>, <L>)
     `read_binary_list(<S>)' reads the entire content of the source <S>
     as a sequence of binary 8-byte floating point numbers, and returns
     it as a list.  The source <S> may be a file name or a stream.

     `read_binary_list(<S>, <L>)' reads 8-byte binary floating point
     numbers from the source <S> until the list <L> is full, or the
     source is exhausted.

     The byte order in elements of the source is specified by
     `assume_external_byte_order'.


 -- Function: write_binary_data (<X>, <D>)
     Writes the object <X>, comprising binary 8-byte IEEE 754
     floating-point numbers, to the destination <D>.  Other kinds of
     numbers are coerced to 8-byte floats.  `write_binary_data' cannot
     write non-numeric data.

     The object <X> may be a list, a nested list, a matrix, or an array
     created by `array' or `make_array'; <X> cannot be an undeclared
     array or any other type of object.  `write_binary_data' writes
     nested lists, matrices, and arrays in row-major order.

     The destination <D> may be a file name or a stream.  When the
     destination is a file name, the global variable
     `file_output_append' governs whether the output file is appended
     or truncated.  When the destination is a stream, no special action
     is taken by `write_binary_data' after all the data are written; in
     particular, the stream remains open.

     The byte order in elements of the destination is specified by
     `assume_external_byte_order'.



File: maxima.info,  Node: opsubst,  Next: orthopoly,  Prev: numericalio,  Up: Top

69 opsubst
**********

* Menu:

* Functions and Variables for opsubst::


File: maxima.info,  Node: Functions and Variables for opsubst,  Prev: opsubst,  Up: opsubst

69.1 Functions and Variables for opsubst
========================================

 -- Function: opsubst (<f>,<g>,<e>)
 -- Function: opsubst (<g>=<f>,<e>)
 -- Function: opsubst ([<g1>=<f1>,<g2>=<f2>,..., <gn>=<fn>],<e>)
     The function `opsubst' is similar to the function `subst', except
     that `opsubst' only makes substitutions for the operators in an
     expression. In general, When <f> is an operator in the expression
     <e>, substitute <g> for <f> in the expression <e>.

     To determine the operator, `opsubst' sets `inflag' to true. This
     means `opsubst' substitutes for the internal, not the displayed,
     operator in the expression.

     Examples:
          (%i1) load (opsubst)$

          (%i2) opsubst(f,g,g(g(x)));
          (%o2)                     f(f(x))
          (%i3) opsubst(f,g,g(g));
          (%o3)                       f(g)
          (%i4) opsubst(f,g[x],g[x](z));
          (%o4)                       f(z)
          (%i5) opsubst(g[x],f, f(z));
          (%o5)                      g (z)
                                      x
          (%i6) opsubst(tan, sin, sin(sin));
          (%o6)                     tan(sin)
          (%i7) opsubst([f=g,g=h],f(x));
          (%o7)                       h(x)

     Internally, Maxima does not use the unary negation, division, or
     the subtraction operators; thus:
          (%i8) opsubst("+","-",a-b);
          (%o8)                     a - b
          (%i9) opsubst("f","-",-a);
          (%o9)                      - a
          (%i10) opsubst("^^","/",a/b);
                                       a
          (%o10)                       -
                                       b

     The internal representation of -a*b is *(-1,a,b); thus
          (%i11) opsubst("[","*", -a*b);
          (%o11)                  [- 1, a, b]

     When either operator isn't a Maxima symbol, generally some other
     function will signal an error:
          (%i12) opsubst(a+b,f, f(x));

          Improper name or value in functional position:
          b + a
           -- an error.  Quitting.  To debug this try debugmode(true);

     However, subscripted operators are allowed:
          (%i13) opsubst(g[5],f, f(x));
          (%o13)                     g (x)
                                      5

     To use this function write first `load("opsubst")'.



File: maxima.info,  Node: orthopoly,  Next: romberg,  Prev: opsubst,  Up: Top

70 orthopoly
************

* Menu:

* Introduction to orthogonal polynomials::
* Functions and Variables for orthogonal polynomials::


File: maxima.info,  Node: Introduction to orthogonal polynomials,  Next: Functions and Variables for orthogonal polynomials,  Prev: orthopoly,  Up: orthopoly

70.1 Introduction to orthogonal polynomials
===========================================

`orthopoly' is a package for symbolic and numerical evaluation of
several kinds of orthogonal polynomials, including Chebyshev, Laguerre,
Hermite, Jacobi, Legendre, and ultraspherical (Gegenbauer) polynomials.
Additionally, `orthopoly' includes support for the spherical Bessel,
spherical Hankel, and spherical harmonic functions.

   For the most part, `orthopoly' follows the conventions of Abramowitz
and Stegun Handbook of Mathematical Functions, Chapter 22 (10th
printing, December 1972); additionally, we use Gradshteyn and Ryzhik,
Table of Integrals, Series, and Products (1980 corrected and enlarged
edition), and Eugen Merzbacher Quantum Mechanics (2nd edition, 1970).

   Barton Willis of the University of Nebraska at Kearney (UNK) wrote
the `orthopoly' package and its documentation. The package is released
under the GNU General Public License (GPL).

70.1.1 Getting Started with orthopoly
-------------------------------------

`load (orthopoly)' loads the `orthopoly' package.

   To find the third-order Legendre polynomial,

     (%i1) legendre_p (3, x);
                           3             2
                  5 (1 - x)    15 (1 - x)
     (%o1)      - ---------- + ----------- - 6 (1 - x) + 1
                      2             2

   To express this as a sum of powers of <x>, apply <ratsimp> or <rat>
to the result.

     (%i2) [ratsimp (%), rat (%)];
                             3           3
                          5 x  - 3 x  5 x  - 3 x
     (%o2)/R/            [----------, ----------]
                              2           2

   Alternatively, make the second argument to `legendre_p' (its "main"
variable) a canonical rational expression (CRE).

     (%i1) legendre_p (3, rat (x));
                                   3
                                5 x  - 3 x
     (%o1)/R/                   ----------
                                    2

   For floating point evaluation, `orthopoly' uses a running error
analysis to estimate an upper bound for the error. For example,

     (%i1) jacobi_p (150, 2, 3, 0.2);
     (%o1) interval(- 0.062017037936715, 1.533267919277521E-11)

   Intervals have the form `interval (<c>, <r>)', where <c> is the
center and <r> is the radius of the interval. Since Maxima does not
support arithmetic on intervals, in some situations, such as graphics,
you want to suppress the error and output only the center of the
interval. To do this, set the option variable
`orthopoly_returns_intervals' to `false'.

     (%i1) orthopoly_returns_intervals : false;
     (%o1)                         false
     (%i2) jacobi_p (150, 2, 3, 0.2);
     (%o2)                  - 0.062017037936715

   Refer to the section *note Floating point Evaluation:: for more
information.

   Most functions in `orthopoly' have a `gradef' property; thus

     (%i1) diff (hermite (n, x), x);
     (%o1)                     2 n H     (x)
                                    n - 1
     (%i2) diff (gen_laguerre (n, a, x), x);
                   (a)               (a)
                n L   (x) - (n + a) L     (x) unit_step(n)
                   n                 n - 1
     (%o2)      ------------------------------------------
                                    x

   The unit step function in the second example prevents an error that
would otherwise arise by evaluating with <n> equal to 0.

     (%i3) ev (%, n = 0);
     (%o3)                           0

   The `gradef' property only applies to the "main" variable;
derivatives with respect other arguments usually result in an error
message; for example

     (%i1) diff (hermite (n, x), x);
     (%o1)                     2 n H     (x)
                                    n - 1
     (%i2) diff (hermite (n, x), n);

     Maxima doesn't know the derivative of hermite with respect the first
     argument
      -- an error.  Quitting.  To debug this try debugmode(true);

   Generally, functions in `orthopoly' map over lists and matrices. For
the mapping to fully evaluate, the option variables `doallmxops' and
`listarith' must both be `true' (the defaults).  To illustrate the
mapping over matrices, consider

     (%i1) hermite (2, x);
                                          2
     (%o1)                    - 2 (1 - 2 x )
     (%i2) m : matrix ([0, x], [y, 0]);
                                 [ 0  x ]
     (%o2)                       [      ]
                                 [ y  0 ]
     (%i3) hermite (2, m);
                    [                             2  ]
                    [      - 2        - 2 (1 - 2 x ) ]
     (%o3)          [                                ]
                    [             2                  ]
                    [ - 2 (1 - 2 y )       - 2       ]

   In the second example, the `i, j' element of the value is `hermite
(2, m[i,j])'; this is not the same as computing `-2 + 4 m . m', as seen
in the next example.

     (%i4) -2 * matrix ([1, 0], [0, 1]) + 4 * m . m;
                         [ 4 x y - 2      0     ]
     (%o4)               [                      ]
                         [     0      4 x y - 2 ]

   If you evaluate a function at a point outside its domain, generally
`orthopoly' returns the function unevaluated. For example,

     (%i1) legendre_p (2/3, x);
     (%o1)                        P   (x)
                                   2/3

   `orthopoly' supports translation into TeX; it also does
two-dimensional output on a terminal.

     (%i1) spherical_harmonic (l, m, theta, phi);
                               m
     (%o1)                    Y (theta, phi)
                               l
     (%i2) tex (%);
     $$Y_{l}^{m}\left(\vartheta,\varphi\right)$$
     (%o2)                         false
     (%i3) jacobi_p (n, a, a - b, x/2);
                               (a, a - b) x
     (%o3)                    P          (-)
                               n          2
     (%i4) tex (%);
     $$P_{n}^{\left(a,a-b\right)}\left({{x}\over{2}}\right)$$
     (%o4)                         false

70.1.2 Limitations
------------------

When an expression involves several orthogonal polynomials with
symbolic orders, it's possible that the expression actually vanishes,
yet Maxima is unable to simplify it to zero. If you divide by such a
quantity, you'll be in trouble. For example, the following expression
vanishes for integers <n> greater than 1, yet Maxima is unable to
simplify it to zero.

     (%i1) (2*n - 1) * legendre_p (n - 1, x) * x - n * legendre_p (n, x)
           + (1 - n) * legendre_p (n - 2, x);
     (%o1)  (2 n - 1) P     (x) x - n P (x) + (1 - n) P     (x)
                       n - 1           n               n - 2

   For a specific <n>, we can reduce the expression to zero.

     (%i2) ev (% ,n = 10, ratsimp);
     (%o2)                           0

   Generally, the polynomial form of an orthogonal polynomial is
ill-suited for floating point evaluation. Here's an example.

     (%i1) p : jacobi_p (100, 2, 3, x)$

     (%i2) subst (0.2, x, p);
     (%o2)                3.4442767023833592E+35
     (%i3) jacobi_p (100, 2, 3, 0.2);
     (%o3)  interval(0.18413609135169, 6.8990300925815987E-12)
     (%i4) float(jacobi_p (100, 2, 3, 2/10));
     (%o4)                   0.18413609135169

   The true value is about 0.184; this calculation suffers from extreme
subtractive cancellation error. Expanding the polynomial and then
evaluating, gives a better result.
     (%i5) p : expand(p)$
     (%i6) subst (0.2, x, p);
     (%o6) 0.18413609766122982

   This isn't a general rule; expanding the polynomial does not always
result in an expression that is better suited for numerical evaluation.
By far, the best way to do numerical evaluation is to make one or more
of the function arguments floating point numbers. By doing that,
specialized floating point algorithms are used for evaluation.

   Maxima's `float' function is somewhat indiscriminate; if you apply
`float' to an expression involving an orthogonal polynomial with a
symbolic degree or order parameter, these parameters may be converted
into floats; after that, the expression will not evaluate fully.
Consider

     (%i1) assoc_legendre_p (n, 1, x);
                                    1
     (%o1)                         P (x)
                                    n
     (%i2) float (%);
                                   1.0
     (%o2)                        P   (x)
                                   n
     (%i3) ev (%, n=2, x=0.9);
                                  1.0
     (%o3)                       P   (0.9)
                                  2

   The expression in (%o3) will not evaluate to a float; `orthopoly'
doesn't recognize floating point values where it requires an integer.
Similarly, numerical evaluation of the `pochhammer' function for orders
that exceed `pochhammer_max_index' can be troublesome; consider

     (%i1) x :  pochhammer (1, 10), pochhammer_max_index : 5;
     (%o1)                         (1)
                                      10

   Applying `float' doesn't evaluate <x> to a float

     (%i2) float (x);
     (%o2)                       (1.0)
                                      10.0

   To evaluate <x> to a float, you'll need to bind
`pochhammer_max_index' to 11 or greater and apply `float' to <x>.

     (%i3) float (x), pochhammer_max_index : 11;
     (%o3)                       3628800.0

   The default value of `pochhammer_max_index' is 100; change its value
after loading `orthopoly'.

   Finally, be aware that reference books vary on the definitions of the
orthogonal polynomials; we've generally used the conventions of
conventions of Abramowitz and Stegun.

   Before you suspect a bug in orthopoly, check some special cases to
determine if your definitions match those used by `orthopoly'.
Definitions often differ by a normalization; occasionally, authors use
"shifted" versions of the functions that makes the family orthogonal on
an interval other than (-1, 1). To define, for example, a Legendre
polynomial that is orthogonal on (0, 1), define

     (%i1) shifted_legendre_p (n, x) := legendre_p (n, 2*x - 1)$

     (%i2) shifted_legendre_p (2, rat (x));
                                 2
     (%o2)/R/                 6 x  - 6 x + 1
     (%i3) legendre_p (2, rat (x));
                                    2
                                 3 x  - 1
     (%o3)/R/                    --------
                                    2

70.1.3 Floating point Evaluation
--------------------------------

Most functions in `orthopoly' use a running error analysis to estimate
the error in floating point evaluation; the exceptions are the
spherical Bessel functions and the associated Legendre polynomials of
the second kind. For numerical evaluation, the spherical Bessel
functions call SLATEC functions. No specialized method is used for
numerical evaluation of the associated Legendre polynomials of the
second kind.

   The running error analysis ignores errors that are second or higher
order in the machine epsilon (also known as unit roundoff). It also
ignores a few other errors. It's possible (although unlikely) that the
actual error exceeds the estimate.

   Intervals have the form `interval (<c>, <r>)', where <c> is the
center of the interval and <r> is its radius. The center of an interval
can be a complex number, and the radius is always a positive real
number.

   Here is an example.

     (%i1) fpprec : 50$

     (%i2) y0 : jacobi_p (100, 2, 3, 0.2);
     (%o2) interval(0.1841360913516871, 6.8990300925815987E-12)
     (%i3) y1 : bfloat (jacobi_p (100, 2, 3, 1/5));
     (%o3) 1.8413609135168563091370224958913493690868904463668b-1

   Let's test that the actual error is smaller than the error estimate

     (%i4) is (abs (part (y0, 1) - y1) < part (y0, 2));
     (%o4)                         true

   Indeed, for this example the error estimate is an upper bound for the
true error.

   Maxima does not support arithmetic on intervals.

     (%i1) legendre_p (7, 0.1) + legendre_p (8, 0.1);
     (%o1) interval(0.18032072148437508, 3.1477135311021797E-15)
             + interval(- 0.19949294375000004, 3.3769353084291579E-15)

   A user could define arithmetic operators that do interval math. To
define interval addition, we can define

     (%i1) infix ("@+")$

     (%i2) "@+"(x,y) := interval (part (x, 1) + part (y, 1), part (x, 2)
           + part (y, 2))$

     (%i3) legendre_p (7, 0.1) @+ legendre_p (8, 0.1);
     (%o3) interval(- 0.019172222265624955, 6.5246488395313372E-15)

   The special floating point routines get called when the arguments
are complex.  For example,

     (%i1) legendre_p (10, 2 + 3.0*%i);
     (%o1) interval(- 3.876378825E+7 %i - 6.0787748E+7,
                                                1.2089173052721777E-6)

   Let's compare this to the true value.

     (%i1) float (expand (legendre_p (10, 2 + 3*%i)));
     (%o1)          - 3.876378825E+7 %i - 6.0787748E+7

   Additionally, when the arguments are big floats, the special
floating point routines get called; however, the big floats are
converted into double floats and the final result is a double.

     (%i1) ultraspherical (150, 0.5b0, 0.9b0);
     (%o1) interval(- 0.043009481257265, 3.3750051301228864E-14)

70.1.4 Graphics and `orthopoly'
-------------------------------

To plot expressions that involve the orthogonal polynomials, you must
do two things:
  1. Set the option variable `orthopoly_returns_intervals' to `false',

  2. Quote any calls to `orthopoly' functions.
        If function calls aren't quoted, Maxima evaluates them to
polynomials before plotting; consequently, the specialized floating
point code doesn't get called.  Here is an example of how to plot an
expression that involves a Legendre polynomial.

     (%i1) plot2d ('(legendre_p (5, x)), [x, 0, 1]),
                             orthopoly_returns_intervals : false;
     (%o1)

   The entire expression `legendre_p (5, x)' is quoted; this is
different than just quoting the function name using `'legendre_p (5,
<x>)'.

70.1.5 Miscellaneous Functions
------------------------------

The `orthopoly' package defines the Pochhammer symbol and a unit step
function. `orthopoly' uses the Kronecker delta function and the unit
step function in `gradef' statements.

   To convert Pochhammer symbols into quotients of gamma functions, use
`makegamma'.

     (%i1) makegamma (pochhammer (x, n));
                               gamma(x + n)
     (%o1)                     ------------
                                 gamma(x)
     (%i2) makegamma (pochhammer (1/2, 1/2));
                                     1
     (%o2)                       ---------
                                 sqrt(%pi)

   Derivatives of the Pochhammer symbol are given in terms of the `psi'
function.

     (%i1) diff (pochhammer (x, n), x);
     (%o1)             (x)  (psi (x + n) - psi (x))
                          n     0             0
     (%i2) diff (pochhammer (x, n), n);
     (%o2)                   (x)  psi (x + n)
                                n    0

   You need to be careful with the expression in (%o1); the difference
of the `psi' functions has polynomials when `<x> = -1, -2, .., -<n>'.
These polynomials cancel with factors in `pochhammer (<x>, <n>)' making
the derivative a degree `<n> - 1' polynomial when <n> is a positive
integer.

   The Pochhammer symbol is defined for negative orders through its
representation as a quotient of gamma functions. Consider

     (%i1) q : makegamma (pochhammer (x, n));
                               gamma(x + n)
     (%o1)                     ------------
                                 gamma(x)
     (%i2) sublis ([x=11/3, n= -6], q);
                                    729
     (%o2)                        - ----
                                    2240

   Alternatively, we can get this result directly.

     (%i1) pochhammer (11/3, -6);
                                    729
     (%o1)                        - ----
                                    2240

   The unit step function is left-continuous; thus

     (%i1) [unit_step (-1/10), unit_step (0), unit_step (1/10)];
     (%o1)                       [0, 0, 1]

   If you need a unit step function that is neither left or right
continuous at zero, define your own using `signum'; for example,

     (%i1) xunit_step (x) := (1 + signum (x))/2$

     (%i2) [xunit_step (-1/10), xunit_step (0), xunit_step (1/10)];
                                     1
     (%o2)                       [0, -, 1]
                                     2

   Do not redefine `unit_step' itself; some code in `orthopoly'
requires that the unit step function be left-continuous.

70.1.6 Algorithms
-----------------

Generally, `orthopoly' does symbolic evaluation by using a hypergeometic
representation of the orthogonal polynomials. The hypergeometic
functions are evaluated using the (undocumented) functions `hypergeo11'
and `hypergeo21'. The exceptions are the half-integer Bessel functions
and the associated Legendre function of the second kind. The
half-integer Bessel functions are evaluated using an explicit
representation, and the associated Legendre function of the second kind
is evaluated using recursion.

   For floating point evaluation, we again convert most functions into
a hypergeometic form; we evaluate the hypergeometic functions using
forward recursion. Again, the exceptions are the half-integer Bessel
functions and the associated Legendre function of the second kind.
Numerically, the half-integer Bessel functions are evaluated using the
SLATEC code.


File: maxima.info,  Node: Functions and Variables for orthogonal polynomials,  Prev: Introduction to orthogonal polynomials,  Up: orthopoly

70.2 Functions and Variables for orthogonal polynomials
=======================================================

 -- Function: assoc_legendre_p (<n>, <m>, <x>)
     The associated Legendre function of the first kind of degree <n>
     and order <m>.

     Reference: Abramowitz and Stegun, equations 22.5.37, page 779,
     8.6.6 (second equation), page 334, and 8.2.5, page 333.


 -- Function: assoc_legendre_q (<n>, <m>, <x>)
     The associated Legendre function of the second kind of degree <n>
     and order <m>.

     Reference: Abramowitz and Stegun, equation 8.5.3 and 8.1.8.


 -- Function: chebyshev_t (<n>, <x>)
     The Chebyshev function of the first kind.

     Reference: Abramowitz and Stegun, equation 22.5.47, page 779.


 -- Function: chebyshev_u (<n>, <x>)
     The Chebyshev function of the second kind.

     Reference: Abramowitz and Stegun, equation 22.5.48, page 779.


 -- Function: gen_laguerre (<n>, <a>, <x>)
     The generalized Laguerre polynomial of degree <n>.

     Reference: Abramowitz and Stegun, equation 22.5.54, page 780.


 -- Function: hermite (<n>, <x>)
     The Hermite polynomial.

     Reference: Abramowitz and Stegun, equation 22.5.55, page 780.


 -- Function: intervalp (<e>)
     Return `true' if the input is an interval and return false if it
     isn't.


 -- Function: jacobi_p (<n>, <a>, <b>, <x>)
     The Jacobi polynomial.

     The Jacobi polynomials are actually defined for all <a> and <b>;
     however, the Jacobi polynomial weight `(1 - <x>)^<a> (1 +
     <x>)^<b>' isn't integrable for `<a> <= -1' or `<b> <= -1'.

     Reference: Abramowitz and Stegun, equation 22.5.42, page 779.


 -- Function: laguerre (<n>, <x>)
     The Laguerre polynomial.

     Reference: Abramowitz and Stegun, equations 22.5.16 and 22.5.54,
     page 780.


 -- Function: legendre_p (<n>, <x>)
     The Legendre polynomial of the first kind.

     Reference: Abramowitz and Stegun, equations 22.5.50 and 22.5.51,
     page 779.


 -- Function: legendre_q (<n>, <x>)
     The Legendre polynomial of the first kind.

     Reference: Abramowitz and Stegun, equations 8.5.3 and 8.1.8.


 -- Function: orthopoly_recur (<f>, <args>)
     Returns a recursion relation for the orthogonal function family
     <f> with arguments <args>. The recursion is with respect to the
     polynomial degree.

          (%i1) orthopoly_recur (legendre_p, [n, x]);
                              (2 n + 1) P (x) x - n P     (x)
                                         n           n - 1
          (%o1)   P     (x) = -------------------------------
                   n + 1                   n + 1

     The second argument to `orthopoly_recur' must be a list with the
     correct number of arguments for the function <f>; if it isn't,
     Maxima signals an error.

          (%i1) orthopoly_recur (jacobi_p, [n, x]);

          Function jacobi_p needs 4 arguments, instead it received 2
           -- an error.  Quitting.  To debug this try debugmode(true);

     Additionally, when <f> isn't the name of one of the families of
     orthogonal polynomials, an error is signalled.

          (%i1) orthopoly_recur (foo, [n, x]);

          A recursion relation for foo isn't known to Maxima
           -- an error.  Quitting.  To debug this try debugmode(true);


 -- Variable: orthopoly_returns_intervals
     Default value: `true'

     When `orthopoly_returns_intervals' is `true', floating point
     results are returned in the form `interval (<c>, <r>)', where <c>
     is the center of an interval and <r> is its radius. The center can
     be a complex number; in that case, the interval is a disk in the
     complex plane.


 -- Function: orthopoly_weight (<f>, <args>)
     Returns a three element list; the first element is the formula of
     the weight for the orthogonal polynomial family <f> with arguments
     given by the list <args>; the second and third elements give the
     lower and upper endpoints of the interval of orthogonality. For
     example,

          (%i1) w : orthopoly_weight (hermite, [n, x]);
                                      2
                                   - x
          (%o1)                 [%e    , - inf, inf]
          (%i2) integrate(w[1]*hermite(3, x)*hermite(2, x), x, w[2], w[3]);
          (%o2)                           0

     The main variable of <f> must be a symbol; if it isn't, Maxima
     signals an error.


 -- Function: pochhammer (<n>, <x>)
     The Pochhammer symbol. For nonnegative integers <n> with `<n> <=
     pochhammer_max_index', the expression `pochhammer (<x>, <n>)'
     evaluates to the product `<x> (<x> + 1) (<x> + 2) ... (<x> + n -
     1)' when `<n> > 0' and to 1 when `<n> = 0'. For negative <n>,
     `pochhammer (<x>, <n>)' is defined as `(-1)^<n> / pochhammer (1 -
     <x>, -<n>)'.  Thus

          (%i1) pochhammer (x, 3);
          (%o1)                   x (x + 1) (x + 2)
          (%i2) pochhammer (x, -3);
                                           1
          (%o2)               - -----------------------
                                (1 - x) (2 - x) (3 - x)

     To convert a Pochhammer symbol into a quotient of gamma functions,
     (see Abramowitz and Stegun, equation 6.1.22) use `makegamma'; for
     example

          (%i1) makegamma (pochhammer (x, n));
                                    gamma(x + n)
          (%o1)                     ------------
                                      gamma(x)

     When <n> exceeds `pochhammer_max_index' or when <n> is symbolic,
     `pochhammer' returns a noun form.

          (%i1) pochhammer (x, n);
          (%o1)                         (x)
                                           n


 -- Variable: pochhammer_max_index
     Default value: 100

     `pochhammer (<n>, <x>)' expands to a product if and only if `<n>
     <= pochhammer_max_index'.

     Examples:

          (%i1) pochhammer (x, 3), pochhammer_max_index : 3;
          (%o1)                   x (x + 1) (x + 2)
          (%i2) pochhammer (x, 4), pochhammer_max_index : 3;
          (%o2)                         (x)
                                           4

     Reference: Abramowitz and Stegun, equation 6.1.16, page 256.


 -- Function: spherical_bessel_j (<n>, <x>)
     The spherical Bessel function of the first kind.

     Reference: Abramowitz and Stegun, equations 10.1.8, page 437 and
     10.1.15, page 439.


 -- Function: spherical_bessel_y (<n>, <x>)
     The spherical Bessel function of the second kind.

     Reference: Abramowitz and Stegun, equations 10.1.9, page 437 and
     10.1.15, page 439.


 -- Function: spherical_hankel1 (<n>, <x>)
     The spherical Hankel function of the first kind.

     Reference: Abramowitz and Stegun, equation 10.1.36, page 439.


 -- Function: spherical_hankel2 (<n>, <x>)
     The spherical Hankel function of the second kind.

     Reference: Abramowitz and Stegun, equation 10.1.17, page 439.


 -- Function: spherical_harmonic (<n>, <m>, <x>, <y>)
     The spherical harmonic function.

     Reference: Merzbacher 9.64.


 -- Function: unit_step (<x>)
     The left-continuous unit step function; thus `unit_step (<x>)'
     vanishes for `<x> <= 0' and equals 1 for `<x> > 0'.

     If you want a unit step function that takes on the value 1/2 at
     zero, use `(1 + signum (<x>))/2'.


 -- Function: ultraspherical (<n>, <a>, <x>)
     The ultraspherical polynomial (also known as the Gegenbauer
     polynomial).

     Reference: Abramowitz and Stegun, equation 22.5.46, page 779.



File: maxima.info,  Node: romberg,  Next: simplex,  Prev: orthopoly,  Up: Top

71 romberg
**********

* Menu:

* Functions and Variables for romberg::


File: maxima.info,  Node: Functions and Variables for romberg,  Prev: Top,  Up: Top

71.1 Functions and Variables for romberg
========================================

 -- Function: romberg (<expr>, <x>, <a>, <b>)
 -- Function: romberg (<F>, <a>, <b>)
     Computes a numerical integration by Romberg's method.

     `romberg(<expr>, <x>, <a>, <b>)' returns an estimate of the
     integral `integrate(<expr>, <x>, <a>, <b>)'.  <expr> must be an
     expression which evaluates to a floating point value when <x> is
     bound to a floating point value.

     `romberg(<F>, <a>, <b>)' returns an estimate of the integral
     `integrate(<F>(x), x, <a>, <b>)' where `x' represents the unnamed,
     sole argument of <F>; the actual argument is not named `x'.  <F>
     must be a Maxima or Lisp function which returns a floating point
     value when the argument is a floating point value.  <F> may name a
     translated or compiled Maxima function.

     The accuracy of `romberg' is governed by the global variables
     `rombergabs' and `rombergtol'.  `romberg' terminates successfully
     when the absolute difference between successive approximations is
     less than `rombergabs', or the relative difference in successive
     approximations is less than `rombergtol'.  Thus when `rombergabs'
     is 0.0 (the default) only the relative error test has any effect
     on `romberg'.

     `romberg' halves the stepsize at most `rombergit' times before it
     gives up; the maximum number of function evaluations is therefore
     `2^rombergit'.  If the error criterion established by `rombergabs'
     and `rombergtol' is not satisfied, `romberg' prints an error
     message.  `romberg' always makes at least `rombergmin' iterations;
     this is a heuristic intended to prevent spurious termination when
     the integrand is oscillatory.

     `romberg' repeatedly evaluates the integrand after binding the
     variable of integration to a specific value (and not before).
     This evaluation policy makes it possible to nest calls to
     `romberg', to compute multidimensional integrals.  However, the
     error calculations do not take the errors of nested integrations
     into account, so errors may be underestimated.  Also, methods
     devised especially for multidimensional problems may yield the
     same accuracy with fewer function evaluations.

     `load(romberg)' loads this function.

     See also `QUADPACK', a collection of numerical integration
     functions.

     Examples:

     A 1-dimensional integration.

          (%i1) load (romberg);
          (%o1)    /usr/share/maxima/5.11.0/share/numeric/romberg.lisp
          (%i2) f(x) := 1/((x - 1)^2 + 1/100) + 1/((x - 2)^2 + 1/1000)
                        + 1/((x - 3)^2 + 1/200);
                              1                 1                1
          (%o2) f(x) := -------------- + --------------- + --------------
                               2    1           2    1            2    1
                        (x - 1)  + ---   (x - 2)  + ----   (x - 3)  + ---
                                   100              1000              200
          (%i3) rombergtol : 1e-6;
          (%o3)                 9.9999999999999995E-7
          (%i4) rombergit : 15;
          (%o4)                          15
          (%i5) estimate : romberg (f(x), x, -5, 5);
          (%o5)                   173.6730736617464
          (%i6) exact : integrate (f(x), x, -5, 5);
          (%o6) 10 sqrt(10) atan(70 sqrt(10))
           + 10 sqrt(10) atan(30 sqrt(10)) + 10 sqrt(2) atan(80 sqrt(2))
           + 10 sqrt(2) atan(20 sqrt(2)) + 10 atan(60) + 10 atan(40)
          (%i7) abs (estimate - exact) / exact, numer;
          (%o7)                7.5527060865060088E-11

     A 2-dimensional integration, implemented by nested calls to
     `romberg'.

          (%i1) load (romberg);
          (%o1)    /usr/share/maxima/5.11.0/share/numeric/romberg.lisp
          (%i2) g(x, y) := x*y / (x + y);
                                              x y
          (%o2)                   g(x, y) := -----
                                             x + y
          (%i3) rombergtol : 1e-6;
          (%o3)                 9.9999999999999995E-7
          (%i4) estimate : romberg (romberg (g(x, y), y, 0, x/2), x, 1, 3);
          (%o4)                   0.81930239628356
          (%i5) assume (x > 0);
          (%o5)                        [x > 0]
          (%i6) integrate (integrate (g(x, y), y, 0, x/2), x, 1, 3);
                                                    3
                                              2 log(-) - 1
                              9                     2        9
          (%o6)       - 9 log(-) + 9 log(3) + ------------ + -
                              2                    6         2
          (%i7) exact : radcan (%);
                              26 log(3) - 26 log(2) - 13
          (%o7)             - --------------------------
                                          3
          (%i8) abs (estimate - exact) / exact, numer;
          (%o8)                1.3711979871851024E-10


 -- Option variable: rombergabs
     Default value: 0.0

     The accuracy of `romberg' is governed by the global variables
     `rombergabs' and `rombergtol'.  `romberg' terminates successfully
     when the absolute difference between successive approximations is
     less than `rombergabs', or the relative difference in successive
     approximations is less than `rombergtol'.  Thus when `rombergabs'
     is 0.0 (the default) only the relative error test has any effect
     on `romberg'.

     See also `rombergit' and `rombergmin'.


 -- Option variable: rombergit
     Default value: 11

     `romberg' halves the stepsize at most `rombergit' times before it
     gives up; the maximum number of function evaluations is therefore
     `2^rombergit'.  `romberg' always makes at least `rombergmin'
     iterations; this is a heuristic intended to prevent spurious
     termination when the integrand is oscillatory.

     See also `rombergabs' and `rombergtol'.


 -- Option variable: rombergmin
     Default value: 0

     `romberg' always makes at least `rombergmin' iterations; this is a
     heuristic intended to prevent spurious termination when the
     integrand is oscillatory.

     See also `rombergit', `rombergabs', and `rombergtol'.


 -- Option variable: rombergtol
     Default value: 1e-4

     The accuracy of `romberg' is governed by the global variables
     `rombergabs' and `rombergtol'.  `romberg' terminates successfully
     when the absolute difference between successive approximations is
     less than `rombergabs', or the relative difference in successive
     approximations is less than `rombergtol'.  Thus when `rombergabs'
     is 0.0 (the default) only the relative error test has any effect
     on `romberg'.

     See also `rombergit' and `rombergmin'.


