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


File: maxima.info,  Node: Simplification,  Next: Plotting,  Prev: Выражения,  Up: Top

7 Simplification
****************

* Menu:

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


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

7.1 Introduction to Simplification
==================================

Maxima interacts with the user through a cycle of actions called the
read-eval-print loop (REPL). This consists of three steps: reading and
parsing, evaluating and simplifying, and outputting.  Parsing converts a
syntactically valid sequence of typed characters into a internal data
structure.  Evaluation replaces variable and function names with their
values and simplification rewrites expressions to be easier for the user
or other programs to understand.  Output displays results in a variety
of different formats and notations.

   Evaluation and simplification sometimes appear to have similar
functionality, and Maxima uses simplification in many cases where other
systems use evaluation.  For example, arithmetic both on numbers and on
symbolic expressions is simplification, not evaluation: ‘2+2’ simplifies
to ‘4’, ‘2+x+x’ simplifies to ‘2+2*x’, and ‘sqrt(7)^4’ simplifies to
‘49’.  Evaluation and simplification are interleaved.  For example,
‘factor(integrate(x+1,x))’ first calls the built-in function
‘integrate’, giving ‘x+x*x*2^-1’; that simplifies to ‘x+(1/2)*x^2’; this
in turn is passed to the ‘factor’ function, which returns ‘(x*(x+2))/2’.

   Evaluation is what makes Maxima a programming language: it implements
functions, subroutines, variables, values, loops, assignments and so on.
Evaluation replaces built-in or user-defined function names by their
definitions and variables by their values.  This is largely the same as
activities of a conventional programming language, but extended to work
with symbolic mathematical data.  The system has various optional
"flags" which the user can set to control the details of evaluation.
*Note Functions and Variables for Evaluation::.

   Simplification maintains the value of an expression while
re-formulating its form to be smaller, simpler to understand, or to
conform to a particular specification (like expanded).  For example,
‘sin(%pi/2)’ to ‘1’, and ‘x+x’ to ‘2*x’.  There are many flags which
control simplification.  For example, with ‘triginverses:true’,
‘atan(tan(x))’ does not simplify to ‘x’, but with ‘triginverses:all’, it
does.

   Simplification can be provided in three ways:
   • The internal, built-in automated simplifier,
   • User-written pattern-matching transformations, linked to the
     simplifier by using "tellsimp" or "tellsimpafter" and called
     automatically,
   • User-written simplification routines adding using the ‘simplifying’
     subsystem.

   The internal simplifier belongs to the heart of Maxima.  It is a
large and complicated collection of programs, and it has been refined
over many years and by thousands of users.  Nevertheless, especially if
you are trying out novel ideas or unconventional notation, you may find
it helpful to make small (or large) changes to the program yourself.
For details see for example the paper at the end of
<https://people.eecs.berkeley.edu/~fateman/papers/intro5.txt>.

   Maxima internally represents expressions as "trees" with operators or
"roots" like ‘+’, ‘*’ , ‘=’ and operands ("leaves") which are variables
like <x>, <y>, <z>, functions or sub-trees, like ‘x*y’.  Each operator
has a simplification program associated with it.  ‘+’ (which also covers
binary ‘-’ since ‘a-b = a+(-1)*b)’ and ‘*’ (which also covers ‘/’ since
‘a/b = a*b^(-1)’) have rather elaborate simplification programs.  These
simplification programs (simplus, simptimes, simpexpt, etc.)  are called
whenever the simplifier encounters the respective arithmetic operators
in an expression tree to be analyzed.

   The structure of the simplifier dates back to 1965, and many hands
have worked on it through the years.  It is data-directed, or
object-oriented in the sense that it dispatches to the appropriate
routine depending on the root of some sub-tree of the expression,
recursively.  This general approach means that modifications to
simplification are generally localized.  In many cases it is
straightforward to add an operator and its simplification routine
without disturbing existing code.

   Maxima also provides a variety of transformation routines that can
change the form of an expression, including ‘factor’ (polynomial
factorization), ‘horner’ (reorganize a polynomial using Horner’s rule),
‘partfrac’ (rewrite a rational function as partial fractions),
‘trigexpand’ (apply the sum formulas for trigonometric functions), and
so on.

   Users can also write routines that change the form of an expression.

   Besides this general simplifier operating on algebraic expression
trees, there are several other representations of expressions in Maxima
which have separate methods.  For example, the ‘rat’ function converts
polynomials to vectors of coefficients to assist in rapid manipulation
of such forms.  Other representations include Taylor series and the
(rarely used) Poisson series.

   All operators introduced by the user initially have no simplification
programs associated with them.  Maxima does not know anything about
function "f" and so typing ‘f(a,b)’ will result in simplifying <a>,<b>,
but not ‘f’.  Even some built-in operators have no simplifications.  For
example, ‘=’ does not "simplify" – it is a place-holder with no
simplification semantics other than to simplify its two arguments, in
this case referred to as the left and right sides.  Other parts of
Maxima such as the solve program take special note of equations, that
is, trees with ‘=’ as the root.  (Note – in Maxima, the assignment
operation is ‘:’ .  That is, ‘q: 4’ sets the value of the symbol <q> to
‘4’.  Function definition is done with ‘:=’.  )

   The general simplifier returns results with an internal flag
indicating the expression and each sub-expression has been simplified.
This does not guarantee that it is unique over all possible equivalent
expressions.  That’s too hard (theoretically, not possible given the
generality of what can be expressed in Maxima).  However, some aspects
of the expression, such as the ordering of terms in a sum or product,
are made uniform.  This is important for the other programs to work
properly.

   A number of option variables control simplification.  Indeed,
simplification can be turned off entirely using ‘simp:false’.  However,
many internal routines will not operate correctly with ‘simp:false’.
(About the only time it seems plausible to turn off the simplifier is in
the rare case that you want to over-ride a built-in simplification.  In
that case you might temporarily disable the simplifier, put in the new
transformation via ‘tellsimp’, and then re-enable the simplifier by
‘simp:true’.)

   It is more plausible for you to associate user-defined symbolic
function names or operators with properties (‘additive’, ‘lassociative’,
‘oddfun’, ‘antisymmetric’, ‘linear’, ‘outative’, ‘commutative’,
‘multiplicative’, ‘rassociative’, ‘evenfun’, ‘nary’ and ‘symmetric’).
These options steer the simplifier processing in systematic directions.

   For example, ‘declare(f,oddfun)’ specifies that ‘f’ is an odd
function.  Maxima will simplify ‘f(-x)’ to ‘-f(x)’.  In the case of an
even function, that is ‘declare(g,evenfun)’, Maxima will simplify
‘g(-x)’ to ‘g(x)’.  You can also associate a programming function with a
name such as ‘h(x):=x^2+1’.  In that case the evaluator will immediately
replace ‘h(3)’ by ‘10’, and ‘h(a+1)’ by ‘(a+1)^2+1’, so any properties
of ‘h’ will be ignored.

   In addition to these directly related properties set up by the user,
facts and properties from the actual context may have an impact on the
simplifier’s behavior, too.  *Note Introduction to Maxima's Database::.

   Example: ‘sin(n*%pi)’ is simplified to zero, if <n> is an integer.

     (%i1) sin(n*%pi);
     (%o1)                      sin(%pi n)
     (%i2) declare(n, integer);
     (%o2)                         done
     (%i3) sin(n*%pi);
     (%o3)                           0

   If automated simplification is not sufficient, you can consider a
variety of built-in, but explicitly called simplfication functions
(‘ratsimp’, ‘expand’, ‘factor’, ‘radcan’ and others).  There are also
flags that will push simplification into one or another direction.
Given ‘demoivre:true’ the simplifier rewrites complex exponentials as
trigonometric forms.  Given ‘exponentialize:true’ the simplifier tries
to do the reverse: rewrite trigonometric forms as complex exponentials.

   As everywhere in Maxima, by writing your own functions (be it in the
Maxima user language or in the implementation language Lisp) and
explicitly calling them at selected places in the program, you can
respond to your individual simplification needs.  Lisp gives you a
handle on all the internal mechanisms, but you rarely need this full
generality.  "Tellsimp" is designed to generate much of the Lisp
internal interface into the simplifier automatically.  See *Note Rules
and Patterns::.

   Over the years (Maxima/Macsyma’s origins date back to about 1966!)
users have contributed numerous application packages and tools to extend
or alter its functional behavior.  Various non-standard and "share"
packages exist to modify or extend simplification as well.  You are
invited to look into this more experimental material where work is still
in progress *Note simplification-pkg::.

   The following appended material is optional on a first reading, and
reading it is not necessary for productive use of Maxima.  It is for the
curious user who wants to understand what is going on, or the ambitious
programmer who might wish to change the (open-source) code.
Experimentation with redefining Maxima Lisp code is easily possible: to
change the definition of a Lisp program (say the one that simplifies
‘cos()’, named ‘simp%cos’), you simply load into Maxima a text file that
will overwrite the ‘simp%cos’ function from the maxima package.


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

7.2 Functions and Variables for Simplification
==============================================

 -- Property: additive

     If ‘declare(f,additive)’ has been executed, then:

     (1) If ‘f’ is univariate, whenever the simplifier encounters ‘f’
     applied to a sum, ‘f’ will be distributed over that sum.  I.e.
     ‘f(y+x)’ will simplify to ‘f(y)+f(x)’.

     (2) If ‘f’ is a function of 2 or more arguments, additivity is
     defined as additivity in the first argument to ‘f’, as in the case
     of ‘sum’ or ‘integrate’, i.e.  ‘f(h(x)+g(x),x)’ will simplify to
     ‘f(h(x),x)+f(g(x),x)’.  This simplification does not occur when ‘f’
     is applied to expressions of the form
     ‘sum(x[i],i,lower-limit,upper-limit)’.

     Example:

          (%i1) F3 (a + b + c);
          (%o1)                     F3(c + b + a)
          (%i2) declare (F3, additive);
          (%o2)                         done
          (%i3) F3 (a + b + c);
          (%o3)                 F3(c) + F3(b) + F3(a)

 -- Property: antisymmetric

     If ‘declare(h,antisymmetric)’ is done, this tells the simplifier
     that ‘h’ is antisymmetric.  E.g.  ‘h(x,z,y)’ will simplify to ‘-
     h(x, y, z)’.  That is, it will give (-1)^n times the result given
     by ‘symmetric’ or ‘commutative’, where n is the number of
     interchanges of two arguments necessary to convert it to that form.

     Examples:

          (%i1) S (b, a);
          (%o1)                        S(b, a)
          (%i2) declare (S, symmetric);
          (%o2)                         done
          (%i3) S (b, a);
          (%o3)                        S(a, b)
          (%i4) S (a, c, e, d, b);
          (%o4)                   S(a, b, c, d, e)
          (%i5) T (b, a);
          (%o5)                        T(b, a)
          (%i6) declare (T, antisymmetric);
          (%o6)                         done
          (%i7) T (b, a);
          (%o7)                       - T(a, b)
          (%i8) T (a, c, e, d, b);
          (%o8)                   T(a, b, c, d, e)

 -- Function: combine (<expr>)

     Simplifies the sum <expr> by combining terms with the same
     denominator into a single term.

     See also: ‘rncombine’.

     Example:

          (%i1) 1*f/2*b + 2*c/3*a + 3*f/4*b +c/5*b*a;
                                5 b f   a b c   2 a c
          (%o1)                 ----- + ----- + -----
                                  4       5       3
          (%i2) combine (%);
                            75 b f + 4 (3 a b c + 10 a c)
          (%o2)             -----------------------------
                                         60

 -- Property: commutative

     If ‘declare(h, commutative)’ is done, this tells the simplifier
     that ‘h’ is a commutative function.  E.g.  ‘h(x, z, y)’ will
     simplify to ‘h(x, y, z)’.  This is the same as ‘symmetric’.

     Example:

          (%i1) S (b, a);
          (%o1)                        S(b, a)
          (%i2) S (a, b) + S (b, a);
          (%o2)                   S(b, a) + S(a, b)
          (%i3) declare (S, commutative);
          (%o3)                         done
          (%i4) S (b, a);
          (%o4)                        S(a, b)
          (%i5) S (a, b) + S (b, a);
          (%o5)                       2 S(a, b)
          (%i6) S (a, c, e, d, b);
          (%o6)                   S(a, b, c, d, e)

 -- Function: demoivre (<expr>)
 -- Option variable: demoivre

     The function ‘demoivre (expr)’ converts one expression without
     setting the global variable ‘demoivre’.

     When the variable ‘demoivre’ is ‘true’, complex exponentials are
     converted into equivalent expressions in terms of circular
     functions: ‘exp (a + b*%i)’ simplifies to ‘%e^a * (cos(b) +
     %i*sin(b))’ if ‘b’ is free of ‘%i’.  ‘a’ and ‘b’ are not expanded.

     The default value of ‘demoivre’ is ‘false’.

     ‘exponentialize’ converts circular and hyperbolic functions to
     exponential form.  ‘demoivre’ and ‘exponentialize’ cannot both be
     true at the same time.

 -- Function: distrib (<expr>)

     Distributes sums over products.  It differs from ‘expand’ in that
     it works at only the top level of an expression, i.e., it doesn’t
     recurse and it is faster than ‘expand’.  It differs from ‘multthru’
     in that it expands all sums at that level.

     Examples:

          (%i1) distrib ((a+b) * (c+d));
          (%o1)                 b d + a d + b c + a c
          (%i2) multthru ((a+b) * (c+d));
          (%o2)                 (b + a) d + (b + a) c
          (%i3) distrib (1/((a+b) * (c+d)));
                                          1
          (%o3)                    ---------------
                                   (b + a) (d + c)
          (%i4) expand (1/((a+b) * (c+d)), 1, 0);
                                          1
          (%o4)                 ---------------------
                                b d + a d + b c + a c

 -- Option variable: distribute_over
     Default value: ‘true’

     ‘distribute_over’ controls the mapping of functions over bags like
     lists, matrices, and equations.  At this time not all Maxima
     functions have this property.  It is possible to look up this
     property with the command ‘properties’.

     The mapping of functions is switched off, when setting
     ‘distribute_over’ to the value ‘false’.

     Examples:

     The ‘sin’ function maps over a list:

          (%i1) sin([x,1,1.0]);
          (%o1)         [sin(x), sin(1), 0.8414709848078965]

     ‘mod’ is a function with two arguments which maps over lists.
     Mapping over nested lists is possible too:

          (%i1) mod([x,11,2*a],10);
          (%o1)             [mod(x, 10), 1, 2 mod(a, 5)]
          (%i2) mod([[x,y,z],11,2*a],10);
          (%o2) [[mod(x, 10), mod(y, 10), mod(z, 10)], 1, 2 mod(a, 5)]

     Mapping of the ‘floor’ function over a matrix and an equation:

          (%i1) floor(matrix([a,b],[c,d]));
                               [ floor(a)  floor(b) ]
          (%o1)                [                    ]
                               [ floor(c)  floor(d) ]
          (%i2) floor(a=b);
          (%o2)                  floor(a) = floor(b)

     Functions with more than one argument map over any of the arguments
     or all arguments:

          (%i1) expintegral_e([1,2],[x,y]);
          (%o1) [[expintegral_e(1, x), expintegral_e(1, y)],
                                [expintegral_e(2, x), expintegral_e(2, y)]]

     Check if a function has the property distribute_over:

          (%i1) properties(abs);
          (%o1) [integral, rule, distributes over bags, noun, gradef,
                                                           system function]

     The mapping of functions is switched off, when setting
     ‘distribute_over’ to the value ‘false’.

          (%i1) distribute_over;
          (%o1)                         true
          (%i2) sin([x,1,1.0]);
          (%o2)         [sin(x), sin(1), 0.8414709848078965]
          (%i3) distribute_over : not distribute_over;
          (%o3)                         false
          (%i4) sin([x,1,1.0]);
          (%o4)                   sin([x, 1, 1.0])

 -- Option variable: domain
     Default value: ‘real’

     When ‘domain’ is set to ‘complex’, ‘sqrt (x^2)’ will remain ‘sqrt
     (x^2)’ instead of returning ‘abs(x)’.

 -- Property: evenfun
 -- Property: oddfun

     ‘declare(f, evenfun)’ or ‘declare(f, oddfun)’ tells Maxima to
     recognize the function ‘f’ as an even or odd function.

     Examples:

          (%i1) o (- x) + o (x);
          (%o1)                     o(x) + o(- x)
          (%i2) declare (o, oddfun);
          (%o2)                         done
          (%i3) o (- x) + o (x);
          (%o3)                           0
          (%i4) e (- x) - e (x);
          (%o4)                     e(- x) - e(x)
          (%i5) declare (e, evenfun);
          (%o5)                         done
          (%i6) e (- x) - e (x);
          (%o6)                           0

 -- Function: expand
          expand (<expr>)
          expand (<expr>, <p>, <n>)

     Expand expression <expr>.  Products of sums and exponentiated sums
     are multiplied out, numerators of rational expressions which are
     sums are split into their respective terms, and multiplication
     (commutative and non-commutative) are distributed over addition at
     all levels of <expr>.

     For polynomials one should usually use ‘ratexpand’ which uses a
     more efficient algorithm.

     ‘maxnegex’ and ‘maxposex’ control the maximum negative and positive
     exponents, respectively, which will expand.

     ‘expand (<expr>, <p>, <n>)’ expands <expr>, using <p> for
     ‘maxposex’ and <n> for ‘maxnegex’.  This is useful in order to
     expand part but not all of an expression.

     ‘expon’ - the exponent of the largest negative power which is
     automatically expanded (independent of calls to ‘expand’).  For
     example if ‘expon’ is 4 then ‘(x+1)^(-5)’ will not be automatically
     expanded.

     ‘expop’ - the highest positive exponent which is automatically
     expanded.  Thus ‘(x+1)^3’, when typed, will be automatically
     expanded only if ‘expop’ is greater than or equal to 3.  If it is
     desired to have ‘(x+1)^n’ expanded where ‘n’ is greater than
     ‘expop’ then executing ‘expand ((x+1)^n)’ will work only if
     ‘maxposex’ is not less than ‘n’.

     ‘expand(expr, 0, 0)’ causes a resimplification of ‘expr’.  ‘expr’
     is not reevaluated.  In distinction from ‘ev(expr, noeval)’ a
     special representation (e.  g.  a CRE form) is removed.  See also
     ‘ev’.

     The ‘expand’ flag used with ‘ev’ causes expansion.

     The file ‘share/simplification/facexp.mac’ contains several related
     functions (in particular ‘facsum’, ‘factorfacsum’ and
     ‘collectterms’, which are autoloaded) and variables
     (‘nextlayerfactor’ and ‘facsum_combine’) that provide the user with
     the ability to structure expressions by controlled expansion.
     Brief function descriptions are available in
     ‘simplification/facexp.usg’.  A demo is available by doing
     ‘demo("facexp")’.

     Examples:

          (%i1) expr:(x+1)^2*(y+1)^3;
                                         2        3
          (%o1)                   (x + 1)  (y + 1)
          (%i2) expand(expr);
                 2  3        3    3      2  2        2      2      2
          (%o2) x  y  + 2 x y  + y  + 3 x  y  + 6 x y  + 3 y  + 3 x  y
                                                                2
                                               + 6 x y + 3 y + x  + 2 x + 1
          (%i3) expand(expr,2);
                         2        3              3          3
          (%o3)         x  (y + 1)  + 2 x (y + 1)  + (y + 1)
          (%i4) expr:(x+1)^-2*(y+1)^3;
                                             3
                                      (y + 1)
          (%o4)                       --------
                                             2
                                      (x + 1)
          (%i5) expand(expr);
                      3               2
                     y             3 y            3 y             1
          (%o5) ------------ + ------------ + ------------ + ------------
                 2              2              2              2
                x  + 2 x + 1   x  + 2 x + 1   x  + 2 x + 1   x  + 2 x + 1
          (%i6) expand(expr,2,2);
                                             3
                                      (y + 1)
          (%o6)                     ------------
                                     2
                                    x  + 2 x + 1

     Resimplify an expression without expansion:

          (%i1) expr:(1+x)^2*sin(x);
                                          2
          (%o1)                    (x + 1)  sin(x)
          (%i2) exponentialize:true;
          (%o2)                         true
          (%i3) expand(expr,0,0);
                                      2    %i x     - %i x
                            %i (x + 1)  (%e     - %e      )
          (%o3)           - -------------------------------
                                           2

 -- Function: expandwrt (<expr>, <x_1>, …, <x_n>)

     Expands expression ‘expr’ with respect to the variables <x_1>, …,
     <x_n>.  All products involving the variables appear explicitly.
     The form returned will be free of products of sums of expressions
     that are not free of the variables.  <x_1>, …, <x_n> may be
     variables, operators, or expressions.

     By default, denominators are not expanded, but this can be
     controlled by means of the switch ‘expandwrt_denom’.

     This function is autoloaded from ‘simplification/stopex.mac’.

 -- Option variable: expandwrt_denom
     Default value: ‘false’

     ‘expandwrt_denom’ controls the treatment of rational expressions by
     ‘expandwrt’.  If ‘true’, then both the numerator and denominator of
     the expression will be expanded according to the arguments of
     ‘expandwrt’, but if ‘expandwrt_denom’ is ‘false’, then only the
     numerator will be expanded in that way.

 -- Function: expandwrt_factored (<expr>, <x_1>, …, <x_n>)

     is similar to ‘expandwrt’, but treats expressions that are products
     somewhat differently.  ‘expandwrt_factored’ expands only on those
     factors of ‘expr’ that contain the variables <x_1>, …, <x_n>.

     This function is autoloaded from ‘simplification/stopex.mac’.

 -- Option variable: expon
     Default value: 0

     ‘expon’ is the exponent of the largest negative power which is
     automatically expanded (independent of calls to ‘expand’).  For
     example, if ‘expon’ is 4 then ‘(x+1)^(-5)’ will not be
     automatically expanded.

 -- Function: exponentialize (<expr>)
 -- Option variable: exponentialize

     The function ‘exponentialize (expr)’ converts circular and
     hyperbolic functions in <expr> to exponentials, without setting the
     global variable ‘exponentialize’.

     When the variable ‘exponentialize’ is ‘true’, all circular and
     hyperbolic functions are converted to exponential form.  The
     default value is ‘false’.

     ‘demoivre’ converts complex exponentials into circular functions.
     ‘exponentialize’ and ‘demoivre’ cannot both be true at the same
     time.

 -- Option variable: expop
     Default value: 0

     ‘expop’ is the highest positive exponent which is automatically
     expanded.  Thus ‘(x + 1)^3’, when typed, will be automatically
     expanded only if ‘expop’ is greater than or equal to 3.  If it is
     desired to have ‘(x + 1)^n’ expanded where ‘n’ is greater than
     ‘expop’ then executing ‘expand ((x + 1)^n)’ will work only if
     ‘maxposex’ is not less than n.

 -- Property: lassociative

     ‘declare (g, lassociative)’ tells the Maxima simplifier that ‘g’ is
     left-associative.  E.g., ‘g (g (a, b), g (c, d))’ will simplify to
     ‘g (g (g (a, b), c), d)’.

 -- Property: linear

     One of Maxima’s operator properties.  For univariate ‘f’ so
     declared, "expansion" ‘f(x + y)’ yields ‘f(x) + f(y)’, ‘f(a*x)’
     yields ‘a*f(x)’ takes place where ‘a’ is a "constant".  For
     functions of two or more arguments, "linearity" is defined to be as
     in the case of ‘sum’ or ‘integrate’, i.e., ‘f (a*x + b, x)’ yields
     ‘a*f(x,x) + b*f(1,x)’ for ‘a’ and ‘b’ free of ‘x’.

     Example:

          (%i1) declare (f, linear);
          (%o1)                         done
          (%i2) f(x+y);
          (%o2)                      f(y) + f(x)
          (%i3) declare (a, constant);
          (%o3)                         done
          (%i4) f(a*x);
          (%o4)                        a f(x)

     ‘linear’ is equivalent to ‘additive’ and ‘outative’.  See also
     ‘opproperties’.

     Example:

          (%i1) 'sum (F(k) + G(k), k, 1, inf);
                                 inf
                                 ====
                                 \
          (%o1)                   >    (G(k) + F(k))
                                 /
                                 ====
                                 k = 1
          (%i2) declare (nounify (sum), linear);
          (%o2)                         done
          (%i3) 'sum (F(k) + G(k), k, 1, inf);
                               inf          inf
                               ====         ====
                               \            \
          (%o3)                 >    G(k) +  >    F(k)
                               /            /
                               ====         ====
                               k = 1        k = 1

 -- Option variable: maxnegex
     Default value: 1000

     ‘maxnegex’ is the largest negative exponent which will be expanded
     by the ‘expand’ command, see also ‘maxposex’.

 -- Option variable: maxposex
     Default value: 1000

     ‘maxposex’ is the largest exponent which will be expanded with the
     ‘expand’ command, see also ‘maxnegex’.

 -- Property: multiplicative

     ‘declare(f, multiplicative)’ tells the Maxima simplifier that ‘f’
     is multiplicative.

       1. If ‘f’ is univariate, whenever the simplifier encounters ‘f’
          applied to a product, ‘f’ distributes over that product.
          E.g., ‘f(x*y)’ simplifies to ‘f(x)*f(y)’.  This simplification
          is not applied to expressions of the form ‘f('product(...))’.
       2. If ‘f’ is a function of 2 or more arguments, multiplicativity
          is defined as multiplicativity in the first argument to ‘f’,
          e.g., ‘f (g(x) * h(x), x)’ simplifies to ‘f (g(x) ,x) * f
          (h(x), x)’.

     ‘declare(nounify(product), multiplicative)’ tells Maxima to
     simplify symbolic products.

     Example:

          (%i1) F2 (a * b * c);
          (%o1)                       F2(a b c)
          (%i2) declare (F2, multiplicative);
          (%o2)                         done
          (%i3) F2 (a * b * c);
          (%o3)                   F2(a) F2(b) F2(c)

     ‘declare(nounify(product), multiplicative)’ tells Maxima to
     simplify symbolic products.

          (%i1) product (a[i] * b[i], i, 1, n);
                                       n
                                     /===\
                                      ! !
          (%o1)                       ! !  a  b
                                      ! !   i  i
                                     i = 1
          (%i2) declare (nounify (product), multiplicative);
          (%o2)                         done
          (%i3) product (a[i] * b[i], i, 1, n);
                                    n         n
                                  /===\     /===\
                                   ! !       ! !
          (%o3)                  ( ! !  a )  ! !  b
                                   ! !   i   ! !   i
                                  i = 1     i = 1

 -- Function: multthru
          multthru (<expr>)
          multthru (<expr_1>, <expr_2>)

     Multiplies a factor (which should be a sum) of <expr> by the other
     factors of <expr>.  That is, <expr> is ‘<f_1> <f_2> ... <f_n>’
     where at least one factor, say <f_i>, is a sum of terms.  Each term
     in that sum is multiplied by the other factors in the product.
     (Namely all the factors except <f_i>).  ‘multthru’ does not expand
     exponentiated sums.  This function is the fastest way to distribute
     products (commutative or noncommutative) over sums.  Since
     quotients are represented as products ‘multthru’ can be used to
     divide sums by products as well.

     ‘multthru (<expr_1>, <expr_2>)’ multiplies each term in <expr_2>
     (which should be a sum or an equation) by <expr_1>.  If <expr_1> is
     not itself a sum then this form is equivalent to ‘multthru
     (<expr_1>*<expr_2>)’.

          (%i1) x/(x-y)^2 - 1/(x-y) - f(x)/(x-y)^3;
                                1        x         f(x)
          (%o1)             - ----- + -------- - --------
                              x - y          2          3
                                      (x - y)    (x - y)
          (%i2) multthru ((x-y)^3, %);
                                     2
          (%o2)             - (x - y)  + x (x - y) - f(x)
          (%i3) ratexpand (%);
                                     2
          (%o3)                   - y  + x y - f(x)
          (%i4) ((a+b)^10*s^2 + 2*a*b*s + (a*b)^2)/(a*b*s^2);
                                  10  2              2  2
                           (b + a)   s  + 2 a b s + a  b
          (%o4)            ------------------------------
                                            2
                                       a b s
          (%i5) multthru (%);  /* note that this does not expand (b+a)^10 */
                                                  10
                                 2   a b   (b + a)
          (%o5)                  - + --- + ---------
                                 s    2       a b
                                     s
          (%i6) multthru (a.(b+c.(d+e)+f));
          (%o6)            a . f + a . c . (e + d) + a . b
          (%i7) expand (a.(b+c.(d+e)+f));
          (%o7)         a . f + a . c . e + a . c . d + a . b

 -- Property: nary

     ‘declare(f, nary)’ tells Maxima to recognize the function ‘f’ as an
     n-ary function.

     The ‘nary’ declaration is not the same as calling the ‘nary’
     function.  The sole effect of ‘declare(f, nary)’ is to instruct the
     Maxima simplifier to flatten nested expressions, for example, to
     simplify ‘foo(x, foo(y, z))’ to ‘foo(x, y, z)’.  See also
     ‘declare’.

     Example:

          (%i1) H (H (a, b), H (c, H (d, e)));
          (%o1)               H(H(a, b), H(c, H(d, e)))
          (%i2) declare (H, nary);
          (%o2)                         done
          (%i3) H (H (a, b), H (c, H (d, e)));
          (%o3)                   H(a, b, c, d, e)

 -- Option variable: negdistrib
     Default value: ‘true’

     When ‘negdistrib’ is ‘true’, -1 distributes over an expression.
     E.g., ‘-(x + y)’ becomes ‘- y - x’.  Setting it to ‘false’ will
     allow ‘- (x + y)’ to be displayed like that.  This is sometimes
     useful but be very careful: like the ‘simp’ flag, this is one flag
     you do not want to set to ‘false’ as a matter of course or
     necessarily for other than local use in your Maxima.

     Example:

          (%i1) negdistrib;
          (%o1)                         true
          (%i2) -(x+y);
          (%o2)                       (- y) - x
          (%i3) negdistrib : not negdistrib ;
          (%o3)                         false
          (%i4) -(x+y);
          (%o4)                       - (y + x)

 -- System variable: opproperties

     ‘opproperties’ is the list of the special operator properties
     recognized by the Maxima simplifier.

     Items are added to the ‘opproperties’ list by the function
     ‘define_opproperty’.

     Example:

          (%i1) opproperties;
          (%o1) [linear, additive, multiplicative, outative, evenfun,
          oddfun, commutative, symmetric, antisymmetric, nary,
          lassociative, rassociative]

 -- Function: define_opproperty (<property_name>, <simplifier_fn>)

     Declares the symbol <property_name> to be an operator property,
     which is simplified by <simplifier_fn>, which may be the name of a
     Maxima or Lisp function or a lambda expression.  After
     ‘define_opproperty’ is called, functions and operators may be
     declared to have the <property_name> property, and <simplifier_fn>
     is called to simplify them.

     <simplifier_fn> must be a function of one argument, which is an
     expression in which the main operator is declared to have the
     <property_name> property.

     <simplifier_fn> is called with the global flag ‘simp’ disabled.
     Therefore <simplifier_fn> must be able to carry out its
     simplification without making use of the general simplifier.

     ‘define_opproperty’ appends <property_name> to the global list
     ‘opproperties’.

     ‘define_opproperty’ returns ‘done’.

     Example:

     Declare a new property, ‘identity’, which is simplified by
     ‘simplify_identity’.  Declare that ‘f’ and ‘g’ have the new
     property.

          (%i1) define_opproperty (identity, simplify_identity);
          (%o1)                         done
          (%i2) simplify_identity(e) := first(e);
          (%o2)           simplify_identity(e) := first(e)
          (%i3) declare ([f, g], identity);
          (%o3)                         done
          (%i4) f(10 + t);
          (%o4)                        t + 10
          (%i5) g(3*u) - f(2*u);
          (%o5)                           u

 -- Property: outative

     ‘declare(f, outative)’ tells the Maxima simplifier that constant
     factors in the argument of ‘f’ can be pulled out.

       1. If ‘f’ is univariate, whenever the simplifier encounters ‘f’
          applied to a product, that product will be partitioned into
          factors that are constant and factors that are not and the
          constant factors will be pulled out.  E.g., ‘f(a*x)’ will
          simplify to ‘a*f(x)’ where ‘a’ is a constant.  Non-atomic
          constant factors will not be pulled out.
       2. If ‘f’ is a function of 2 or more arguments, outativity is
          defined as in the case of ‘sum’ or ‘integrate’, i.e., ‘f
          (a*g(x), x)’ will simplify to ‘a * f(g(x), x)’ for ‘a’ free of
          ‘x’.

     ‘sum’, ‘integrate’, and ‘limit’ are all ‘outative’.

     Example:

          (%i1) F1 (100 * x);
          (%o1)                       F1(100 x)
          (%i2) declare (F1, outative);
          (%o2)                         done
          (%i3) F1 (100 * x);
          (%o3)                       100 F1(x)
          (%i4) declare (zz, constant);
          (%o4)                         done
          (%i5) F1 (zz * y);
          (%o5)                       zz F1(y)

 -- Function: radcan (<expr>)

     Simplifies <expr>, which can contain logs, exponentials, and
     radicals, by converting it into a form which is canonical over a
     large class of expressions and a given ordering of variables; that
     is, all functionally equivalent forms are mapped into a unique
     form.  For a somewhat larger class of expressions, ‘radcan’
     produces a regular form.  Two equivalent expressions in this class
     do not necessarily have the same appearance, but their difference
     can be simplified by ‘radcan’ to zero.

     For some expressions ‘radcan’ is quite time consuming.  This is the
     cost of exploring certain relationships among the components of the
     expression for simplifications based on factoring and
     partial-fraction expansions of exponents.

     Examples:

          (%i1) radcan((log(x+x^2)-log(x))^a/log(1+x)^(a/2));
                                              a/2
          (%o1)                     log(x + 1)
          (%i2) radcan((log(1+2*a^x+a^(2*x))/log(1+a^x)));
          (%o2)                           2
          (%i3) radcan((%e^x-1)/(1+%e^(x/2)));
                                        x/2
          (%o3)                       %e    - 1

 -- Option variable: radexpand
     Default value: ‘true’

     ‘radexpand’ controls some simplifications of radicals.

     When ‘radexpand’ is ‘all’, causes nth roots of factors of a product
     which are powers of n to be pulled outside of the radical.  E.g.
     if ‘radexpand’ is ‘all’, ‘sqrt (16*x^2)’ simplifies to ‘4*x’.

     More particularly, consider ‘sqrt (x^2)’.
        • If ‘radexpand’ is ‘all’ or ‘assume (x > 0)’ has been executed,
          ‘sqrt(x^2)’ simplifies to ‘x’.
        • If ‘radexpand’ is ‘true’ and ‘domain’ is ‘real’ (its default),
          ‘sqrt(x^2)’ simplifies to ‘abs(x)’.
        • If ‘radexpand’ is ‘false’, or ‘radexpand’ is ‘true’ and
          ‘domain’ is ‘complex’, ‘sqrt(x^2)’ is not simplified.

     Note that ‘domain’ only matters when ‘radexpand’ is ‘true’.

 -- Property: rassociative

     ‘declare (g, rassociative)’ tells the Maxima simplifier that ‘g’ is
     right-associative.  E.g., ‘g(g(a, b), g(c, d))’ simplifies to ‘g(a,
     g(b, g(c, d)))’.

 -- Function: scsimp (<expr>, <rule_1>, …, <rule_n>)

     Sequential Comparative Simplification (method due to Stoute).
     ‘scsimp’ attempts to simplify <expr> according to the rules
     <rule_1>, …, <rule_n>.  If a smaller expression is obtained, the
     process repeats.  Otherwise after all simplifications are tried, it
     returns the original answer.

     ‘example (scsimp)’ displays some examples.

 -- Option variable: simp
     Default value: ‘true’

     ‘simp’ enables simplification.  This is the default.  ‘simp’ is
     also an ‘evflag’, which is recognized by the function ‘ev’.  See
     ‘ev’.

     When ‘simp’ is used as an ‘evflag’ with a value ‘false’, the
     simplification is suppressed only during the evaluation phase of an
     expression.  The flag does not suppress the simplification which
     follows the evaluation phase.

     Many Maxima functions and operations require simplification to be
     enabled to work normally.  When simplification is disabled, many
     results will be incomplete, and in addition there may be incorrect
     results or program errors.

     Examples:

     The simplification is switched off globally.  The expression
     ‘sin(1.0)’ is not simplified to its numerical value.  The
     ‘simp’-flag switches the simplification on.

          (%i1) simp:false;
          (%o1)                         false
          (%i2) sin(1.0);
          (%o2)                       sin(1.0)
          (%i3) sin(1.0),simp;
          (%o3)                  0.8414709848078965

     The simplification is switched on again.  The ‘simp’-flag cannot
     suppress the simplification completely.  The output shows a
     simplified expression, but the variable ‘x’ has an unsimplified
     expression as a value, because the assignment has occurred during
     the evaluation phase of the expression.

          (%i1) simp:true;
          (%o1)                         true
          (%i2) x:sin(1.0),simp:false;
          (%o2)                  0.8414709848078965
          (%i3) :lisp $x
          ((%SIN) 1.0)

 -- Property: symmetric

     ‘declare (h, symmetric)’ tells the Maxima simplifier that ‘h’ is a
     symmetric function.  E.g., ‘h (x, z, y)’ simplifies to ‘h (x, y,
     z)’.

     ‘commutative’ is synonymous with ‘symmetric’.

 -- Function: xthru (<expr>)

     Combines all terms of <expr> (which should be a sum) over a common
     denominator without expanding products and exponentiated sums as
     ‘ratsimp’ does.  ‘xthru’ cancels common factors in the numerator
     and denominator of rational expressions but only if the factors are
     explicit.

     Sometimes it is better to use ‘xthru’ before ‘ratsimp’ing an
     expression in order to cause explicit factors of the gcd of the
     numerator and denominator to be canceled thus simplifying the
     expression to be ‘ratsimp’ed.

     Examples:

          (%i1) ((x+2)^20 - 2*y)/(x+y)^20 + (x+y)^(-19) - x/(x+y)^20;
                                          20
                           1       (x + 2)   - 2 y       x
          (%o1)        --------- + --------------- - ---------
                              19             20             20
                       (y + x)        (y + x)        (y + x)
          (%i2) xthru (%);
                                           20
                                    (x + 2)   - y
          (%o2)                     -------------
                                             20
                                      (y + x)


File: maxima.info,  Node: Plotting,  Next: Ввод и вывод,  Prev: Simplification,  Up: Top

8 Plotting
**********

* Menu:

* Introduction to Plotting::
* Plotting Formats::
* Functions and Variables for Plotting::
* Plotting Options::
* Gnuplot Options::
* Gnuplot_pipes Format Functions::


File: maxima.info,  Node: Introduction to Plotting,  Next: Plotting Formats,  Prev: Plotting,  Up: Plotting

8.1 Introduction to Plotting
============================

To make the plots, Maxima can use an external plotting package or its
own graphical interface Xmaxima (see the section on ‘Plotting Formats’).
The plotting functions calculate a set of points and pass them to the
plotting package together with a set of commands specific to that
graphic program.  In some cases those commands and data are saved in a
file and the graphic program is executed giving it the name of that file
to be parsed.

   When a file is created, it will begiven the name ‘maxout_xxx.format’,
where ‘xxx’ is a number that is unique to every concurrently-running
instance of Maxima and ‘format’ is the name of the plotting format being
used (‘gnuplot’, ‘xmaxima’, ‘mgnuplot’ or ‘geomview’).

   There are commands to save the plot in a graphic format file, rather
than showing it in the screen.  The default name for that graphic file
is ‘maxplot.extension’, where ‘extension’ is the extension normally used
for the kind of graphic file selected, but that name can also be
specified by the user.

   The ‘maxout_xxx.format’ and ‘maxplot.extension’ files are created in
the directory specified by the system variable ‘maxima_tempdir’.  That
location can be changed by assigning to that variable (or to the
environment variable ‘MAXIMA_TEMPDIR’) a string that represents a valid
directory where Maxima can create new files.  The output of the Maxima
plotting command will be a list with the names of the file(s) created,
including their complete path, or empty if no files are created.  Those
files should be deleted after the maxima session ends.

   If the format used is either ‘gnuplot’ or ‘xmaxima’, and the
‘maxout_xxx.gnuplot’ or ‘maxout_xxx.xmaxima’ was saved, ‘gnuplot’ or
‘xmaxima’ can be run, giving it the name of that file as argument, in
order to view again a plot previously created in Maxima.  Thus, when a
Maxima plotting command fails, the format can be set to ‘gnuplot’ or
‘xmaxima’ and the plain-text file ‘maxout_xxx.gnuplot’ (or
‘maxout_xxx.xmaxima’) can be inspected to look for the source of the
problem.

   The additional package *note draw:: provides functions similar to the
ones described in this section with some extra features, but it only
works with ‘gnuplot’.  Note that some plotting options have the same
name in both plotting packages, but their syntax and behavior is
different.  To view the documentation for a graphic option ‘opt’, type
‘?? opt’ in order to choose the information for either of those two
packages.


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

8.2 Plotting Formats
====================

Maxima can use either Gnuplot, Xmaxima or Geomview as graphics program.
Gnuplot and Geomview are external programs which must be installed
separately, while Xmaxima is distributed with Maxima.  To see which
plotting format you are currently using, use the command
‘get_plot_option(plot_format);’ and to change to another format, you can
use ‘set_plot_option([plot_format, <format>])’, where ‘<format>’ is the
name of one of the formats described below.  Those two commands show and
change the global plot format, while each individual plotting command
can use its own format, if it includes an option ‘[plot_format,
<format>]’ (see ‘get_plot_option’ and ‘set_plot_option’).

   The plotting formats are the following:

   • *gnuplot*

     Used to launch the external program gnuplot, which must be
     installed in your system.  All plotting commands and data are saved
     into the file ‘maxout_xxx.gnuplot’.

   • *gnuplot_pipes* (default value)

     It is similar to the ‘gnuplot’ format except that the commands and
     plot data are sent directly to ‘gnuplot’ without creating any
     files.  A single gnuplot process is kept open, with a single
     graphic window, and subsequent plot commands will be sent to the
     same process, replacing previous plots in that same window.  Even
     if the graphic window is closed, the ‘gnuplot’ process is still
     running until the end of the session or until it is killed with
     ‘gnuplot_close’..  The function ‘gnuplot_replot’ can be used to
     modify a plot that has already been displayed on the screen or to
     open again the graphic window after it was closed.

     This format does not work with some versions of Lisp under Windows
     and it is only used to plot to the screen; whenever graphic files
     are to be created, the format is silently switched to ‘gnuplot’ and
     the commands needed to create the graphic file are saved with the
     data in file ‘maxout_xxx.gnuplot’.

   • *mgnuplot*

     Mgnuplot is a Tk-based wrapper around gnuplot.  It is an old
     interface still included in the Maxima distribution, but it is
     currently disabled because it does not have most of the features
     introduced by the newer versions of the plotting commands.
     Mgnuplot requires an external gnuplot installation and, in Unix
     systems, the Tcl/Tk system.

   • *xmaxima*

     Xmaxima is a Tcl/Tk graphical interface for Maxima that can also be
     used to display plots created when Maxima is run from the console
     or from other graphical interfaces.  To use this format, the
     xmaxima program, which is distributed together with Maxima, must be
     installed; in some Linux distributions Xmaxima is distributed in a
     package separate from other parts of Maxima.  If Maxima is being
     run from the Xmaxima console, the data and commands are passed to
     xmaxima through the same socket used for the communication between
     Maxima and the Xmaxima console.  When used from a terminal or from
     graphical interfaces different from Xmaxima, the commands and data
     are saved in the file ‘maxout_xxx.xmaxima’ and xmaxima is run with
     the name of that file as argument.

   • *geomview*

     Geomview, a Motif based interactive 3D viewing program for Unix.
     It can only be used to display plots created with ‘plot3d’.  To use
     this format, the geomview program must be installed.


File: maxima.info,  Node: Functions and Variables for Plotting,  Next: Plotting Options,  Prev: Plotting Formats,  Up: Plotting

8.3 Functions and Variables for Plotting
========================================

 -- System variable: geomview_command

     This variable stores the name of the command used to run the
     geomview program when the plot format is ‘geomview’.  Its default
     value is "geomview".  If the geomview program is not found unless
     you give its complete path or if you want to try a different
     version of it, you may change the value of this variable.  For
     instance,

          (%i1) geomview_command: "/usr/local/bin/my_geomview"$

 -- Function: get_plot_option (<keyword>, <index>)

     Returns the current default value of the option named <keyword>,
     which is a list.  The optional argument <index> must be a positive
     integer which can be used to extract only one element from the list
     (element 1 is the name of the option).

     See also ‘set_plot_option’, ‘remove_plot_option’ and the section on
     ‘Plotting Options’.

 -- System variable: gnuplot_command

     This variable stores the name of the command used to run the
     gnuplot program when the plot format is ‘gnuplot’ or
     ‘gnuplot_pipes’.  Its default value is "gnuplot".  If the gnuplot
     program is not found unless you give its complete path or if you
     want to try a different version of it, you may change the value of
     this variable.  For instance,

          (%i1) gnuplot_command: "/usr/local/bin/my_gnuplot"$

 -- System variable: gnuplot_file_args

     When a graphic file is going to be created using ‘gnuplot’, this
     variable is used to specify the format used to print the file name
     given to gnuplot.  Its default value is "~a" in SBCL and Openmcl,
     and "~s" in other lisp versions, which means that the name of the
     file will be passed without quotes if SBCL or Openmcl are used and
     within quotes if other Lisp versions are used.  The contents of
     this variable can be changed in order to add options for the
     gnuplot program, adding those options before the format directive
     "~s".

 -- System variable: gnuplot_view_args

     This variable is the format used to parse the argument that will be
     passed to the gnuplot program when the plot format is ‘gnuplot’.
     Its default value is "-persist ~a" when SBCL or Openmcl are used,
     and "-persist ~s" with other Lisp variants, where "~a" or "~s" will
     be replaced with the name of the file where the gnuplot commands
     have been written (usually "maxout_xxx.gnuplot").  The option
     ‘-persist’ tells gnuplot to exit after the commands in the file
     have been executed, without closing the window that displays the
     plot.

     Those familiar with gnuplot, might want to change the value of this
     variable.  For example, by changing it to:

          (%i1) gnuplot_view_args: "~s -"$

     gnuplot will not be closed after the commands in the file have been
     executed; thus, the window with the plot will remain, as well as
     the gnuplot interactive shell where other commands can be issued in
     order to modify the plot.

     In Windows versions of Gnuplot older than 4.6.3 the behavior of "~s
     -" and "-persist ~s" were the opposite; namely, "-persist ~s" made
     the plot window and the gnuplot interactive shell remain, while "~s
     -" closed the gnuplot shell keeping the plot window.  Therefore,
     when older gnuplot versions are used in Windows, it might be
     necessary to adjust the value of ‘gnuplot_view_args’.

 -- Function: julia (<x>, <y>, ...<options>...)

     Creates a graphic representation of the Julia set for the complex
     number (<x> + i <y>).  The two mandatory parameters <x> and <y>
     must be real.  This program is part of the additional package
     ‘dynamics’, but that package does not have to be loaded; the first
     time julia is used, it will be loaded automatically.

     Each pixel in the grid is given a color corresponding to the number
     of iterations it takes the sequence that starts at that point to
     move out of the convergence circle of radius 2 centered at the
     origin.  The number of pixels in the grid is controlled by the
     ‘grid’ plot option (default 30 by 30).  The maximum number of
     iterations is set with the option ‘iterations’.  The program sets
     its own default palette: magenta, violet, blue, cyan, green,
     yellow, orange, red, brown and black, but it can be changed by
     adding an explicit ‘palette’ option in the command.

     The default domain used goes from -2 to 2 in both axes and can be
     changed with the ‘x’ and ‘y’ options.  By default, the two axes are
     shown with the same scale, unless the option ‘yx_ratio’ is used or
     the option ‘same_xy’ is disabled.  Other general plot options are
     also accepted.

     The following example shows a region of the Julia set for the
     number -0.55 + i0.6.  The option ‘color_bar_tics’ is used to
     prevent Gnuplot from adjusting the color box up to 40, in which
     case the points corresponding the maximum 36 iterations would not
     be black.

          (%i1) julia (-0.55, 0.6, [iterations, 36], [x, -0.3, 0.2],
                [y, 0.3, 0.9], [grid, 400, 400], [color_bar_tics, 0, 6, 36])$

 -- Function: make_transform ([<var1>, <var2>, <var3>], <fx>, <fy>,
          <fz>)

     Returns a function suitable to be used in the option ‘transform_xy’
     of plot3d.  The three variables <var1>, <var2>, <var3> are three
     dummy variable names, which represent the 3 variables given by the
     plot3d command (first the two independent variables and then the
     function that depends on those two variables).  The three functions
     <fx>, <fy>, <fz> must depend only on those 3 variables, and will
     give the corresponding x, y and z coordinates that should be
     plotted.  There are two transformations defined by default:
     ‘polar_to_xy’ and ‘spherical_to_xyz’.  See the documentation for
     those two transformations.

 -- Function: mandelbrot (<options>)

     Creates a graphic representation of the Mandelbrot set.  This
     program is part of the additional package ‘dynamics’, but that
     package does not have to be loaded; the first time mandelbrot is
     used, the package will be loaded automatically.

     This program can be called without any arguments, in which case it
     will use a default value of 9 iterations per point, a grid with
     dimensions set by the ‘grid’ plot option (default 30 by 30) and a
     region that extends from -2 to 2 in both axes.  The options are all
     the same that plot2d accepts, plus an option ‘iterations’ to change
     the number of iterations.

     Each pixel in the grid is given a color corresponding to the number
     of iterations it takes the sequence starting at zero to move out of
     the convergence circle of radius 2, centered at the origin.  The
     maximum number of iterations is set by the option ‘iterations’.
     The program uses its own default palette: magenta,violet, blue,
     cyan, green, yellow, orange, red, brown and black, but it can be
     changed by adding an explicit ‘palette’ option in the command.  By
     default, the two axes are shown with the same scale, unless the
     option ‘yx_ratio’ is used or the option ‘same_xy’ is disabled.

     Example:

     [grid,400,400])$
          (%i1) mandelbrot ([iterations, 30], [x, -2, 1], [y, -1.2, 1.2],
                      [grid,400,400])$

 -- System function: polar_to_xy

     It can be given as value for the ‘transform_xy’ option of plot3d.
     Its effect will be to interpret the two independent variables in
     plot3d as the distance from the z axis and the azimuthal angle
     (polar coordinates), and transform them into x and y coordinates.

 -- Function: plot2d
          plot2d (<expr>, <range_x>, <options>)
          plot2d (<expr_1>=<expr_2>, <range_x>, <range_y>, <options>)
          plot2d ([parametric, <expr_x>, <expr>_y, <range>], <options>)
          plot2d ([discrete, <points>], <options>)
          plot2d ([contour, <expr>], <range_x>, <range_y>, <options>)
          plot2d ([<type_1>, …, <type_n>], <options>)

     There are 5 types of plots that can be plotted by ‘plot2d’:

       1. Explicit functions.  ‘plot2d’ (<expr>, <range_x>, <options>),
          where <expr> is an expression that depends on only one
          variable, or the name of a function with one input parameter
          and numerical results.  <range_x> is a list with three
          elements, the first one being the name of the variable that
          will be shown on the horizontal axis of the plot, and the
          other two elements should be two numbers, the first one
          smaller than the second, that define the minimum and maximum
          values to be shown on the horizontal axis.  The name of the
          variable used in <range_x> must be the same variable on which
          <expr> depends.  The result will show in the vertical axis the
          corresponding values of the expression or function for each
          value of the variable in the horizontal axis.

       2. Implicit functions.  ‘plot2d’ (<expr_1>=<expr_2>, <range_x>,
          <range_y>, <options>), where <expr_1> and <expr_2> are two
          expressions that can depend on one or two variables.
          <range_x> and <range_y> must be two lists of three elements
          that define the ranges for the variables in the two axes of
          the plot; the first element of each list is the name of the
          corresponding variable, and the other two elements are the
          minimum and maximum values for that variable.  The two
          variables on which <expr_1> and <expr_2> can depend are those
          specified by <range_x> and <range_y>.  The result will be a
          curve or a set of curves where the equation <expr_1>=<expr_2>
          is true.

       3. Parametric functions.  ‘plot2d’ ([parametric, <expr_x>,
          <expr>_y, <range>], <options>), where <expr_x> and <expr>_y
          are two expressions that depend on a single parameter.
          <range> must be a three-element list; the first element must
          be the name of the parameter on which <expr_x> and <expr>_y
          depend, and the other two elements must be the minimum and
          maximum values for that parameter.  The result will be a curve
          in which the horizontal and vertical coordinates of each point
          are the values of <expr_x> and <expr>_y for a value of the
          parameter within the range given.

       4. Set of points.  ‘plot2d’ ([discrete, <points>], <options>),
          displays a list of points, joined by segments by default.  The
          horizontal and vertical coordinates of each of those points
          can be specified in three different ways: With two lists of
          the same length, in which the elements of the first list are
          the horizontal coordinates of the points and the second list
          are the vertical coordinates, or with a list of two-element
          lists, each one corresponding to the two coordinates of one of
          the points, or with a single list that defines the vertical
          coordinates of the points; in this last case, the horizontal
          coordinates of the n points will be assumed to be the first n
          natural numbers.

       5. Contour lines.  ‘plot2d’ ([contour, <expr>], <range_x>,
          <range_y>, <options>), where <expr> is an expression that
          depends on two variables.  <range_x> and <range_y> will be
          lists whose first elements are the names of those two
          variables, followed by two numbers that set the minimum and
          maximum values for them.  The first variable will be
          represented along the horizontal axis and the second along the
          vertical axis.  The result will be a set of curves along which
          the given expression has certain values.  If those values are
          not specified with the option ‘levels’, plotd2d will try to
          choose, at the most, 8 values of the form d*10^n, where d is
          either 1, 2 or 5, all of them within the minimum and maximum
          values of <expr> within the given ranges.

     At the end of a plot2d command several of the options described in
     ‘Plotting Options’ can be used.  Many instances of the 5 types
     described above can be combined into a single plot, by putting them
     inside a list: ‘plot2d’ ([<type_1>, …, <type_n>], <options>).  If
     one of the types included in the list require <range_x> or
     <range_y>, those ranges should come immediately after the list.

     If there are several plots to be plotted, a legend will be written
     to identity each of the expressions.  The labels that should be
     used in that legend can be given with the option ‘legend’.  If that
     option is not used, Maxima will create labels from the expressions
     or function names.

     *Examples:*

       1. Explicit function.

               (%i1) plot2d (sin(x), [x, -%pi, %pi])$

       2. Implicit function.

               (%i1) plot2d (x^2-y^3+3*y=2, [x,-2.5,2.5], [y,-2.5,2.5])$

       3. Parametric function.

               (%i1) r: (exp(cos(t))-2*cos(4*t)-sin(t/12)^5)$
               (%i2) plot2d([parametric, r*sin(t), r*cos(t), [t,-8*%pi,8*%pi]])$

       4. Set of points.

               (%i1) plot2d ([discrete, makelist(i*%pi, i, 1, 5),
                                           [0.6, 0.9, 0.2, 1.3, 1]])$

       5. Contour lines.

               (%i1) plot2d ([contour, u^3 + v^2], [u, -4, 4], [v, -4, 4])$

     *Examples using options*.

     If an explicit function grows too fast, the ‘y’ option can be used
     to limit the values in the vertical axis:

          (%i1) plot2d (sec(x), [x, -2, 2], [y, -20, 20])$

     When the plot box is disabled, no labels are created for the axes.
     In that case, instead of using ‘xlabel’ and ‘ylabel’ to set the
     names of the axes, it is better to use option ‘label’, which allows
     more flexibility.  Option ‘yx_ratio’ is used to change the default
     rectangular shape of the plot; in this example the plot will fill a
     square.

          (%i1) plot2d ( x^2 - 1, [x, -3, 3], nobox, grid2d,
                [yx_ratio, 1], [axes, solid], [xtics, -2, 4, 2],
                [ytics, 2, 2, 6], [label, ["x", 2.9, -0.3],
                ["x^2-1", 0.1, 8]], [title, "A parabola"])$

     A plot with a logarithmic scale in the vertical axis:

          (%i1) plot2d (exp(3*s), [s, -2, 2], logy)$

     Plotting functions by name:

          (%i1) F(x) := x^2 $
          (%i2) :lisp (defun |$g| (x) (m* x x x))
          $g
          (%i2) H(x) := if x < 0 then x^4 - 1 else 1 - x^5 $
          (%i3) plot2d ([F, G, H], [u, -1, 1], [y, -1.5, 1.5])$

     Plot of a circle, using its parametric representation, together
     with the function -‘|<x>|’.  The circle will only look like a
     circle if the scale in the two axes is the same, which is done with
     the option ‘same_xy’.

          (%i1) plot2d([[parametric, cos(t), sin(t), [t,0,2*%pi]], -abs(x)],
                   [x, -sqrt(2), sqrt(2)], same_xy)$

     A plot of 200 random numbers between 0 and 9:

          (%i1) plot2d ([discrete, makelist ( random(10), 200)])$

     In the next example a table with three columns is saved in a file
     “data.txt” which is then read and the second and third column are
     plotted on the two axes:

          (%i1) display2d:false$
          (%i2) with_stdout ("data.txt", for x:0 thru 10 do
                                       print (x, x^2, x^3))$
          (%i3) data: read_matrix ("data.txt")$
          (%i4) plot2d ([discrete, transpose(data)[2], transpose(data)[3]],
            [style,points], [point_type,diamond], [color,red])$

     A plot of discrete data points together with a continuous function:

          (%i1) xy: [[10, .6], [20, .9], [30, 1.1], [40, 1.3], [50, 1.4]]$
          (%i2) plot2d([[discrete, xy], 2*%pi*sqrt(l/980)], [l,0,50],
                  [style, points, lines], [color, red, blue],
                  [point_type, asterisk],
                  [legend, "experiment", "theory"],
                  [xlabel, "pendulum's length (cm)"],
                  [ylabel, "period (s)"])$

     See also the section about Plotting Options.

 -- Function: plot3d
          plot3d (<expr>, <x_range>, <y_range>, …, <options>, …)
          plot3d ([<expr_1>, …, <expr_n>], <x_range>, <y_range>, …,
          <options>, …)

     Displays a plot of one or more surfaces defined as functions of two
     variables or in parametric form.

     The functions to be plotted may be specified as expressions or
     function names.  The mouse can be used to rotate the plot looking
     at the surface from different sides.

     *Examples*.

     Plot of a function of two variables:

          (%i1) plot3d (u^2 - v^2, [u, -2, 2], [v, -3, 3], [grid, 100, 100],
                  nomesh_lines)$

     Use of the ‘z’ option to limit a function that goes to infinity (in
     this case the function is minus infinity on the x and y axes); this
     also shows how to plot with only lines and no shading:

          (%i1) plot3d ( log ( x^2*y^2 ), [x, -2, 2], [y, -2, 2], [z, -8, 4],
                   nopalette, [color, magenta])$

     The infinite values of z can also be avoided by choosing a grid
     that does not fall on any points where the function is undefined,
     as in the next example, which also shows how to change the palette
     and how to include a color bar that relates colors to values of the
     z variable:

          (%i1) plot3d (log (x^2*y^2), [x, -2, 2], [y, -2, 2],[grid, 29, 29],
                 [palette, [gradient, red, orange, yellow, green]],
                 color_bar, [xtics, 1], [ytics, 1], [ztics, 4],
                 [color_bar_tics, 4])$

     Two surfaces in the same plot.  Ranges specific to one of the
     surfaces can be given by placing each expression and its ranges in
     a separate list; global ranges for the complete plot are also given
     after the function definitions.

          (%i1) plot3d ([[-3*x - y, [x, -2, 2], [y, -2, 2]],
             4*sin(3*(x^2 + y^2))/(x^2 + y^2), [x, -3, 3], [y, -3, 3]],
             [x, -4, 4], [y, -4, 4])$

     Plot of a Klein bottle, defined parametrically:

          (%i1) expr_1: 5*cos(x)*(cos(x/2)*cos(y)+sin(x/2)*sin(2*y)+3)-10$
          (%i2) expr_2: -5*sin(x)*(cos(x/2)*cos(y)+sin(x/2)*sin(2*y)+3)$
          (%i3) expr_3: 5*(-sin(x/2)*cos(y)+cos(x/2)*sin(2*y))$
          (%i4) plot3d ([expr_1, expr_2, expr_3], [x, -%pi, %pi],
                  [y, -%pi, %pi], [grid, 50, 50])$

     Plot of a “spherical harmonic” function, using the predefined
     transformation, ‘spherical_to_xyz’ to transform from spherical
     coordinates to rectangular coordinates.  See the documentation for
     ‘spherical_to_xyz’.

          (%i1) plot3d (sin(2*theta)*cos(phi), [theta,0,%pi], [phi,0,2*%pi],
                [transform_xy, spherical_to_xyz], [grid, 30, 60], nolegend)$

     Use of the pre-defined function ‘polar_to_xy’ to transform from
     cylindrical to rectangular coordinates.  See the documentation for
     ‘polar_to_xy’.

          (%i1) plot3d (r^.33*cos(th/3), [r,0,1], [th,0,6*%pi], nobox,
              nolegend, [grid, 12, 80], [transform_xy, polar_to_xy])$

     Plot of a sphere using the transformation from spherical to
     rectangular coordinates.  Option ‘same_xyz’ is used to get the
     three axes scaled in the same proportion.  When transformations are
     used, it is not convenient to eliminate the mesh lines, because
     Gnuplot will not show the surface correctly.

          (%i1) plot3d ( 5, [theta,0,%pi], [phi,0,2*%pi], same_xyz, nolegend,
            [transform_xy, spherical_to_xyz], [mesh_lines_color,blue],
            [palette,[gradient,"#1b1b4e", "#8c8cf8"]])$

     Definition of a function of two-variables using a matrix.  Notice
     the single quote in the definition of the function, to prevent
     ‘plot3d’ from failing when it realizes that the matrix will require
     integer indices.

          (%i1) M: matrix([1,2,3,4], [1,2,3,2], [1,2,3,4], [1,2,3,3])$
          (%i2) f(x, y) := float('M [round(x), round(y)])$
          (%i3) plot3d (f(x,y), [x,1,4], [y,1,4], [grid,3,3], nolegend)$

     By setting the elevation equal to zero, a surface can be seen as a
     map in which each color represents a different level.

          (%i1) plot3d (cos (-x^2 + y^3/4), [x,-4,4], [y,-4,4], [zlabel,""],
                 [mesh_lines_color,false], [elevation,0], [azimuth,0],
                 color_bar, [grid,80,80], noztics, [color_bar_tics,1])$

     See also ‘Plotting Options’.

 -- System variable: plot_options

     This option is being kept for compatibility with older versions,
     but its use is deprecated.  To set global plotting options, see
     their current values or remove options, use ‘set_plot_option’,
     ‘get_plot_option’ and ‘remove_plot_option’.

 -- Function: remove_plot_option (<name>)

     Removes the default value of an option.  The name of the option
     must be given.

     See also ‘set_plot_option’, ‘get_plot_option’ and ‘Plotting
     Options’.

 -- Function: set_plot_option (<option>)

     Accepts any of the options listed in the section Plotting Options,
     and saves them for use in plotting commands.  The values of the
     options set in each plotting command will have precedence, but if
     those options are not given, the default values set with this
     function will be used.

     ‘set_plot_option’ evaluates its argument and returns the complete
     list of options (after modifying the option given).  If called
     without any arguments, it will simply show the list of current
     default options.

     See also ‘remove_plot_option’, ‘get_plot_option’ and the section on
     Plotting Options.

     Example:

     Modification of the ‘grid’ values.

          (%i1) set_plot_option ([grid, 30, 40]);
          (%o1) [[plot_format, gnuplot_pipes], [grid, 30, 40],
          [run_viewer, true], [axes, true], [nticks, 29], [adapt_depth, 5],
          [color, blue, red, green, magenta, black, cyan],
          [point_type, bullet, box, triangle, plus, times, asterisk],
          [palette, [gradient, green, cyan, blue, violet],
          [gradient, magenta, violet, blue, cyan, green, yellow, orange,
          red, brown, black]], [gnuplot_preamble, ], [gnuplot_term, default]]

 -- System function: spherical_to_xyz

     It can be given as value for the ‘transform_xy’ option of ‘plot3d’.
     Its effect will be to interpret the two independent variables and
     the function in ‘plot3d’ as the spherical coordinates of a point
     (first, the angle with the z axis, then the angle of the xy
     projection with the x axis and finally the distance from the
     origin) and transform them into x, y and z coordinates.


File: maxima.info,  Node: Plotting Options,  Next: Gnuplot Options,  Prev: Functions and Variables for Plotting,  Up: Plotting

8.4 Plotting Options
====================

All options consist of a list starting with one of the keywords in this
section, followed by one or more values.  If the option appears inside
one of the plotting commands, its value will be local for that command.
It the option is given as argument to ‘set_plot_option’, its value will
be global and used in all plots, unless it is overridden by a local
value.

   Some of the options may have different effects in different plotting
commands as it will be pointed out in the following list.  The options
that accept among their possible values true or false, can also be set
to true by simply writing their names, and false by writing their names
with the prefix no.  For instance, typing ‘logx’ as an option is
equivalent to writing ‘[logx, true]’ and ‘nobox’ is equivalent to ‘[box,
false]’.  When just the name of the option is used for an option which
cannot have a value ‘true’, it means that any value previously assigned
to that option will be removed, leaving it to the graphic program to
decide what to do.

 -- Plot option: adapt_depth [adapt_depth, <integer>]
     Default value: ‘5’

     The maximum number of splittings used by the adaptive plotting
     routine of ‘plot2d’; <integer> must be a non-negative integer.  A
     value of zero means that adaptive plotting will not be used and the
     resulting plot will have 1+4*<nticks> points (see option ‘nticks’).
     To have more control on the number of points and their positions, a
     list of points can be created and then plotted using the ‘discrete’
     method of ‘plot2d’.

 -- Plot option: axes [axes, <symbol>], axes, noaxes

     Default value: ‘true’

     Where <symbol> can be either ‘true’, ‘false’, ‘x’, ‘y’ or ‘solid’.
     If ‘false’, no axes are shown; if equal to ‘x’ or ‘y’ only the x or
     y axis will be shown; if it is equal to ‘true’, both axes will be
     shown and ‘solid’ will show the two axes with a solid line, rather
     than the default broken line.  This option does not have any effect
     in the 3 dimensional plots.  The single keywords ‘axes’ and
     ‘noaxes’ can be used as synonyms for ‘[axes, true]’ and ‘[axes,
     false]’.

 -- Plot option: azimuth [azimuth, <number>]

     Default value: ‘30’

     A plot3d plot can be thought of as starting with the x and y axis
     in the horizontal and vertical axis, as in plot2d, and the z axis
     coming out of the screen.  The z axis is then rotated around the x
     axis through an angle equal to ‘elevation’ and then the new xy
     plane is rotated around the new z axis through an angle ‘azimuth’.
     This option sets the value for the azimuth, in degrees.

     See also ‘elevation’.

 -- Plot option: box [box, <symbol>], box, nobox

     Default value: ‘true’

     If set to ‘true’, a bounding box will be drawn for the plot; if set
     to ‘false’, no box will be drawn.  The single keywords ‘box’ and
     ‘nobox’ can be used as synonyms for ‘[box, true]’ and ‘[box,
     false]’.

 -- Plot option: color [color, <color_1>, …, <color_n>]

     In 2d plots it defines the color (or colors) for the various
     curves.  In ‘plot3d’, it defines the colors used for the mesh lines
     of the surfaces, when no palette is being used.

     If there are more curves or surfaces than colors, the colors will
     be repeated in sequence.  The valid colors are ‘red’, ‘green’,
     ‘blue’, ‘magenta’, ‘cyan’, ‘yellow’, ‘orange’, ‘violet’, ‘brown’,
     ‘gray’, ‘black’, ‘white’, or a string starting with the character #
     and followed by six hexadecimal digits: two for the red component,
     two for green component and two for the blue component.  If the
     name of a given color is unknown color, black will be used instead.

 -- Plot option: color_bar [color_bar, <symbol>], color_bar, nocolor_bar

     Default value: ‘false’ in plot3d, ‘true’ in mandelbrot and julia

     Where <symbol> can be either ‘true’ or ‘false’.  If ‘true’,
     whenever ‘plot3d’, ‘mandelbrot’ or ‘julia’ use a palette to
     represent different values, a box will be shown on the right,
     showing the corresponding between colors and values.  The single
     keywords ‘color_bar’ and ‘nocolor_bar’ can be used as synonyms for
     ‘[color_bar, true]’ and ‘[color_bar, false]’.

 -- Plot option: color_bar_tics [color_bar_tics, <x1>, <x2>, <x3>],
          color_bar_tics, nocolor_bar_tics

     Defines the values at which a mark and a number will be placed in
     the color bar.  The first number is the initial value, the second
     the increments and the third is the last value where a mark is
     placed.  The second and third numbers can be omitted.  When only
     one number is given, it will be used as the increment from an
     initial value that will be chosen automatically.  The single
     keyword ‘color_bar_tics’ removes a value given previously, making
     the graphic program use its default for the values of the tics and
     ‘nocolor_bar_tics’ will not show any tics on the color bar.

 -- Plot option: elevation [elevation, <number>]

     Default value: ‘60’

     A plot3d plot can be thought of as starting with the x and y axis
     in the horizontal and vertical axis, as in plot2d, and the z axis
     coming out of the screen.  The z axis is then rotated around the x
     axis through an angle equal to ‘elevation’ and then the new xy
     plane is rotated around the new z axis through an angle ‘azimuth’.
     This option sets the value for the elevation, in degrees.

     See also ‘azimuth’.

 -- Plot option: grid [grid, <integer>, <integer>]
     Default value: ‘30’, ‘30’

     Sets the number of grid points to use in the x- and y-directions
     for three-dimensional plotting or for the ‘julia’ and ‘mandelbrot’
     programs.

     For a way to actually draw a grid See ‘grid2d’.

 -- Plot option: grid2d [grid2d, <value>], grid2d, nogrid2d

     Default value: ‘false’

     Shows a grid of lines on the xy plane.  The points where the grid
     lines are placed are the same points where tics are marked in the x
     and y axes, which can be controlled with the ‘xtics’ and ‘ytics’
     options.  The single keywords ‘grid2d’ and ‘nogrid2d’ can be used
     as synonyms for ‘[grid2d, true]’ and ‘[grid2d, false]’.

     See also ‘grid’.

 -- Plot option: iterations [iterations, <value>]

     Default value: ‘9’

     Number of iterations made by the programs mandelbrot and julia.

 -- Plot option: label [label, [<string>, <x>, <y>], …]

     Writes one or several labels in the points with <x>, <y>
     coordinates indicated after each label.

 -- Plot option: legend [legend, <string_1>, …, <string_n>], legend,
          nolegend

     It specifies the labels for the plots when various plots are shown.
     If there are more plots than the number of labels given, they will
     be repeated.  If given the value ‘false’, no legends will be shown.
     By default, the names of the expressions or functions will be used,
     or the words discrete1, discrete2, …, for discrete sets of points.
     The single keyword ‘legend’ removes any previously defined legends,
     leaving it to the plotting program to set up a legend.  The keyword
     ‘nolegend’ is a synonym for ‘[legend, false]’.

 -- Plot option: levels [levels, <number>, …]

     This option is used by ‘plot2d’ to do contour plots.  If only one
     number is given after the keyword ‘levels’, it must be a natural
     number; ‘plot2d’ will try to plot that number of contours with
     values between the minimum and maximum value of the expression
     given, with the form d*10^n, where d is either 1, 2 or 5.  Since
     not always it will be possible to find that number of levels in
     that interval, the number of contour lines show will be smaller
     than the number specified by this option.

     If more than one number are given after the keyword ‘levels’,
     ‘plot2d’.  will show the contour lines corresponding to those
     values of the expression plotted, if they exist within the domain
     used.

 -- Plot option: logx [logx, <value>], logx, nologx

     Default value: ‘false’

     Makes the horizontal axes to be scaled logarithmically.  It can be
     either true or false.  The single keywords ‘logx’ and ‘nologx’ can
     be used as synonyms for ‘[logx, true]’ and ‘[logx, false]’.

 -- Plot option: logy [logy, <value>], logy, nology

     Default value: ‘false’

     Makes the vertical axes to be scaled logarithmically.  It can be
     either true or false.  The single keywords ‘logy’ and ‘nology’ can
     be used as synonyms for ‘[logy, true]’ and ‘[logy, false]’.

 -- Plot option: mesh_lines_color [mesh_lines_color, <color>],
          mesh_lines_color, no_mesh_lines

     Default value: ‘black’

     It sets the color used by plot3d to draw the mesh lines, when a
     palette is being used.  It accepts the same colors as for the
     option ‘color’ (see the list of allowed colors in ‘color’).  It can
     also be given a value ‘false’ to eliminate completely the mesh
     lines.  The single keyword ‘mesh_lines_color’ removes any
     previously defined colors, leaving it to the graphic program to
     decide what color to use.  The keyword ‘no_mesh_lines’ is a synonym
     for ‘[mesh_lines_color, false]’

 -- Plot option: nticks [nticks, <integer>]

     Default value: ‘29’

     When plotting functions with ‘plot2d’, it is gives the initial
     number of points used by the adaptive plotting routine for plotting
     functions.  When plotting parametric functions with ‘plot3d’, it
     sets the number of points that will be shown for the plot.

 -- Plot option: palette [palette, [<palette_1>], …, [<palette_n>]],
          palette, nopalette

     It can consist of one palette or a list of several palettes.  Each
     palette is a list with a keyword followed by values.  If the
     keyword is gradient, it should be followed by a list of valid
     colors.

     If the keyword is hue, saturation or value, it must be followed by
     4 numbers.  The first three numbers, which must be between 0 and 1,
     define the hue, saturation and value of a basic color to be
     assigned to the minimum value of z.  The keyword specifies which of
     the three attributes (hue, saturation or value) will be increased
     according to the values of z.  The last number indicates the
     increase corresponding to the maximum value of z.  That last number
     can be bigger than 1 or negative; the corresponding values of the
     modified attribute will be rounded modulo 1.

     Gnuplot only uses the first palette in the list; xmaxima will use
     the palettes in the list sequentially, when several surfaces are
     plotted together; if the number of palettes is exhausted, they will
     be repeated sequentially.

     The color of the mesh lines will be given by the option
     ‘mesh_lines_color’.  If ‘palette’ is given the value ‘false’, the
     surfaces will not be shaded but represented with a mesh of curves
     only.  In that case, the colors of the lines will be determined by
     the option ‘color’.

     The single keyword ‘palette’ removes any palette previously
     defined, leaving it to the graphic program to decide the palette to
     use and ‘nopalette’ is a synonym for ‘[palette, false]’.

 -- Plot option: plotepsilon [plotepsilon, <value>]

     Default value: 1e-6

     This value is used by ‘plot2d’ when plotting implicit functions or
     contour lines.  When plotting an explicit function ‘expr_1=expr_2’,
     it is converted into ‘expr_1-expr_2’ and the points where that
     equals zero are searched.  When a contour line for ‘expr’ equal to
     some value is going to be plotted, the points where ‘expr’ minus
     that value are equal to zero are searched.  The search is done by
     computing those expressions at a grid of points (see ‘sample’).  If
     at one of the points in that grid the absolute value of the
     expression is less than the value of ‘plotepsilon’, it will be
     assumed to be zero, and therefore, as being part of the curve to be
     plotted.

 -- Plot option: plot_format [plot_format, <format>]

     Default value: ‘gnuplot’, in Windows systems, or ‘gnuplot_pipes’ in
     other systems.

     Where <format> is one of the following: gnuplot, xmaxima, mgnuplot,
     gnuplot_pipes or geomview.

     It sets the format to be used for plotting as explained in
     ‘Plotting Formats’.

 -- Plot option: plot_realpart [plot_realpart, <symbol>], plot_realpart,
          noplot_realpart

     Default value: ‘false’

     If set to ‘true’, the functions to be plotted will be considered as
     complex functions whose real value should be plotted; this is
     equivalent to plotting ‘realpart(<function>)’.  If set to ‘false’,
     nothing will be plotted when the function does not give a real
     value.  For instance, when ‘x’ is negative, ‘log(x)’ gives a
     complex value, with real value equal to ‘log(abs(x))’; if
     ‘plot_realpart’ were ‘true’, ‘log(-5)’ would be plotted as
     ‘log(5)’, while nothing would be plotted if ‘plot_realpart’ were
     ‘false’.  The single keyword ‘plot_realpart’ can be used as a
     synonym for ‘[plot_realpart, true]’ and ‘noplot_realpart’ is a
     synonym for ‘[plot_realpart, false]’.

 -- Plot option: point_type [point_type, <type_1>, …, <type_n>]

     In gnuplot, each set of points to be plotted with the style
     “points” or “linespoints” will be represented with objects taken
     from this list, in sequential order.  If there are more sets of
     points than objects in this list, they will be repeated
     sequentially.  The possible objects that can be used are: ‘bullet’,
     ‘circle’, ‘plus’, ‘times’, ‘asterisk’, ‘box’, ‘square’, ‘triangle’,
     ‘delta’, ‘wedge’, ‘nabla’, ‘diamond’, ‘lozenge’.

 -- Plot option: pdf_file [pdf_file, <file_name>]

     Saves the plot into a PDF file with name equal to <file_name>,
     rather than showing it in the screen.  By default, the file will be
     created in the directory defined by the variable ‘maxima_tempdir’,
     unless <file_name> contains the character “/”, in which case it
     will be assumed to contain the complete path where the file should
     be created.  The value of ‘maxima_tempdir’ can be changed to save
     the file in a different directory.  When the option
     ‘gnuplot_pdf_term_command’ is also given, it will be used to set up
     Gnuplot’s PDF terminal; otherwise, Gnuplot’s pdfcairo terminal will
     be used with solid colored lines of width 3, plot size of 17.2 cm
     by 12.9 cm and font of 18 points.

 -- Plot option: png_file [png_file, <file_name>]

     Saves the plot into a PNG graphics file with name equal to
     <file_name>, rather than showing it in the screen.  By default, the
     file will be created in the directory defined by the variable
     ‘maxima_tempdir’, unless <file_name> contains the character “/”, in
     which case it will be assumed to contain the complete path where
     the file should be created.  The value of ‘maxima_tempdir’ can be
     changed to save the file in a different directory.  When the option
     ‘gnuplot_png_term_command’ is also given, it will be used to set up
     Gnuplot’s PNG terminal; otherwise, Gnuplot’s pngcairo terminal will
     be used, with a font of size 12.

 -- Plot option: ps_file [ps_file, <file_name>]

     Saves the plot into a Postscript file with name equal to
     <file_name>, rather than showing it in the screen.  By default, the
     file will be created in the directory defined by the variable
     ‘maxima_tempdir’, unless <file_name> contains the character “/”, in
     which case it will be assumed to contain the complete path where
     the file should be created.  The value of ‘maxima_tempdir’ can be
     changed to save the file in a different directory.  When the option
     ‘gnuplot_ps_term_command’ is also given, it will be used to set up
     Gnuplot’s Postscript terminal; otherwise, Gnuplot’s postscript
     terminal will be used with the EPS option, solid colored lines of
     width 2, plot size of 16.4 cm by 12.3 cm and font of 24 points.

 -- Plot option: run_viewer [run_viewer, <symbol>], run_viewer,
          norun_viewer

     Default value: ‘true’

     This option is only used when the plot format is ‘gnuplot’ and the
     terminal is ‘default’ or when the Gnuplot terminal is set to ‘dumb’
     (see ‘gnuplot_term’) and can have a true or false value.

     If the terminal is ‘default’, a file ‘maxout_xxx.gnuplot’ (or other
     name specified with ‘gnuplot_out_file’) is created with the gnuplot
     commands necessary to generate the plot.  Option ‘run_viewer’
     controls whether or not Gnuplot will be launched to execute those
     commands and show the plot.

     If the terminal is ‘default’, gnuplot is run to execute the
     commands in ‘maxout_xxx.gnuplot’, producing another file
     ‘maxplot.txt’ (or other name specified with ‘gnuplot_out_file’).
     Option ‘run_viewer’ controls whether or not that file, with an
     ASCII representation of the plot, will be shown in the Maxima or
     Xmaxima console.

     Its default value, true, makes the plots appear in either the
     console or a separate graphics window.  ‘run_viewer’ and
     ‘norun_viewer’ are synonyms for ‘[run_viewer, true]’ and
     ‘[run_viewer, false]’.

 -- Plot option: same_xy [same_xy , <value>], same_xy, nosame_xy

     It can be either true or false.  If true, the scales used in the x
     and y axes will be the same, in either 2d or 3d plots.  See also
     ‘yx_ratio’.  ‘same_xy’ and ‘nosame_xy’ are synonyms for ‘[same_xy,
     true]’ and ‘[same_xy, false]’.

 -- Plot option: same_xyz [same_xyz , <value>], same_xyz, nosame_xyz

     It can be either true or false.  If true, the scales used in the 3
     axes of a 3d plot will be the same.  ‘same_xyz’ and ‘nosame_xyz’
     are synonyms for ‘[same_xyz, true]’ and ‘[same_xyz, false]’.

 -- Plot option: sample [sample, <nx>, <ny>]

     Default value: ‘[sample, 50, 50]’

     <nx> and <ny> must be two natural numbers that will be used by
     ‘plot2d’ to look for the points that make part of the plot of an
     implicit function or a contour line.  The domain is divided into
     <nx> intervals in the horizontal axis and <ny> intervals in the
     vertical axis and the numerical value of the expression is computed
     at the borders of those intervals.  Higher values of <nx> and <ny>
     will give smoother curves, but will increase the time needed to
     trace the plot.  When there are critical points in the plot where
     the curve changes direction, to get better results it is more
     important to try to make those points to be at the border of the
     intervals, rather than increasing <nx> and <ny>.

 -- Plot option: style [style, <type_1>, …, <type_n>], [style,
          [<style_1>], …, [<style_n>]]

     The styles that will be used for the various functions or sets of
     data in a 2d plot.  The word <style> must be followed by one or
     more styles.  If there are more functions and data sets than the
     styles given, the styles will be repeated.  Each style can be
     either <lines> for line segments, <points> for isolated points,
     <linespoints> for segments and points, or <dots> for small isolated
     dots.  Gnuplot accepts also an <impulses> style.

     Each of the styles can be enclosed inside a list with some
     additional parameters.  <lines> accepts one or two numbers: the
     width of the line and an integer that identifies a color.  The
     default color codes are: 1: blue, 2: red, 3: magenta, 4: orange, 5:
     brown, 6: lime and 7: aqua.  If you use Gnuplot with a terminal
     different than X11, those colors might be different; for example,
     if you use the option [<gnuplot_term>, <ps>], color index 4 will
     correspond to black, instead of orange.

     <points> accepts one two or three parameters; the first parameter
     is the radius of the points, the second parameter is an integer
     that selects the color, using the same code used for <lines> and
     the third parameter is currently used only by Gnuplot and it
     corresponds to several objects instead of points.  The default
     types of objects are: 1: filled circles, 2: open circles, 3: plus
     signs, 4: x, 5: *, 6: filled squares, 7: open squares, 8: filled
     triangles, 9: open triangles, 10: filled inverted triangles, 11:
     open inverted triangles, 12: filled lozenges and 13: open lozenges.

     <linespoints> accepts up to four parameters: line width, points
     radius, color and type of object to replace the points.

     See also ‘color’ and ‘point_type’.

 -- Plot option: svg_file [svg_file, <file_name>]

     Saves the plot into an SVG file with name equal to <file_name>,
     rather than showing it in the screen.  By default, the file will be
     created in the directory defined by the variable ‘maxima_tempdir’,
     unless <file_name> contains the character “/”, in which case it
     will be assumed to contain the complete path where the file should
     be created.  The value of ‘maxima_tempdir’ can be changed to save
     the file in a different directory.  When the option
     ‘gnuplot_svg_term_command’ is also given, it will be used to set up
     Gnuplot’s SVG terminal; otherwise, Gnuplot’s svg terminal will be
     used with font of 14 points.

 -- Plot option: t [t, <min>, <max>]

     Default range for parametric plots.

 -- Plot option: title [title, <text>]

     Defines a title that will be written at the top of the plot.

 -- Plot option: transform_xy [transform_xy, <symbol>], notransform_xy

     Where <symbol> is either ‘false’ or the result obtained by using
     the function ‘transform_xy’.  If different from ‘false’, it will be
     used to transform the 3 coordinates in plot3d.  ‘notransform_xy’
     removes any transformation function previously defined.

     See ‘make_transform’, ‘polar_to_xy’ and ‘spherical_to_xyz’.

 -- Plot option: window [window, <n>]

     Opens the plot in window number <n>, instead of the default window
     0.  If window number <n> is already opened, the plot in that window
     will be replaced by the current plot.

 -- Plot option: x [x, <min>, <max>]

     When used as the first option in a ‘plot2d’ command (or any of the
     first two in ‘plot3d’), it indicates that the first independent
     variable is x and it sets its range.  It can also be used again
     after the first option (or after the second option in plot3d) to
     define the effective horizontal domain that will be shown in the
     plot.

 -- Plot option: xlabel [xlabel, <string>]

     Specifies the <string> that will label the first axis; if this
     option is not used, that label will be the name of the independent
     variable, when plotting functions with ‘plot2d’ the name of the
     first variable, when plotting surfaces with ‘plot3d’, or the first
     expression in the case of a parametric plot.

 -- Plot option: xtics [xtics, <x1>, <x2>, <x3>], [xtics, ‘false’],
          xtics, noxtics

     Defines the values at which a mark and a number will be placed in
     the x axis.  The first number is the initial value, the second the
     increments and the third is the last value where a mark is placed.
     The second and third numbers can be omitted, in which case the
     first number is the increment from an initial value that will be
     chosen by the graphic program.  If ‘[xtics, false]’ is used, no
     marks or numbers will be shown along the x axis.

     The single keyword ‘xtics’ removes any values previously defined,
     leaving it to the graphic program to decide the values to use and
     ‘noxtics’ is a synonym for ‘[xtics, false]’

 -- Plot option: xy_scale [xy_scale, <sx>, <sy>]

     In a 2d plot, it defines the ratio of the total size of the Window
     to the size that will be used for the plot.  The two numbers given
     as arguments are the scale factors for the x and y axes.

     This option does not change the size of the graphic window or the
     placement of the graph in the window.  If you want to change the
     aspect ratio of the plot, it is better to use option ‘yx_ratio’.
     For instance, ‘[yx_ratio, 10]’ instead of ‘[xy_scale, 0.1, 1]’.

 -- Plot option: y [y, <min>, <max>]

     When used as one of the first two options in ‘plot3d’, it indicates
     that one of the independent variables is y and it sets its range.
     Otherwise, it defines the effective domain of the second variable
     that will be shown in the plot.

 -- Plot option: ylabel [ylabel, <string>]

     Specifies the <string> that will label the second axis; if this
     option is not used, that label will be “y”, when plotting explicit
     functions with ‘plot2d’, or the name of the second variable, when
     plotting surfaces with ‘plot3d’, or the second expression in the
     case of a parametric plot.

 -- Plot option: ytics [ytics, <y1>, <y2>, <y3>], [ytics, ‘false’],
          ytics, noytics

     Defines the values at which a mark and a number will be placed in
     the y axis.  The first number is the initial value, the second the
     increments and the third is the last value where a mark is placed.
     The second and third numbers can be omitted, in which case the
     first number is the increment from an initial value that will be
     chosen by the graphic program.  If ‘[ytics, false]’ is used, no
     marks or numbers will be shown along the y axis.

     The single keyword ‘ytics’ removes any values previously defined,
     leaving it to the graphic program to decide the values to use and
     ‘noytics’ is a synonym for ‘[ytics, false]’

 -- Plot option: yx_ratio [yx_ratio, <r>]

     In a 2d plot, the ratio between the vertical and the horizontal
     sides of the rectangle used to make the plot.  See also ‘same_xy’.

 -- Plot option: z [z, <min>, <max>]

     Used in ‘plot3d’ to set the effective range of values of z that
     will be shown in the plot.

 -- Plot option: zlabel [zlabel, <string>]

     Specifies the <string> that will label the third axis, when using
     ‘plot3d’.  If this option is not used, that label will be “z”, when
     plotting surfaces, or the third expression in the case of a
     parametric plot.  It can not be used with ‘set_plot_option’ and it
     will be ignored by ‘plot2d’.

 -- Plot option: zmin [zmin, <z>], zmin

     In 3d plots, the value of z that will be at the bottom of the plot
     box.

     The single keyword ‘zmin’ removes any value previously defined,
     leaving it to the graphic program to decide the value to use.

 -- Plot option: ztics [ztics, <z1>, <z2>, <z3>], [ztics, ‘false’],
          ztics, noztics

     Defines the values at which a mark and a number will be placed in
     the z axis.  The first number is the initial value, the second the
     increments and the third is the last value where a mark is placed.
     The second and third numbers can be omitted, in which case the
     first number is the increment from an initial value that will be
     chosen by the graphic program.  If ‘[ztics, false]’ is used, no
     marks or numbers will be shown along the z axis.

     The single keyword ‘ztics’ removes any values previously defined,
     leaving it to the graphic program to decide the values to use and
     ‘noztics’ is a synonym for ‘[ztics, false]’


File: maxima.info,  Node: Gnuplot Options,  Next: Gnuplot_pipes Format Functions,  Prev: Plotting Options,  Up: Plotting

8.5 Gnuplot Options
===================

There are several plot options specific to gnuplot.  All of them consist
of a keyword (the name of the option), followed by a string that should
be a valid gnuplot command, to be passed directly to gnuplot.  In most
cases, there exist a corresponding plotting option that will produce a
similar result and whose use is more recommended than the gnuplot
specific option.

 -- Plot option: gnuplot_term [gnuplot_term, <terminal_name>]

     Sets the output terminal type for gnuplot.  The argument
     <terminal_name> can be a string or one of the following 3 special
     symbols
        • *default* (default value)

          Gnuplot output is displayed in a separate graphical window and
          the gnuplot terminal used will be specified by the value of
          the option ‘gnuplot_default_term_command’.

        • *dumb*

          Gnuplot output is saved to a file ‘maxout_xxx.gnuplot’ using
          "ASCII art" approximation to graphics.  If the option
          ‘gnuplot_out_file’ is set to <filename>, the plot will be
          saved there, instead of the default ‘maxout_xxx.gnuplot’.  The
          settings for the “dumb” terminal of Gnuplot are given by the
          value of option ‘gnuplot_dumb_term_command’.  If option
          ‘run_viewer’ is set to true and the plot_format is ‘gnuplot’
          that ASCII representation will also be shown in the Maxima or
          Xmaxima console.

        • *ps*

          Gnuplot generates commands in the PostScript page description
          language.  If the option ‘gnuplot_out_file’ is set to
          <filename>, gnuplot writes the PostScript commands to
          <filename>.  Otherwise, it is saved as ‘maxplot.ps’ file.  The
          settings for this terminal are given by the value of the
          option ‘gnuplot_dumb_term_command’.

        • A string representing any valid gnuplot term specification

          Gnuplot can generate output in many other graphical formats
          such as png, jpeg, svg etc.  To use those formats, option
          ‘gnuplot_term’ can be set to any supported gnuplot term name
          (which must be a symbol) or even a full gnuplot term
          specification with any valid options (which must be a string).
          For example ‘[gnuplot_term, png]’ creates output in PNG
          (Portable Network Graphics) format while ‘[gnuplot_term, "png
          size 1000,1000"]’ creates PNG of 1000 x 1000 pixels size.  If
          the option ‘gnuplot_out_file’ is set to <filename>, gnuplot
          writes the output to <filename>.  Otherwise, it is saved as
          ‘maxplot.<term>’ file, where <term> is gnuplot terminal name.

 -- Plot option: gnuplot_out_file [gnuplot_out_file, <file_name>]

     It can be used to replace the default name for the file that
     contains the commands that will interpreted by gnuplot, when the
     terminal is set to ‘default’, or to replace the default name of the
     graphic file that gnuplot creates, when the terminal is different
     from ‘default’.  If it contains one or more slashes, “/”, the name
     of the file will be left as it is; otherwise, it will be appended
     to the path of the temporary directory.  The complete name of the
     files created by the plotting commands is always sent as output of
     those commands so they can be seen if the command is ended by
     semi-colon.

     When used in conjunction with the ‘gnuplot_term’ option, it can be
     used to save the plot in a file, in one of the graphic formats
     supported by Gnuplot.  To create PNG, PDF, Postscript or SVG, it is
     easier to use options ‘png_file’, ‘pdf_file’, ‘ps_file’, or
     ‘svg_file’.

 -- Plot option: gnuplot_script_file [gnuplot_script_file,
          <file_name_or_function>]

     Creates a plot with ‘plot2d’, ‘plot3d’, ‘mandelbrot’ or ‘julia’
     using the ‘gnuplot’ ‘plot_format’ and saving the script sent to
     Gnuplot in the file specified by <file_name_or_function>.  The
     value <file_name_or_function> can be a string or a Maxima function
     of one variable that returns a string.  If that string corresponds
     to a complete file path (directory and file name), the script will
     be created in that file and will not be deleted after Maxima is
     closed; otherwise, the string will give the name of a file to be
     created in the temporary directory and deleted when Maxima is
     closed.

     In this example, the script file name is set to “sin.gnuplot”, in
     the current directory.

          (%i1) plot2d( sin(x), [x,0,2*%pi], [gnuplot_script_file, "./sin.gnuplot"]);

          (%o1) ["./sin.gnuplot"]

     In this example, ‘gnuplot_maxout_prt(<file>)’ is a function that
     takes the default file name, <file>.  It constructs a full file
     name for the data file by interpolating a random 8-digit integer
     with a pad of zeros into the default file name (“maxout” followed
     by the id number of the Maxima process, followed by “.gnuplot”).
     The temporary directory is determined by ‘maxima_tempdir’ (it is
     “/tmp” in this example).

          (%i1) gnuplot_maxout_prt(file) := block([beg,end],
                  [beg,end] : split(file,"."),
                  printf(false,"~a_~8,'0d.~a",beg,random(10^8-1),end)) $

          (%i2) plot2d( sin(x), [x,0,2*%pi], [gnuplot_script_file, gnuplot_maxout_prt]);

          (%o2) ["/tmp/maxout68715_09606909.gnuplot"]

     By default, the script would have been saved in a file named
     ‘maxoutXXXXX.gnuplot’ (XXXXX=68715 in this example) in the
     temporary directory.  If the print statement in function
     ‘gnuplot_maxout_prt’ above included a directory path, the file
     would have been saved in that directory rather than in the
     temporary directory.

 -- Plot option: gnuplot_pm3d [gnuplot_pm3d, <value>]

     With a value of ‘false’, it can be used to disable the use of PM3D
     mode, which is enabled by default.

 -- Plot option: gnuplot_preamble [gnuplot_preamble, <string>]

     This option inserts gnuplot commands before any other commands sent
     to Gnuplot.  Any valid gnuplot commands may be used.  Multiple
     commands should be separated with a semi-colon.  See also
     ‘gnuplot_postamble’.

 -- Plot option: gnuplot_postamble [gnuplot_postamble, <string>]

     This option inserts gnuplot commands after other commands sent to
     Gnuplot and right before the plot command is sent.  Any valid
     gnuplot commands may be used.  Multiple commands should be
     separated with a semi-colon.  See also ‘gnuplot_preamble’.

 -- Plot option: gnuplot_default_term_command
     [gnuplot_default_term_command, <command>]

     The gnuplot command to set the terminal type for the default
     terminal.  It this option is not set, the command used will be:
     ‘"set term wxt size 640,480 font \",12\"; set term pop"’.

 -- Plot option: gnuplot_dumb_term_command
     [gnuplot_dumb_term_command, <command>]

     The gnuplot command to set the terminal type for the dumb terminal.
     It this option is not set, the command used will be: ‘"set term
     dumb 79 22"’, which makes the text output 79 characters by 22
     characters.

 -- Plot option: gnuplot_pdf_term_command [gnuplot_pdf_term_command,
          <command>]

     The gnuplot command to set the terminal type for the PDF terminal.
     If this option is not set, the command used will be: ‘"set term
     pdfcairo color solid lw 3 size 17.2 cm, 12.9 cm font \",18\""’.
     See the gnuplot documentation for more information.

 -- Plot option: gnuplot_png_term_command [gnuplot_png_term_command,
          <command>]

     The gnuplot command to set the terminal type for the PNG terminal.
     If this option is not set, the command used will be: ‘"set term
     pngcairo font \",12\""’.  See the gnuplot documentation for more
     information.

 -- Plot option: gnuplot_ps_term_command [gnuplot_ps_term_command,
          <command>]

     The gnuplot command to set the terminal type for the PostScript
     terminal.  If this option is not set, the command used will be:
     ‘"set term postscript eps color solid lw 2 size 16.4 cm, 12.3 cm
     font \",24\""’.  See the gnuplot documentation for ‘set term
     postscript’ for more information.

 -- Plot option: gnuplot_strings [gnuplot_strings, <value>]

     With a value of ‘true’, all strings used in labels and titles will
     be interpreted by gnuplot as “enhanced” text, if the terminal being
     used supports it.  In enhanced mode, some characters such as ^ and
     _ are not printed, but interpreted as formatting characters.  For a
     list of the formatting characters and their meaning, see the
     documentation for enhanced in Gnuplot.  The default value for this
     option is ‘false’, which will not treat any characters as
     formatting characters.

 -- Plot option: gnuplot_svg_term_command [gnuplot_svg_term_command,
          <command>]

     The gnuplot command to set the terminal type for the SVG terminal.
     If this option is not set, the command used will be: ‘"set term svg
     font \",14\""’.  See the gnuplot documentation for more
     information.

 -- Plot option: gnuplot_curve_titles

     This is an obsolete option that has been replaced by ‘legend’
     described above.

 -- Plot option: gnuplot_curve_styles

     This is an obsolete option that has been replaced by ‘style’.


File: maxima.info,  Node: Gnuplot_pipes Format Functions,  Prev: Gnuplot Options,  Up: Plotting

8.6 Gnuplot_pipes Format Functions
==================================

 -- Function: gnuplot_start ()

     Opens the pipe to gnuplot used for plotting with the
     ‘gnuplot_pipes’ format.  Is not necessary to manually open the pipe
     before plotting.

 -- Function: gnuplot_close ()

     Closes the pipe to gnuplot which is used with the ‘gnuplot_pipes’
     format.

 -- Function: gnuplot_send (<s>)

     Sends the command <s> to the gnuplot pipe.  If that pipe is not
     currently opened, it will be opened before sending the command.
     <s> must be a string.

 -- Function: gnuplot_restart ()

     Closes the pipe to gnuplot which is used with the ‘gnuplot_pipes’
     format and opens a new pipe.

 -- Function: gnuplot_replot
          gnuplot_replot ()
          gnuplot_replot (<s>)

     Updates the gnuplot window.  If ‘gnuplot_replot’ is called with a
     gnuplot command in a string <s>, then ‘s’ is sent to gnuplot before
     reploting the window.

 -- Function: gnuplot_reset ()

     Resets the state of gnuplot used with the ‘gnuplot_pipes’ format.
     To update the gnuplot window call ‘gnuplot_replot’ after
     ‘gnuplot_reset’.


File: maxima.info,  Node: Ввод и вывод,  Next: Контексты,  Prev: Plotting,  Up: Top

9 Ввод и вывод
**************

* Menu:

* Комментарии::
* Файлы::                       
* Функции и переменные для ввода и вывода::


File: maxima.info,  Node: Комментарии,  Next: Файлы,  Prev: Ввод и вывод,  Up: Ввод и вывод

9.1 Комментарии
===============

В Maxima любой текст, расположенный между ‘/*’ и ‘*/’, является
комментарием.

   Анализатор Maxima обрабатывает комментарии как пробелы, чтобы проще
было различать лексемы во входном потоке, комментарий всегда завершает
лексему.  Следующий ввод ‘a/* foo */b’ содержит две лексемы ‘a’ и ‘b’, а
не одну ‘ab’.  Во всех остальных случаях комментарии игнорируются, что
бы в них ни находилось.

   Комментарии могут иметь сколько угодно уровней вложенности.
Разделители ‘/*’ и ‘*/’ образуют соответствующие пары.  Количество
открывающих разделителей ‘/*’ должно быть равно количеству закрывающих
‘*/’.

   Примеры:

     (%i1) /* aa is a variable of interest */  aa : 1234;
     (%o1)                         1234
     (%i2) /* Value of bb depends on aa */  bb : aa^2;
     (%o2)                        1522756
     (%i3) /* User-defined infix operator */  infix ("b");
     (%o3)                           b
     (%i4) /* Parses same as a b c, not abc */  a/* foo */b/* bar */c;
     (%o4)                         a b c
     (%i5) /* Comments /* can be nested /* to any depth */ */ */  1 + xyz;
     (%o5)                        xyz + 1


File: maxima.info,  Node: Файлы,  Next: Функции и переменные для ввода и вывода,  Prev: Комментарии,  Up: Ввод и вывод

9.2 Файлы
=========

Файл – это область на определенном запоминающем устройстве, содержащая
данные или текст.  Файлы на дисках как-бы группируются в "директории",
которые являются просто списками файлов.  Для работы с файлами
существуют следующие команды: ‘save’, ‘load’,

   ‘loadfile’, ‘stringout’, ‘batch’, ‘demo’, ‘writefile’, ‘closefile’ и
‘appendfile’.


File: maxima.info,  Node: Функции и переменные для ввода и вывода,  Prev: Файлы,  Up: Ввод и вывод

9.3 Функции и переменные для ввода и вывода
===========================================

 -- Системная переменная: __
     ‘__’ - введенное выражение, обрабатываемое в данный момент.  То
     есть, пока вычисляется <expr>, ‘__’ равно <expr>.

     Введенное выражение присваивается переменной ‘__’ до упрощения или
     вычисления.  Однако, значение ‘__’ упрощается (но не вычисляется)
     во время вывода.

     ‘__’ распознается функциями ‘batch’ и ‘load’.  В файле,
     обрабатываемом с помощью ‘batch’, ‘__’ означает то же самое, что и
     в режиме диалога.  Когда файл обрабатывается функцией ‘load’, ‘__’
     имеет значения последнего, введенного в режиме диалога или пакетном
     файле, выражения.  ‘__’ не принимает значения выражений, которые
     вводятся в обрабатываемом файле.  В частности, если ‘load
     (<filename>)’ вызывается в режиме диалога, то во время выполнения
     файла ‘__’ имеет значение ‘load(<filename>)’.

     См.  также ‘_’ и ‘%’.

     Примеры:

          (%i1) print ("I was called as", __);
          I was called as print(I was called as, __)
          (%o1)              print(I was called as, __)
          (%i2) foo (__);
          (%o2)                     foo(foo(__))
          (%i3) g (x) := (print ("Current input expression =", __), 0);
          (%o3) g(x) := (print("Current input expression =", __), 0)
          (%i4) [aa : 1, bb : 2, cc : 3];
          (%o4)                       [1, 2, 3]
          (%i5) (aa + bb + cc)/(dd + ee + g(x));
                                      cc + bb + aa
          Current input expression = --------------
                                     g(x) + ee + dd
                                          6
          (%o5)                        -------
                                       ee + dd

 -- Системная переменная: _

     ‘_’ - самое последнее из введенных выражений (таких как ‘%i1’,
     ‘%i2’, ‘%i3’, ...).

     Введенное выражение присваивается переменной ‘_’ до упрощения или
     вычисления.  Однако, это значение упрощается (но не вычисляется) во
     время вывода.

     ‘_’ обрабатывается функциями ‘batch’ и ‘load’.  Во время обработки
     файла функцией ‘batch’ переменная ‘_’ означает то же, что и в
     режиме диалога.  Когда файл обрабатывается функцией ‘load’,
     значение переменной ‘_’ принимает последнее вычисленное выражение,
     которое было введено в диалоговом режиме или пакетном файле.
     Выражения, вводимые в обрабатываемом файле, не присваиваются
     переменной ‘_’.

     См.  также ‘__’ и ‘%’.

     Примеры:

          (%i1) 13 + 29;
          (%o1)                          42
          (%i2) :lisp $_
          ((MPLUS) 13 29)
          (%i2) _;
          (%o2)                          42
          (%i3) sin (%pi/2);
          (%o3)                           1
          (%i4) :lisp $_
          ((%SIN) ((MQUOTIENT) $%PI 2))
          (%i4) _;
          (%o4)                           1
          (%i5) a: 13$
          (%i6) b: 29$
          (%i7) a + b;
          (%o7)                          42
          (%i8) :lisp $_
          ((MPLUS) $A $B)
          (%i8) _;
          (%o8)                         b + a
          (%i9) a + b;
          (%o9)                          42
          (%i10) ev (_);
          (%o10)                         42

 -- Системная переменная: %
     ‘%’ - вывод (‘%o1’, ‘%o2’, ‘o3’, ...)  последнего обработанного
     выражения, даже если он не выводится.

     ‘%’ обрабатывается командами ‘batch’ и ‘load’.  В файле,
     обрабатываемом командой ‘batch’, ‘%’ имеет то же значение, что и в
     режиме диалога.  В файле, обрабатываемого командой ‘load’, Значение
     ‘%’ принимает вывод последнего обработанного в диалоговом режиме
     выражения.  Переменной ‘%’ не присваивается вывод выражений
     обрабатываемого файла.

     См.  также ‘_’, ‘%%’ и ‘%th’.

 -- Системная переменная: %%
     В составных выражениях таких как ‘block’, ‘lambda’, или ‘(<s_1>,
     ..., <s_n>)’, ‘%%’ - значение предыдущего утверждения.  К примеру
     выражения,

          block (integrate (x^5, x), ev (%%, x=2) - ev (%%, x=1));
          block ([prev], prev: integrate (x^5, x),
                         ev (prev, x=2) - ev (prev, x=1));

     дадут один и тот же результат, то есть ‘21/2’.

     Составное выражение может быть частью другого составного выражения.
     И в случае простого утверждения, и в случае, когда утверждение
     является составным выражением, ‘%%’ принимает значение предыдущего
     утверждения.  К примеру,

          block (block (a^n, %%*42), %%/6)

     выдаст ‘7*a^n’.

     Внутри составного утверждения, значение ‘%%’ можно проверить в
     диалоге команды ‘break’.  К примеру, следующее выражение

          block (a: 42, break ())$

     открывает диалог, в котором результатом ввода ‘%%;’ будет ‘42’.

     В первом утверждении составного выражения или вне составного
     выражения переменная ‘%%’ не определена.

     Переменная ‘%%’ распознается функциями ‘batch’ и ‘load’, и имеет то
     же значение, что и в режиме диалога.

     См.  также ‘%’.

 -- Управляющая переменная: %edispflag
     Значение по умолчанию: ‘false’

     Когда ‘%edispflag’ установлена равной ‘true’, Maxima отображает
     ‘%e’ отрицательной степени.  К примеру, ‘%e^-x’ отображается как
     ‘1/%e^x’.

 -- Функция: %th (<i>)
     Значение <i>-го предыдущего вывода.  То есть, если следующим
     вычисленным выражением будет вывод с номером <n>, то ‘%th (<m>)’
     примет значение вывода с номером (<n> - <m>).

     ‘%th’ полезна в пакетных ‘batch’-файлах или в ссылках на группу
     выведенных выражений.  К примеру,

          block (s: 0, for i:1 thru 10 do s: s + %th (i))$

     присвоит переменной ‘s’ сумму последних десяти выведенных
     выражений.

     ‘%th’ обрабатывается функциями ‘batch’ и ‘load’.  В файле,
     обрабатываемом функцией ‘batch’, ‘%th’ означает то же, что и в
     режиме диалога.  В файле, обрабатываемом командой ‘load’, ‘%th’
     ссылается на выведенные выражения, которые были вычислены
     последними в режиме диалога или пакетном файле.  ‘%th’ не ссылается
     на выражения, выводимые в процессе работы ‘load’.

     См.  также ‘%’.

 -- Специальный символ: ?
     Стоящий перед именем функции или переменной символ ‘?’ означает что
     это имя функции или переменной из Lisp, а не из Maxima.  К примеру,
     ‘?round’ означает Lisp-функцию ‘ROUND’.  См.  дополнительно *note
     Lisp и Maxima::.

     Запись ‘? word’ (вопросительный знак и следующее за ним слово
     разделены пробелом) эквивалентна записи ‘describe("word")’.
     Вопросительный знак должен находиться в начале строки ввода, иначе
     он не определится как запрос на документацию.

 -- Специальный символ: ??

     Запись ‘?? word’ (‘??’ и следующее за ним слово разделяются
     символом пробела) эквивалентна записи ‘descrive("word", inexact)’.

 -- Управляющая переменная: absboxchar
     Значение по умолчанию: ‘!’

     Символ ‘absboxchar’ используется для изображения знака модуля
     вокруг, выражений, занимающих по высоте больше одной строчки.

 -- Управляющая переменная: file_output_append
     Значение по умолчанию: ‘false’

     ‘file_output_append’ управляет тем, будет ли вывод в функции
     добавляться в конец или замещать содержимое выводимого файла.
     Когда ‘file_output_append’ равна ‘true’, такие функции добавляют
     вывод к файлу, иначе выводимый файл переписывается заново.

     Функции ‘save’, ‘strungout’ и ‘with_stdout’ учитывают
     ‘file_output_append’.  Остальные функции, которые записываю выход
     во внешние файлы, не учитывают ‘file_output_append’.  В частности,
     графические и транслирующие функции всегда замещает содержимое
     выводимого файла, а ‘tex’ и ‘strungout’ всегда дописываю в конец.

 -- Функция: appendfile (<filename>)
     Добавляет копию консольного вывода в <filename>.  ‘appendfile’
     работает так же как и ‘writefile’, но отличие в том, что если файл
     существует, он всегда дописывается.

     ‘closefile’ закрывает трансляцию в файл открытый функциями
     ‘appendfile’ или ‘writefile’.

 -- Функция: batch (<filename>)
     Считывает выражения Maxima из <filename>, и обрабатывает их.
     ‘batch’ ищет <filename> в директориях списка ‘file_search_maxima’.
     См.  ‘file_search’.

     <filename> содержит последовательность выражений Maxima,
     завершающихся символами ‘;’ или ‘$’.  Специальные переменная ‘%’ и
     функция ‘%th’ ссылаются на предыдущие результаты внутри файла.
     Файл может включать конструкции ‘:lisp’.  Символы пробела,
     табуляции и новой строки в файле игнорируются.  Подходящий входной
     файл может быть создан при помощи текстового редактора или функцией
     ‘stringout’.

     ‘batch’ считывает каждое входящее выражение из <filename>,
     отображает его ввод в консоли, вычисляет соответствующее выходящее
     выражение и выводит его.  Входящим выражениям присваиваются входные
     метки, а выходящим – выходные.  ‘batch’ вычисляет все входящие
     выражения файла до тех пор пока в них не встретится ошибка.  Если
     запрашивается пользовательский ввод (к примеру, командами ‘asksign’
     или ‘askinteger’), выполнение ‘batch’ останавливается для сбора
     требуемого ввода и затем продолжается.

     Возможна остановка ‘batch’ нажатием ‘control-C’ в консоли.  Эффект
     нажатия ‘control-C’ зависит от реализации лежащего в основе Lisp.

     ‘batch’ может использоваться в различных целях.  Для хранения
     рабочих командных строк, дающих возможность проводить демонстрации
     без ошибок, или может помочь организовать работу над решением
     сложных задач.

     ‘batch’ вычисляет свой аргумент.  ‘batch’ не возвращает значений.

     См.  также ‘load’, ‘batchload’ и ‘demo’.

 -- Функция: batchload (<filename>)
     Считывает выражения Maxima из <filename> и вычисляет их, не
     отображая входные и выходные выражения и не присваивая ссылок
     выходным выражениям.  Однако, печатаемый вывод (такой, какой
     производят команды ‘print’ или ‘describe’) отображается.

     Специальная переменная ‘%’ и функция ‘%th’ ссылается на предыдущие
     результаты из режима диалога, но не на результаты внутри файла.
     Файл не может включать конструкции ‘:lisp’.

     ‘batchload’ возвращает путь к <filename> в виде строки.
     ‘batchload’ вычисляет свой аргумент.

     См.  также ‘batch’ и ‘load’.

 -- Функция: closefile ()
     Закрывает запись в файл, открытую командой ‘writefile’ или
     ‘appendfile’.

 -- Функция: collapse (<expr>)
     Сворачивает выражение <expr> делая все его общие (т.е.  равные)
     ссылающимися на одни ячейки памяти, тем самым сохраняя память.
     Функция (‘collapse’ используется командой ‘optimize’.  Таким
     образом, вызов ‘collapse’ может быть полезным до выгрузки в ‘save’
     файл.  Можно свернуть несколько выражений вместе используя команду
     ‘collapse ([<expr_1>, ..., <expr_n>])’.  Аналогично, можно свернуть
     элементы массива ‘A’ при помощи команды ‘collapse (listarray
     ('A))’.

 -- Функция: concat (<arg_1>, <arg_2>, ...)
     Сцепляет свои аргументы.  Аргументы должны быть атомами.
     Возвращаемое значение является символом, если первый аргумент –
     символ, и строкой в противном случае.

     ‘concat’ вычисляет свои аргументы.  Одиночная кавычка ‘'’
     предотвращает вычисление.

          (%i1) y: 7$
          (%i2) z: 88$
          (%i3) concat (y, z/2);
          (%o3)                          744
          (%i4) concat ('y, z/2);
          (%o4)                          y44

     Символу, полученному с помощью ‘concat’, можно присваивать значения
     и использовать его в выражениях.  ‘::’ (двойное двоеточие) –
     оператор присваивания, который вычисляет свой левый операнд.

          (%i5) a: concat ('y, z/2);
          (%o5)                          y44
          (%i6) a:: 123;
          (%o6)                          123
          (%i7) y44;
          (%o7)                          123
          (%i8) b^a;
                                         y44
          (%o8)                         b
          (%i9) %, numer;
                                         123
          (%o9)                         b

     Заметьте, что несмотря на то, что ‘concat (1, 2)’ выглядит как
     число, результат является строкой.

          (%i10) concat (1, 2) + 3;
          (%o10)                       12 + 3

 -- Функция: sconcat (<arg_1>, <arg_2>, ...)

     Сцепляет аргументы в строки.  В отличии от ‘concat’, аргументы не
     обязаны быть атомами.

          (%i1) sconcat ("xx[", 3, "]:", expand ((x+y)^3));
          (%o1)               xx[3]:y^3+3*x*y^2+3*x^2*y+x^3

 -- Функция: disp (<expr_1>, <expr_2>, ...)
     то же что и ‘display’, но отличается тем что значение аргументов
     отображаются без выражений.  Это полезно для сложных аргументов, у
     которых нет имени или в случае, когда интерес представляет только
     значение без имени.

 -- Функция: dispcon (<tensor_1>, <tensor_2>, ...)
 -- Функция: dispcon (all)
     Отображает ограничения аргументов, наложенные на них командой
     ‘defcon’.  ‘dispcon (all)’ отображает все ограничения, которые были
     заданы.

 -- Функция: display (<expr_1>, <expr_2>, ...)
     Отображает равенства, выравненные по центру.  Левыми частями
     равенств являются не вычисленные выражения <expr_i>, a правыми – их
     значения.  Эта функция полезна в блоках и конструкциях ‘for’ для
     вывода промежуточных результатов.  Аргументы ‘display’ обычно
     являются атомами, переменными с индексом, или вызовами функций.
     См.  также ‘disp’.

          (%i1) display(B[1,2]);
                                                2
                                   B     = X - X
                                    1, 2
          (%o1)                            done

 -- Управляющая переменная: display2d
     Значение по умолчанию: ‘true’

     Когда ‘display2d’ равна ‘false’, консольный вывод производится в
     строковой (одномерной) форме, а не в наглядной (двумерной).

 -- Управляющая переменная: display_format_internal
     Значение по умолчанию: ‘false’

     Когда ‘display_format_internal’ равна ‘true’, выражения
     отображаются без преобразования, которое "прячет" внутреннее
     математическое представление.  Тогда вывод соответствует результату
     функции ‘inpart’, а не ‘part’.

     Примеры:

          User     part       inpart
          a-b;      a - b     a + (- 1) b

                     a            - 1
          a/b;       -         a b
                     b
                                 1/2
          sqrt(x);   sqrt(x)    x

                    4 X        4
          X*4/3;    ---        - X
                     3         3

 -- Функция: dispterms (<expr>)
     Выводит друг под другом части <expr>.  Первым отображается оператор
     выражения <expr>, затем каждое слагаемое суммы, множители
     произведения или части более общего выражения отображаются
     отдельно.  Это полезно, когда <expr> слишком большое для иных
     способов отображения.  К примеру, если ‘P1’, ‘P2’, ...  – очень
     большие выражения, то программе может не хватить памяти при попытке
     отобразить ‘P1 + P2 + ...’ как единое целое.  Однако, ‘dispterms
     (P1 + P2 + ...)’ отображает ‘P1’, затем ниже ‘P2’ и т.  д.  Если не
     использовать ‘dispterms’, когда показательное выражение слишком
     широко, для отображения в виде ‘A^B’, то оно выводится в виде ‘expt
     (A, B)’ (или ‘ncexpt (A, B)’ в случае ‘A^^B’).

 -- Управляющая переменная: error_size
     Значение по умолчанию: 10

     ‘error_size’ изменяет сообщения об ошибках, в зависимости от
     размера выражения, которое появляется в нем.  Если размер выражения
     (определенный с помощью Lisp-функции ‘ERROR-SIZE’) больше чем
     ‘error_size’, выражение замещается символом, а символу
     присваивается выражение.  Символы берутся из списка ‘error_syms’.

     В противном случае, когда выражение меньше чем ‘error_size’, оно и
     выводится в сообщении.

     См.  также ‘error’ и ‘error_syms’.

     Пример:

     ‘ERROR-SIZE’ задает размер ‘U’ равным 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);

 -- Управляющая переменная: error_syms
     Значение по умолчанию: ‘[errexp1, errexp2, errexp3]’

     В сообщениях об ошибках, выражения большие чем ‘error_size’
     заменяются символами и присваиваются этим символам.  Символы
     берутся из списка ‘error_syms’.  Первое слишком большое выражения
     заменяется символом ‘error_syms[1]’, второе символом
     ‘error_syms[2]’ и так далее.

     Если слишком больших выражений больше чем элементов в ‘error_syms’,
     то символы генерируются автоматически, ‘n’-ный символ равен ‘concat
     ('errexp, <n>)’.

     См.  также ‘error’ и ‘error_size’.

 -- Функция: expt (<a>, <b>)
     Если показательное выражение слишком широко для отображения в виде
     ‘<a>^<b>’), оно выводится в виде ‘expt (<a>, <b>)’ (или ‘ncexpt
     (<a>, <b>)’ в случае ‘<a>^^<b>’).

     ‘expt’ и ‘ncexpt’ не распознаются при вводе.

 -- Управляющая переменная: exptdispflag
     Значение по умолчанию: ‘true’

     Когда ‘exptdispflag’ равна ‘true’, Maxima отображает выражения с
     отрицательными степенями в виде дробей, например ‘X^(-1)’ в виде
     ‘1/X’.

 -- Функция: filename_merge (<path>, <filename>)
     Составляет путь из <path> и <filename>.  Если последняя часть пути
     <path> имеет форму ‘###.<something>’, эта часть заменяется на
     ‘<filename>.<something>’.  В противном случае последняя часть
     заменяется на <filename>.

     Результатом является объект пути Lisp.

 -- Функция: file_search (<filename>)
 -- Функция: file_search (<filename>, <pathlist>)

     ‘file_search’ ищет файл <filename> и возвращает путь к этому файлу
     (в виде строки), если может его найти, иначе возвращает ‘false’.
     ‘file_search (<filename>)’ ищет в определенных по умолчанию
     каталогах для поиска, которые указаны в переменных
     ‘file_search_maxima’, ‘file_search_lisp’ и ‘file_search_demo’.

     Перед попыткой сопоставить имя с шаблонами поиска файлов.
     ‘file_search’ первым делом проверяет существование искомого файла.
     См.  ‘file_search_maxima’ о шаблонах поиска файла.

     Аргумент <filename> может быть как путем с именем, так и просто
     именем файла.  Если каталог включен в пути поиска вместе с
     поисковым шаблоном файла, то <filename> может быть именем без
     расширения.  В примере

          file_search ("/home/wfs/special/zeta.mac");
          file_search ("zeta.mac");
          file_search ("zeta");

     будет найден один и тот же файл, если он существует и
     ‘/home/wfs/special/###.mac’ включен в ‘file_search_maxima’.

     ‘file_search (<filename>, <pathlist>)’ осуществляет поиск в
     каталогах, заданных переменной <pathlist>, которая представляет из
     себя список строк.  Аргумент <pathlist> замещает каталоги поиска,
     определенные по умолчанию, так если дан список путей, ‘file_search’
     ищет только в заданных там и не ищет в путях по умолчанию.  Даже
     если <pathlist> содержит только один каталог, <pathlist> должен
     быть задан, как список из одного элемента.

     Пользователь может изменять пути, определенные по умолчанию.  См.
     ‘file_search_maxima’.

     ‘file_search’ используется функцией ‘load’, шаблоны поиска файлов
     берутся из ‘file_search_maxima’ и ‘file_search_lisp’.

 -- Управляющая переменная: file_search_maxima
 -- Управляющая переменная: file_search_lisp
 -- Управляющая переменная: file_search_demo
     Эти переменные задают списки каталогов, в которых производят поиск
     функции ‘load’, ‘demo’ и некоторые другие функции Maxima.  По
     умолчанию в них заданы различные каталоги из путей установки
     Maxima.

     Пользователь может изменить эти переменные, удалить значения по
     умолчанию или добавить дополнительные каталоги.  Например,

          file_search_maxima: ["/usr/local/foo/###.mac",
              "/usr/local/bar/###.mac"]$

     удаляет начальные директории списка ‘file_search_maxima’, в то
     время как

          file_search_maxima: append (file_search_maxima,
              ["/usr/local/foo/###.mac", "/usr/local/bar/###.mac"])$

     добавляет две дополнительные директории.  Иногда удобно разместить
     такие выражения в файле ‘maxima-init.mac’, чтобы путь поиска файла
     назначался автоматически при запуске Maxima.

     При помощи шаблонов поиска файлов можно определить несколько
     расширений файлов и несколько путей.  Строка ‘###’ заменяется
     запрашиваемым именем, в то время как список разделенных запятыми
     имен, заключенный в фигурные скобки, ‘{foo,bar,baz}’ раскрывается в
     множество строк.  В качестве примера предположим, что искомое имя –
     ‘neumann’, тогда

          "/home/{wfs,gcj}/###.{lisp,mac}"

     раскроется в ‘/home/wfs/neumann.lisp’, ‘/home/gcj/neumann.lisp’,
     ‘/home/wfs/neumann.mac’ и ‘/home/gcj/neumann.mac’.

 -- Функция: file_type (<filename>)
     Возвращает предположение о содержимом <filename>, на основе его
     расширения.  <filename> не должен ссылаться на существующий файл,
     не происходит попыток открыть файл и проверить содержимое.

     Возвращаемое значение является одним из символов: ‘object’, ‘lisp’
     или ‘maxima’.  Если расширение начинается на ‘m’ или ‘d’,
     ‘file_type’ возвращается ‘maxima’.  Если расширение начинается на
     ‘l’, ‘file_type’ возвращается ‘lisp’.  Если ни один из
     перечисленных вариантов, то ‘file_type’ возвращается ‘object’.

 -- Функция: grind (<expr>)
 -- Управляющая переменная: grind
     Функция ‘grind’ выводит <expr> в консоль в форме подходящем для
     ввода в Maxima.  ‘grind’ всегда возвращает ‘done’.

     Когда <expr> является именем функции или макрокоманды, ‘grind’
     печатает определение функции или макрокоманды вместо просто имени.

     См.  также ‘string’, которая возвращает строку, а не печатает
     вывод.  ‘grind’ пытается печатать выражение способом, который
     делает его проще для чтения, чем вывод команды ‘string’.

     Когда переменная ‘grind’ равна ‘true’, вывод ‘string’ и ‘stringout’
     имеет тот же вид, что и вывод ‘grind’.  В противном случае
     специального форматирования вывода этих функций не производится.
     По умолчанию значение переменной ‘grind’ равно ‘false’.

     ‘grind’ может так же быть задана как аргумент ‘playback’.  Когда
     ‘grind’ задана, ‘playback’ печатает входное выражение в таком же
     виде как функция ‘grind’.  В противном случае специального
     форматирования вывода не производится.

     ‘grind’ вычисляет свой аргумент.

     Примеры:

          (%i1) aa + 1729;
          (%o1)                       aa + 1729
          (%i2) grind (%);
          aa+1729$
          (%o2)                         done
          (%i3) [aa, 1729, aa + 1729];
          (%o3)                 [aa, 1729, aa + 1729]
          (%i4) grind (%);
          [aa,1729,aa+1729]$
          (%o4)                         done
          (%i5) matrix ([aa, 17], [29, bb]);
                                     [ aa  17 ]
          (%o5)                      [        ]
                                     [ 29  bb ]
          (%i6) grind (%);
          matrix([aa,17],[29,bb])$
          (%o6)                         done
          (%i7) set (aa, 17, 29, bb);
          (%o7)                   {17, 29, aa, bb}
          (%i8) grind (%);
          {17,29,aa,bb}$
          (%o8)                         done
          (%i9) exp (aa / (bb + 17)^29);
                                          aa
                                      -----------
                                               29
                                      (bb + 17)
          (%o9)                     %e
          (%i10) grind (%);
          %e^(aa/(bb+17)^29)$
          (%o10)                        done
          (%i11) expr: expand ((aa + bb)^10);
                   10           9        2   8         3   7         4   6
          (%o11) bb   + 10 aa bb  + 45 aa  bb  + 120 aa  bb  + 210 aa  bb
                   5   5         6   4         7   3        8   2
           + 252 aa  bb  + 210 aa  bb  + 120 aa  bb  + 45 aa  bb
                  9        10
           + 10 aa  bb + aa
          (%i12) grind (expr);
          bb^10+10*aa*bb^9+45*aa^2*bb^8+120*aa^3*bb^7+210*aa^4*bb^6
               +252*aa^5*bb^5+210*aa^6*bb^4+120*aa^7*bb^3+45*aa^8*bb^2
               +10*aa^9*bb+aa^10$
          (%o12)                        done
          (%i13) string (expr);
          (%o13) bb^10+10*aa*bb^9+45*aa^2*bb^8+120*aa^3*bb^7+210*aa^4*bb^6\
          +252*aa^5*bb^5+210*aa^6*bb^4+120*aa^7*bb^3+45*aa^8*bb^2+10*aa^9*\
          bb+aa^10
          (%i14) cholesky (A):= block ([n : length (A), L : copymatrix (A),
            p : makelist (0, i, 1, length (A))], for i thru n do
            for j : i thru n do
            (x : L[i, j], x : x - sum (L[j, k] * L[i, k], k, 1, i - 1),
            if i = j then p[i] : 1 / sqrt(x) else L[j, i] : x * p[i]),
            for i thru n do L[i, i] : 1 / p[i],
            for i thru n do for j : i + 1 thru n do L[i, j] : 0, L)$
          (%i15) grind (cholesky);
          cholesky(A):=block(
                   [n:length(A),L:copymatrix(A),
                    p:makelist(0,i,1,length(A))],
                   for i thru n do
                       (for j from i thru n do
                            (x:L[i,j],x:x-sum(L[j,k]*L[i,k],k,1,i-1),
                             if i = j then p[i]:1/sqrt(x)
                                 else L[j,i]:x*p[i])),
                   for i thru n do L[i,i]:1/p[i],
                   for i thru n do (for j from i+1 thru n do L[i,j]:0),L)$
          (%o15)                        done
          (%i16) string (fundef (cholesky));
          (%o16) cholesky(A):=block([n:length(A),L:copymatrix(A),p:makelis\
          t(0,i,1,length(A))],for i thru n do (for j from i thru n do (x:L\
          [i,j],x:x-sum(L[j,k]*L[i,k],k,1,i-1),if i = j then p[i]:1/sqrt(x\
          ) else L[j,i]:x*p[i])),for i thru n do L[i,i]:1/p[i],for i thru \
          n do (for j from i+1 thru n do L[i,j]:0),L)

 -- Управляющая переменная: ibase
     Значение по умолчанию: 10

     Целые вводимые в Maxima распознаются с учетом основания системы
     счисления ‘ibase’.

     Переменной ‘ibase’ может быть присвоено значение между 2 и 35 (в
     десятичной), включительно.  Когда ‘ibase’ больше чем 10, в состав
     цифр входят десятичные цифры от 0 до 9 и заглавные буквы алфавита
     A, B, C, ..., по мере необходимости.

     Цифры для основания 35, наибольшего возможного, включают цифры от 0
     до 9 и буквы от A до Z.

     См.  также ‘obase’.

 -- Управляющая переменная: inchar
     Значение по умолчанию: ‘%i’

     ‘inchar’ – префикс перед метками выражений, вводимых пользователем.
     Maxima автоматически генерирует ссылку для каждого входного
     выражения, соединяя ‘inchar’ и ‘linenum’.  Переменной ‘inchar’
     может быть присвоена любая строка или обозначение, не обязательно
     состоящее из одной буквы.

          (%i1) inchar: "input";
          (%o1)                                input
          (input1) expand ((a+b)^3);
                                      3        2      2      3
          (%o1)                      b  + 3 a b  + 3 a  b + a
          (input2)

     См.  также ‘labels’.

 -- Функция: ldisp (<expr_1>, ..., <expr_n>)
     Отображает выражения <expr_1>, ..., <expr_n> в консоли как в
     печатном выводе.  ‘ldisp’ присваивает метки промежуточных выражений
     для каждого аргумента и возвращает список меток.

     См.  также ‘disp’.

          (%i1) e: (a+b)^3;
                                             3
          (%o1)                       (b + a)
          (%i2) f: expand (e);
                               3        2      2      3
          (%o2)               b  + 3 a b  + 3 a  b + a
          (%i3) ldisp (e, f);
                                             3
          (%t3)                       (b + a)

                               3        2      2      3
          (%t4)               b  + 3 a b  + 3 a  b + a

          (%o4)                      [%t3, %t4]
          (%i4) %t3;
                                             3
          (%o4)                       (b + a)
          (%i5) %t4;
                               3        2      2      3
          (%o5)               b  + 3 a b  + 3 a  b + a

 -- Функция: ldisplay (<expr_1>, ..., <expr_n>)
     Отображает выражения <expr_1>, ..., <expr_n> в консоли как при
     выводе.  Каждое выражение печатается в виде равенства ‘lhs = rhs’,
     в котором ‘lhs’ – один из аргументов функции ‘ldisplay’, а ‘rhs’ –
     его значение.  Обычно каждый аргумент – переменная.  ‘ldisp’
     присваивает метки промежуточных выражений каждому равенству и
     возвращает список меток.

     См.  также ‘display’.

          (%i1) e: (a+b)^3;
                                             3
          (%o1)                       (b + a)
          (%i2) f: expand (e);
                               3        2      2      3
          (%o2)               b  + 3 a b  + 3 a  b + a
          (%i3) ldisplay (e, f);
                                               3
          (%t3)                     e = (b + a)

                                 3        2      2      3
          (%t4)             f = b  + 3 a b  + 3 a  b + a

          (%o4)                      [%t3, %t4]
          (%i4) %t3;
                                               3
          (%o4)                     e = (b + a)
          (%i5) %t4;
                                 3        2      2      3
          (%o5)             f = b  + 3 a b  + 3 a  b + a

 -- Управляющая переменная: linechar
     Значение по умолчанию: ‘%t’

     ‘linechar’ – префикс меток промежуточных выражений, генерируемых
     Maxima.  Maxima генерирует метки для каждого промежуточного
     выражения (если оно отображается), соединяя ‘linechar’ и ‘linenum’.
     Переменной ‘linechar’ может быть присвоена любая строка или символ,
     не обязательно одиночная буква.

     Промежуточный выражения могут отображаться, а могут и не
     отображаться.  См.  ‘programmode’ и ‘labels’.

 -- Управляющая переменная: linel
     Значение по умолчанию: 79

     ‘linel’ – ширина консоли (в символах) для вывода выражений.
     Пользователь может задать любое значение ‘linel’, хотя очень
     маленькие или очень большие значения могут оказаться неудобными.
     Текст выводимый встроенными функциями Maxima, такой как сообщения
     об ошибках и вывод ‘describe’, не зависит от ‘linel’.

 -- Управляющая переменная: lispdisp
     Значение по умолчанию: ‘false’

     Когда ‘lispdisp’ равна ‘true’, Lisp символы отображаются с
     вопросительным знаком ‘?’ перед ними.  В противном случае Lisp
     символы отображаются без знака.

     Примеры:

          (%i1) lispdisp: false$
          (%i2) ?foo + ?bar;
          (%o2)                       foo + bar
          (%i3) lispdisp: true$
          (%i4) ?foo + ?bar;
          (%o4)                      ?foo + ?bar

 -- Функция: load (<filename>)
     Вычисляет выражения в <filename>, тем самым загружая переменные,
     функции и другие объекты в Maxima.  Значения любых существовавших
     объектов заменяются связями, полученными из <filename>.  Для поиска
     файла ‘load’ вызывает ‘file_search’, пути поиска берутся из
     ‘file_search_maxima’ и ‘file_search_lisp’.  Если ‘load’ выполнена
     успешно, то возвращается имя файла, иначе печатается сообщение об
     ошибке.

     ‘load’ работает с равным успехом как для Lisp, так и для Maxima
     программ.  Файлы, созданные командами ‘save’, ‘translate_file’ и
     ‘compile_file’, которые создают код Lisp, и ‘stringout’, которая
     создает код Maxima, могут быть обработаны функцией ‘load’.  ‘load’
     вызывает ‘loadfile’ для загрузки Lisp файлов и ‘batchload’ для
     загрузки Maxima файлов.

     ‘load’ не распознает конструкции ‘:lisp’ в файлах Maxima, и во
     время обработки <filename>, глобальные переменные ‘_’, ‘__’, ‘%’ и
     ‘%th’ имеют те связи, которые были у них в момент вызова ‘load’.

     См.  также ‘loadfile’, ‘batch’, ‘batchload’ и ‘demo’.  ‘batch’,
     ‘batchload’ и ‘demo’ выполняют Maxima файлы.

     См.  ‘file_search’ для более подробного ознакомления с механизмом
     поиска файлов.

     ‘load’ вычисляет свой аргумент.

 -- Функция: loadfile (<filename>)
     Вычисляет выражения Lisp в <filename>.  ‘loadfile’ не вызывает
     ‘file_search’, поэтому ‘filename’ должен включать расширение и
     информацию о пути, достаточную для поиска файла.

     ‘loadfile’ может обрабатывать файлы, созданные командами ‘save’,
     ‘translate_file’ и ‘compile_file’.  Возможно, удобнее использовать
     ‘load’ вместо ‘loadfile’.

 -- Управляющая переменная: loadprint
     Значение по умолчанию: ‘true’

     ‘loadprint’ управляет печатью сообщение после загрузки файла.

        • Если ‘loadprint’ равна ‘true’, сообщение всегда выводится.
        • Если ‘loadprint’ равна ‘'loadfile’, сообщение выводится только
          в случае, когда файл загружается функцией ‘loadfile’.
        • Когда ‘loadprint’ равна ‘'autoload’, сообщение выводится
          только если файл загружается автоматически.  См.
          ‘setup_autoload’.
        • Когда ‘loadprint’ равен ‘false’, сообщение не выводится.

 -- Управляющая переменная: obase
     Значение по умолчанию: 10

     ‘obase’ – основание системы счисления в которой Maxima отображает
     целые числа.

     Переменной ‘obase’ можно присвоить любое целое число между 2 и 35
     (десятичное), включительно.  Когда ‘obase’ больше десяти, цифрами
     являются десятичные цифры от 0 до 9 и заглавные буквы латинского
     алфавита A, B, C, ..., по мере необходимости.  Цифры системы с
     основанием 35, самым большим из допустимых, включают цифры от 0 до
     9 и буквы от A до Y.

     См.  также ‘ibase’.

 -- Управляющая переменная: outchar
     Значение по умолчанию: ‘%o’

     ‘outchar’ – это префикс меток для выражений, вычисленных системой
     Maxima.  Maxima автоматически генерирует метки для каждого
     вычисленного выражения, соединяя ‘outchar’ с ‘linenum’.  Переменной
     ‘outchar’ можно присвоить любую строку или символ, не обязательно
     одиночную букву.

          (%i1) outchar: "output";
          (output1)                           output
          (%i2) expand ((a+b)^3);
                                      3        2      2      3
          (output2)                  b  + 3 a b  + 3 a  b + a
          (%i3)

     См.  также ‘labels’.

 -- Управляющая переменная: packagefile
     Значение по умолчанию: ‘false’

     Разработчики, которые используют ‘save’ или ‘translate’, создавая
     пакеты (файлы) для использования другими, возможно захотят
     установить ‘packagefile: true’, чтобы при загрузке файла
     предотвратить занесение информации, кроме необходимой, в списки
     Maxima (такие как ‘values’, ‘functions’).  В этом случае содержимое
     пакета будет загружено не в виде пользовательских данных.  Заметим,
     что это не решает проблему возможного конфликта имен.  Также
     заметим, что переменная просто указывает на то, что выводится в
     пакетный файл.  Установка управляющей переменной в ‘true’ также
     полезна для создания инициализационных файлов Maxima.

 -- Управляющая переменная: pfeformat
     Значение по умолчанию: ‘false’

     Когда ‘pfeformat’ равна ‘true’, рациональная дробь отображается при
     помощи косой черты (прямого слэша).  Целочисленный знаменатель ‘n’
     отображается как множитель ‘1/n’.

          (%i1) pfeformat: false$
          (%i2) 2^16/7^3;
                                        65536
          (%o2)                         -----
                                         343
          (%i3) (a+b)/8;
                                        b + a
          (%o3)                         -----
                                          8
          (%i4) pfeformat: true$
          (%i5) 2^16/7^3;
          (%o5)                       65536/343
          (%i6) (a+b)/8;
          (%o6)                      1/8 (b + a)

 -- Функция: print (<expr_1>, ..., <expr_n>)
     Вычисляет и отображает <expr_1>, ..., <expr_n> одно за другим,
     слева направо, начиная с левого края экрана консоли.

     Функция ‘print’ возвращает значение своего последнего аргумента.
     ‘print’ не создает меток промежуточных выражений.

     См.  также ‘display’, ‘disp’, ‘ldisplay’ и ‘ldisp’.  Эти функции
     отображают по одному выражению на строку, в то время как ‘print’
     старается отобразить по два или больше выражений в каждой строке.

     Чтобы отобразить содержимое файла, см.  ‘printfile’.

          (%i1) r: print ("(a+b)^3 is", expand ((a+b)^3), "log (a^10/b) is",
                radcan (log (a^10/b)))$
                      3        2      2      3
          (a+b)^3 is b  + 3 a b  + 3 a  b + a  log (a^10/b) is

                                                        10 log(a) - log(b)
          (%i2) r;
          (%o2)                  10 log(a) - log(b)
          (%i3) disp ("(a+b)^3 is", expand ((a+b)^3), "log (a^10/b) is",
                radcan (log (a^10/b)))$
                                     (a+b)^3 is

                               3        2      2      3
                              b  + 3 a b  + 3 a  b + a

                                   log (a^10/b) is

                                 10 log(a) - log(b)

 -- Функция: printfile (<path>)

     Выводит файл с именем <path> на консоль.  Значение <path> может
     быть строкой или символом.  Если символ, то он преобразуется в
     строку.

     Если файл с именем <path> доступен в текущей директории, то он
     печатается на консоли.  В противном случае ‘printfile’ пытается
     найти файл добавляя <path> ко всем элементам ‘file_search_usage’
     при помощи ‘filename_merge’.

     ‘printfile’ возвращает <path>, если файл существует, и результат
     успешного поиска файла.

 -- Функция: tcl_output (<list>, <i0>, <skip>)
 -- Функция: tcl_output (<list>, <i0>)
 -- Функция: tcl_output ([<list_1>, ..., <list_n>], <i>)

     Выводит элементы списков заключенными в фигурные скобки ‘{ }’, в
     виде пригодном для использования в языке Tcl/Tk.

     ‘tcl_output (<list>, <i0>, <skip>)’ выводит элементы списка <list>
     с номерами <i0>, ‘<i0> + <skip>’, ‘<i0> + 2 <skip>’ и так далее.

     ‘tcl_output (<list>, <i0>)’ равнозначна ‘tcl_output (<list>, <i0>,
     2)’.

     ‘tcl_output ([<list_1>, ..., <list_n>], <i>)’ выводит <i>-ые
     элементы списков <list_1>, ..., <list_n>.

     Примеры:

          (%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
           }

 -- Функция: read (<expr_1>, ..., <expr_n>)
     Выводит <expr_1>, ..., <expr_n>, затем считывает одно выражение с
     консоли и возвращает вычисленное выражение.

     См.  также ‘readonly’.

          (%i1) foo: 42$
          (%i2) foo: read ("foo is", foo, " -- enter new value.")$
          foo is 42  -- enter new value.
          (a+b)^3;
          (%i3) foo;
                                               3
          (%o3)                         (b + a)

 -- Функция: readonly (<expr_1>, ..., <expr_n>)
     Выводит <expr_1>, ..., <expr_n>, затем считывает одно выражение с
     консоли и Возвращает его без вычисления.

          (%i1) aa: 7$
          (%i2) foo: readonly ("Enter an expression:");
          Enter an expression:
          2^aa;
                                            aa
          (%o2)                            2
          (%i3) foo: read ("Enter an expression:");
          Enter an expression:
          2^aa;
          (%o3)                            128

     См.  также ‘read’.

 -- Функция: reveal (<expr>, <depth>)
     Замещает части выражения <expr> заданного уровня вложенности
     <depth> кратким описанием.

        • Суммы и разности заменяются на ‘Sum(<n>)’, где <n> –
          количество слагаемых.
        • Произведения заменяются на ‘Product(<n>)’, где <n> –
          количество множителей.
        • Степени заменяются на ‘Expt’.
        • Дроби заменяются на ‘Quotient’.
        • Унарное отрицание заменяется на ‘Negterm’.

     Если <depth> больше или равен максимальному уровню вложенности в
     выражении <expr>, то ‘reveal (<expr>, <depth>)’ возвращает <expr>
     без изменений.

     ‘reveal’ вычисляет свои аргументы.  ‘reveal’ возвращает
     анализируемое выражение.

     Пример:

          (%i1) e: expand ((a - b)^2)/expand ((exp(a) + exp(b))^2);
                                    2            2
                                   b  - 2 a b + a
          (%o1)               -------------------------
                                  b + a     2 b     2 a
                              2 %e      + %e    + %e
          (%i2) reveal (e, 1);
          (%o2)                       Quotient
          (%i3) reveal (e, 2);
                                       Sum(3)
          (%o3)                        ------
                                       Sum(3)
          (%i4) reveal (e, 3);
                               Expt + Negterm + Expt
          (%o4)               ------------------------
                              Product(2) + Expt + Expt
          (%i5) reveal (e, 4);
                                 2                 2
                                b  - Product(3) + a
          (%o5)         ------------------------------------
                                   Product(2)     Product(2)
                        2 Expt + %e           + %e
          (%i6) reveal (e, 5);
                                   2            2
                                  b  - 2 a b + a
          (%o6)              --------------------------
                                 Sum(2)     2 b     2 a
                             2 %e       + %e    + %e
          (%i7) reveal (e, 6);
                                    2            2
                                   b  - 2 a b + a
          (%o7)               -------------------------
                                  b + a     2 b     2 a
                              2 %e      + %e    + %e

 -- Управляющая переменная: rmxchar
     Значение по умолчанию: ‘]’

     Правая сторона матриц изображается символами ‘rmxchar’.

     См.  также ‘lmxchar’.

 -- Функция: save (<filename>, <name_1>, <name_2>, <name_3>, ...)
 -- Функция: save (<filename>, values, functions, labels, ...)
 -- Функция: save (<filename>, [<m>, <n>])
 -- Функция: save (<filename>, <name_1>=<expr_1>, ...)
 -- Функция: save (<filename>, all)
 -- Функция: save (<filename>, <name_1>=<expr_1>, <name_2>=<expr_2>,
          ...)

     Сохраняет текущие значения аргументов <name_1>, <name_2>, <name_3>,
     ..., в <filename>.  Аргументами являются имена переменных, функций
     и прочих объектов.  Если имя не имеет значения или связанной с ним
     функцией, оно игнорируется.  ‘save’ возвращает <filename>.

     ‘save’ сохраняет данные в форме Lisp выражений.  Данные,
     сохраненные функцией ‘save’, можно загрузить при помощи ‘load
     (<filename>)’.

     Глобальная управляющая переменная ‘file_output_append’ управляет
     тем, будет ли информация добавлена к файлу, или файл будет
     переписан заново.  Когда ‘file_output_append’ равен ‘true’,
     происходит добавление, иначе ‘save’ переписывает файл вывода.  В
     обоих случаях ‘save’ создает файл, если он до этого не существовал.

     Особая форма ‘save (<filename>, values, functions, labels, ...)’
     сохраняет элементы перечисленные в списках ‘values’, ‘functions’,
     ‘labels’ и т.  д.  Возможны любые имена определенные в ‘infolist’.
     ‘values’ включает все определенные пользователем переменные.

     Особая форма ‘save (<filename>, [<m>, <n>])’ сохраняет значения
     входных и результирующих выражений с номерами от <m> до <n>.
     Заметим, что <m> и <n> должны быть буквальными целыми.  Входные и
     результирующие метки можно также записать одну за другой, например,
     ‘save ("foo.1", %i42, %o42)’.  ‘save (<filename>, labels)’
     сохраняет все входные и результирующие выражения.  Сохраненные
     выражения при загрузке заменяют существующие.

     Особая форма ‘save (<filename>, <name_1>=<expr_1>,
     <name_2>=<expr_2>, ...)’ сохраняет значения <expr_1>, <expr_2>, ...
     с именами <name_1>, <name_2>, ...  Эту форму полезно применять для
     входных и результирующих меток, например, ‘save ("foo.1",
     aa=%o88)’.  С правой стороны равенства в этой форме может стоять
     любое выражение, которое вычисляется.  Эта форма не вводит новые
     имена в текущий сеанс Maxima, только сохраняет их в <filename>.

     Эти особые формы и общую форму функции ‘save’ можно как угодно
     смешивать.  Например: ‘save (<filename>, aa, bb, cc=42, functions,
     [11, 17])’.

     Особая форма ‘save (<filename>, all)’ сохраняет текущее состояние
     Maxima, включая все определенные пользователем переменные, функции,
     массивы и т.  д., а также элементы, заданные автоматически.
     Сохраняемые элементы включают в себя системные переменные, такие
     как ‘file_search_maxima’ или ‘showtime’, если пользователь присвоил
     им новые значения.  См.  ‘myoptions’.

     ‘save’ вычисляет <filename>, все остальные аргументы не
     вычисляются.

 -- Управляющая переменная: savedef
     Значение по умолчанию: ‘true’

     Когда ‘savedef’ равно ‘true’, Maxima версия определенной
     пользователем функции защищается, при ее трансляции.  Это позволяет
     отобразить ее определение при помощи ‘dispfun’ и дает возможность
     редактировать ее.

     Когда ‘savedef’ равна ‘false’, имена транслируемых функций
     удаляются из списка ‘functions’.

 -- Функция: show (<expr>)
     При отображении ‘expr’, у индексированных объектов ковариантные
     индексы показываются как нижние, а контравариантные – как верхние.
     Индексы дифференцирования отображаются нижними и отделяются от
     ковариантных запятой.

 -- Функция: showratvars (<expr>)
     Возвращает список переменных в каноническом рациональном выражении
     ‘expr’.

     См.  также ‘ratvars’.

 -- Управляющая переменная: stardisp
     Значение по умолчанию: ‘false’

     Когда ‘stardisp’ равно ‘true’, произведение отображается со
     звездочкой между операндами.

 -- Функция: string (<expr>)
     Преобразовывает ‘expr’ в линейное представление, как оно было бы
     введено с клавиатуры.

     Значение, возвращаемое функцией ‘string’, является строкой, поэтому
     не может использоваться в вычислениях.

 -- Управляющая переменная: stringdisp
     Значение по умолчанию: ‘false’

     Когда ‘stringdisp’ равна ‘true’, строки отображаются заключенными в
     двойные кавычки.  В противном случае кавычки опускаются.

     ‘stringdisp’ всегда ‘true’, при выводе определений функций.

     Примеры:

          (%i1) stringdisp: false$
          (%i2) "This is an example string.";
          (%o2)              This is an example string.
          (%i3) foo () :=
                print ("This is a string in a function definition.");
          (%o3) foo() :=
                        print("This is a string in a function definition.")
          (%i4) stringdisp: true$
          (%i5) "This is an example string.";
          (%o5)             "This is an example string."

 -- Функция: stringout (<filename>, <expr_1>, <expr_2>, <expr_3>, ...)
 -- Функция: stringout (<filename>, [<m>, <n>])
 -- Функция: stringout (<filename>, input)
 -- Функция: stringout (<filename>, functions)
 -- Функция: stringout (<filename>, values)

     ‘stringout’ записывает выражение в файл в той же форме, в которой
     оно было бы введено с клавиатуры.  Файл можно использовать в
     качестве входного для команд ‘batch’ или ‘demo’, его также можно
     редактировать для любых целей.  ‘stringout’ можно выполнять во
     время работы ‘writefile’.

     Глобальная переменная ‘file_output_append’ определяет будет ли
     ‘stringout’ добавлять или переписывать выходной файл.  Если
     ‘file_output_append’ равна ‘true’, ‘stringout’ дописывает выходной
     файл, иначе переписывает его.  В обоих случаях ‘stringout’ создает
     файл, если тот не существовал.

     Общий вид команды ‘stringout’ записывает значения одного или
     нескольких выражений в файл.  Заметим, что если выражения являются
     переменной, записывается только значение переменной, но не ее имя.
     В полезном специальном случае, выражения могут быть метками входных
     (‘%i1’, ‘%i2’, ‘%i3’, ...)  или результирующих (‘%o1’, ‘%o2’,
     ‘%o3’, ...)  выражений.

     Если ‘grind’ равна ‘true’, ‘stringout’ форматирует выход используя
     формат ‘grind’.  Иначе используется формат ‘string’.  См.  ‘grind’
     и ‘string’.

     Особая форма ‘stringout (<filename>, [<m>, <n>)’ записывает
     значения входных выражений, с номерами от m до n, включительно.

     Особая форма ‘stringout (<filename>, input)’ записывает в файл все
     входные выражения.

     Особая форма ‘stringout (<filename>, functions)’ записывает в файл
     все пользовательские функции (перечисленные в глобальном списке
     ‘functions’).

     Особая форма ‘stringout (<filename>, values)’ записывает в файл все
     пользовательские переменные (перечисленные в глобальном списке
     ‘values’).  Каждая переменная выводится как оператор присваивания:
     с именем переменной, двоеточием и ее значением.  Заметим, что общая
     форма ‘stringout’ не выводит переменные в виде операторов
     присваивания.

 -- Функция: tex (<expr>)
 -- Функция: tex (<expr>, <filename>)
 -- Функция: tex (<expr>, false)
 -- Функция: tex (<label>)
 -- Функция: tex (<label>, <filename>)
 -- Функция: tex (<label>, false)

     Отображает выражение в представлении подходящим для системы
     подготовки документов TeX. Результат – фрагмент документа, который
     можно скопировать в больший документ, но сам по себе он для
     обработки не подходит.

     ‘tex (<expr>)’ отображает TeX-представление выражения <expr> в
     консоль.

     ‘ (<label>)’ отображает TeX-представление выражения, помеченное
     <label>, и назначает его метке выражения (отображаемой слева от
     выражения).  Метки выражений TeX совпадают с метками Maxima.

     ‘tex (<expr>, <filename>)’ и ‘tex (<label>, <filename>)’ добавляют
     свой TeX-вывод в файл <filename>.

     ‘tex (<expr>, false)’ и ‘tex (<label>, false)’ возвращают свой
     вывод в виде строки.

     ‘tex’ вычисляет свой первый аргумент после попытки определить, не
     является ли он меткой.  Оператор две кавычки ‘''’ вызывает
     вычисление аргумента, предотвращая попытки проверить, является ли
     он меткой.

     См.  также ‘texput’.

     Примеры:

          (%i1) integrate (1/(1+x^3), x);
                                              2 x - 1
                            2            atan(-------)
                       log(x  - x + 1)        sqrt(3)    log(x + 1)
          (%o1)      - --------------- + ------------- + ----------
                              6             sqrt(3)          3
          (%i2) tex (%o1);
          $$-{{\log \left(x^2-x+1\right)}\over{6}}+{{\arctan \left({{2\,x-1
           }\over{\sqrt{3}}}\right)}\over{\sqrt{3}}}+{{\log \left(x+1\right)
           }\over{3}}\leqno{\tt (\%o1)}$$
          (%o2)                          (\%o1)
          (%i3) tex (integrate (sin(x), x));
          $$-\cos x$$
          (%o3)                           false
          (%i4) tex (%o1, "foo.tex");
          (%o4)                          (\%o1)

     ‘tex (<expr>, false)’ возвращает свой вывод в виде строки.

          (%i1) S : tex (x * y * z, false);
          (%o1) $$x\,y\,z$$
          (%i2) S;
          (%o2) $$x\,y\,z$$

 -- Функция: texput (<a>, <s>)
 -- Функция: texput (<a>, <s>, <operator_type>)
 -- Функция: texput (<a>, [<s_1>, <s_2>], matchfix)
 -- Функция: texput (<a>, [<s_1>, <s_2>, <s_3>], matchfix)

     Задает TeX вывод для атома <a>, который может быть символом или
     именем оператора.

     ‘texput (<a>, <s>)’ заставляет функцию ‘tex’ в своем выводе
     вставлять строку <s> вместо <a>.

     ‘texput (<a>, <s>, <operator_type>)’, где <operator_type> можеть
     принимать значения ‘prefix’, ‘infix’, ‘postfix’, ‘nary’ или
     ‘nofix’, заставляет функцию ‘tex’ вставлять <s> вместо <a> и
     помещать вставленный текст в подходящую позицию.

     ‘texput (<a>, [<s_1>, <s_2>], matchfix)’ заставляет ‘tex’ вставлять
     <s_1> и <s_2> в вывод TeX с обоих сторон аргументов атома <a>.
     Аргументы (если их несколько) разделяются запятыми.

     ‘textpput (<a>, [<s_1>, <s_2>, <s_3>], matchfix)’ заставляет ‘tex’
     в TeX-выводе вставлять <s_1> и <s_2> с обоих сторон аргументов
     атома <a> и разделять их аргументом <s_3>.

     Примеры:

     Определение TeX вывода переменной.

          (%i1) texput (me,"\\mu_e");
          (%o1)                         \mu_e
          (%i2) tex (me);
          $$\mu_e$$
          (%o2)                         false

     Определение TeX вывода обычной функции (не оператору).

          (%i1) texput (lcm, "\\mathrm{lcm}");
          (%o1)                     \mathrm{lcm}
          (%i2) tex (lcm (a, b));
          $$\mathrm{lcm}\left(a , b\right)$$
          (%o2)                         false

     Определение TeX вывода префиксного оператора.

          (%i1) prefix ("grad");
          (%o1)                         grad
          (%i2) texput ("grad", " \\nabla ", prefix);
          (%o2)                        \nabla
          (%i3) tex (grad f);
          $$ \nabla f$$
          (%o3)                         false

     Определение вывода инфиксного оператора.

          (%i1) infix ("~");
          (%o1)                           ~
          (%i2) texput ("~", " \\times ", infix);
          (%o2)                        \times
          (%i3) tex (a ~ b);
          $$a \times b$$
          (%o3)                         false

     Определение вывода постфиксного оператора.

          (%i1) postfix ("##");
          (%o1)                          ##
          (%i2) texput ("##", "!!", postfix);
          (%o2)                          !!
          (%i3) tex (x ##);
          $$x!!$$
          (%o3)                         false

     Определение вывода n-арного оператора.

          (%i1) nary ("@@");
          (%o1)                          @@
          (%i2) texput ("@@", " \\circ ", nary);
          (%o2)                         \circ
          (%i3) tex (a @@ b @@ c @@ d);
          $$a \circ b \circ c \circ d$$
          (%o3)                         false

     Определение TeX вывода безфиксного оператора без аргументов.

          (%i1) nofix ("foo");
          (%o1)                          foo
          (%i2) texput ("foo", "\\mathsc{foo}", nofix);
          (%o2)                     \mathsc{foo}
          (%i3) tex (foo);
          $$\mathsc{foo}$$
          (%o3)                         false

     Назначение вывода матчфиксному парному оператору.

          (%i1) matchfix ("<<", ">>");
          (%o1)                          <<
          (%i2) texput ("<<", [" \\langle ", " \\rangle "], matchfix);
          (%o2)                [ \langle ,  \rangle ]
          (%i3) tex (<<a>>);
          $$ \langle a \rangle $$
          (%o3)                         false
          (%i4) tex (<<a, b>>);
          $$ \langle a , b \rangle $$
          (%o4)                         false
          (%i5) texput ("<<", [" \\langle ", " \\rangle ", " \\, | \\,"],
                matchfix);
          (%o5)           [ \langle ,  \rangle ,  \, | \,]
          (%i6) tex (<<a>>);
          $$ \langle a \rangle $$
          (%o6)                         false
          (%i7) tex (<<a, b>>);
          $$ \langle a \, | \,b \rangle $$
          (%o7)                         false

 -- Функция: system (<command>)
     Выполняет команду <command> как отдельный процесс.  Команда
     отправляется на выполнение командной оболочке, заданной по
     умолчанию.  ‘system’ поддерживается не всеми операционными
     системами, она в основном существует в Unix и Unix-подобных
     окружениях.

     Предположим, что ‘_hist.out’ – список частот, который вы хотите
     изобразить в виде гистограммы при помощи программы ‘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"));

     Для того чтобы создать готовый график в фоновом режиме (вернуться к
     управлению Maxima) и удалить временный файл после завершения,
     сделайте так:

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

 -- Управляющая переменная: ttyoff
     Значение по умолчанию: ‘false’

     Когда ‘ttyoff’ равна ‘true’, выводимые выражения не отображаются.
     Выводимые выражения по прежнему вычисляются и связываются с
     метками.  См.  ‘labels’.

     ‘ttyoff’ не влияет на текст, отображаемый встроенными функциями,
     такой как сообщения об ошибках и вывод ‘describe’.

 -- Функция: with_stdout (<f>, <expr_1>, <expr_2>, <expr_3>, ...)
 -- Функция: with_stdout (<s>, <expr_1>, <expr_2>, <expr_3>, ...)
     Вычисляет <expr_1>, <expr_2>, <expr_3>, ...  и записывает любой
     сгенерированный вывод в файл <f> или в выходной поток <s>.
     Вычисленные выражения не записываются в вывод.  Вывод может
     генерироваться кроме прочих функциями ‘print’, ‘display’, ‘grind’.

     Глобальная переменная ‘file_output_append’ управляет тем, будет ли
     ‘with_stdout’ дописывать или переписывать заново файл <f>.  Если
     ‘file_output_append’ равна ‘true’, ‘with_stdout’ добавляет вывод к
     файлу.  Иначе ‘with_stdout’ переписывает файл.  В обоих случаях,
     ‘with_stdout’ создает файл, если тот не существовал.

     ‘with_stdout’ возвращает значение своего последнего аргумента.

     См.  также ‘writefile’.

          (%i1) with_stdout ("tmp.out", for i:5 thru 10 do
                print (i, "! yields", i!))$
          (%i2) printfile ("tmp.out")$
          5 ! yields 120
          6 ! yields 720
          7 ! yields 5040
          8 ! yields 40320
          9 ! yields 362880
          10 ! yields 3628800

 -- Функция: writefile (<filename>)
     Начинает записывать копию сессии Maxima в <filename>.  Все
     взаимодействия между пользователем и Maxima записываются в этот
     файл точно в том виде, в котором они показываются в консоли.

     Копия печатается в формате консольного вывода, который не может
     быть перезагружен в Maxima.  Если хотите создать файл, содержащий
     выражения, с возможностью его загрузки, см.  ‘save’ и ‘stringout’.
     ‘save’ сохраняет выражения в форме Lisp, в то время как ‘stringout’
     сохраняет их в форме Maxima.

     Результат выполнения ‘writefile’, когда <filename> уже существует,
     зависит от реализации лежащего в основе Lisp.  Выходной файл может
     быть стерт или дописан.  ‘appendfile’ всегда дописывает файл.

     Может оказаться удобным выполнить ‘playback’ после ‘writefile’
     чтобы сохранить отображение предыдущих взаимодействий.  Так
     ‘playback’ отображает только входные или результирующие переменные
     (‘%i1’, ‘%o1’ и т.  д.), любой вывод, создаваемый печатающими
     выражениями в функциях (в противоположность возвращаемому
     значению), не отображается функцией ‘playback’.

     ‘closefile’ закрывает файл, который открыла ‘writefile’ или
     ‘appendfile’.


File: maxima.info,  Node: Контексты,  Next: Polynomials,  Prev: Ввод и вывод,  Up: Top

10 Контексты
************

* Menu:

* Функции для работы с контекстами::


File: maxima.info,  Node: Функции для работы с контекстами,  Prev: Контексты,  Up: Контексты

10.1 Функции для работы с контекстами
=====================================

 -- Функция: activate (<context_1>, ..., <context_n>)
     Активизирует контексты <context_1>, ..., <context_n>.  Факты в этих
     контекстах становятся доступными для процедур дедукции.  Факты в
     данных контекстах не отображаются функцией ‘facts ()’.

     Переменная ‘activecontexts’ содержит список активных контекстов,
     активированных с помощью ‘activate’.

 -- Системная переменная: activecontexts
     Значение по умолчанию: ‘[]’

     ‘activecontexts’ – список активных контекстов, активизированных при
     помощи функции ‘activate’, в отличии от контекстов, которые
     являются активными как подконтексты текущего контекста.

 -- Функция: assume (<pred_1>, ..., <pred_n>)
     Добавляет предикаты <pred_1>, ..., <pred_n> к текущему контексту.
     Если предикаты являются противоречивыми или избыточными в текущем
     контексте, то добавление не производится.  Контекст объединяет все
     предикаты от всех вызовов ‘assume’.

     ‘assume’ возвращает список предикатов, добавленных к базе данных и
     атомы ‘redundant’ или ‘inconsistent’ для избыточных или
     противоречивых предикатов соответственно.

     Предикаты <pred_1>, ..., <pred_n> могут быть только выражениями,
     содержащими операторы отношения ‘< <= equal notequal >=’ и ‘>’.
     Предикаты не могут быть буквальными равенствами ‘=’ или
     неравенствами ‘#’ выражений, и не могут включать функции-предикаты
     ‘integerp’.

     Распознаются составные предикаты вида ‘<pred_1> and ... and
     <pred_n>’, но не предикаты ‘<pred_1> or ... or <pred_n>’.
     Распознается ‘not <pred_k>’, если <pred_k> является предикатом
     отношения.  Выражения вида ‘not (<pred_1> and <pred_2>)’ и ‘not
     (<pred_1> or <pred_2>)’ не распознаются.

     Механизм дедукции Maxima не очень силен.  Существует много
     очевидных следствий, которые не могут быть выведены ‘is’.  Это
     известная слабость.

     ‘assume’ вычисляет свои аргументы.

     См.  также ‘is’, ‘facts’, ‘forget’, ‘context’ и ‘declare’.

     Примеры:

          (%i1) assume (xx > 0, yy < -1, zz >= 0);
          (%o1)              [xx > 0, yy < - 1, zz >= 0]
          (%i2) assume (aa < bb and bb < cc);
          (%o2)                  [bb > aa, cc > bb]
          (%i3) facts ();
          (%o3)     [xx > 0, - 1 > yy, zz >= 0, bb > aa, cc > bb]
          (%i4) is (xx > yy);
          (%o4)                         true
          (%i5) is (yy < -yy);
          (%o5)                         true
          (%i6) is (sinh (bb - aa) > 0);
          (%o6)                         true
          (%i7) forget (bb > aa);
          (%o7)                       [bb > aa]
          (%i8) prederror : false;
          (%o8)                         false
          (%i9) is (sinh (bb - aa) > 0);
          (%o9)                        unknown
          (%i10) is (bb^2 < cc^2);
          (%o10)                       unknown

 -- Управляющая переменная: assumescalar
     Значение по умолчанию: ‘true’

     ‘assumescalar’ определяет, что выражения ‘expr’, для которых
     ‘nonscalarp (expr)’ равно ‘false’, рассматриваются как скаляры при
     некоторых преобразованиях.

     Пусть ‘expr’ есть выражение отличное от списка или матрицы, и ‘[1,
     2, 3]’ есть список (или матрица).  Тогда ‘expr . [1, 2, 3]’ дает
     ‘[expr, 2 expr, 3 expr]’ если ‘assumescalar’ равно ‘true’, или
     ‘scalarp (expr)’ равно ‘true’, или ‘constantp (expr)’ равно ‘true’.

     Если ‘assumescalar’ равно ‘true’, такие выражения трактуются как
     скаляры только для коммутативных операций, но не для
     некоммутативного умножения ‘.’.

     Когда ‘assumescalar’ равно ‘false’, такие выражения трактуются как
     не-скалярные.

     Когда ‘assumescalar’ равно ‘all’, такие выражения трактуются как
     скаляры для всех перечисленных выше операций, включая
     некоммутативное умножение.

 -- Управляющая переменная: assume_pos
     Значение по умолчанию: ‘false’

     Если ‘assume_pos’ равно ‘true’ и знак параметра <x> не может быть
     определен исходя из текущего контекста или другим способом, тогда
     ‘sign’ и ‘asksign (<x>)’ дают ‘true’.  Таким образом подавить
     некоторые автоматические запросы ‘asksign’, возникающие при работе
     ‘integrate’ или других вычислениях.

     По умолчанию параметр <x> таков, что ‘symbolp (<x>)’ или ‘subvarp
     (<x>)’ истинны.  Класс выражений, которые могут рассматриваться в
     качестве параметров, может в некоторой степени изменяться с помощью
     переменной ‘assume_pos_pred’.

     ‘sign’ и ‘asksign’ пытаются определить знак выражения исходя из
     знаков операндов.  Например, если ‘a’ и ‘b’ оба положительны, тогда
     ‘a + b’ тоже положительно.

     Однако, невозможно совсем обойтись без интерактивных запросов
     ‘asksign’.  В частности, когда аргумент ‘asksign’ является разницей
     ‘<x> - <y>’ или логарифмом ‘log(<x>)’, тогда ‘asksign’ всегда
     запросит пользователя о знаке параметра, даже если ‘assume_pos’
     равно ‘true’ и ‘assume_pos_pred’ есть функция, возвращающая ‘true’
     для всех аргументов.

 -- Управляющая переменная: assume_pos_pred
     Значение по умолчанию: ‘false’

     Если ‘assume_pos_pred’ присвоено значение, являющееся именем
     функции или лямбда-выражение с одним аргументом <x>, тогда эта
     функция вызывается для того чтобы определить является ли <x>
     параметрам для ‘assume_pos’.  ‘assume_pos_pred’ игнорируется, когда
     ‘assume_pos’ равно ‘false’.

     Функция ‘assume_pos_pred’ вызывается ‘sign’ и ‘asksign’ с
     аргументом <x>, который является либо атомом, либо переменной с
     индексом, либо вызовом функции.  Если ‘assume_pos_pred’ возвращает
     ‘true’, тогда <x> рассматривается как допустимый параметр для
     ‘assume_pos’.

     По умолчанию параметром является <x> ткой, что ‘symbolp (<x>)’ или
     ‘subvarp (<x>)’ истинно.

     См.  также ‘assume’ и ‘assume_pos’.

     Примеры:

          (%i1) assume_pos: true$
          (%i2) assume_pos_pred: symbolp$
          (%i3) sign (a);
          (%o3)                          pos
          (%i4) sign (a[1]);
          (%o4)                          pnz
          (%i5) assume_pos_pred: lambda ([x], display (x), true)$
          (%i6) asksign (a);
                                        x = a

          (%o6)                          pos
          (%i7) asksign (a[1]);
                                       x = a
                                            1

          (%o7)                          pos
          (%i8) asksign (foo (a));
                                     x = foo(a)

          (%o8)                          pos
          (%i9) asksign (foo (a) + bar (b));
                                     x = foo(a)

                                     x = bar(b)

          (%o9)                          pos
          (%i10) asksign (log (a));
                                        x = a

          Is  a - 1  positive, negative, or zero?

          p;
          (%o10)                         pos
          (%i11) asksign (a - b);
                                        x = a

                                        x = b

                                        x = a

                                        x = b

          Is  b - a  positive, negative, or zero?

          p;
          (%o11)                         neg

 -- Управляющая переменная: context
     Значение по умолчанию: ‘initial’

     ‘context’ служит для обозначения набора фактов формируемого при
     помощи ‘assume’ и ‘forget’.  ‘assume’ добавляет факты к набору,
     обозначаемому ‘context’, а ‘forget’ удаляет факты.

     Присваивание ‘context’ имени <foo> изменяет текущий контекст на
     <foo>.  Если контекст с таким именем <foo> пока еще не существует,
     то он автоматически создается вызовом функции ‘newcontext’.
     Указанный контекст автоматически активируется.

     См.  ‘contexts’ для общего описания механизма контекстов.

 -- Управляющая переменная: contexts
     Значение по умолчанию: ‘[initial, global]’

     ‘contexts’ – список существующих на данный момент контекстов,
     включая активный.

     Механизм контекстов позволяет пользователю создавать поименованные
     наборы фактов (контексты).  В результате можно легко активировать
     или деактивировать большие наборы фактов просто активируя или
     деактивируя соответствующие контексты.

     Любой символ может быть контекстом, и факты содержащиеся в этом
     контексте сохраняются до тех пор пока не будут уничтожены
     поодиночке с помощью ‘forget’ или целиком с помощью ‘kill’,
     уничтожающем весь контекст, которому они принадлежат.

     Контексты имеют иерархическую структуру.  Корневым элементом всегда
     является контекст ‘global’, который содержит информацию о Maxima
     нужную некоторым функциям.  Когда мы находимся в определенном
     контексте, все его факты являются активными, т.е.  используются в
     логических выводах.  Аналогично активными являются все факты в
     подконтекстах текущего контекста.

     При запуске Maxima, активным является контекст ‘initial’,
     подконтекстом которого является ‘global’.

     См.  также ‘facts’, ‘newcontext’, ‘supcontext’, ‘killcontext’,
     ‘activate’, ‘deactivate’, ‘assume’ и ‘forget’.

 -- Функция: deactivate (<context_1>, ..., <context_n>)
     Деактивирует все указанные контексты <context_1>, ..., <context_n>.

 -- Функция: facts (<item>)
 -- Функция: facts ()
     Если <item> является именем контекста, тогда ‘facts (<item>)’
     возвращает список содержащихся в нем фактов.

     Если <item> не является именем контекста, тогда ‘facts (<item>)’
     возвращает список фактов известных о <item> в текущем контексте.
     Факты являющиеся активными, но принадлежащие другим контекстам не
     отображаются.

     ‘facts ()’ (т.е.  без аргументов) отображает все факты текущего
     контекста.

 -- Декларация: features
     Maxima "распознает" некоторые математические свойства (features)
     функций и переменных.

     ‘declare (<x>, <foo>)’ устанавливает свойство <foo> для функции или
     переменной <x>.

     ‘declare (<foo>, feature)’ объявляет новое свойство <foo>.
     Например, ‘declare ([red, green, blue], feature)’ объявляет три
     свойства ‘red’, ‘green’ и ‘blue’.

     Предикат ‘featurep (<x>, <foo>)’ возвращает ‘true’ если <x> имеет
     свойство <foo>, и ‘false’ в противном случае.

     Информационный список ‘features’ содержит все известные свойства.
     А именно ‘integer’, ‘noninteger’, ‘even’, ‘odd’, ‘rational’,
     ‘irrational’, ‘real’, ‘imaginary’, ‘complex’, ‘analytic’,
     ‘increasing’, ‘decreasing’, ‘oddfun’, ‘evenfun’, ‘posfun’,
     ‘commutative’, ‘lassociative’, ‘rassociative’, ‘symmetric’ и
     ‘antisymmetric’, плюс свойства определенные пользователем.

     ‘features’ является списком математических свойств.  Существует
     также список нематематических, системо-зависимых свойств.  См.
     ‘status’.

 -- Функция: forget (<pred_1>, ..., <pred_n>)
 -- Функция: forget (<L>)
     Удаляет предикаты установленные ‘assume’.  Предикаты могут быть
     выражениями эквивалентными (но не обязательно идентичными) тем,
     которые первоначально были установлены с помощью ‘assume’.

     ‘forget (<L>)’, где <L> есть список предикатов, удаляет все
     предикаты из данного списка.

 -- Функция: killcontext (<context_1>, ..., <context_n>)
     Уничтожает контексты <context_1>, ..., <context_n>.

     Если один из уничтожаемых контекстов является текущим, то в
     качестве нового текущего контекста выбирается первый доступный не
     уничтожаемый подконтекст текущего.  Если первым доступным
     контекстом является ‘global’, тогда используется ‘initial’.  Если
     ‘initial’ тоже удаляется, то создается новый контекст ‘initial’.

     ‘killcontext’ отказывается удалять контекст, котрый является
     активным по причине того, что является подконтекстом текущего
     контекста или был активизирован функцией ‘activate’.

     ‘killcontext’ вычисляет свои аргументы.  ‘killcontext’ возвращает
     ‘done’.

 -- Функция: newcontext (<name>)
     Создает новый пустой контекст с именем <name>, имеющий контекст
     ‘global’ в качестве своего подконтекста.  Новый контекст становится
     текущим активным контекстом.

     ‘newcontext’ вычисляет свои аргумент.  ‘newcontext’ возвращает
     <name>.

 -- Функция: supcontext (<name>, <context>)
 -- Функция: supcontext (<name>)
     Создает новый контекст с именем <name>, котрый имеет <context> в
     качестве подконтекста.  <context> должен существовать.

     Если <context> не указан, тогда подразумевается текущий контекст.


File: maxima.info,  Node: Polynomials,  Next: Константы,  Prev: Контексты,  Up: Top

11 Polynomials
**************

* Menu:

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


File: maxima.info,  Node: Introduction to Polynomials,  Next: Functions and Variables for Polynomials

11.1 Introduction to Polynomials
================================

Polynomials are stored in Maxima either in General Form or as Canonical
Rational Expressions (CRE) form.  The latter is a standard form, and is
used internally by operations such as ‘factor’, ‘ratsimp’, and so on.

   Canonical Rational Expressions constitute a kind of representation
which is especially suitable for expanded polynomials and rational
functions (as well as for partially factored polynomials and rational
functions when ‘ratfac’ is set to ‘true’).  In this CRE form an ordering
of variables (from most to least main) is assumed for each expression.

   Polynomials are represented recursively by a list consisting of the
main variable followed by a series of pairs of expressions, one for each
term of the polynomial.  The first member of each pair is the exponent
of the main variable in that term and the second member is the
coefficient of that term which could be a number or a polynomial in
another variable again represented in this form.  Thus the principal
part of the CRE form of ‘3*x^2-1’ is ‘(X 2 3 0 -1)’ and that of
‘2*x*y+x-3’ is ‘(Y 1 (X 1 2) 0 (X 1 1 0 -3))’ assuming ‘y’ is the main
variable, and is ‘(X 1 (Y 1 2 0 1) 0 -3)’ assuming ‘x’ is the main
variable.  "Main"-ness is usually determined by reverse alphabetical
order.

   The "variables" of a CRE expression needn’t be atomic.  In fact any
subexpression whose main operator is not ‘+’, ‘-’, ‘*’, ‘/’ or ‘^’ with
integer power will be considered a "variable" of the expression (in CRE
form) in which it occurs.  For example the CRE variables of the
expression ‘x+sin(x+1)+2*sqrt(x)+1’ are ‘x’, ‘sqrt(X)’, and ‘sin(x+1)’.
If the user does not specify an ordering of variables by using the
‘ratvars’ function Maxima will choose an alphabetic one.

   In general, CRE’s represent rational expressions, that is, ratios of
polynomials, where the numerator and denominator have no common factors,
and the denominator is positive.  The internal form is essentially a
pair of polynomials (the numerator and denominator) preceded by the
variable ordering list.  If an expression to be displayed is in CRE form
or if it contains any subexpressions in CRE form, the symbol ‘/R/’ will
follow the line label.

   See the ‘rat’ function for converting an expression to CRE form.

   An extended CRE form is used for the representation of Taylor series.
The notion of a rational expression is extended so that the exponents of
the variables can be positive or negative rational numbers rather than
just positive integers and the coefficients can themselves be rational
expressions as described above rather than just polynomials.  These are
represented internally by a recursive polynomial form which is similar
to and is a generalization of CRE form, but carries additional
information such as the degree of truncation.  As with CRE form, the
symbol ‘/T/’ follows the line label of such expressions.


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

11.2 Functions and Variables for Polynomials
============================================

 -- Option variable: algebraic
     Default value: ‘false’

     ‘algebraic’ must be set to ‘true’ in order for the simplification
     of algebraic integers to take effect.

 -- Option variable: berlefact
     Default value: ‘true’

     When ‘berlefact’ is ‘false’ then the Kronecker factoring algorithm
     will be used otherwise the Berlekamp algorithm, which is the
     default, will be used.

 -- Function: bezout (<p1>, <p2>, <x>)

     an alternative to the ‘resultant’ command.  It returns a matrix.
     ‘determinant’ of this matrix is the desired resultant.

     Examples:

          (%i1) bezout(a*x+b, c*x^2+d, x);
                                   [ b c  - a d ]
          (%o1)                    [            ]
                                   [  a     b   ]
          (%i2) determinant(%);
                                      2      2
          (%o2)                      a  d + b  c
          (%i3) resultant(a*x+b, c*x^2+d, x);
                                      2      2
          (%o3)                      a  d + b  c

 -- Function: bothcoef (<expr>, <x>)

     Returns a list whose first member is the coefficient of <x> in
     <expr> (as found by ‘ratcoef’ if <expr> is in CRE form otherwise by
     ‘coeff’) and whose second member is the remaining part of <expr>.
     That is, ‘[A, B]’ where ‘<expr> = A*<x> + B’.

     Example:

          (%i1) islinear (expr, x) := block ([c],
                  c: bothcoef (rat (expr, x), x),
                  is (freeof (x, c) and c[1] # 0))$
          (%i2) islinear ((r^2 - (x - r)^2)/x, x);
          (%o2)                         true

 -- Function: coeff
          coeff (<expr>, <x>, <n>)
          coeff (<expr>, <x>)

     Returns the coefficient of ‘<x>^<n>’ in <expr>, where <expr> is a
     polynomial or a monomial term in <x>.  Other than ‘ratcoef’ ‘coeff’
     is a strictly syntactical operation and will only find literal
     instances of ‘<x>^<n>’ in the internal representation of <expr>.

     ‘coeff(<expr>, <x>^<n>)’ is equivalent to ‘coeff(<expr>, <x>,
     <n>)’.  ‘coeff(<expr>, <x>, 0)’ returns the remainder of <expr>
     which is free of <x>.  If omitted, <n> is assumed to be 1.

     <x> may be a simple variable or a subscripted variable, or a
     subexpression of <expr> which comprises an operator and all of its
     arguments.

     It may be possible to compute coefficients of expressions which are
     equivalent to <expr> by applying ‘expand’ or ‘factor’.  ‘coeff’
     itself does not apply ‘expand’ or ‘factor’ or any other function.

     ‘coeff’ distributes over lists, matrices, and equations.

     See also ‘ratcoef’.

     Examples:

     ‘coeff’ returns the coefficient ‘<x>^<n>’ in <expr>.

          (%i1) coeff (b^3*a^3 + b^2*a^2 + b*a + 1, a^3);
                                          3
          (%o1)                          b

     ‘coeff(<expr>, <x>^<n>)’ is equivalent to ‘coeff(<expr>, <x>,
     <n>)’.

          (%i1) coeff (c[4]*z^4 - c[3]*z^3 - c[2]*z^2 + c[1]*z, z, 3);
          (%o1)                         - c
                                           3
          (%i2) coeff (c[4]*z^4 - c[3]*z^3 - c[2]*z^2 + c[1]*z, z^3);
          (%o2)                         - c
                                           3

     ‘coeff(<expr>, <x>, 0)’ returns the remainder of <expr> which is
     free of <x>.

          (%i1) coeff (a*u + b^2*u^2 + c^3*u^3, b, 0);
                                      3  3
          (%o1)                      c  u  + a u

     <x> may be a simple variable or a subscripted variable, or a
     subexpression of <expr> which comprises an operator and all of its
     arguments.

          (%i1) coeff (h^4 - 2*%pi*h^2 + 1, h, 2);
          (%o1)                        - 2 %pi
          (%i2) coeff (v[1]^4 - 2*%pi*v[1]^2 + 1, v[1], 2);
          (%o2)                        - 2 %pi
          (%i3) coeff (sin(1+x)*sin(x) + sin(1+x)^3*sin(x)^3, sin(1+x)^3);
                                          3
          (%o3)                        sin (x)
          (%i4) coeff ((d - a)^2*(b + c)^3 + (a + b)^4*(c - d), a + b, 4);
          (%o4)                         c - d

     ‘coeff’ itself does not apply ‘expand’ or ‘factor’ or any other
     function.

          (%i1) coeff (c*(a + b)^3, a);
          (%o1)                           0
          (%i2) expand (c*(a + b)^3);
                           3          2        2        3
          (%o2)           b  c + 3 a b  c + 3 a  b c + a  c
          (%i3) coeff (%, a);
                                          2
          (%o3)                        3 b  c
          (%i4) coeff (b^3*c + 3*a*b^2*c + 3*a^2*b*c + a^3*c, (a + b)^3);
          (%o4)                           0
          (%i5) factor (b^3*c + 3*a*b^2*c + 3*a^2*b*c + a^3*c);
                                            3
          (%o5)                      (b + a)  c
          (%i6) coeff (%, (a + b)^3);
          (%o6)                           c

     ‘coeff’ distributes over lists, matrices, and equations.

          (%i1) coeff ([4*a, -3*a, 2*a], a);
          (%o1)                      [4, - 3, 2]
          (%i2) coeff (matrix ([a*x, b*x], [-c*x, -d*x]), x);
                                    [  a    b  ]
          (%o2)                     [          ]
                                    [ - c  - d ]
          (%i3) coeff (a*u - b*v = 7*u + 3*v, u);
          (%o3)                         a = 7

 -- Function: content (<p_1>, <x_1>, …, <x_n>)

     Returns a list whose first element is the greatest common divisor
     of the coefficients of the terms of the polynomial <p_1> in the
     variable <x_n> (this is the content) and whose second element is
     the polynomial <p_1> divided by the content.

     Examples:

          (%i1) content (2*x*y + 4*x^2*y^2, y);
                                             2
          (%o1)                   [2 x, 2 x y  + y]

 -- Function: denom (<expr>)

     Returns the denominator of the rational expression <expr>.

     See also ‘num’

          (%i1) g1:(x+2)*(x+1)/((x+3)^2);
                                   (x + 1) (x + 2)
          (%o1)                    ---------------
                                             2
                                      (x + 3)
          (%i2) denom(g1);
                                             2
          (%o2)                       (x + 3)
          (%i3) g2:sin(x)/10*cos(x)/y;
                                    cos(x) sin(x)
          (%o3)                     -------------
                                        10 y
          (%i4) denom(g2);
          (%o4)                         10 y

 -- Function: divide (<p_1>, <p_2>, <x_1>, …, <x_n>)

     computes the quotient and remainder of the polynomial <p_1> divided
     by the polynomial <p_2>, in a main polynomial variable, <x_n>.  The
     other variables are as in the ‘ratvars’ function.  The result is a
     list whose first element is the quotient and whose second element
     is the remainder.

     Examples:

          (%i1) divide (x + y, x - y, x);
          (%o1)                       [1, 2 y]
          (%i2) divide (x + y, x - y);
          (%o2)                      [- 1, 2 x]

     Note that ‘y’ is the main variable in the second example.

 -- Function: eliminate ([<eqn_1>, …, <eqn_n>], [<x_1>, …, <x_k>])

     Eliminates variables from equations (or expressions assumed equal
     to zero) by taking successive resultants.  This returns a list of
     ‘<n> - <k>’ expressions with the <k> variables <x_1>, …, <x_k>
     eliminated.  First <x_1> is eliminated yielding ‘<n> - 1’
     expressions, then ‘x_2’ is eliminated, etc.  If ‘<k> = <n>’ then a
     single expression in a list is returned free of the variables
     <x_1>, …, <x_k>.  In this case ‘solve’ is called to solve the last
     resultant for the last variable.

     Example:

          (%i1) expr1: 2*x^2 + y*x + z;
                                                2
          (%o1)                    z + x y + 2 x
          (%i2) expr2: 3*x + 5*y - z - 1;
          (%o2)                  - z + 5 y + 3 x - 1
          (%i3) expr3: z^2 + x - y^2 + 5;
                                    2    2
          (%o3)                    z  - y  + x + 5
          (%i4) eliminate ([expr3, expr2, expr1], [y, z]);
                       8         7         6          5          4
          (%o4) [7425 x  - 1170 x  + 1299 x  + 12076 x  + 22887 x

                                              3         2
                                      - 5154 x  - 1291 x  + 7688 x + 15376]

 -- Function: ezgcd (<p_1>, <p_2>, <p_3>, …)

     Returns a list whose first element is the greatest common divisor
     of the polynomials <p_1>, <p_2>, <p_3>, … and whose remaining
     elements are the polynomials divided by the greatest common
     divisor.  This always uses the ‘ezgcd’ algorithm.

     See also ‘gcd’, ‘gcdex’, ‘gcdivide’, and ‘poly_gcd’.

     Examples:

     The three polynomials have the greatest common divisor ‘2*x-3’.
     The gcd is first calculated with the function ‘gcd’ and then with
     the function ‘ezgcd’.

          (%i1) p1 : 6*x^3-17*x^2+14*x-3;
                                  3       2
          (%o1)                6 x  - 17 x  + 14 x - 3
          (%i2) p2 : 4*x^4-14*x^3+12*x^2+2*x-3;
                              4       3       2
          (%o2)            4 x  - 14 x  + 12 x  + 2 x - 3
          (%i3) p3 : -8*x^3+14*x^2-x-3;
                                    3       2
          (%o3)                - 8 x  + 14 x  - x - 3

          (%i4) gcd(p1, gcd(p2, p3));
          (%o4)                        2 x - 3

          (%i5) ezgcd(p1, p2, p3);
                             2               3      2           2
          (%o5) [2 x - 3, 3 x  - 4 x + 1, 2 x  - 4 x  + 1, - 4 x  + x + 1]

 -- Option variable: facexpand
     Default value: ‘true’

     ‘facexpand’ controls whether the irreducible factors returned by
     ‘factor’ are in expanded (the default) or recursive (normal CRE)
     form.

 -- Function: factor
          factor (<expr>)
          factor (<expr>, <p>)

     Factors the expression <expr>, containing any number of variables
     or functions, into factors irreducible over the integers.  ‘factor
     (<expr>, <p>)’ factors <expr> over the field of rationals with an
     element adjoined whose minimum polynomial is <p>.

     ‘factor’ uses ‘ifactors’ function for factoring integers.

     ‘factorflag’ if ‘false’ suppresses the factoring of integer factors
     of rational expressions.

     ‘dontfactor’ may be set to a list of variables with respect to
     which factoring is not to occur.  (It is initially empty).
     Factoring also will not take place with respect to any variables
     which are less important (using the variable ordering assumed for
     CRE form) than those on the ‘dontfactor’ list.

     ‘savefactors’ if ‘true’ causes the factors of an expression which
     is a product of factors to be saved by certain functions in order
     to speed up later factorizations of expressions containing some of
     the same factors.

     ‘berlefact’ if ‘false’ then the Kronecker factoring algorithm will
     be used otherwise the Berlekamp algorithm, which is the default,
     will be used.

     ‘intfaclim’ if ‘true’ maxima will give up factorization of integers
     if no factor is found after trial divisions and Pollard’s rho
     method.  If set to ‘false’ (this is the case when the user calls
     ‘factor’ explicitly), complete factorization of the integer will be
     attempted.  The user’s setting of ‘intfaclim’ is used for internal
     calls to ‘factor’.  Thus, ‘intfaclim’ may be reset to prevent
     Maxima from taking an inordinately long time factoring large
     integers.

     ‘factor_max_degree’ if set to a positive integer ‘n’ will prevent
     certain polynomials from being factored if their degree in any
     variable exceeds ‘n’.

     See also ‘collectterms’ and ‘sqfr’

     Examples:

          (%i1) factor (2^63 - 1);
                              2
          (%o1)              7  73 127 337 92737 649657
          (%i2) factor (-8*y - 4*x + z^2*(2*y + x));
          (%o2)               (2 y + x) (z - 2) (z + 2)
          (%i3) -1 - 2*x - x^2 + y^2 + 2*x*y^2 + x^2*y^2;
                          2  2        2    2    2
          (%o3)          x  y  + 2 x y  + y  - x  - 2 x - 1
          (%i4) block ([dontfactor: [x]], factor (%/36/(1 + 2*y + y^2)));
                                 2
                               (x  + 2 x + 1) (y - 1)
          (%o4)                ----------------------
                                     36 (y + 1)
          (%i5) factor (1 + %e^(3*x));
                                x         2 x     x
          (%o5)              (%e  + 1) (%e    - %e  + 1)
          (%i6) factor (1 + x^4, a^2 - 2);
                              2              2
          (%o6)             (x  - a x + 1) (x  + a x + 1)
          (%i7) factor (-y^2*z^2 - x*z^2 + x^2*y^2 + x^3);
                                 2
          (%o7)              - (y  + x) (z - x) (z + x)
          (%i8) (2 + x)/(3 + x)/(b + x)/(c + x)^2;
                                       x + 2
          (%o8)               ------------------------
                                                     2
                              (x + 3) (x + b) (x + c)
          (%i9) ratsimp (%);
                          4                  3
          (%o9) (x + 2)/(x  + (2 c + b + 3) x

               2                       2             2                   2
           + (c  + (2 b + 6) c + 3 b) x  + ((b + 3) c  + 6 b c) x + 3 b c )
          (%i10) partfrac (%, x);
                     2                   4                3
          (%o10) - (c  - 4 c - b + 6)/((c  + (- 2 b - 6) c

               2              2         2                2
           + (b  + 12 b + 9) c  + (- 6 b  - 18 b) c + 9 b ) (x + c))

                           c - 2
           - ---------------------------------
               2                             2
             (c  + (- b - 3) c + 3 b) (x + c)

                                   b - 2
           + -------------------------------------------------
                       2             2       3      2
             ((b - 3) c  + (6 b - 2 b ) c + b  - 3 b ) (x + b)

                                   1
           - ----------------------------------------------
                       2
             ((b - 3) c  + (18 - 6 b) c + 9 b - 27) (x + 3)
          (%i11) map ('factor, %);
                        2
                       c  - 4 c - b + 6                 c - 2
          (%o11) - ------------------------- - ------------------------
                          2        2                                  2
                   (c - 3)  (c - b)  (x + c)   (c - 3) (c - b) (x + c)

                                 b - 2                        1
                      + ------------------------ - ------------------------
                                       2                          2
                        (b - 3) (c - b)  (x + b)   (b - 3) (c - 3)  (x + 3)
          (%i12) ratsimp ((x^5 - 1)/(x - 1));
                                 4    3    2
          (%o12)                x  + x  + x  + x + 1
          (%i13) subst (a, x, %);
                                 4    3    2
          (%o13)                a  + a  + a  + a + 1
          (%i14) factor (%th(2), %);
                                 2        3        3    2
          (%o14)   (x - a) (x - a ) (x - a ) (x + a  + a  + a + 1)
          (%i15) factor (1 + x^12);
                                 4        8    4
          (%o15)               (x  + 1) (x  - x  + 1)
          (%i16) factor (1 + x^99);
                           2            6    3
          (%o16) (x + 1) (x  - x + 1) (x  - x  + 1)

             10    9    8    7    6    5    4    3    2
           (x   - x  + x  - x  + x  - x  + x  - x  + x  - x + 1)

             20    19    17    16    14    13    11    10    9    7    6
           (x   + x   - x   - x   + x   + x   - x   - x   - x  + x  + x

              4    3            60    57    51    48    42    39    33
           - x  - x  + x + 1) (x   + x   - x   - x   + x   + x   - x

              30    27    21    18    12    9    3
           - x   - x   + x   + x   - x   - x  + x  + 1)

 -- Option variable: factor_max_degree
     Default value: ‘1000’

     When factor_max_degree is set to a positive integer ‘n’, it will
     prevent Maxima from attempting to factor certain polynomials whose
     degree in any variable exceeds ‘n’.  If
     ‘factor_max_degree_print_warning’ is true, a warning message will
     be printed.  ‘factor_max_degree’ can be used to prevent excessive
     memory usage and/or computation time and stack overflows.  Note
     that "obvious" factoring of polynomials such as ‘x^2000+x^2001’ to
     ‘x^2000*(x+1)’ will still take place.  To disable this behavior,
     set ‘factor_max_degree’ to ‘0’.

     Example:
          (%i1) factor_max_degree : 100$
          (%i2) factor(x^100-1);
                                  2        4    3    2
          (%o2) (x - 1) (x + 1) (x  + 1) (x  - x  + x  - x + 1)
             4    3    2            8    6    4    2
           (x  + x  + x  + x + 1) (x  - x  + x  - x  + 1)
             20    15    10    5        20    15    10    5
           (x   - x   + x   - x  + 1) (x   + x   + x   + x  + 1)
             40    30    20    10
           (x   - x   + x   - x   + 1)
          (%i3) factor(x^101-1);
                                         101
          Refusing to factor polynomial x    - 1
                         because its degree exceeds factor_max_degree (100)
                                       101
          (%o3)                       x    - 1

     See also: ‘factor_max_degree_print_warning’

 -- Option variable: factor_max_degree_print_warning
     Default value: ‘true’

     When factor_max_degree_print_warning is true, then Maxima will
     print a warning message when the factoring of a polynomial is
     prevented because its degree exceeds the value of
     factor_max_degree.

     See also: ‘factor_max_degree’

 -- Option variable: factorflag
     Default value: ‘false’

     When ‘factorflag’ is ‘false’, suppresses the factoring of integer
     factors of rational expressions.

 -- Function: factorout (<expr>, <x_1>, <x_2>, …)

     Rearranges the sum <expr> into a sum of terms of the form ‘f
     (<x_1>, <x_2>, …)*g’ where ‘g’ is a product of expressions not
     containing any <x_i> and ‘f’ is factored.

     Note that the option variable ‘keepfloat’ is ignored by
     ‘factorout’.

     Example:

          (%i1) expand (a*(x+1)*(x-1)*(u+1)^2);
                       2  2          2      2      2
          (%o1)     a u  x  + 2 a u x  + a x  - a u  - 2 a u - a
          (%i2) factorout(%,x);
                   2
          (%o2) a u  (x - 1) (x + 1) + 2 a u (x - 1) (x + 1)
                                                        + a (x - 1) (x + 1)

 -- Function: factorsum (<expr>)

     Tries to group terms in factors of <expr> which are sums into
     groups of terms such that their sum is factorable.  ‘factorsum’ can
     recover the result of ‘expand ((x + y)^2 + (z + w)^2)’ but it can’t
     recover ‘expand ((x + 1)^2 + (x + y)^2)’ because the terms have
     variables in common.

     Example:

          (%i1) expand ((x + 1)*((u + v)^2 + a*(w + z)^2));
                     2      2                            2      2
          (%o1) a x z  + a z  + 2 a w x z + 2 a w z + a w  x + v  x

                                               2        2    2            2
                                  + 2 u v x + u  x + a w  + v  + 2 u v + u
          (%i2) factorsum (%);
                                             2          2
          (%o2)            (x + 1) (a (z + w)  + (v + u) )

 -- Function: fasttimes (<p_1>, <p_2>)

     Returns the product of the polynomials <p_1> and <p_2> by using a
     special algorithm for multiplication of polynomials.  ‘p_1’ and
     ‘p_2’ should be multivariate, dense, and nearly the same size.
     Classical multiplication is of order ‘n_1 n_2’ where ‘n_1’ is the
     degree of ‘p_1’ and ‘n_2’ is the degree of ‘p_2’.  ‘fasttimes’ is
     of order ‘max (n_1, n_2)^1.585’.

 -- Function: fullratsimp (<expr>)

     ‘fullratsimp’ repeatedly applies ‘ratsimp’ followed by non-rational
     simplification to an expression until no further change occurs, and
     returns the result.

     When non-rational expressions are involved, one call to ‘ratsimp’
     followed as is usual by non-rational ("general") simplification may
     not be sufficient to return a simplified result.  Sometimes, more
     than one such call may be necessary.  ‘fullratsimp’ makes this
     process convenient.

     ‘fullratsimp (<expr>, <x_1>, ..., <x_n>)’ takes one or more
     arguments similar to ‘ratsimp’ and ‘rat’.

     Example:

          (%i1) expr: (x^(a/2) + 1)^2*(x^(a/2) - 1)^2/(x^a - 1);
                                 a/2     2   a/2     2
                               (x    - 1)  (x    + 1)
          (%o1)                -----------------------
                                        a
                                       x  - 1
          (%i2) ratsimp (expr);
                                    2 a      a
                                   x    - 2 x  + 1
          (%o2)                    ---------------
                                        a
                                       x  - 1
          (%i3) fullratsimp (expr);
                                        a
          (%o3)                        x  - 1
          (%i4) rat (expr);
                                 a/2 4       a/2 2
                               (x   )  - 2 (x   )  + 1
          (%o4)/R/             -----------------------
                                        a
                                       x  - 1

 -- Function: fullratsubst (<new>, <old>, <expr>)
          fullratsubst (‘<old> = <new>’, <expr>)
          fullratsubst (‘[ <old_1> = <new_1>, …, <old_n> = <new_n> ]’,
          <expr>)

     ‘fullratsubst’ applies ‘lratsubst’ repeatedly until <expr> stops
     changing (or ‘lrats_max_iter’ is reached).  This function is useful
     when the replacement expression and the replaced expression have
     one or more variables in common.

     ‘fullratsubst’ accepts its arguments in the format of ‘ratsubst’ or
     ‘lratsubst’.

     Examples:

        • ‘subst’ can carry out multiple substitutions.  ‘lratsubst’ is
          analogous to ‘subst’.
          (%i2) subst ([a = b, c = d], a + c);
          (%o2)                         d + b
          (%i3) lratsubst ([a^2 = b, c^2 = d], (a + e)*c*(a + c));
          (%o3)                (d + a c) e + a d + b c
        • If only one substitution is desired, then a single equation
          may be given as first argument.
          (%i4) lratsubst (a^2 = b, a^3);
          (%o4)                          a b
        • ‘fullratsubst’ is equivalent to ‘ratsubst’ except that it
          recurses until its result stops changing.
          (%i5) ratsubst (b*a, a^2, a^3);
                                         2
          (%o5)                         a  b
          (%i6) fullratsubst (b*a, a^2, a^3);
                                           2
          (%o6)                         a b
        • ‘fullratsubst’ also accepts a list of equations or a single
          equation as first argument.
          (%i7) fullratsubst ([a^2 = b, b^2 = c, c^2 = a], a^3*b*c);
          (%o7)                           b
          (%i8) fullratsubst (a^2 = b*a, a^3);
                                           2
          (%o8)                         a b
        • ‘fullratsubst’ catches potential infinite recursions.  *note
          lrats_max_iter::.
          (%i9) fullratsubst (b*a^2, a^2, a^3), lrats_max_iter=15;
          Warning: fullratsubst1(substexpr,forexpr,expr): reached maximum iterations of 15 . Increase `lrats_max_iter' to increase this limit.
                                               3  15
          (%o7)                               a  b

     See also ‘lrats_max_iter’ and ‘fullratsubstflag’.

 -- Option variable: fullratsubstflag
     Default value: ‘false’

     An option variable that is set to ‘true’ in ‘fullratsubst’.

 -- Function: gcd (<p_1>, <p_2>, <x_1>, …)

     Returns the greatest common divisor of <p_1> and <p_2>.  The flag
     ‘gcd’ determines which algorithm is employed.  Setting ‘gcd’ to
     ‘ez’, ‘subres’, ‘red’, or ‘spmod’ selects the ‘ezgcd’, subresultant
     ‘prs’, reduced, or modular algorithm, respectively.  If ‘gcd’
     ‘false’ then ‘gcd (<p_1>, <p_2>, <x>)’ always returns 1 for all
     <x>.  Many functions (e.g.  ‘ratsimp’, ‘factor’, etc.)  cause gcd’s
     to be taken implicitly.  For homogeneous polynomials it is
     recommended that ‘gcd’ equal to ‘subres’ be used.  To take the gcd
     when an algebraic is present, e.g., ‘gcd (<x>^2 - 2*sqrt(2)* <x> +
     2, <x> - sqrt(2))’, the option variable ‘algebraic’ must be ‘true’
     and ‘gcd’ must not be ‘ez’.

     The ‘gcd’ flag, default: ‘spmod’, if ‘false’ will also prevent the
     greatest common divisor from being taken when expressions are
     converted to canonical rational expression (CRE) form.  This will
     sometimes speed the calculation if gcds are not required.

     See also ‘ezgcd’, ‘gcdex’, ‘gcdivide’, and ‘poly_gcd’.

     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) gcd(p1, p2);
                                      2
          (%o3)                    6 x  + 13 x + 6
          (%i4) p1/gcd(p1, p2), ratsimp;
          (%o4)                         x + 1
          (%i5) p2/gcd(p1, p2), ratsimp;
                                        3
          (%o5)                        x  + x

     ‘ezgcd’ returns a list whose first element is the greatest common
     divisor of the polynomials <p_1> and <p_2>, and whose remaining
     elements are the polynomials divided by the greatest common
     divisor.

          (%i6) ezgcd(p1, p2);
                              2                     3
          (%o6)           [6 x  + 13 x + 6, x + 1, x  + x]

 -- Function: gcdex
          gcdex (<f>, <g>)
          gcdex (<f>, <g>, <x>)

     Returns a list ‘[<a>, <b>, <u>]’ where <u> is the greatest common
     divisor (gcd) of <f> and <g>, and <u> is equal to ‘<a> <f> + <b>
     <g>’.  The arguments <f> and <g> should be univariate polynomials,
     or else polynomials in <x> a supplied main variable since we need
     to be in a principal ideal domain for this to work.  The gcd means
     the gcd regarding <f> and <g> as univariate polynomials with
     coefficients being rational functions in the other variables.

     ‘gcdex’ implements the Euclidean algorithm, where we have a
     sequence of ‘L[i]: [a[i], b[i], r[i]]’ which are all perpendicular
     to ‘[f, g, -1]’ and the next one is built as if ‘q =
     quotient(r[i]/r[i+1])’ then ‘L[i+2]: L[i] - q L[i+1]’, and it
     terminates at ‘L[i+1]’ when the remainder ‘r[i+2]’ is zero.

     The arguments <f> and <g> can be integers.  For this case the
     function ‘igcdex’ is called by ‘gcdex’.

     See also ‘ezgcd’, ‘gcd’, ‘gcdivide’, and ‘poly_gcd’.

     Examples:

          (%i1) gcdex (x^2 + 1, x^3 + 4);
                                 2
                                x  + 4 x - 1  x + 4
          (%o1)/R/           [- ------------, -----, 1]
                                     17        17
          (%i2) % . [x^2 + 1, x^3 + 4, -1];
          (%o2)/R/                        0

     Note that the gcd in the following is ‘1’ since we work in
     ‘k(y)[x]’, not the ‘y+1’ we would expect in ‘k[y, x]’.

          (%i1) gcdex (x*(y + 1), y^2 - 1, x);
                                         1
          (%o1)/R/                 [0, ------, 1]
                                        2
                                       y  - 1

 -- Function: gcfactor (<n>)

     Factors the Gaussian integer <n> over the Gaussian integers, i.e.,
     numbers of the form ‘<a> + <b> %i’ where <a> and <b> are rational
     integers (i.e., ordinary integers).  Factors are normalized by
     making <a> and <b> non-negative.

 -- Function: gfactor (<expr>)

     Factors the polynomial <expr> over the Gaussian integers (that is,
     the integers with the imaginary unit ‘%i’ adjoined).  This is like
     ‘factor (<expr>, <a>^2+1)’ where <a> is ‘%i’.

     Example:

          (%i1) gfactor (x^4 - 1);
          (%o1)           (x - 1) (x + 1) (x - %i) (x + %i)

 -- Function: gfactorsum (<expr>)

     is similar to ‘factorsum’ but applies ‘gfactor’ instead of
     ‘factor’.

 -- Function: hipow (<expr>, <x>)

     Returns the highest explicit exponent of <x> in <expr>.  <x> may be
     a variable or a general expression.  If <x> does not appear in
     <expr>, ‘hipow’ returns ‘0’.

     ‘hipow’ does not consider expressions equivalent to ‘expr’.  In
     particular, ‘hipow’ does not expand ‘expr’, so ‘hipow (<expr>,
     <x>)’ and ‘hipow (expand (<expr>, <x>))’ may yield different
     results.

     Examples:

          (%i1) hipow (y^3 * x^2 + x * y^4, x);
          (%o1)                           2
          (%i2) hipow ((x + y)^5, x);
          (%o2)                           1
          (%i3) hipow (expand ((x + y)^5), x);
          (%o3)                           5
          (%i4) hipow ((x + y)^5, x + y);
          (%o4)                           5
          (%i5) hipow (expand ((x + y)^5), x + y);
          (%o5)                           0

 -- Option variable: intfaclim
     Default value: true

     If ‘true’, maxima will give up factorization of integers if no
     factor is found after trial divisions and Pollard’s rho method and
     factorization will not be complete.

     When ‘intfaclim’ is ‘false’ (this is the case when the user calls
     ‘factor’ explicitly), complete factorization will be attempted.
     ‘intfaclim’ is set to ‘false’ when factors are computed in
     ‘divisors’, ‘divsum’ and ‘totient’.

     Internal calls to ‘factor’ respect the user-specified value of
     ‘intfaclim’.  Setting ‘intfaclim’ to ‘true’ may reduce the time
     spent factoring large integers.

 -- Option variable: keepfloat
     Default value: ‘false’

     When ‘keepfloat’ is ‘true’, prevents floating point numbers from
     being rationalized when expressions which contain them are
     converted to canonical rational expression (CRE) form.

     Note that the function ‘solve’ and those functions calling it
     (‘eigenvalues’, for example) currently ignore this flag, converting
     floating point numbers anyway.

     Examples:

          (%i1) rat(x/2.0);

          rat: replaced 0.5 by 1/2 = 0.5
                                          x
          (%o1)/R/                        -
                                          2
          (%i2) rat(x/2.0), keepfloat;
          (%o2)/R/                      0.5 x

     ‘solve’ ignores ‘keepfloat’:

          (%i1) solve(1.0-x,x), keepfloat;

          rat: replaced 1.0 by 1/1 = 1.0
          (%o1)                        [x = 1]

 -- Function: lopow (<expr>, <x>)

     Returns the lowest exponent of <x> which explicitly appears in
     <expr>.  Thus

          (%i1) lopow ((x+y)^2 + (x+y)^a, x+y);
          (%o1)                       min(a, 2)

 -- Function: lratsubst (<new>, <old>, <expr>)
          lratsubst (‘<old> = <new>’, <expr>)
          lratsubst (‘[ <old_1> = <new_1>, …, <old_n> = <new_n> ]’,
          <expr>)

     ‘lratsubst’ is analogous to ‘subst’ except that it uses ‘ratsubst’
     to perform substitutions.

     The first argument of ‘lratsubst’ is an equation, a list of
     equations or a list of unit length whose first element is a list of
     equations (that is, the first argument is identical in format to
     that accepted by ‘subst’).  The substitutions are made in the order
     given by the list of equations, that is, from left to right.

     Examples:

        • ‘subst’ can carry out multiple substitutions.  ‘lratsubst’ is
          analogous to ‘subst’.
          (%i2) lratsubst ([a = b, c = d], a + c);
          (%o2)                         d + b
          (%i3) lratsubst ([a^2 = b, c^2 = d], (a + e)*c*(a + c));
          (%o3)                (d + a c) e + a d + b c
        • If only one substitution is desired, then a single equation
          may be given as first argument.
          (%i4) lratsubst (a^2 = b, a^3);
          (%o4)                          a b
        • A nested list of substitutions can be used–but it must contain
          only one list.
          (%i5) lratsubst ([[a^2=b*a, b=c]], a^3);

                                                2
          (%o5)                               a  c
          (%i6) lratsubst ([[a^2=b*a, b=c],[a=b]], a^3);


                                           2
          lratsubst: improper argument: [[a  = a b, b = c], [a = b]]
          #0: lratsubst(listofeqns=[[a^2 = a*b,b = c],[a = b]],expr=a^3)
           -- an error. To debug this try: debugmode(true);

     See also ‘fullratsubst’.

 -- Option variable: lrats_max_iter
     Default value: ‘100000’

     The upper limit on the number of iterations that ‘fullratsubst’ and
     ‘lratsubst’ may perform.  It must be set to a positive integer.
     See the example for ‘fullratsubst’.

 -- Option variable: modulus
     Default value: ‘false’

     When ‘modulus’ is a positive number <p>, operations on canonical
     rational expressions (CREs, as returned by ‘rat’ and related
     functions) are carried out modulo <p>, using the so-called
     "balanced" modulus system in which ‘<n> modulo <p>’ is defined as
     an integer <k> in ‘[-(<p>-1)/2, ..., 0, ..., (<p>-1)/2]’ when <p>
     is odd, or ‘[-(<p>/2 - 1), ..., 0, ...., <p>/2]’ when <p> is even,
     such that ‘<a> <p> + <k>’ equals <n> for some integer <a>.

     If <expr> is already in canonical rational expression (CRE) form
     when ‘modulus’ is reset, then you may need to re-rat <expr>, e.g.,
     ‘expr: rat (ratdisrep (expr))’, in order to get correct results.

     Typically ‘modulus’ is set to a prime number.  If ‘modulus’ is set
     to a positive non-prime integer, this setting is accepted, but a
     warning message is displayed.  Maxima signals an error, when zero
     or a negative integer is assigned to ‘modulus’.

     Examples:

          (%i1) modulus:7;
          (%o1)                           7
          (%i2) polymod([0,1,2,3,4,5,6,7]);
          (%o2)            [0, 1, 2, 3, - 3, - 2, - 1, 0]
          (%i3) modulus:false;
          (%o3)                         false
          (%i4) poly:x^6+x^2+1;
                                      6    2
          (%o4)                      x  + x  + 1
          (%i5) factor(poly);
                                      6    2
          (%o5)                      x  + x  + 1
          (%i6) modulus:13;
          (%o6)                          13
          (%i7) factor(poly);
                                2        4      2
          (%o7)               (x  + 6) (x  - 6 x  - 2)
          (%i8) polymod(%);
                                      6    2
          (%o8)                      x  + x  + 1

 -- Function: num (<expr>)

     Returns the numerator of <expr> if it is a ratio.  If <expr> is not
     a ratio, <expr> is returned.

     ‘num’ evaluates its argument.

     See also ‘denom’

          (%i1) g1:(x+2)*(x+1)/((x+3)^2);
                                   (x + 1) (x + 2)
          (%o1)                    ---------------
                                             2
                                      (x + 3)
          (%i2) num(g1);
          (%o2)                    (x + 1) (x + 2)
          (%i3) g2:sin(x)/10*cos(x)/y;
                                    cos(x) sin(x)
          (%o3)                     -------------
                                        10 y
          (%i4) num(g2);
          (%o4)                     cos(x) sin(x)

 -- Function: polydecomp (<p>, <x>)

     Decomposes the polynomial <p> in the variable <x> into the
     functional composition of polynomials in <x>.  ‘polydecomp’ returns
     a list ‘[<p_1>, ..., <p_n>]’ such that

          lambda ([x], p_1) (lambda ([x], p_2) (... (lambda ([x], p_n) (x))
            ...))

     is equal to <p>.  The degree of <p_i> is greater than 1 for <i>
     less than <n>.

     Such a decomposition is not unique.

     Examples:

          (%i1) polydecomp (x^210, x);
                                    7   5   3   2
          (%o1)                   [x , x , x , x ]
          (%i2) p : expand (subst (x^3 - x - 1, x, x^2 - a));
                          6      4      3    2
          (%o2)          x  - 2 x  - 2 x  + x  + 2 x - a + 1
          (%i3) polydecomp (p, x);
                                  2       3
          (%o3)                 [x  - a, x  - x - 1]

     The following function composes ‘L = [e_1, ..., e_n]’ as functions
     in ‘x’; it is the inverse of polydecomp:

          (%i1) compose (L, x) :=
            block ([r : x], for e in L do r : subst (e, x, r), r) $

     Re-express above example using ‘compose’:

          (%i1) polydecomp (compose ([x^2 - a, x^3 - x - 1], x), x);
                                    2       3
          (%o1)          [compose([x  - a, x  - x - 1], x)]

     Note that though ‘compose (polydecomp (<p>, <x>), <x>)’ always
     returns <p> (unexpanded), ‘polydecomp (compose ([<p_1>, ...,
     <p_n>], <x>), <x>)’ does not necessarily return ‘[<p_1>, ...,
     <p_n>]’:

          (%i1) polydecomp (compose ([x^2 + 2*x + 3, x^2], x), x);
                                     2             2
          (%o1)           [compose([x  + 2 x + 3, x ], x)]
          (%i2) polydecomp (compose ([x^2 + x + 1, x^2 + x + 1], x), x);
                                  2           2
          (%o2)        [compose([x  + x + 1, x  + x + 1], x)]

 -- Function: polymod
          polymod (<p>)
          polymod (<p>, <m>)

     Converts the polynomial <p> to a modular representation with
     respect to the current modulus which is the value of the variable
     ‘modulus’.

     ‘polymod (<p>, <m>)’ specifies a modulus <m> to be used instead of
     the current value of ‘modulus’.

     See ‘modulus’.

 -- Function: polynomialp
          polynomialp (<p>, <L>, <coeffp>, <exponp>)
          polynomialp (<p>, <L>, <coeffp>)
          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: quotient
          quotient (<p_1>, <p_2>)
          quotient (<p_1>, <p_2>, <x_1>, …, <x_n>)

     Returns the polynomial <p_1> divided by the polynomial <p_2>.  The
     arguments <x_1>, …, <x_n> are interpreted as in ‘ratvars’.

     ‘quotient’ returns the first element of the two-element list
     returned by ‘divide’.

 -- Function: rat
          rat (<expr>)
          rat (<expr>, <x_1>, …, <x_n>)

     Converts <expr> to canonical rational expression (CRE) form by
     expanding and combining all terms over a common denominator and
     cancelling out the greatest common divisor of the numerator and
     denominator, as well as converting floating point numbers to
     rational numbers within a tolerance of ‘ratepsilon’.  The variables
     are ordered according to the <x_1>, …, <x_n>, if specified, as in
     ‘ratvars’.

     ‘rat’ does not generally simplify functions other than addition
     ‘+’, subtraction ‘-’, multiplication ‘*’, division ‘/’, and
     exponentiation to an integer power, whereas ‘ratsimp’ does handle
     those cases.  Note that atoms (numbers and variables) in CRE form
     are not the same as they are in the general form.  For example,
     ‘rat(x)- x’ yields ‘rat(0)’ which has a different internal
     representation than 0.

     When ‘ratfac’ is ‘true’, ‘rat’ yields a partially factored form for
     CRE. During rational operations the expression is maintained as
     fully factored as possible without an actual call to the factor
     package.  This should always save space and may save some time in
     some computations.  The numerator and denominator are still made
     relatively prime (e.g., ‘rat((x^2 - 1)^4/(x + 1)^2)’ yields ‘(x -
     1)^4 (x + 1)^2’ when ‘ratfac’ is ‘true’), but the factors within
     each part may not be relatively prime.

     ‘ratprint’ if ‘false’ suppresses the printout of the message
     informing the user of the conversion of floating point numbers to
     rational numbers.

     ‘keepfloat’ if ‘true’ prevents floating point numbers from being
     converted to rational numbers.

     See also ‘ratexpand’ and ‘ratsimp’.

     Examples:
          (%i1) ((x - 2*y)^4/(x^2 - 4*y^2)^2 + 1)*(y + a)*(2*y + x) /
                (4*y^2 + x^2);
                                                     4
                                            (x - 2 y)
                        (y + a) (2 y + x) (------------ + 1)
                                             2      2 2
                                           (x  - 4 y )
          (%o1)         ------------------------------------
                                        2    2
                                     4 y  + x
          (%i2) rat (%, y, a, x);
                                      2 a + 2 y
          (%o2)/R/                    ---------
                                       x + 2 y

 -- Option variable: ratalgdenom
     Default value: ‘true’

     When ‘ratalgdenom’ is ‘true’, allows rationalization of
     denominators with respect to radicals to take effect.
     ‘ratalgdenom’ has an effect only when canonical rational
     expressions (CRE) are used in algebraic mode.

 -- Function: ratcoef
          ratcoef (<expr>, <x>, <n>)
          ratcoef (<expr>, <x>)

     Returns the coefficient of the expression ‘<x>^<n>’ in the
     expression <expr>.  If omitted, <n> is assumed to be 1.

     The return value is free (except possibly in a non-rational sense)
     of the variables in <x>.  If no coefficient of this type exists, 0
     is returned.

     ‘ratcoef’ expands and rationally simplifies its first argument and
     thus it may produce answers different from those of ‘coeff’ which
     is purely syntactic.  Thus ‘ratcoef ((x + 1)/y + x, x)’ returns ‘(y
     + 1)/y’ whereas ‘coeff’ returns 1.

     ‘ratcoef (<expr>, <x>, 0)’, viewing <expr> as a sum, returns a sum
     of those terms which do not contain <x>.  Therefore if <x> occurs
     to any negative powers, ‘ratcoef’ should not be used.

     Since <expr> is rationally simplified before it is examined,
     coefficients may not appear quite the way they were envisioned.

     Example:

          (%i1) s: a*x + b*x + 5$
          (%i2) ratcoef (s, a + b);
          (%o2)                           x

 -- Function: ratdenom (<expr>)

     Returns the denominator of <expr>, after coercing <expr> to a
     canonical rational expression (CRE). The return value is a CRE.

     <expr> is coerced to a CRE by ‘rat’ if it is not already a CRE.
     This conversion may change the form of <expr> by putting all terms
     over a common denominator.

     ‘denom’ is similar, but returns an ordinary expression instead of a
     CRE. Also, ‘denom’ does not attempt to place all terms over a
     common denominator, and thus some expressions which are considered
     ratios by ‘ratdenom’ are not considered ratios by ‘denom’.

 -- Option variable: ratdenomdivide
     Default value: ‘true’

     When ‘ratdenomdivide’ is ‘true’, ‘ratexpand’ expands a ratio in
     which the numerator is a sum into a sum of ratios, all having a
     common denominator.  Otherwise, ‘ratexpand’ collapses a sum of
     ratios into a single ratio, the numerator of which is the sum of
     the numerators of each ratio.

     Examples:

          (%i1) expr: (x^2 + x + 1)/(y^2 + 7);
                                      2
                                     x  + x + 1
          (%o1)                      ----------
                                        2
                                       y  + 7
          (%i2) ratdenomdivide: true$
          (%i3) ratexpand (expr);
                                 2
                                x        x        1
          (%o3)               ------ + ------ + ------
                               2        2        2
                              y  + 7   y  + 7   y  + 7
          (%i4) ratdenomdivide: false$
          (%i5) ratexpand (expr);
                                      2
                                     x  + x + 1
          (%o5)                      ----------
                                        2
                                       y  + 7
          (%i6) expr2: a^2/(b^2 + 3) + b/(b^2 + 3);
                                               2
                                     b        a
          (%o6)                    ------ + ------
                                    2        2
                                   b  + 3   b  + 3
          (%i7) ratexpand (expr2);
                                            2
                                       b + a
          (%o7)                        ------
                                        2
                                       b  + 3

 -- Function: ratdiff (<expr>, <x>)

     Differentiates the rational expression <expr> with respect to <x>.
     <expr> must be a ratio of polynomials or a polynomial in <x>.  The
     argument <x> may be a variable or a subexpression of <expr>.

     The result is equivalent to ‘diff’, although perhaps in a different
     form.  ‘ratdiff’ may be faster than ‘diff’, for rational
     expressions.

     ‘ratdiff’ returns a canonical rational expression (CRE) if ‘expr’
     is a CRE. Otherwise, ‘ratdiff’ returns a general expression.

     ‘ratdiff’ considers only the dependence of <expr> on <x>, and
     ignores any dependencies established by ‘depends’.

     Example:

          (%i1) expr: (4*x^3 + 10*x - 11)/(x^5 + 5);
                                     3
                                  4 x  + 10 x - 11
          (%o1)                   ----------------
                                        5
                                       x  + 5
          (%i2) ratdiff (expr, x);
                              7       5       4       2
                           8 x  + 40 x  - 55 x  - 60 x  - 50
          (%o2)          - ---------------------------------
                                    10       5
                                   x   + 10 x  + 25
          (%i3) expr: f(x)^3 - f(x)^2 + 7;
                                   3       2
          (%o3)                   f (x) - f (x) + 7
          (%i4) ratdiff (expr, f(x));
                                     2
          (%o4)                   3 f (x) - 2 f(x)
          (%i5) expr: (a + b)^3 + (a + b)^2;
                                        3          2
          (%o5)                  (b + a)  + (b + a)
          (%i6) ratdiff (expr, a + b);
                              2                    2
          (%o6)            3 b  + (6 a + 2) b + 3 a  + 2 a

 -- Function: ratdisrep (<expr>)

     Returns its argument as a general expression.  If <expr> is a
     general expression, it is returned unchanged.

     Typically ‘ratdisrep’ is called to convert a canonical rational
     expression (CRE) into a general expression.  This is sometimes
     convenient if one wishes to stop the "contagion", or use rational
     functions in non-rational contexts.

     See also ‘totaldisrep’.

 -- Function: ratexpand (<expr>)
 -- Option variable: ratexpand

     Expands <expr> by multiplying out products of sums and
     exponentiated sums, combining fractions over a common denominator,
     cancelling the greatest common divisor of the numerator and
     denominator, then splitting the numerator (if a sum) into its
     respective terms divided by the denominator.

     The return value of ‘ratexpand’ is a general expression, even if
     <expr> is a canonical rational expression (CRE).

     The switch ‘ratexpand’ if ‘true’ will cause CRE expressions to be
     fully expanded when they are converted back to general form or
     displayed, while if it is ‘false’ then they will be put into a
     recursive form.  See also ‘ratsimp’.

     When ‘ratdenomdivide’ is ‘true’, ‘ratexpand’ expands a ratio in
     which the numerator is a sum into a sum of ratios, all having a
     common denominator.  Otherwise, ‘ratexpand’ collapses a sum of
     ratios into a single ratio, the numerator of which is the sum of
     the numerators of each ratio.

     When ‘keepfloat’ is ‘true’, prevents floating point numbers from
     being rationalized when expressions which contain them are
     converted to canonical rational expression (CRE) form.

     Examples:

          (%i1) ratexpand ((2*x - 3*y)^3);
                               3         2       2        3
          (%o1)          - 27 y  + 54 x y  - 36 x  y + 8 x
          (%i2) expr: (x - 1)/(x + 1)^2 + 1/(x - 1);
                                   x - 1       1
          (%o2)                   -------- + -----
                                         2   x - 1
                                  (x + 1)
          (%i3) expand (expr);
                              x              1           1
          (%o3)          ------------ - ------------ + -----
                          2              2             x - 1
                         x  + 2 x + 1   x  + 2 x + 1
          (%i4) ratexpand (expr);
                                  2
                               2 x                 2
          (%o4)           --------------- + ---------------
                           3    2            3    2
                          x  + x  - x - 1   x  + x  - x - 1

 -- Option variable: ratfac
     Default value: ‘false’

     When ‘ratfac’ is ‘true’, canonical rational expressions (CRE) are
     manipulated in a partially factored form.

     During rational operations the expression is maintained as fully
     factored as possible without calling ‘factor’.  This should always
     save space and may save time in some computations.  The numerator
     and denominator are made relatively prime, for example ‘factor
     ((x^2 - 1)^4/(x + 1)^2)’ yields ‘(x - 1)^4 (x + 1)^2’, but the
     factors within each part may not be relatively prime.

     In the ‘ctensor’ (Component Tensor Manipulation) package, Ricci,
     Einstein, Riemann, and Weyl tensors and the scalar curvature are
     factored automatically when ‘ratfac’ is ‘true’.  ‘ratfac’ should
     only be set for cases where the tensorial components are known to
     consist of few terms.

     The ‘ratfac’ and ‘ratweight’ schemes are incompatible and may not
     both be used at the same time.

 -- Function: ratnumer (<expr>)

     Returns the numerator of <expr>, after coercing <expr> to a
     canonical rational expression (CRE). The return value is a CRE.

     <expr> is coerced to a CRE by ‘rat’ if it is not already a CRE.
     This conversion may change the form of <expr> by putting all terms
     over a common denominator.

     ‘num’ is similar, but returns an ordinary expression instead of a
     CRE. Also, ‘num’ does not attempt to place all terms over a common
     denominator, and thus some expressions which are considered ratios
     by ‘ratnumer’ are not considered ratios by ‘num’.

 -- Function: ratp (<expr>)

     Returns ‘true’ if <expr> is a canonical rational expression (CRE)
     or extended CRE, otherwise ‘false’.

     CRE are created by ‘rat’ and related functions.  Extended CRE are
     created by ‘taylor’ and related functions.

 -- Option variable: ratprint
     Default value: ‘true’

     When ‘ratprint’ is ‘true’, a message informing the user of the
     conversion of floating point numbers to rational numbers is
     displayed.

 -- Function: ratsimp (<expr>)
 -- Function: ratsimp (<expr>, <x_1>, …, <x_n>)

     Simplifies the expression <expr> and all of its subexpressions,
     including the arguments to non-rational functions.  The result is
     returned as the quotient of two polynomials in a recursive form,
     that is, the coefficients of the main variable are polynomials in
     the other variables.  Variables may include non-rational functions
     (e.g., ‘sin (x^2 + 1)’) and the arguments to any such functions are
     also rationally simplified.

     ‘ratsimp (<expr>, <x_1>, ..., <x_n>)’ enables rational
     simplification with the specification of variable ordering as in
     ‘ratvars’.

     When ‘ratsimpexpons’ is ‘true’, ‘ratsimp’ is applied to the
     exponents of expressions during simplification.

     See also ‘ratexpand’.  Note that ‘ratsimp’ is affected by some of
     the flags which affect ‘ratexpand’.

     Examples:

          (%i1) sin (x/(x^2 + x)) = exp ((log(x) + 1)^2 - log(x)^2);
                                                   2      2
                             x         (log(x) + 1)  - log (x)
          (%o1)        sin(------) = %e
                            2
                           x  + x
          (%i2) ratsimp (%);
                                       1          2
          (%o2)                  sin(-----) = %e x
                                     x + 1
          (%i3) ((x - 1)^(3/2) - (x + 1)*sqrt(x - 1))/sqrt((x - 1)*(x + 1));
                                 3/2
                          (x - 1)    - sqrt(x - 1) (x + 1)
          (%o3)           --------------------------------
                               sqrt((x - 1) (x + 1))
          (%i4) ratsimp (%);
                                     2 sqrt(x - 1)
          (%o4)                    - -------------
                                           2
                                     sqrt(x  - 1)
          (%i5) x^(a + 1/a), ratsimpexpons: true;
                                         2
                                        a  + 1
                                        ------
                                          a
          (%o5)                        x

 -- Option variable: ratsimpexpons
     Default value: ‘false’

     When ‘ratsimpexpons’ is ‘true’, ‘ratsimp’ is applied to the
     exponents of expressions during simplification.

 -- Option variable: radsubstflag
     Default value: ‘false’

     ‘radsubstflag’, if ‘true’, permits ‘ratsubst’ to make substitutions
     such as ‘u’ for ‘sqrt (x)’ in ‘x’.

 -- Function: ratsubst (<a>, <b>, <c>)

     Substitutes <a> for <b> in <c> and returns the resulting
     expression.  <b> may be a sum, product, power, etc.

     ‘ratsubst’ knows something of the meaning of expressions whereas
     ‘subst’ does a purely syntactic substitution.  Thus ‘subst (a, x +
     y, x + y + z)’ returns ‘x + y + z’ whereas ‘ratsubst’ returns ‘z +
     a’.

     When ‘radsubstflag’ is ‘true’, ‘ratsubst’ makes substitutions for
     radicals in expressions which don’t explicitly contain them.

     ‘ratsubst’ ignores the value ‘true’ of the option variables
     ‘keepfloat’, ‘float’, and ‘numer’.

     Examples:

          (%i1) ratsubst (a, x*y^2, x^4*y^3 + x^4*y^8);
                                        3      4
          (%o1)                      a x  y + a
          (%i2) cos(x)^4 + cos(x)^3 + cos(x)^2 + cos(x) + 1;
                         4         3         2
          (%o2)       cos (x) + cos (x) + cos (x) + cos(x) + 1
          (%i3) ratsubst (1 - sin(x)^2, cos(x)^2, %);
                      4           2                     2
          (%o3)    sin (x) - 3 sin (x) + cos(x) (2 - sin (x)) + 3
          (%i4) ratsubst (1 - cos(x)^2, sin(x)^2, sin(x)^4);
                                  4           2
          (%o4)                cos (x) - 2 cos (x) + 1
          (%i5) radsubstflag: false$
          (%i6) ratsubst (u, sqrt(x), x);
          (%o6)                           x
          (%i7) radsubstflag: true$
          (%i8) ratsubst (u, sqrt(x), x);
                                          2
          (%o8)                          u

 -- Function: ratvars (<x_1>, …, <x_n>)
 -- Function: ratvars ()
 -- System variable: ratvars

     Declares main variables <x_1>, …, <x_n> for rational expressions.
     <x_n>, if present in a rational expression, is considered the main
     variable.  Otherwise, <x_[n-1]> is considered the main variable if
     present, and so on through the preceding variables to <x_1>, which
     is considered the main variable only if none of the succeeding
     variables are present.

     If a variable in a rational expression is not present in the
     ‘ratvars’ list, it is given a lower priority than <x_1>.

     The arguments to ‘ratvars’ can be either variables or non-rational
     functions such as ‘sin(x)’.

     The variable ‘ratvars’ is a list of the arguments of the function
     ‘ratvars’ when it was called most recently.  Each call to the
     function ‘ratvars’ resets the list.  ‘ratvars ()’ clears the list.

 -- Option variable: ratvarswitch
     Default value: ‘true’

     Maxima keeps an internal list in the Lisp variable ‘VARLIST’ of the
     main variables for rational expressions.  If ‘ratvarswitch’ is
     ‘true’, every evaluation starts with a fresh list ‘VARLIST’.  This
     is the default behavior.  Otherwise, the main variables from
     previous evaluations are not removed from the internal list
     ‘VARLIST’.

     The main variables, which are declared with the function ‘ratvars’
     are not affected by the option variable ‘ratvarswitch’.

     Examples:

     If ‘ratvarswitch’ is ‘true’, every evaluation starts with a fresh
     list ‘VARLIST’.

          (%i1) ratvarswitch:true$

          (%i2) rat(2*x+y^2);
                                       2
          (%o2)/R/                    y  + 2 x
          (%i3) :lisp varlist
          ($X $Y)

          (%i3) rat(2*a+b^2);
                                       2
          (%o3)/R/                    b  + 2 a

          (%i4) :lisp varlist
          ($A $B)

     If ‘ratvarswitch’ is ‘false’, the main variables from the last
     evaluation are still present.

          (%i4) ratvarswitch:false$

          (%i5) rat(2*x+y^2);
                                       2
          (%o5)/R/                    y  + 2 x
          (%i6) :lisp varlist
          ($X $Y)

          (%i6) rat(2*a+b^2);
                                       2
          (%o6)/R/                    b  + 2 a

          (%i7) :lisp varlist
          ($A $B $X $Y)

 -- Function: ratweight
          ratweight (<x_1>, <w_1>, …, <x_n>, <w_n>)
          ratweight ()

     Assigns a weight <w_i> to the variable <x_i>.  This causes a term
     to be replaced by 0 if its weight exceeds the value of the variable
     ‘ratwtlvl’ (default yields no truncation).  The weight of a term is
     the sum of the products of the weight of a variable in the term
     times its power.  For example, the weight of ‘3 x_1^2 x_2’ is ‘2
     w_1 + w_2’.  Truncation according to ‘ratwtlvl’ is carried out only
     when multiplying or exponentiating canonical rational expressions
     (CRE).

     ‘ratweight ()’ returns the cumulative list of weight assignments.

     Note: The ‘ratfac’ and ‘ratweight’ schemes are incompatible and may
     not both be used at the same time.

     Examples:

          (%i1) ratweight (a, 1, b, 1);
          (%o1)                     [a, 1, b, 1]
          (%i2) expr1: rat(a + b + 1)$
          (%i3) expr1^2;
                            2                  2
          (%o3)/R/         b  + (2 a + 2) b + a  + 2 a + 1
          (%i4) ratwtlvl: 1$
          (%i5) expr1^2;
          (%o5)/R/                  2 b + 2 a + 1

 -- System variable: ratweights
     Default value: ‘[]’

     ‘ratweights’ is the list of weights assigned by ‘ratweight’.  The
     list is cumulative: each call to ‘ratweight’ places additional
     items in the list.

     ‘kill (ratweights)’ and ‘save (ratweights)’ both work as expected.

 -- Option variable: ratwtlvl
     Default value: ‘false’

     ‘ratwtlvl’ is used in combination with the ‘ratweight’ function to
     control the truncation of canonical rational expressions (CRE). For
     the default value of ‘false’, no truncation occurs.

 -- Function: remainder
          remainder (<p_1>, <p_2>)
          remainder (<p_1>, <p_2>, <x_1>, …, <x_n>)

     Returns the remainder of the polynomial <p_1> divided by the
     polynomial <p_2>.  The arguments <x_1>, …, <x_n> are interpreted as
     in ‘ratvars’.

     ‘remainder’ returns the second element of the two-element list
     returned by ‘divide’.

 -- Function: resultant (<p_1>, <p_2>, <x>)

     The function ‘resultant’ computes the resultant of the two
     polynomials <p_1> and <p_2>, eliminating the variable <x>.  The
     resultant is a determinant of the coefficients of <x> in <p_1> and
     <p_2>, which equals zero if and only if <p_1> and <p_2> have a
     non-constant factor in common.

     If <p_1> or <p_2> can be factored, it may be desirable to call
     ‘factor’ before calling ‘resultant’.

     The option variable ‘resultant’ controls which algorithm will be
     used to compute the resultant.  See the option variable
     ‘resultant’.

     The function ‘bezout’ takes the same arguments as ‘resultant’ and
     returns a matrix.  The determinant of the return value is the
     desired resultant.

     Examples:

          (%i1) resultant(2*x^2+3*x+1, 2*x^2+x+1, x);
          (%o1)                           8
          (%i2) resultant(x+1, x+1, x);
          (%o2)                           0
          (%i3) resultant((x+1)*x, (x+1), x);
          (%o3)                           0
          (%i4) resultant(a*x^2+b*x+1, c*x + 2, x);
                                   2
          (%o4)                   c  - 2 b c + 4 a

          (%i5) bezout(a*x^2+b*x+1, c*x+2, x);
                                  [ 2 a  2 b - c ]
          (%o5)                   [              ]
                                  [  c      2    ]
          (%i6) determinant(%);
          (%o6)                   4 a - (2 b - c) c

 -- Option variable: resultant
     Default value: ‘subres’

     The option variable ‘resultant’ controls which algorithm will be
     used to compute the resultant with the function ‘resultant’.  The
     possible values are:

     ‘subres’
          for the subresultant polynomial remainder sequence (PRS)
          algorithm,
     ‘mod’
          (not enabled) for the modular resultant algorithm, and
     ‘red’
          for the reduced polynomial remainder sequence (PRS) algorithm.

     On most problems the default value ‘subres’ should be best.

 -- Option variable: savefactors
     Default value: ‘false’

     When ‘savefactors’ is ‘true’, causes the factors of an expression
     which is a product of factors to be saved by certain functions in
     order to speed up later factorizations of expressions containing
     some of the same factors.

 -- Function: showratvars (<expr>)

     Returns a list of the canonical rational expression (CRE) variables
     in expression ‘expr’.

     See also ‘ratvars’.

 -- Function: sqfr (<expr>)

     is similar to ‘factor’ except that the polynomial factors are
     "square-free."  That is, they have factors only of degree one.
     This algorithm, which is also used by the first stage of ‘factor’,
     utilizes the fact that a polynomial has in common with its n’th
     derivative all its factors of degree greater than n.  Thus by
     taking greatest common divisors with the polynomial of the
     derivatives with respect to each variable in the polynomial, all
     factors of degree greater than 1 can be found.

     Example:

          (%i1) sqfr (4*x^4 + 4*x^3 - 3*x^2 - 4*x - 1);
                                          2   2
          (%o1)                  (2 x + 1)  (x  - 1)

 -- Function: tellrat
          tellrat (<p_1>, …, <p_n>)
          tellrat ()

     Adds to the ring of algebraic integers known to Maxima the elements
     which are the solutions of the polynomials <p_1>, …, <p_n>.  Each
     argument <p_i> is a polynomial with integer coefficients.

     ‘tellrat (<x>)’ effectively means substitute 0 for <x> in rational
     functions.

     ‘tellrat ()’ returns a list of the current substitutions.

     ‘algebraic’ must be set to ‘true’ in order for the simplification
     of algebraic integers to take effect.

     Maxima initially knows about the imaginary unit ‘%i’ and all roots
     of integers.

     There is a command ‘untellrat’ which takes kernels and removes
     ‘tellrat’ properties.

     When ‘tellrat’’ing a multivariate polynomial, e.g., ‘tellrat (x^2 -
     y^2)’, there would be an ambiguity as to whether to substitute
     ‘<y>^2’ for ‘<x>^2’ or vice versa.  Maxima picks a particular
     ordering, but if the user wants to specify which, e.g.  ‘tellrat
     (y^2 = x^2)’ provides a syntax which says replace ‘<y>^2’ by
     ‘<x>^2’.

     Examples:

          (%i1) 10*(%i + 1)/(%i + 3^(1/3));
                                     10 (%i + 1)
          (%o1)                      -----------
                                            1/3
                                      %i + 3
          (%i2) ev (ratdisrep (rat(%)), algebraic);
                       2/3      1/3              2/3      1/3
          (%o2)    (4 3    - 2 3    - 4) %i + 2 3    + 4 3    - 2
          (%i3) tellrat (1 + a + a^2);
                                      2
          (%o3)                     [a  + a + 1]
          (%i4) 1/(a*sqrt(2) - 1) + a/(sqrt(3) + sqrt(2));
                                1                 a
          (%o4)           ------------- + -----------------
                          sqrt(2) a - 1   sqrt(3) + sqrt(2)
          (%i5) ev (ratdisrep (rat(%)), algebraic);
                   (7 sqrt(3) - 10 sqrt(2) + 2) a - 2 sqrt(2) - 1
          (%o5)    ----------------------------------------------
                                         7
          (%i6) tellrat (y^2 = x^2);
                                  2    2   2
          (%o6)                 [y  - x , a  + a + 1]

 -- Function: totaldisrep (<expr>)

     Converts every subexpression of <expr> from canonical rational
     expressions (CRE) to general form and returns the result.  If
     <expr> is itself in CRE form then ‘totaldisrep’ is identical to
     ‘ratdisrep’.

     ‘totaldisrep’ may be useful for ratdisrepping expressions such as
     equations, lists, matrices, etc., which have some subexpressions in
     CRE form.

 -- Function: untellrat (<x_1>, …, <x_n>)

     Removes ‘tellrat’ properties from <x_1>, …, <x_n>.

