DocumentationÂ¶
Getting startedÂ¶
InstallationÂ¶
Yacas is available for a variety of platforms. See http://www.yacas.org/getting_started/downloads/ for binary packages and installation instructions.
Installation from sourcesÂ¶
Getting sourcesÂ¶
Version 1.8.0 can be downloaded from https://github.com/grzegorzmazur/yacas/archive/v1.8.0.zip or https://github.com/grzegorzmazur/yacas/archive/v1.8.0.tar.gz, while the current development version is accessible from https://github.com/grzegorzmazur/yacas/archive/develop.zip.
CompilationÂ¶
Common build optionsÂ¶
 ENABLE_CYACAS_CONSOLE
Build text console for the native yacas engine. Enabled by default.
 ENABLE_CYACAS_GUI
Build graphical interface for the native yacas engine. Requires Qt 5.5. Enabled by default.
 ENABLE_CYACAS_GUI_PRIVATE_CODEMIRROR
Use bundled copy of CodeMirror. Enabled by default.
 ENABLE_CYACAS_GUI_PRIVATE_MATHJAX
Use bundled copy of MathJax. Enabled by default.
 ENABLE_CYACAS_KERNEL
Build native yacas kernel for Jupyter Notebook. Requires Boost, ZeroMQ and zmqpp. Disabled by default.
 ENABLE_JYACAS
Build the Java yacas engine and text console for it. Disabled by default.
 ENABLE_DOCS
Generate HTML documentation. Disabled by default.
MacOS XÂ¶
Open
Terminal
windowChange directory to the yacas source directory
Execute
mkdir build cd build cmake G Xcode [Dcommon_option=value ...] ..
Open generated project in
Xcode
and build the Release variant
Microsoft WindowsÂ¶
Open
Command Prompt
windowChange directory to the yacas source directory
Execute
mkdir build cd build cmake G "Visual Studio 14 2015 Win64" [Dcommon_option=value ...] ..
Open generated project in
Visual Studio
and build the Release variant
LinuxÂ¶
Open
Terminal
windowChange directory to the yacas source directory
Execute
mkdir build cd build cmake DCMAKE_BUILD_TYPE=Release [Dcommon_option=value ...] .. make
To install newly built binaries execute
make install
JavaÂ¶
Open
Terminal
orCommand Prompt
windowChange directory to the yacas source directory
Execute
ant jar
yacasonlineÂ¶
build yacas using emscripten
mkdir build_js cd build_js cmake DCMAKE_TOOLCHAIN_FILE=<EMSCRIPTEN_ROOT>/cmake/Modules/Platform/Emscripten.cmake \ DENABLE_CYACAS_GUI=No DENABLE_CYACAS_KERNEL=No DENABLE_JYACAS=No \ DENABLE_DOCS=No DCMAKE_BUILD_TYPE=Release .. make cd ..
where
<EMSCRIPTEN_ROOT>
stands for the Emscripten root directorycopy
build_js/cyacas/yacas/yacas.js
build_js/cyacas/yacas/yacas.js.mem
cyacas/yacasgui/resources/yacasonline.html
cyacas/yacasgui/resources/jquery/
cyacas/yacasgui/resources/mathbar/
cyacas/yacasgui/resources/plot3d/
cyacas/yacasgui/resources/yacas_gui/
to the installation directory
TutorialÂ¶
Yacas syntaxÂ¶
Expressions in Yacas are generally built up of words. We will not bore
you with the exact definitions of such words, but roughly speaking
they are either sequences of alphabetic letters, or a number, or a
bracket, or space to separate words, or a word built up from symbols
like +
, 
, *
, <
, etc.. If you want, you can mix
these different types of characters, by surrounding them with
quotes. Thus, "This text"
is what is called one token, surrounded
by quotes.
The usual notation people use when writing down a calculation is
called the infix notation, and you can readily recognize it, as for
example 2+3
and 3*4
. Prefix operators also exist. These
operators come before an expression, like for example the unary minus
sign (called unary because it accepts one argument), (3*4)
. In
addition to prefix operators there are also postfix operators, like
the exclamation mark to calculate the factorial of a number, 10!
.
Yacas understands standard simple arithmetic expressions. Some examples:
2+3
(addition)2*3
(multiplication)23
(subtraction)2^3
(raising powers)2+3*4
(2+3)*4
6/3
(division)1/3
Divisions are not reduced to real numbers, but kept as a rational for
as long as possible, since the rational is an exact correct expression
(and any real number would just be an approximation). Yacas is able to
change a rational in to a number with the function N
, for example
N(1/3)
.
Operators have precedence, meaning that certain operations are done
first before others are done. For example, in 2+3*4
the
multiplication is performed before the addition. The usual way to
change the order of a calculation is with round brackets. The round
brackets in the expression (2+3)*4
will force Yacas to first add 2
and 3, and then multiply the result.
Simple function calls have their arguments between round brackets,
separated by commas. Examples are Sin(Pi)
(which indicates that
you are interested in the value of the trigonometric function
\(\sin\) applied to the constant \(\pi\)), and
Min(5,1,3,5,10)
(which should return the lowest of its arguments,
5
in this case). Functions usually have the form f()
,
f(x)
or f(x,y,z,...)
depending on how many arguments the
function accepts. Functions always return a result. For example,
Cos(0)
should return 1
. Evaluating functions can be thought of
as simplifying an expression as much as possible. Sometimes further
simplification is not possible and a function returns itself
unsimplified, like taking the square root of an integer Sqrt(2)
. A
reduction to a number would be an approximation. We explain elsewhere
how to get Yacas to simplify an expression to a number.
Yacas allows for use of the infix notation, but with some
additions. Functions can be bodied, meaning that the last argument
is written past the close bracket. An example is ForEach
, where we
write ForEach(item, 1 .. 10) Echo(item);
. Echo(item)
is the
last argument to the function ForEach
.
A list is enclosed with curly braces, and is written out with commas between the
elements, like for example {1,2,3}
. items in lists (and things
that can be made to look like lists, like arrays and strings), can
then be accessed by indicating the index between square brackets after
the object. {a,b,c}[2]
should return b
, as b
is the second
element in the list (Yacas starts counting from 1 when accessing
elements). The same can be done with strings: "abc"[2]
.
And finally, function calls can be grouped together, where they get
executed one at a time, and the result of executing the last
expression is returned. This is done through square brackets, as [
Echo("Hello"); Echo("World"); True; ];
, which first writes Hello
to screen, then World
on the next line, and then returns True
.
When you type in an expression, you have to take in to account the
fact that Yacas is casesensitive. This means that a function sin
(with all lowercase) is a different function from Sin
(which
starts with a capital S), and the variable v
is a different one
from V
.
Using Yacas from the calculation centerÂ¶
As mentioned earlier, you can type in commands on the command line in
the calculation center. Typically, you would enter one statement per
line, for example, click on Sin(Pi/2);
. The has a memory, and
remembers results from calculations performed before. For example, if
you define a function on a line (or set a variable to a value), the
defined function (or variable) are available to be used in following
lines. A session can be restarted (forgetting all previous definitions
and results) by typing restart
. All memory is erased in that
case.
Statements should end with a semicolon ;
although this is not
required in interactive sessions (Yacas will append a semicolon at end
of line to finish the statement).
The command line has a history list, so it should be easy to browse through the expressions you entered previously using the up and down arrow keys.
When a few characters have been typed, the command line will use the characters before the cursor as a filter into the history, and allow you to browse through all the commands in the history that start with these characters quickly, instead of browsing through the entire history. If the system recognized the first few characters, it will also show the commands that start with the sequence entered. You can use the arrow keys to browse through this list, and then select the intended function to be inserted by pressing enter.
Commands spanning multiple lines can (and actually have to) be entered
by using a trailing backslash at end of each continued line. For
example, clicking on 2+3+
will result in an
error, but entering the same with a backslash at the end and then
entering another expression will concatenate the two lines and
evaluate the concatenated input.
Incidentally, any text Yacas prints without a prompt is either
a message printed by a function as a sideeffect, or an error
message. Resulting values of expressions are always printed after an
Out>
prompt.
Yacas as a symbolic calculatorÂ¶
We are ready to try some calculations. Yacas uses a Clike
infix syntax and is casesensitive. Here are some exact manipulations
with fractions for a start: 1/14+5/21*(30(1+1/2)*5^2);
The standard scripts already contain a simple math library for
symbolic simplification of basic algebraic functions. Any names such
as x
are treated as independent, symbolic variables and are not
evaluated by default. Some examples to try:
0+x
x+1*y
Sin(ArcSin(alpha))+Tan(ArcTan(beta))
Note that the answers are not just simple numbers here, but actual expressions. This is where Yacas shines. It was built specifically to do calculations that have expressions as answers.
In Yacas after a calculation is done, you can refer to the previous
result with %
. For example, we could first type (x+1)*(x1)
,
and then decide we would like to see a simpler version of that
expression, and thus type Simplify(%)
,
which should result in x^21
.
The special operator %
automatically recalls the result from the
previous line. The function Simplify
attempts to reduce an
expression to a simpler form. Note that standard function names in
Yacas are typically capitalized. Multiple capitalization such as
ArcSin
is sometimes used. The underscore character _
is a
reserved operator symbol and cannot be part of variable or function
names.
Yacas offers some more powerful symbolic manipulation operations. A few will be shown here to wetten the appetite.
Some simple equation solving algorithms are in place:
Solve(x/(1+x) == a, x);
Solve(x^2+x == 0, x);
Solve(a+x*y==z,x);
(Note the use of the ==
operator, which does not evaluate to
anything, to denote an â€śequationâ€ť object.)
Taylor series are supported, for example: Taylor(x,0,3) Exp(x)
is
a bodied operator that expands Exp(x)
for x
around x=0
, up
to order 3.
Symbolic manipulation is the main application of Yacas. This is a small tour of the capabilities Yacas currently offers. Note that this list of examples is far from complete. Yacas contains a few hundred commands, of which only a few are shown here.
Expand((1+x)^5);
(expand the expression into a polynomial)Limit(x,0) Sin(x)/x;
(calculate the limit ofSin(x)/x
asx
approaches zero)Newton(Sin(x),x,3,0.0001);
(use Newtonâ€™s method to find the value ofx
near3
whereSin(x)
equals zero numerically and stop if the result is closer than0.0001
to the real result)DiagonalMatrix({a,b,c});
(create a matrix with the elements specified in the vector on the diagonal)Integrate(x,a,b) x*Sin(x);
(integrate a function over variablex
, froma
tob
)Factor(x^21);
(factorize a polynomial)Apart(1/(x^21),x);
(create a partial fraction expansion of a polynomial)Simplify((x^21)/(x1));
(simplification of expressions)CanProve( (a And b) Or (a And Not b) );
(specialpurpose simplifier that tries to simplify boolean expressions as much as possible)TrigSimpCombine(Cos(a)*Sin(b));
(specialpurpose simplifier that tries to transform trigonometric expressions into a form where there are only additions of trigonometric functions involved and no multiplications)
Arbitrary precision numbersÂ¶
Yacas can deal with arbitrary precision numbers. It can work with
large integers, like 20!
(The ! means factorial, thus
1*2*3*...*20
).
As we saw before, rational numbers will stay rational as long as the
numerator and denominator are integers, so 55/10
will evaluate to
11/2
. You can override this behavior by using the numerical
evaluation function N()
. For example, N(55/10)
will evaluate
to 5.5
. This behavior holds for most math functions. Yacas will
try to maintain an exact answer (in terms of integers or fractions)
instead of using floating point numbers, unless N()
is used. Where
the value for the constant pi is needed, use the builtin variable
Pi
. It will be replaced by the (approximate) numerical value when
N(Pi)
is called. Yacas knows some simplification rules using
Pi
(especially with trigonometric functions).
The function N
takes either one or two arguments. It evaluates its
first argument and tries to reduce it as much as possible to a
realvalued approximation of the expression. If the second argument is
present, it states the number of digits precision required. Thus
N(1/234)
returns a number with the current default precision
(which starts at 20 digits), but you can request as many digits as you
like by passing a second argument, as in N(1/234, 10)
, N(1/234,
20)
, N(1/234, 30)
, etcetera.
Note that we need to enter N()
to force the approximate
calculation, otherwise the fraction would have been left unevaluated.
Revisiting Pi
, we can get as many digits of Pi
as we like, by
providing the precision required as argument to N
. So to get 50
digits precision, we can evaluate N(Pi,50)
.
Taking a derivative of a function was amongst the very first of
symbolic calculations to be performed by a computer, as the operation
lends itself surprisingly well to being performed
automatically. Naturally, it is also implemented in Yacas, through the
function D
. D
is a bodied function, meaning that its
last argument is past the closing brackets. Where normal functions are
called with syntax similar to f(x,y,z)
, a bodied function would be
called with a syntax f(x,y)z
. Here are two examples of taking a
derivative:
D(x) Sin(x);
(taking a derivative)D(x) D(x) Sin(x);
(taking a derivative twice)
The D()
function also accepts an argument specifying how many times the
derivative has to be taken. In that case, the above expressions can also be
written as:
D(x,1) Sin(x);
(taking a derivative)D(x,2) Sin(x);
(taking a derivative twice)
Analytic functionsÂ¶
Many of the usual analytic functions have been defined in the yacas library.
Examples are Exp(1)
, Sin(2)
, ArcSin(1/2)
, Sqrt(2)
. These will
not evaluate to a numeric result in general, unless the result is an integer,
like Sqrt(4)
. If asked to reduce the result to a numeric approximation with
the function N()
, then yacas will do so, as for example in
N(Sqrt(2),50)
.
VariablesÂ¶
Yacas supports variables. You can set the value of a variable with the
:=
infix operator, as in a:=1;
. The variable can then be used
in expressions, and everywhere where it is referred to, it will be
replaced by its value.
To clear a variable binding, execute Clear(a);
. A variable will
evaluate to itself after a call to clear it (so after the call to
clear a
above, calling <span class=â€ťcommandlinkâ€ť>a`` should now
return a
). This is one of the properties of the evaluation scheme
of Yacas; when some object can not be evaluated or transformed any
further, it is returned as the final result.
FunctionsÂ¶
The :=
operator can also be used to define simple functions:
f(x):=2*x*x
. will define a new function, f
, that accepts one
argument and returns twice the square of that argument. This function
can now be called, f(a)
. You can change the definition of a
function by defining it again.
One and the same function name such as f
may define different
functions if they take different numbers of arguments. One can define
a function f
which takes one argument, as for example
f(x):=x^2;
, or two arguments, f(x,y):=x*y;
. If you clicked on
both links, both functions should now be defined, and f(a)
calls
the one function whereas f(a,b)
calls the other.
Yacas is very flexible when it comes to types of mathematical objects. Functions can in general accept or return any type of argument.
Boolean expressions and predicatesÂ¶
Yacas predefines True
and False
as boolean values. Functions
returning boolean values are called predicates. For example, IsNumber()
and IsInteger()
are predicates defined in the yacas environment. For
example, try IsNumber(2+x)
, or IsInteger(15/5)
.
There are also comparison operators. Typing 2 > 1
would return True
.
You can also use the infix operators And
and Or
, and the prefix operator
Not
, to make more complex boolean expressions. For example, try True And
False
, True Or False
, True And Not(False)
.
Strings and listsÂ¶
In addition to numbers and variables, Yacas supports strings and
lists. Strings are simply sequences of characters enclosed by double
quotes, for example: "this is a string with \"quotes\" in it"
.
Lists are ordered groups of items, as usual. Yacas represents lists by
putting the objects between braces and separating them with
commas. The list consisting of objects a, b, and c could be entered by
typing {a,b,c}
. In Yacas, vectors are represented as lists and
matrices as lists of lists.
Items in a list can be accessed through the [ ]
operator. The
first element has index one. Examples: when you enter
uu:={a,b,c,d,e,f};
then uu[2];
evaluates to b
, and
uu[2 .. 4];
evaluates to {b,c,d}
. The â€śrangeâ€ť expression
2 .. 4
evaluates to {2,3,4}
. Note that spaces around the
..
operator are necessary, or else the parser will not be able to
distinguish it from a part of a number.
Lists evaluate their arguments, and return a list with results of
evaluating each element. So, typing {1+2,3};
would evaluate to {3,3}
.
The idea of using lists to represent expressions dates back to the language LISP developed in the 1970â€™s. From a small set of operations on lists, very powerful symbolic manipulation algorithms can be built. Lists can also be used as function arguments when a variable number of arguments are necessary.
Letâ€™s try some list operations now. First click on m:={a,b,c};
to
set up an initial list to work on. Then click on links below:
Length(m)
(return the length of a list)Reverse(m)
(return the string reversed)Concat(m,m)
(concatenate two strings)m[1]:=d
(setting the first element of the list to a new value,d
, as can be verified by evaluatingm
)
Many more list operations are described in the reference manual.
Writing simplification rulesÂ¶
Mathematical calculations require versatile transformations on symbolic quantities. Instead of trying to define all possible transformations, Yacas provides a simple and easy to use pattern matching scheme for manipulating expressions according to userdefined rules. Yacas itself is designed as a small core engine executing a large library of rules to match and replace patterns.
One simple application of patternmatching rules is to define new
functions. (This is actually the only way Yacas can learn about new
functions.) As an example, letâ€™s define a function f
that will
evaluate factorials of nonnegative integers. We will define a
predicate to check whether our argument is indeed a nonnegative
integer, and we will use this predicate and the obvious recursion
f(n)=n*f(n1) if n>0 and 1 if n=0
to evaluate the factorial.
We start with the simple termination condition, which is that f(n)
should return one if n
is zero: 10 # f(0) < 1;
. You can verify
that this already works for input value zero, with f(0)
.
Now we come to the more complex line 20 # f(n_IsIntegerGreaterThanZero) <
n*f(n1);
Now we realize we need a function IsGreaterThanZero()
, so we
define this function, with IsIntegerGreaterThanZero(_n) < (IsInteger(n) And
n > 0);
You can verify that it works by trying f(5)
, which should return
the same value as 5!
.
In the above example we have first defined two simplification rules
for a new function f()
. Then we realized that we need to define a
predicate IsIntegerGreaterThanZero()
. A predicate equivalent to
IsIntegerGreaterThanZero()
is actually already defined in the
standard library and itâ€™s called IsPositiveInteger()
, so it was not
necessary, strictly speaking, to define our own predicate to do the
same thing. We did it here just for illustration purposes.
The first two lines recursively define a factorial function \(f(n)=n(n1)\ldots 1\). The rules are given precedence values 10 and 20, so the first rule will be applied first. Incidentally, the factorial is also defined in the standard library as a postfix operator ! and it is bound to an internal routine much faster than the recursion in our example. The example does show how to create your own routine with a few lines of code. One of the design goals of Yacas was to allow precisely that, definition of a new function with very little effort.
The operator <
defines a rule to be applied to a specific
function. (The <
operation cannot be applied to an atom.)
The _n
in the rule for IsIntegerGreaterThanZero()
specifies
that any object which happens to be the argument of that predicate is
matched and assigned to the local variable n
. The expression to
the right of <
can use n
(without the underscore) as a
variable.
Now we consider the rules for the function f()
. The first rule just
specifies that f(0)
should be replaced by 1 in any expression. The
second rule is a little more involved. n_IsIntegerGreaterThanZero
is a match for the argument of f
, with the proviso that the
predicate IsIntegerGreaterThanZero(n)
should return True
,
otherwise the pattern is not matched. The underscore operator is to be
used only on the left hand side of the rule definition operator
<
.
There is another, slightly longer but equivalent way of writing the second rule:
20 # f(_n)_(IsIntegerGreaterThanZero(n)) < n*f(n1);
The underscore after
the function object denotes a postpredicate that should return True
or
else there is no match. This predicate may be a complicated expression involving
several logical operations, unlike the simple checking of just one predicate in
the n_IsIntegerGreaterThanZero
construct. The postpredicate can also use the
variable n
(without the underscore).
Precedence values for rules are given by a number followed by the
#
infix operator (and the transformation rule after it). This
number determines the ordering of precedence for the pattern matching
rules, with 0 the lowest allowed precedence value, i.e. rules with
precedence 0 will be tried first. Multiple rules can have the same
number: this just means that it doesnâ€™t matter what order these
patterns are tried in. If no number is supplied, 0 is assumed. In our
example, the rule f(0) < 1
must be applied earlier than the
recursive rule, or else the recursion will never terminate. But as
long as there are no other rules concerning the function f
, the
assignment of numbers 10 and 20 is arbitrary, and they could have been
500 and 501 just as well. It is usually a good idea however to keep
some space between these numbers, so you have room to insert new
transformation rules later on.
Predicates can be combined: for example, IsIntegerGreaterThanZero()
could also have been defined as:
10 # IsIntegerGreaterThanZero(n_IsInteger)_(n>0) < True;
20 # IsIntegerGreaterThanZero(_n) < False;
The first rule specifies that if n
is an integer, and is greater than
zero, the result is True
, and the second rule states that
otherwise (when the rule with precedence 10 did not apply) the
predicate returns False
.
In the above example, the expression n > 0
is added after the
pattern and allows the pattern to match only if this predicate return
True
. This is a useful syntax for defining rules with complicated
predicates. There is no difference between the rules
F(n_IsPositiveInteger) < ...
and F(_n)_(IsPositiveInteger(n))
< ...
except that the first syntax is a little more concise.
The rule expression has the following form:
[precedence #] pattern [_ postpredicate] < replacement;
The optional precedence must be a positive integer.
Some more examples of rules (not made clickable because their equivalents are already in the basic yacas library):
10 # _x + 0 < x;
20 # _x  _x < 0;
ArcSin(Sin(_x)) < x;
The last rule has no explicit precedence specified in it (the precedence zero will be assigned automatically by the system).
Yacas will first try to match the pattern as a template. Names
preceded or followed by an underscore can match any one object: a
number, a function, a list, etc. Yacas will assign the relevant
variables as local variables within the rule, and try the predicates
as stated in the pattern. The postpredicate (defined after the
pattern) is tried after all these matched. As an example, the
simplification rule _x  _x <0
specifies that the two objects
at left and at right of the minus sign should be the same for this
transformation rule to apply.
Local simplification rulesÂ¶
Sometimes you have an expression, and you want to use specific
simplification rules on it that should not be universally applied.
This can be done with the /:
and the /::
operators. Suppose
we have the expression containing things such as Ln(a*b)
, and we
want to change these into Ln(a)+Ln(b)
. The easiest way to do this
is using the /:
operator as follows:
Sin(x)*Ln(a*b)
(example expression without simplification)Sin(x)*Ln(a*b) /: {Ln(_x*_y) < Ln(x)+Ln(y) }
(with instruction to simplify the expression)
A whole list of simplification rules can be built up in the list, and
they will be applied to the expression on the left hand side of
/:
.
Note that for these local rules, <
should be used instead of
<
. Using latter would result in a global definition of a new
transformation rule on evaluation, which is not the intention.
The /:
operator traverses an expression from the top down, trying
to apply the rules from the beginning of the list of rules to the end
of the list of rules. If no rules can be applied to the whole
expression, it will try the subexpressions of the expression being
analyzed.
It might be sometimes necessary to use the /::
operator, which
repeatedly applies the /:
operator until the result does not
change any more. Caution is required, since rules can contradict each
other, and that could result in an infinite loop. To detect this
situation, just use /:
repeatedly on the expression. The
repetitive nature should become apparent.
Programming essentialsÂ¶
An important feature of yacas is its programming language which allows you to create your own programs for doing calculations. This section describes some constructs and functions for control flow.
Looping can be done with the function ForEach()
. There are more
options, but ForEach()
is the simplest to use for now and will suffice
for this turorial. The statement form ForEach(x, list) body
executes its body for each element of the list and assigns the
variable x
to that element each time. The statement form
While(predicate) body
repeats execution of the expression
represented by body
until evaluation of the expression represented
by predicate
returns False
.
This example loops over the integers from one to three, and writes out
a line for each, multiplying the integer by 3 and displaying the
result with the function Echo()
:
ForEach(x,1 .. 5) Echo(x," times 3 equals ",3*x);
Compound statementsÂ¶
Multiple statements can be grouped together using the [
and ]
brackets. The compound [a; Echo("In the middle"); 1+2;];
evaluates
a
, then the Echo()
command, and finally evaluates 1+2
, and
returns the result of evaluating the last statement 1+2
.
A variable can be declared local to a compound statement block by the
function Local(var1, var2, ...)
. For example, if you execute
[Local(v);v:=1+2;v;];
the result will be 3
. The program body
created a variable called v
, assigned the value of evaluating
1+2
to it, and made sure the contents of the variable v
were
returned. If you now evaluate v
afterwards you will notice that
the variable v
is not bound to a value any more. The variable
v
was defined locally in the program body between the two square
brackets [
and ]
.
Conditional execution is implemented by the
If(predicate, body1, body2)
function call. If the expression predicate
evaluates to
True
, the expression represented by body1
is evaluated,
otherwise body2
is evaluated, and the corresponding value is
returned. For example, the absolute value of a number can be computed
with: f(x) := If(x < 0,x,x);
(note that there already is a
standard library function that calculates the absolute value of a
number).
Variables can also be made to be local to a small set of functions,
with LocalSymbols(variables) body
. For example, the following code
snippet:
LocalSymbols(a,b) [
a:=0;
b:=0;
inc():=[a:=a+1;b:=b1;show();];
show():=Echo("a = ",a," b = ",b);
];
defines two functions, inc()
and show()
. Calling inc()
repeatedly increments a
and decrements b
, and calling
show()
then shows the result (the function inc()
also calls the
function show()
, but the purpose of this example is to show how two
functions can share the same variable while the outside world cannot
get at that variable). The variables are local to these two functions,
as you can see by evaluating a
and b
outside the scope of
these two functions. This feature is very important when writing a
larger body of code, where you want to be able to guarantee that there
are no unintended sideeffects due to two bits of code defined in
different files accidentally using the same global variable.
To illustrate these features, let us create a list of all even integers from 2 to 20 and compute the product of all those integers except those divisible by 3:
[
Local(L,i,answer);
L:={}; i:=2;
/*Make a list of all even integers from 2 to 20 */
While (i <= 20) [ L := Append(L, i); i := i + 2; ];
/* Now calculate the product of all of these numbers that are not divisible by 3 */
answer := 1;
ForEach(i,L) If (Mod(i, 3) != 0, answer := answer * i);
/* And return the answer */
answer;
];
(Note that it is not necessarily the most economical way to do it in yacas.)
We used a shorter form of If(predicate, body)
with only one body
which is executed when the condition holds. If the condition does not
hold, this function call returns False
. We also introduced
comments, which can be placed between /*
and */
. Yacas will
ignore anything between those two. When putting a program in a file
you can also use //
. Everything after //
up until the end of
the line will be a comment. Also shown is the use of the While
function. Its form is While (predicate) body
. While the
expression represented by predicate
evaluates to True
, the
expression represented by body
will keep on being evaluated.
The above example is not the shortest possible way to write out the algorithm. It is written out in a procedural way, where the program explains step by step what the computer should do. There is nothing fundamentally wrong with the approach of writing down a program in a procedural way, but the symbolic nature of Yacas also allows you to write it in a more concise, elegant, compact way, by combining function calls.
There is nothing wrong with procedural style, but there is amore â€functionalâ€™ approach to the same problem would go as follows below. The advantage of the functional approach is that it is shorter and more concise (the difference is cosmetic mostly).
Before we show how to do the same calculation in a functional style,
we need to explain what a pure function is, as you will need it a
lot when programming in a functional style. We will jump in with an
example that should be selfexplanatory. Consider the expression
Lambda({x,y},x+y)
. This has two arguments, the first listing x
and y
, and the second an expression. We can use this construct with
the function Apply()
as follows:
Apply(Lambda({x,y},x+y),{2,3})
The result should be 5
, the result of adding 2
and 3
. The
expression starting with Lambda()
is essentially a prescription for
a specific operation, where it is stated that it accepts 2 arguments,
and returns the arguments added together. In this case, since the
operation was so simple, we could also have used the name of a
function to apply the arguments to, the addition operator in this case
Apply("+",{2,3})
. When the operations become more complex however,
the Lambda()
construct becomes more useful.
Now we are ready to do the same example using a functional
approach. First, let us construct a list with all even numbers from 2
to 20. For this we use the ..
operator to set up all numbers from
one to ten, and then multiply that with two: 2 * (1 .. 10)
.
Now we want an expression that returns all the even numbers up to 20
which are not divisible by 3. For this we can use Select
, which
takes as first argument a predicate that should return True
if the
list item is to be accepted, and False
otherwise, and as second
argument the list in question:
Select(Lambda({n},Mod(n,3)!=0),2*(1 .. 10))
The numbers 6, 12 and 18 have been correctly filtered out. Here you see one example of a pure function where the operation is a little bit more complex.
All that remains is to factor the items in this list. For this we can
use UnFlatten
. Two examples of the use of UnFlatten
are
UnFlatten({a,b,c},"*",1)
UnFlatten({a,b,c},"+",0)
The 0 and 1 are a base element to start with when grouping the arguments in to an expression (they should be the respective identity elements, hence it is zero for addition and 1 for multiplication).
Now we have all the ingredients to finally do the same calculation we did above in a procedural way, but this time we can do it in a functional style, and thus captured in one concise single line:
UnFlatten(Select(Lambda({n},Mod(n,3)!=0),2*(1 .. 10)),"*",1)
As was mentioned before, the choice between the two is mostly a matter of style.
MacrosÂ¶
One of the powerful constructs in yacas is the construct of a macro. In its essence, a macro is a prescription to create another program before executing the program. An example perhaps explains it best. Evaluate the following expression
Macro(for,{st,pr,in,bd}) [(@st);While(@pr)[(@bd);(@in);];];
This expression defines a macro that allows for looping. Yacas has a
For()
function already, but this is how it could be defined in one line
(In yacas the For()
function is bodied, we left that out here for clarity,
as the example is about macros).
To see it work just type for(i:=0,i<3,i:=i+1,Echo(i))
. You will see
the count from one to three.
The construct works as follows; The expression defining the macro sets
up a macro named for()
with four arguments. On the right is the body
of the macro. This body contains expressions of the form @var
.
These are replaced by the values passed in on calling the macro.
After all the variables have been replaced, the resulting expression
is evaluated. In effect a new program has been created. Such macro constructs
come from LISP, and are famous for allowing you to almost design your own
programming language constructs just for your own problem at hand. When used
right, macros can greatly simplify the task of writing a program.
You can also use the backquote `
to expand a macro inplace. It
takes on the form `(expression)
, where the expression can again
contain subexpressions of the form @variable
. These instances
will be replaced with the values of these variables.
The practice of programming in yacasÂ¶
When you become more proficient in working with yacas you will be
doing more and more sophisticated calculations. For such calculations
it is generally necessary to write little programs. In real life you
will usually write these programs in a text editor, and then start
yacas, load the text file you just wrote, and try out the
calculation. Generally this is an iterative process, where you go back
to the text editor to modify something, and then go back to yacas,
type restart
and then reload the file.
On this site you can run yacas in a little window called a yacas calculation center (the same as the one below this tutorial). On page there is tab that contains a Yacas calculation center. If you click on that tab you will be directed to a larger calculation center than the one below this tutorial. In this page you can easily switch between doing a calculation and editing a program to load at startup. We tried to make the experience match the general use of Yacas on a desktop as much as possible. The Yacas journal (which you see when you go to the Yacas web site) contains examples of calculations done before by others.
Defining your own operatorsÂ¶
Large part of the yacas system is defined in the scripting language itself. This includes the definitions of the operators it accepts, and their precedences. This means that you too can define your own operators. This section shows you how to do that.
Suppose we wanted to define a function F(x,y)=x/y+y/x
. We could
use the standard syntax F(a,b) := a/b + b/a;
. F(1,2);
. For
the purpose of this demonstration, lets assume that we want to define
an infix operator xx
for this operation. We can teach yacas about
this infix operator with Infix("xx", OpPrecedence("/"));
. Here we
told Yacas that the operator xx
is to have the same precedence as
the division operator. We can now proceed to tell Yacas how to
evaluate expressions involving the operator xx
by defining it as
we would with a function, a xx b := a/b + b/a;
.
You can verify for yourself 3 xx 2 + 1;
and 1 + 3 xx 2;
return
the same value, and that they follow the precedence rules (eg. xx
binds stronger than +
).
We have chosen the name xx
just to show that we donâ€™t need to use
the special characters in the infix operatorâ€™s name. However we must
define this operator as infix before using it in expressions,
otherwise yacas will raise a syntax error.
Finally, we might decide to be completely flexible with this important
function and also define it as a mathematical operator ##
. First
we define ##
as a bodied function and then proceed as
before. First we can tell yacas that ##
is a bodied operator with
Bodied("##", OpPrecedence("/"));
. Then we define the function
itself: ##(a) b := a xx b;
. And now we can use the function,
##(1) 3 + 2;
.
We have used the name ##
but we could have used any other name
such as xx
or F
or even _+@+_
. Apart from possibly
confusing yourself, it doesnâ€™t matter what you call the functions you
define.
There is currently one limitation in yacas: once a function name is
declared as infix (prefix, postfix) or bodied, it will always be
interpreted that way. If we declare a function f
to be bodied, we
may later define different functions named f
with different
numbers of arguments, however all of these functions must be bodied.
When you use infix operators and either a prefix of postfix operator next to it you can run in to a situation where yacas can not quite figure out what you typed. This happens when the operators are right next to each other and all consist of symbols (and could thus in principle form a single operator). Yacas will raise an error in that case. This can be avoided by inserting spaces.
Some assorted programming topicsÂ¶
One use of lists is the associative list, sometimes called a
dictionary in other programming languages, which is implemented in
Yacas simply as a list of keyvalue pairs. Keys must be strings and
values may be any objects. Associative lists can also work as
minidatabases, where a name is associated to an object. As an
example, first enter record:={};
to set up
an empty record. After that, we can fill arbitrary fields in this
record:
record["name"]:="Isaia";
record["occupation"]:="prophet";
record["is alive"]:=False;
Now, evaluating record["name"]
should result in the answer
"Isaia"
. The record is now a list that contains three sublists, as
you can see by evaluating record
.
Assignment of multiple variables is also possible using lists. For
instance, evaluating {x,y}:={2!,3!}
will result in 2 being
assigned to x
and 6 to y
.
When assigning variables, the right hand side is evaluated before it
is assigned. Thus a:=2*2
will set a to 4. This is however
not the case for functions. When entering f(x):=x+x
the
right hand side, x+x
, is not evaluated before being assigned. This
can be forced by using Eval()
. Defining f(x)
with
f(x):=Eval(x+x)
will tell the system to first evaluate x+x
(which results in 2*x
) before assigning it to the user function
f()
. This specific example is not a very useful one but it will come
in handy when the operation being performed on the right hand side is
expensive. For example, if we evaluate a Taylor series expansion
before assigning it to the userdefined function, the engine doesnâ€™t
need to create the Taylor series expansion each time that userdefined
function is called.
The imaginary unit \(\imath\) is denoted I
and complex numbers can be
entered as either expressions involving I
, as for example
1+I*2
, or explicitly as Complex(a,b)
for \(a+\imath b\). The form
Complex(re,im)
is the way yacas deals with complex numbers
internally.
Linear AlgebraÂ¶
Vectors of fixed dimension are represented as lists of their
components. The list {1, 2+x, 3*Sin(p)}
would be a
threedimensional vector with components 1
, 2+x
and
3*Sin(p)
. Matrices are represented as a lists of lists.
Vector components can be assigned values just like list items, since
they are in fact list items. If we first set up a variable called
â€śvectorâ€ť to contain a threedimensional vector with the command
vector:=ZeroVector(3);
(you can verify that it is indeed a vector
with all components set to zero by evaluating vector
), you can
change elements of the vector just like you would the elements of a
list (seeing as it is represented as a list). For example, to set the
second element to two, just evaluate vector[2] := 2;
. This results
in a new value for vector
.
Yacas can perform multiplication of matrices, vectors and numbers as
usual in linear algebra. The standard Yacas script library also
includes taking the determinant and inverse of a matrix, finding
eigenvectors and eigenvalues (in simple cases) and solving linear sets
of equations, such as A * x = b where A is a matrix, and x and b are
vectors. As a little example to wetten your appetite, we define a
Hilbert matrix: hilbert:=HilbertMatrix(3)
. We can then calculate
the determinant with Determinant(hilbert)
, or the inverse with
Inverse(hilbert)
. There are several more matrix operations
supported. See the reference manual for more details.
Threading of functionsÂ¶
Some functions in Yacas can be threaded. This means that calling the
function with a list as argument will result in a list with that
function being called on each item in the list. E.g. Sin({a,b,c});
will result in {Sin(a),Sin(b),Sin(c)}
. This functionality is
implemented for most normal analytic functions and arithmetic
operators.
Functions as listsÂ¶
For some work it pays to understand how things work under the
hood. Internally, Yacas represents all atomic expressions (numbers and
variables) as strings and all compound expressions as lists, like
Lisp. Try FullForm(a+b*c);
and you will see the text (+ a (* b c
))
appear on the screen. This function is occasionally useful, for
example when trying to figure out why a specific transformation rule
does not work on a specific expression.
If you try FullForm(1+2)
you will see that the result is not quite
what we intended. The system first adds up one and two, and then shows
the tree structure of the end result, which is a simple number
3
. To stop Yacas from evaluating something, you can use the
function Hold
, as FullForm(Hold(1+2))
. The function Eval
is the opposite, it instructs Yacas to reevaluate its argument
(effectively evaluating it twice). This undoes the effect of Hold
,
as for example Eval(Hold(1+2))
.
Also, any expression can be converted to a list by the function
Listify
or back to an expression by the function UnList
:
Listify(a+b*(c+d));
UnList({Atom("+"),x,1});
Note that the first element of the list is the name of the function
+
which is equivalently represented as Atom("+")
and that the
subexpression b*(c+d)
was not converted to list form. Listify just
took the top node of the expression.
Reference ManualÂ¶
Yacas (Yet Another Computer Algebra System) is a small and highly flexible generalpurpose computer algebra system and programming language. The language has a familiar, Clike infixoperator syntax. The distribution contains a small library of mathematical functions, but its real strength is in the language in which you can easily write your own symbolic manipulation algorithms. The core engine supports arbitrary precision arithmetic, and is able to execute symbolic manipulations on various mathematical objects by following userdefined rules.
This document describes the functions that are useful in the context of using yacas as an end user. It is recommended to first read the online interactive tutorial to get acquainted with the basic language constructs first. This document expands on the tutorial by explaining the usage of the functions that are useful when doing calculations.
Arithmetic and other operations on numbersÂ¶

x
+
yÂ¶ addition
Addition can work on integers, rational numbers, complex numbers, vectors, matrices and lists.
Hint
Addition is implemented in the standard math library (as opposed to being builtin). This means that it can be extended by the user.
 Example
In> 2+3 Out> 5


xÂ¶ negation
Negation can work on integers, rational numbers, complex numbers, vectors, matrices and lists.
Hint
Negation is implemented in the standard math library (as opposed to being builtin). This means that it can be extended by the user.
 Example
In>  3 Out> 3

x

y subtraction
Subtraction can work on integers, rational numbers, complex numbers, vectors, matrices and lists.
Hint
Subtraction is implemented in the standard math library (as opposed to being builtin). This means that it can be extended by the user.
 Example
In> 23 Out> 1

x
*
yÂ¶ multiplication
Multiplication can work on integers, rational numbers, complex numbers, vectors, matrices and lists.
Note
In the case of matrices, multiplication is defined in terms of standard matrix product.
Hint
Multiplication is implemented in the standard math library (as opposed to being builtin). This means that it can be extended by the user.
 Example
In> 2*3 Out> 6

x
/
yÂ¶ division
Division can work on integers, rational numbers, complex numbers, vectors, matrices and lists.
Note
For matrices division is elementwise.
Hint
Division is implemented in the standard math library (as opposed to being builtin). This means that it can be extended by the user.
 Example
In> 6/2 Out> 3

x
^
yÂ¶ exponentiation
Exponentiation can work on integers, rational numbers, complex numbers, vectors, matrices and lists.
Note
In the case of matrices, exponentiation is defined in terms of standard matrix product.
Hint
Exponentiation is implemented in the standard math library (as opposed to being builtin). This means that it can be extended by the user.
 Example
In> 2^3 Out> 8

Div
(x, y)Â¶ determine divisor
Div()
performs integer division. IfDiv(x,y)
returnsa
andMod(x,y)
equalsb
, then these numbers satisfy \(x =ay + b\) and \(0 \leq b < y\). Example
In> Div(5,3) Out> 1

Mod
(x, y)Â¶ determine remainder
Mod()
returns the division remainder. IfDiv(x,y)
returnsa
andMod(x,y)
equalsb
, then these numbers satisfy \(x =ay + b\) and \(0 \leq b < y\). Example
In> Div(5,3) Out> 1 In> Mod(5,3) Out> 2

Gcd
(n, m)Â¶ 
Gcd
(list) greatest common divisor
This function returns the greatest common divisor of
n
andm
or of all elements oflist
.See also

Lcm
(n, m)Â¶ 
Lcm
(list) least common multiple
This command returns the least common multiple of
n
andm
or of all elements oflist
. Example
In> Lcm(60,24) Out> 120 In> Lcm({3,5,7,9}) Out> 315
See also

n
<<
mÂ¶ 
n
>>
mÂ¶ binary shift operators
These operators shift integers to the left or to the right. They are similar to the C shift operators. These are signextended shifts, so they act as multiplication or division by powers of 2.
 Example
In> 1 << 10 Out> 1024 In> 1024 >> 10 Out> 1

FromBase
(base, "string")Â¶ conversion of a number from nondecimal base to decimal base
 Param base
integer, base to convert to/from
 Param number
integer, number to write out in a different base
 Param â€śstringâ€ť
string representing a number in a different base
In Yacas, all numbers are written in decimal notation (base 10). The two functions {FromBase}, {ToBase} convert numbers between base 10 and a different base. Numbers in nondecimal notation are represented by strings. {FromBase} converts an integer, written as a string in base {base}, to base 10. {ToBase} converts {number}, written in base 10, to base {base}.

N
(expression)Â¶ try determine numerical approximation of expression
 Param expression
expression to evaluate
 Param precision
integer, precision to use
The function
N()
instructs yacas to try to coerce an expression in to a numerical approximation to the expressionexpr
, usingprec
digits precision if the second calling sequence is used, and the default precision otherwise. This overrides the normal behaviour, in which expressions are kept in symbolic form (eg.Sqrt(2)
instead of1.41421
). Application of theN()
operator will make yacas calculate floating point representations of functions whenever possible. In addition, the variablePi
is bound to the value of \(\pi\) calculated at the current precision.Note
N()
is a macro. Its argumentexpr
will only be evaluated after switching to numeric mode. Example
In> 1/2 Out> 1/2; In> N(1/2) Out> 0.5; In> Sin(1) Out> Sin(1); In> N(Sin(1),10) Out> 0.8414709848; In> Pi Out> Pi; In> N(Pi,20) Out> 3.14159265358979323846;
See also

Rationalize
(expr)Â¶ convert floating point numbers to fractions
 Param expr
an expression containing real numbers
This command converts every real number in the expression â€śexprâ€ť into a rational number. This is useful when a calculation needs to be done on floating point numbers and the algorithm is unstable. Converting the floating point numbers to rational numbers will force calculations to be done with infinite precision (by using rational numbers as representations). It does this by finding the smallest integer \(n\) such that multiplying the number with \(10^n\) is an integer. Then it divides by \(10^n\) again, depending on the internal gcd calculation to reduce the resulting division of integers.
 Example
In> {1.2,3.123,4.5} Out> {1.2,3.123,4.5}; In> Rationalize(%) Out> {6/5,3123/1000,9/2};
See also

ContFrac
(x[, depth=6])Â¶ continued fraction expansion
 Param x
number or polynomial to expand in continued fractions
 Param depth
positive integer, maximum required depth
This command returns the continued fraction expansion of
x
, which should be either a floating point number or a polynomial. The remainder is denoted byrest
. This is especially useful for polynomials, since series expansions that converge slowly will typically converge a lot faster if calculated using a continued fraction expansion. Example
In> PrettyForm(ContFrac(N(Pi))) 1  + 3 1  + 7 1  + 15 1  + 1 1  + 292 rest + 1 Out> True; In> PrettyForm(ContFrac(x^2+x+1, 3)) x  + 1 x 1   x  + 1 rest + 1 Out> True;
See also

Decimal
(frac)Â¶ decimal representation of a rational
 Param frac
a rational number
This function returns the infinite decimal representation of a rational number {frac}. It returns a list, with the first element being the number before the decimal point and the last element the sequence of digits that will repeat forever. All the intermediate list elements are the initial digits before the period sets in.
 Example
In> Decimal(1/22) Out> {0,0,{4,5}}; In> N(1/22,30) Out> 0.045454545454545454545454545454;
See also

Floor
(x)Â¶ round a number downwards
 Param x
a number
This function returns \(\left \lfloor{x}\right \rfloor\), the largest integer smaller than or equal to
x
. Example
In> Floor(1.1) Out> 1; In> Floor(1.1) Out> 2;

Ceil
(x)Â¶ round a number upwards
 Param x
a number
This function returns \(\left \lceil{x}\right \rceil\), the smallest integer larger than or equal to
x
. Example
In> Ceil(1.1) Out> 2; In> Ceil(1.1) Out> 1;

Round
(x)Â¶ round a number to the nearest integer
 Param x
a number
This function returns the integer closest to \(x\). Halfintegers (i.e. numbers of the form \(n + 0.5\), with \(n\) an integer) are rounded upwards.
 Example
In> Round(1.49) Out> 1; In> Round(1.51) Out> 2; In> Round(1.49) Out> 1; In> Round(1.51) Out> 2;

Min
(x, y)Â¶ 
Min
(list) minimum of a number of values
This function returns the minimum value of its argument(s). If the first calling sequence is used, the smaller of
x
andy
is returned. If one uses the second form, the smallest of the entries inlist
is returned. In both cases, this function can only be used with numerical values and not with symbolic arguments. Example
In> Min(2,3) Out> 2 In> Min({5,8,4}) Out> 4 In> Min(Pi, Exp(1)) Out> Exp(1)

Max
(x, y)Â¶ 
Max
(list) maximum of a number of values
This function returns the maximum value of its argument(s). If the first calling sequence is used, the larger of
x
andy
is returned. If one uses the second form, the largest of the entries inlist
is returned. In both cases, this function can only be used with numerical values and not with symbolic arguments. Example
In> Max(2,3); Out> 3; In> Max({5,8,4}); Out> 8;

Numer
(expr)Â¶ numerator of an expression
This function determines the numerator of the rational expression
expr
and returns it. As a special case, if its argument is numeric but not rational, it returns this number. Ifexpr
is neither rational nor numeric, the function returns unevaluated. Example
In> Numer(2/7) Out> 2; In> Numer(a / x^2) Out> a; In> Numer(5) Out> 5;
See also

Denom
(expr)Â¶ denominator of an expression
This function determines the denominator of the rational expression
expr
and returns it. As a special case, if its argument is numeric but not rational, it returns1
. Ifexpr
is neither rational nor numeric, the function returns unevaluated. Example
In> Denom(2/7) Out> 7; In> Denom(a / x^2) Out> x^2; In> Denom(5) Out> 1;
See also

Pslq
(xlist[, precision=6])Â¶ search for integer relations between reals
 Param xlist
list of numbers
 Param precision
required number of digits precision of calculation
This function is an integer relation detection algorithm. This means that, given the numbers \(x_i\) in the list
xlist
, it tries to find integer coefficients \(a_i\) such that \(a_1*x_1+\ldots+a_n*x_n = 0\). The list of integer coefficients is returned. The numbers in â€śxlistâ€ť must evaluate to floating point numbers when theN()
operator is applied to them.

e1
<
e2Â¶ test for â€śless thanâ€ť
 Param e1
expression to be compared
 Param e2
expression to be compared
The two expression are evaluated. If both results are numeric, they are compared. If the first expression is smaller than the second one, the result is
True
and it isFalse
otherwise. If either of the expression is not numeric, after evaluation, the expression is returned with evaluated arguments. The word â€śnumericâ€ť in the previous paragraph has the following meaning. An expression is numeric if it is either a number (i.e. {IsNumber} returnsTrue
), or the quotient of two numbers, or an infinity (i.e. {IsInfinity} returnsTrue
). Yacas will try to coerce the arguments passed to this comparison operator to a real value before making the comparison. Example
In> 2 < 5; Out> True; In> Cos(1) < 5; Out> True;
See also

e1
>
e2Â¶ test for â€śgreater thanâ€ť
 Param e1
expression to be compared
 Param e2
expression to be compared
The two expression are evaluated. If both results are numeric, they are compared. If the first expression is larger than the second one, the result is
True
and it isFalse
otherwise. If either of the expression is not numeric, after evaluation, the expression is returned with evaluated arguments. The word â€śnumericâ€ť in the previous paragraph has the following meaning. An expression is numeric if it is either a number (i.e. {IsNumber} returnsTrue
), or the quotient of two numbers, or an infinity (i.e. {IsInfinity} returnsTrue
). Yacas will try to coerce the arguments passed to this comparison operator to a real value before making the comparison. Example
In> 2 > 5; Out> False; In> Cos(1) > 5; Out> False
See also

e1
<=
e2Â¶ test for â€śless or equalâ€ť
 Param e1
expression to be compared
 Param e2
expression to be compared
The two expression are evaluated. If both results are numeric, they are compared. If the first expression is smaller than or equals the second one, the result is
True
and it isFalse
otherwise. If either of the expression is not numeric, after evaluation, the expression is returned with evaluated arguments. The word â€śnumericâ€ť in the previous paragraph has the following meaning. An expression is numeric if it is either a number (i.e. {IsNumber} returnsTrue
), or the quotient of two numbers, or an infinity (i.e. {IsInfinity} returnsTrue
). Yacas will try to coerce the arguments passed to this comparison operator to a real value before making the comparison. Example
In> 2 <= 5; Out> True; In> Cos(1) <= 5; Out> True
See also

e1
>=
e2Â¶ test for â€śgreater or equalâ€ť
 Param e1
expression to be compared
 Param e2
expression to be compared
The two expression are evaluated. If both results are numeric, they are compared. If the first expression is larger than or equals the second one, the result is
True
and it isFalse
otherwise. If either of the expression is not numeric, after evaluation, the expression is returned with evaluated arguments. The word â€śnumericâ€ť in the previous paragraph has the following meaning. An expression is numeric if it is either a number (i.e. {IsNumber} returnsTrue
), or the quotient of two numbers, or an infinity (i.e. {IsInfinity} returnsTrue
). Yacas will try to coerce the arguments passed to this comparison operator to a real value before making the comparison. Example
In> 2 >= 5; Out> False; In> Cos(1) >= 5; Out> False
See also

IsZero
(n)Â¶ test whether argument is zero
 Param n
number to test
IsZero(n)
evaluates toTrue
ifn
is zero. In casen
is not a number, the function returnsFalse
. Example
In> IsZero(3.25) Out> False; In> IsZero(0) Out> True; In> IsZero(x) Out> False;
See also

IsRational
(expr)Â¶ test whether argument is a rational
 Param expr
expression to test
This commands tests whether the expression â€śexprâ€ť is a rational number, i.e. an integer or a fraction of integers.
 Example
In> IsRational(5) Out> False; In> IsRational(2/7) Out> True; In> IsRational(0.5) Out> False; In> IsRational(a/b) Out> False; In> IsRational(x + 1/x) Out> False;
Elementary functionsÂ¶

Sin
(x)Â¶ trigonometric sine function
 Example
In> Sin(1) Out> Sin(1); In> N(Sin(1),20) Out> 0.84147098480789650665; In> Sin(Pi/4) Out> Sqrt(2)/2;

Cos
(x)Â¶ trigonometric cosine function
 Example
In> Cos(1) Out> Cos(1); In> N(Cos(1),20) Out> 0.5403023058681397174; In> Cos(Pi/4) Out> Sqrt(1/2);

Tan
(x)Â¶ trigonometric tangent function
 Example
In> Tan(1) Out> Tan(1); In> N(Tan(1),20) Out> 1.5574077246549022305; In> Tan(Pi/4) Out> 1;

ArcSin
(x)Â¶ inverse trigonometric function arcsine
 Example
In> ArcSin(1) Out> Pi/2; In> ArcSin(1/3) Out> ArcSin(1/3); In> Sin(ArcSin(1/3)) Out> 1/3; In> x:=N(ArcSin(0.75)) Out> 0.848062; In> N(Sin(x)) Out> 0.7499999477;

ArcCos
(x)Â¶ inverse trigonometric function arccosine
 Example
In> ArcCos(0) Out> Pi/2 In> ArcCos(1/3) Out> ArcCos(1/3) In> Cos(ArcCos(1/3)) Out> 1/3 In> x:=N(ArcCos(0.75)) Out> 0.7227342478 In> N(Cos(x)) Out> 0.75

ArcTan
(x)Â¶ inverse trigonometric function arctangent
 Example
In> ArcTan(1) Out> Pi/4 In> ArcTan(1/3) Out> ArcTan(1/3) In> Tan(ArcTan(1/3)) Out> 1/3 In> x:=N(ArcTan(0.75)) Out> 0.643501108793285592213351264945231378078460693359375 In> N(Tan(x)) Out> 0.75

Exp
(x)Â¶ exponential function
 Example
In> Exp(0) Out> 1; In> Exp(I*Pi) Out> 1; In> N(Exp(1)) Out> 2.7182818284;

Ln
(x)Â¶ natural logarithm
 Example
In> Ln(1) Out> 0; In> Ln(Exp(x)) Out> x; In> D(x) Ln(x) Out> 1/x;
See also
Exp()
,Arg()

Sqrt
(x)Â¶ square root
 Example
In> Sqrt(16) Out> 4; In> Sqrt(15) Out> Sqrt(15); In> N(Sqrt(15)) Out> 3.8729833462; In> Sqrt(4/9) Out> 2/3; In> Sqrt(1) Out> Complex(0,1);
CalculusÂ¶
In this chapter, some facilities for doing calculus are described. These include functions implementing differentiation, integration, calculating limits etc.

D
(variable[, n=1]) expressionÂ¶ derivative
 Param variable
variable
 Param expression
expression to take derivatives of
 Param n
order
 Returns
n
th derivative ofexpression
with respect tovariable

D
(variable) expression derivative
 Param variable
variable
 Param list
a list of variables
 Param expression
expression to take derivatives of
 Param n
order of derivative
 Returns
derivative of
expression
with respect tovariable
This function calculates the derivative of the expression {expr} with respect to the variable {var} and returns it. If the third calling format is used, the {n}th derivative is determined. Yacas knows how to differentiate standard functions such as {Ln} and {Sin}. The {D} operator is threaded in both {var} and {expr}. This means that if either of them is a list, the function is applied to each entry in the list. The results are collected in another list which is returned. If both {var} and {expr} are a list, their lengths should be equal. In this case, the first entry in the list {expr} is differentiated with respect to the first entry in the list {var}, the second entry in {expr} is differentiated with respect to the second entry in {var}, and so on. The {D} operator returns the original function if \(n=0\), a common mathematical idiom that simplifies many formulae.
 Example
In> D(x)Sin(x*y) Out> y*Cos(x*y); In> D({x,y,z})Sin(x*y) Out> {y*Cos(x*y),x*Cos(x*y),0}; In> D(x,2)Sin(x*y) Out> Sin(x*y)*y^2; In> D(x){Sin(x),Cos(x)} Out> {Cos(x),Sin(x)};
See also
Integrate()
,Taylor()
,Diverge()
,Curl()

Curl
(vector, basis)Â¶ curl of a vector field
 Param vector
vector field to take the curl of
 Param basis
list of variables forming the basis
This function takes the curl of the vector field
vector
with respect to the variablesbasis
. The curl is defined in the usual way,Curl(f,x) = {D(x[2]) f[3]  D(x[3]) f[2], D(x[3]) f[1]  D(x[1])f[3], D(x[1]) f[2]  D(x[2]) f[1]}
. Bothvector
andbasis
should be lists of length 3.

Diverge
(vector, basis)Â¶ divergence of a vector field
 Param vector
vector field to calculate the divergence of
 Param basis
list of variables forming the basis
This function calculates the divergence of the vector field
vector
with respect to the variablesbasis
. The divergence is defined asDiverge(f,x) = D(x[1]) f[1] + ... + D(x[n]) f[n]
, wheren
is the length of the listsvector
andbasis
. These lists should have equal length.

HessianMatrix
(function, var)Â¶ create the Hessian matrix
 Param function
a function in \(n\) variables
 Param var
an \(n\)dimensional vector of variables
The function
HessianMatrix()
calculates the Hessian matrix of a vector. If \(f(x)\) is a function of an \(n\)dimensional vector \(x\), then the \((i,j)\)th element of the Hessian matrix of the function \(f(x)\) is defined as :math:` Deriv(x[i]) Deriv(x[j]) f(x)`. If the second order mixed partials are continuous, then the Hessian matrix is symmetric (a standard theorem of calculus). The Hessian matrix is used in the second derivative test to discern if a critical point is a local maximum, a local minimum or a saddle point. Example
In> HessianMatrix(3*x^22*x*y+y^28*y, {x,y} ) Out> {{6,2},{2,2}}; In> PrettyForm(%) / \  ( 6 ) ( 2 )     ( 2 ) ( 2 )  \ /

JacobianMatrix
(functions, variables)Â¶ calculate the Jacobian matrix of \(n\) functions in \(n\) variables
 Param functions
an \(n\)dimensional vector of functions
 Param variables
an \(n\)dimensional vector of variables
The function {JacobianMatrix} calculates the Jacobian matrix of n functions in n variables. The \((i,j)\)th element of the Jacobian matrix is defined as the derivative of \(i\)th function with respect to the \(j\)th variable.
 Example
In> JacobianMatrix( {Sin(x),Cos(y)}, {x,y} ); Out> {{Cos(x),0},{0,Sin(y)}}; In> PrettyForm(%) / \  ( Cos( x ) ) ( 0 )     ( 0 ) ( ( Sin( y ) ) )  \ /

Integrate
(var) exprÂ¶ 
Integrate
(var, x1, x2) expr integral
 Param expr
expression to integrate
 Param var
atom, variable to integrate over
 Param x1
first point of definite integration
 Param x2
second point of definite integration
This function integrates the expression expr with respect to the variable var. In the case of definite integral, the integration is carried out from \(var=x1\) to \(var=x2\)â€ť. Some simple integration rules have currently been implemented. Polynomials, some quotients of polynomials, trigonometric functions and their inverses, hyperbolic functions and their inverses, {Exp}, and {Ln}, and products of these functions with polynomials can be integrated.
 Example
In> Integrate(x,a,b) Cos(x) Out> Sin(b)Sin(a); In> Integrate(x) Cos(x) Out> Sin(x);
See also

Limit
(var, val) exprÂ¶ limit of an expression
 Param var
variable
 Param val
number or
Infinity
 Param dir
direction (
Left
orRight
) Param expr
an expression
This command tries to determine the value that the expression â€śexprâ€ť converges to when the variable â€śvarâ€ť approaches â€śvalâ€ť. One may use {Infinity} or {Infinity} for â€śvalâ€ť. The result of {Limit} may be one of the symbols {Undefined} (meaning that the limit does not exist), {Infinity}, or {Infinity}. The second calling sequence is used for unidirectional limits. If one gives â€śdirâ€ť the value {Left}, the limit is taken as â€śvarâ€ť approaches â€śvalâ€ť from the positive infinity; and {Right} will take the limit from the negative infinity.
 Example
In> Limit(x,0) Sin(x)/x Out> 1; In> Limit(x,0) (Sin(x)Tan(x))/(x^3) Out> 1/2; In> Limit(x,0) 1/x Out> Undefined; In> Limit(x,0,Left) 1/x Out> Infinity; In> Limit(x,0,Right) 1/x Out> Infinity;

Add
(val1, val2, ...)Â¶ 
Add
(list) find sum of a list of values
 Param val1 val2
expressions
 Param list
list of expressions to add
This function adds all its arguments and returns their sum. It accepts any number of arguments. The arguments can be also passed as a list.
 Example
In> Add(1,4,9); Out> 14; In> Add(1 .. 10); Out> 55;

Multiply
(val1, val2, ...)Â¶ 
Multiply
(list) product of a list of values
 Param val1 val2
expressions
 Param list
list of expressions to add
Multiply all arguments and returns their product. It accepts any number of arguments. The arguments can be also passed as a list.
 Example
In> Multiply(2,3,4); Out> 24 In> Multiply(1 .. 10) Out> 3628800

Sum
(var, from, to, body)Â¶ find sum of a sequence
 Param var
variable to iterate over
 Param from
integer value to iterate from
 Param to
integer value to iterate up to
 Param body
expression to evaluate for each iteration
The command finds the sum of the sequence generated by an iterative formula. The expression â€śbodyâ€ť is evaluated while the variable â€śvarâ€ť ranges over all integers from â€śfromâ€ť up to â€śtoâ€ť, and the sum of all the results is returned. Obviously, â€śtoâ€ť should be greater than or equal to â€śfromâ€ť. Warning: {Sum} does not evaluate its arguments {var} and {body} until the actual loop is run.
 Example
In> Sum(i, 1, 3, i^2); Out> 14;
See also

Factorize
(list)Â¶ product of a list of values
 Param list
list of values to multiply
 Param var
variable to iterate over
 Param from
integer value to iterate from
 Param to
integer value to iterate up to
 Param body
expression to evaluate for each iteration
The first form of the {Factorize} command simply multiplies all the entries in â€ślistâ€ť and returns their product. If the second calling sequence is used, the expression â€śbodyâ€ť is evaluated while the variable â€śvarâ€ť ranges over all integers from â€śfromâ€ť up to â€śtoâ€ť, and the product of all the results is returned. Obviously, â€śtoâ€ť should be greater than or equal to â€śfromâ€ť.
 Example
In> Factorize({1,2,3,4}); Out> 24; In> Factorize(i, 1, 4, i); Out> 24;

Taylor(var, at, order) expr
univariate Taylor series expansion
 Param var
variable
 Param at
point to get Taylor series around
 Param order
order of approximation
 Param expr
expression to get Taylor series for
This function returns the Taylor series expansion of the expression â€śexprâ€ť with respect to the variable â€śvarâ€ť around â€śatâ€ť up to order â€śorderâ€ť. This is a polynomial which agrees with â€śexprâ€ť at the point â€śvar = atâ€ť, and furthermore the first â€śorderâ€ť derivatives of the polynomial at this point agree with â€śexprâ€ť. Taylor expansions around removable singularities are correctly handled by taking the limit as â€śvarâ€ť approaches â€śatâ€ť.
 Example
In> PrettyForm(Taylor(x,0,9) Sin(x)) 3 5 7 9 x x x x x   +    +  6 120 5040 362880 Out> True;
See also
D()
,InverseTaylor()
,ReversePoly()
,BigOh()

InverseTaylor(var, at, order) expr
Taylor expansion of inverse
 Param var
variable
 Param at
point to get inverse Taylor series around
 Param order
order of approximation
 Param expr
expression to get inverse Taylor series for
This function builds the Taylor series expansion of the inverse of the expression â€śexprâ€ť with respect to the variable â€śvarâ€ť around â€śatâ€ť up to order â€śorderâ€ť. It uses the function {ReversePoly} to perform the task.
 Example
In> PrettyPrinter'Set("PrettyForm") True In> exp1 := Taylor(x,0,7) Sin(x) 3 5 7 x x x x   +    6 120 5040 In> exp2 := InverseTaylor(x,0,7) ArcSin(x) 5 7 3 x x x      + x 120 5040 6 In> Simplify(exp1exp2) 0
See also
ReversePoly()
,Taylor()
,BigOh()

ReversePoly
(f, g, var, newvar, degree)Â¶ solve \(h(f(x)) = g(x) + O(x^n)\) for \(h\)
 Param f
function of
var
 Param g
function of
var
 Param var
a variable
 Param newvar
a new variable to express the result in
 Param degree
the degree of the required solution
This function returns a polynomial in â€śnewvarâ€ť, say â€śh(newvar)â€ť, with the property that â€śh(f(var))â€ť equals â€śg(var)â€ť up to order â€śdegreeâ€ť. The degree of the result will be at most â€śdegree1â€ť. The only requirement is that the first derivative of â€śfâ€ť should not be zero. This function is used to determine the Taylor series expansion of the inverse of a function â€śfâ€ť: if we take â€śg(var)=varâ€ť, then â€śh(f(var))=varâ€ť (up to order â€śdegreeâ€ť), so â€śhâ€ť will be the inverse of â€śfâ€ť.
 Example
In> f(x):=Eval(Expand((1+x)^4)) Out> True; In> g(x) := x^2 Out> True; In> h(y):=Eval(ReversePoly(f(x),g(x),x,y,8)) Out> True; In> BigOh(h(f(x)),x,8) Out> x^2; In> h(x) Out> (2695*(x1)^7)/131072+(791*(x1)^6)/32768 +(119*(x1)^5)/4096+(37*(x1)^4)/1024+(3*(x1)^3)/64+(x1)^2/16;
See also
InverseTaylor()
,Taylor()
,BigOh()

BigOh
(poly, var, degree)Â¶ drop all terms of a certain order in a polynomial
 Param poly
a univariate polynomial
 Param var
a free variable
 Param degree
positive integer
This function drops all terms of order â€śdegreeâ€ť or higher in â€śpolyâ€ť, which is a polynomial in the variable â€śvarâ€ť.
 Example
In> BigOh(1+x+x^2+x^3,x,2) Out> x+1;
See also
Taylor()
,InverseTaylor()

LagrangeInterpolant
(xlist, ylist, var)Â¶ polynomial interpolation
 Param xlist
list of argument values
 Param ylist
list of function values
 Param var
free variable for resulting polynomial
This function returns a polynomial in the variable â€śvarâ€ť which interpolates the points â€ś(xlist, ylist)â€ť. Specifically, the value of the resulting polynomial at â€śxlist[1]â€ť is â€śylist[1]â€ť, the value at â€śxlist[2]â€ť is â€śylist[2]â€ť, etc. The degree of the polynomial is not greater than the length of â€śxlistâ€ť. The lists â€śxlistâ€ť and â€śylistâ€ť should be of equal length. Furthermore, the entries of â€śxlistâ€ť should be all distinct to ensure that there is one and only one solution. This routine uses the Lagrange interpolant formula to build up the polynomial.
 Example
In> f := LagrangeInterpolant({0,1,2}, \ {0,1,1}, x); Out> (x*(x1))/2x*(x2); In> Eval(Subst(x,0) f); Out> 0; In> Eval(Subst(x,1) f); Out> 1; In> Eval(Subst(x,2) f); Out> 1; In> PrettyPrinter'Set("PrettyForm"); True In> LagrangeInterpolant({x1,x2,x3}, {y1,y2,y3}, x) y1 * ( x  x2 ) * ( x  x3 )  ( x1  x2 ) * ( x1  x3 ) y2 * ( x  x1 ) * ( x  x3 ) +  ( x2  x1 ) * ( x2  x3 ) y3 * ( x  x1 ) * ( x  x2 ) +  ( x3  x1 ) * ( x3  x2 )
See also

n
!
Â¶ factorial
 Param m
integer
 Param n
integer, halfinteger, or list
 Param a}, {b
numbers
The factorial function {n!} calculates the factorial of integer or halfinteger numbers. For nonnegative integers, \(n! := n*(n1)*(n2)*...*1\). The factorial of halfintegers is defined via Eulerâ€™s Gamma function, \(z! := Gamma(z+1)\). If \(n=0\) the function returns \(1\). The â€śdouble factorialâ€ť function {n!!} calculates \(n*(n2)*(n4)*...\). This product terminates either with \(1\) or with \(2\) depending on whether \(n\) is odd or even. If \(n=0\) the function returns \(1\). The â€śpartial factorialâ€ť function {a * b} calculates the product :math:`a*(a+1)*â€¦` which is terminated at the least integer not greater than :math:`b`. The arguments :math:`a` and :math:`b` do not have to be integers; for integer arguments, {a * b} = \(b! / (a1)!\). This function is sometimes a lot faster than evaluating the two factorials, especially if \(a\) and \(b\) are close together. If \(a>b\) the function returns \(1\). The {Subfactorial} function can be interpreted as the number of permutations of {m} objects in which no object appears in its natural place, also called â€śderangements.â€ť The factorial functions are threaded, meaning that if the argument {n} is a list, the function will be applied to each element of the list. Note: For reasons of Yacas syntax, the factorial sign {!} cannot precede other nonletter symbols such as {+} or {*}. Therefore, you should enter a space after {!} in expressions such as {x! +1}. The factorial functions terminate and print an error message if the arguments are too large (currently the limit is \(n < 65535\)) because exact factorials of such large numbers are computationally expensive and most probably not useful. One can call {Internalâ€™LnGammaNum()} to evaluate logarithms of such factorials to desired precision.
 Example
In> 5! Out> 120; In> 1 * 2 * 3 * 4 * 5 Out> 120; In> (1/2)! Out> Sqrt(Pi)/2; In> 7!!; Out> 105; In> 1/3 *** 10; Out> 17041024000/59049; In> Subfactorial(10) Out> 1334961;
See also
Bin()
,Factorize()
,Gamma()
,!()
,***()
,Subfactorial()

n
!!
Â¶ double factorial

x
***
yÂ¶ whatever

Bin
(n, m)Â¶ binomial coefficients
 Param n}, {m
integers
This function calculates the binomial coefficient â€śnâ€ť above â€śmâ€ť, which equals \(n! / (m! * (nm)!)\) This is equal to the number of ways to choose â€śmâ€ť objects out of a total of â€śnâ€ť objects if order is not taken into account. The binomial coefficient is defined to be zero if â€śmâ€ť is negative or greater than â€śnâ€ť; {Bin(0,0)}=1.
 Example
In> Bin(10, 4) Out> 210; In> 10! / (4! * 6!) Out> 210;
See also
()
,Eulerian()

Eulerian
(n, m)Â¶ Eulerian numbers
The Eulerian numbers can be viewed as a generalization of the binomial coefficients, and are given explicitly by \(Sum(j,0,k+1,(1)^j*Bin(n+1,j)*(kj+1)^n)\).
 Example
In> Eulerian(6,2) Out> 302; In> Eulerian(10,9) Out> 1;
See also

KroneckerDelta
(i, j)Â¶ 
KroneckerDelta
({i, j, ...}) Kronecker delta
Calculates the Kronecker delta, which gives \(1\) if all arguments are equal and \(0\) otherwise.

LeviCivita
(list)Â¶ totally antisymmetric LeviCivita symbol
 Param list
a list of integers \(1,\ldots,n\) in some order
LeviCivita()
implements the LeviCivita symbol.list
should be a list of integers, and this function returns 1 if the integers are in successive order, eg.LeviCivita({1,2,3,...})
would return 1. Swapping two elements of this list would return 1. So,LeviCivita({2,1,3})
would evaluate to 1. Example
In> LeviCivita({1,2,3}) Out> 1; In> LeviCivita({2,1,3}) Out> 1; In> LeviCivita({2,2,3}) Out> 0;
See also

Permutations
(list)Â¶ get all permutations of a list
 Param list
a list of elements
Permutations returns a list with all the permutations of the original list.
 Example
In> Permutations({a,b,c}) Out> {{a,b,c},{a,c,b},{c,a,b},{b,a,c}, {b,c,a},{c,b,a}};
See also

Fibonacci
(n)Â¶ Fibonacci sequence
The function returns \(n\)th Fibonacci number
 Example
In> Fibonacci(4) Out> 3 In> Fibonacci(8) Out> 21 In> Table(Fibonacci(i), i, 1, 10, 1) Out> {1,1,2,3,5,8,13,21,34,55}
Simplification of expressionsÂ¶
Simplification of expression is a big and nontrivial subject. Simplification implies that there is a preferred form. In practice the preferred form depends on the calculation at hand. This chapter describes the functions offered that allow simplification of expressions.

Simplify
(expr)Â¶ try to simplify an expression
This function tries to simplify the expression
expr
as much as possible. It does this by grouping powers within terms, and then grouping similar terms. Example
In> a*b*a^2/ba^3 Out> (b*a^3)/ba^3; In> Simplify(a*b*a^2/ba^3) Out> 0;
See also
FactorialSimplify()
,LnCombine()
,LnExpand()
,RadSimp()
,TrigSimpCombine()

RadSimp
(expr)Â¶ simplify expression with nested radicals
This function tries to write the expression
expr
as a sum of roots of integers: \(\sqrt{e_1} + \sqrt{e_2} + ...\), where \(e_1,e_2\) and so on are natural numbers. The expressionexpr
may not contain free variables.It does this by trying all possible combinations for \(e_1,e_2,\ldots\). Every possibility is numerically evaluated using
N()
and compared with the numerical evaluation ofexpr
. If the approximations are equal (up to a certain margin), this possibility is returned. Otherwise, the expression is returned unevaluated.Note
Due to the use of numerical approximations, there is a small chance that the expression returned by
RadSimp()
is close but not equal toexpr
:In> RadSimp(Sqrt(1+10^(6))) Out> 1;
Note
If the numerical value of
expr
is large, the number of possibilities becomes exorbitantly big so the evaluation may take very long. Example
In> RadSimp(Sqrt(9+4*Sqrt(2))) Out> Sqrt(8)+1; In> RadSimp(Sqrt(5+2*Sqrt(6)) + Sqrt(52*Sqrt(6))) Out> Sqrt(12); In> RadSimp(Sqrt(14+3*Sqrt(3+2*Sqrt(512*Sqrt(32*Sqrt(2)))))) Out> Sqrt(2)+3;
See also

FactorialSimplify
(expression)Â¶ simplify hypergeometric expressions containing factorials
FactorialSimplify()
takes an expression that may contain factorials, and tries to simplify it. An expression like \(\frac{(n+1)!}{n!}\) would simplify to \((n+1)\).See also
Simplify()
,()

LnExpand
(expr)Â¶ expand a logarithmic expression using standard logarithm rules
LnExpand()
takes an expression of the form \(\ln(expr)\), and applies logarithm rules to expand this into multipleLn()
expressions where possible. An expression like \(\ln(ab^n)\) would be expanded to \(\ln(a)+n\ln(b)\). If the logarithm of an integer is discovered, it is factorised usingFactors()
and expanded as thoughLnExpand()
had been given the factorised form. So \(\ln(18)\) goes to \(\ln(2)+2\ln(3)\).See also

LnCombine
(expr)Â¶ combine logarithmic expressions using standard logarithm rules
LnCombine()
findsLn()
terms in the expression it is given, and combines them using logarithm rules. It is intended to be the converse ofLnExpand()
.See also

TrigSimpCombine
(expr)Â¶ combine products of trigonometric functions
This function applies the product rules of trigonometry, e.g. \(\cos{u}\sin{v} = \frac{1}{2}(\sin(vu) + \sin(v+u))\). As a result, all products of the trigonometric functions
Cos()
andSin()
disappear. The function also tries to simplify the resulting expression as much as possible by combining all similar terms. This function is used in for instanceIntegrate()
, to bring down the expression into a simpler form that hopefully can be integrated easily. Example
In> PrettyPrinter'Set("PrettyForm"); True In> TrigSimpCombine(Cos(a)^2+Sin(a)^2) 1 In> TrigSimpCombine(Cos(a)^2Sin(a)^2) Cos( 2 * a ) Out> In> TrigSimpCombine(Cos(a)^2*Sin(b)) Sin( b ) Sin( 2 * a + b )  +  2 4 Sin( 2 * a  b )   4
See also
SolversÂ¶
By solving one tries to find a mathematical object that meets certain criteria. This chapter documents the functions that are available to help find solutions to specific types of problems.
Symbolic SolversÂ¶

Solve
(eq, var)Â¶ solve an equation
 Param eq
equation to solve
 Param var
variable to solve for
This command tries to solve an equation. If {eq} does not contain the {==} operator, it is assumed that the user wants to solve \(eq == 0\). The result is a list of equations of the form {var == value}, each representing a solution of the given equation. The {Where} operator can be used to substitute this solution in another expression. If the given equation {eq} does not have any solutions, or if {Solve} is unable to find any, then an empty list is returned. The current implementation is far from perfect. In particular, the user should keep the following points in mind:

OldSolve
(eq, var)Â¶ old version of {Solve}
 Param eq
single identity equation
 Param var
single variable
 Param eqlist
list of identity equations
 Param varlist
list of variables
This is an older version of {Solve}. It is retained for two reasons. The first one is philosophical: it is good to have multiple algorithms available. The second reason is more practical: the newer version cannot handle systems of equations, but {OldSolve} can. This command tries to solve one or more equations. Use the first form to solve a single equation and the second one for systems of equations. The first calling sequence solves the equation â€śeqâ€ť for the variable â€śvarâ€ť. Use the {==} operator to form the equation. The value of â€śvarâ€ť which satisfies the equation, is returned. Note that only one solution is found and returned. To solve a system of equations, the second form should be used. It solves the system of equations contained in the list â€śeqlistâ€ť for the variables appearing in the list â€śvarlistâ€ť. A list of results is returned, and each result is a list containing the values of the variables in â€śvarlistâ€ť. Again, at most a single solution is returned. The task of solving a single equation is simply delegated to {SuchThat}. Multiple equations are solved recursively: firstly, an equation is sought in which one of the variables occurs exactly once; then this equation is solved with {SuchThat}; and finally the solution is substituted in the other equations by {Eliminate} decreasing the number of equations by one. This suffices for all linear equations and a large group of simple nonlinear equations.
 Example
In> OldSolve(a+x*y==z,x) Out> (za)/y; In> OldSolve({a*x+y==0,x+z==0},{x,y}) Out> {{z,z*a}}; This means that "x = (za)/y" is a solution of the first equation and that "x = z", "y = z*a" is a solution of the systems of equations in the second command. An example which {OldSolve} cannot solve: In> OldSolve({x^2x == y^2y,x^2x == y^3+y},{x,y}); Out> {};
See also
Solve()
,SuchThat()
,Eliminate()
,PSolve()
,==()

SuchThat
(expr, var)Â¶ special purpose solver
 Param expr
expression to make zero
 Param var
variable (or subexpression) to solve for
This functions tries to find a value of the variable â€śvarâ€ť which makes the expression â€śexprâ€ť zero. It is also possible to pass a subexpression as â€śvarâ€ť, in which case {SuchThat} will try to solve for that subexpression. Basically, only expressions in which â€śvarâ€ť occurs only once are handled; in fact, {SuchThat} may even give wrong results if the variables occurs more than once. This is a consequence of the implementation, which repeatedly applies the inverse of the top function until the variable â€śvarâ€ť is reached.
 Example
In> SuchThat(a+b*x, x) Out> (a)/b; In> SuchThat(Cos(a)+Cos(b)^2, Cos(b)) Out> Cos(a)^(1/2); In> A:=Expand(a*x+b*x+c, x) Out> (a+b)*x+c; In> SuchThat(A, x) Out> (c)/(a+b);
See also

Eliminate
(var, value, expr)Â¶ substitute and simplify
 Param var
variable (or subexpression) to substitute
 Param value
new value of â€śvarâ€ť
 Param expr
expression in which the substitution should take place
This function uses {Subst} to replace all instances of the variable (or subexpression) â€śvarâ€ť in the expression â€śexprâ€ť with â€śvalueâ€ť, calls {Simplify} to simplify the resulting expression, and returns the result.
 Example
In> Subst(Cos(b), c) (Sin(a)+Cos(b)^2/c) Out> Sin(a)+c^2/c; In> Eliminate(Cos(b), c, Sin(a)+Cos(b)^2/c) Out> Sin(a)+c;
See also

PSolve
(poly, var)Â¶ solve a polynomial equation
 Param poly
a polynomial in â€śvarâ€ť
 Param var
a variable
This commands returns a list containing the roots of â€śpolyâ€ť, considered as a polynomial in the variable â€śvarâ€ť. If there is only one root, it is not returned as a oneentry list but just by itself. A double root occurs twice in the result, and similarly for roots of higher multiplicity. All polynomials of degree up to 4 are handled.
 Example
In> PSolve(b*x+a,x) Out> a/b; In> PSolve(c*x^2+b*x+a,x) Out> {(Sqrt(b^24*c*a)b)/(2*c),((b+ Sqrt(b^24*c*a)))/(2*c)};

MatrixSolve
(A, b)Â¶ solve a system of equations
 Param A
coefficient matrix
 Param b
row vector
{MatrixSolve} solves the matrix equations {A*x = b} using Gaussian Elimination with Backward substitution. If your matrix is triangular or diagonal, it will be recognized as such and a faster algorithm will be used.
 Example
In> A:={{2,4,2,2},{1,2,4,3},{3,3,8,2},{1,1,6,3}}; Out> {{2,4,2,2},{1,2,4,3},{3,3,8,2},{1,1,6,3}}; In> b:={4,5,7,7}; Out> {4,5,7,7}; In> MatrixSolve(A,b); Out> {1,2,3,4}; Numeric solvers
Numeric SolversÂ¶

Newton
(expr, var, initial, accuracy)Â¶ solve an equation numerically with Newtonâ€™s method
 Param expr
an expression to find a zero for
 Param var
free variable to adjust to find a zero
 Param initial
initial value for â€śvarâ€ť to use in the search
 Param accuracy
minimum required accuracy of the result
 Param min
minimum value for â€śvarâ€ť to use in the search
 Param max
maximum value for â€śvarâ€ť to use in the search
This function tries to numerically find a zero of the expression {expr}, which should depend only on the variable {var}. It uses the value {initial} as an initial guess. The function will iterate using Newtonâ€™s method until it estimates that it has come within a distance {accuracy} of the correct solution, and then it will return its best guess. In particular, it may loop forever if the algorithm does not converge. When {min} and {max} are supplied, the Newton iteration takes them into account by returning {Fail} if it failed to find a root in the given range. Note this doesnâ€™t mean there isnâ€™t a root, just that this algorithm failed to find it due to the trial values going outside of the bounds.
 Example
In> Newton(Sin(x),x,3,0.0001) Out> 3.1415926535; In> Newton(x^21,x,2,0.0001,5,5) Out> 1; In> Newton(x^2+1,x,2,0.0001,5,5) Out> Fail;
See also

FindRealRoots
(p)Â¶ find the real roots of a polynomial
 Param p
a polynomial in {x}
Return a list with the real roots of \(p\). It tries to find the realvalued roots, and thus requires numeric floating point calculations. The precision of the result can be improved by increasing the calculation precision.
 Example
In> p:=Expand((x+3.1)^5*(x6.23)) Out> x^6+9.27*x^50.465*x^4300.793*x^3 1394.2188*x^22590.476405*x1783.5961073; In> FindRealRoots(p) Out> {3.1,6.23};
See also
SquareFree()
,NumRealRoots()
,MinimumBound()
,MaximumBound()
,Factor()

NumRealRoots
(p)Â¶ return the number of real roots of a polynomial
 Param p
a polynomial in
x
Returns the number of real roots of a polynomial \(p\). The polynomial must use the variable
x
and no other variables. Example
In> NumRealRoots(x^21) Out> 2; In> NumRealRoots(x^2+1) Out> 0;
See also
FindRealRoots()
,SquareFree()
,MinimumBound()
,MaximumBound()
,Factor()

MinimumBound
(p)Â¶ return lower bounds on the absolute values of real roots of a polynomial
 Param p
a polynomial in \(x\)
Return minimum and maximum bounds for the absolute values of the real roots of a polynomial {p}. The polynomial has to be converted to one with rational coefficients first, and be made squarefree. The polynomial must use the variable {x}.
 Example
In> p:=SquareFree(Rationalize((x3.1)*(x+6.23))) Out> (40000*x^2125200*x+772520)/870489; In> MinimumBound(p) Out> 5000000000/2275491039; In> N(%) Out> 2.1973279236; In> MaximumBound(p) Out> 10986639613/1250000000; In> N(%) Out> 8.7893116904;
See also
Auxilliary FunctionsÂ¶

expr
Where
x==vÂ¶ substitute result into expression
 Param expr
expression to evaluate
 Param x
variable to set
 Param v
value to substitute for variable
The operator
Where()
fills in values for variables, in its simplest form. It accepts sets of variable/value pairs defined asvar1==val1 And var2==val2 And ...
and fills in the corresponding values. Lists of value pairs are also possible, as:{var1==val1 And var2==val2, var1==val3 And var2==val4}
. These values might be obtained throughSolve()
. Example
In> x^2+y^2 Where x==2 Out> y^2+4; In> x^2+y^2 Where x==2 And y==3 Out> 13; In> x^2+y^2 Where {x==2 And y==3} Out> {13}; In> x^2+y^2 Where {x==2 And y==3,x==4 And y==5} Out> {13,41};

eq1
AddTo
eq2Â¶ add an equation to a set of equations or set of set of equations
 Param eq
(set of) set of equations
Given two (sets of) sets of equations, the command AddTo combines multiple sets of equations into one. A list {a,b} means that a is a solution, OR b is a solution. AddTo then acts as a AND operation: (a or b) and (c or d) => (a or b) Addto (c or d) => (a and c) or (a and d) or (b and c) or (b and d) This function is useful for adding an identity to an already existing set of equations. Suppose a solve command returned {a>=0 And x==a,a<0 And x== a} from an expression x==Abs(a), then a new identity a==2 could be added as follows: In> a==2 AddTo {a>=0 And x==a,a<0 And x== a} Out> {a==2 And a>=0 And x==a,a==2 And a<0 And x== a}; Passing this set of set of identities back to solve, solve should recognize that the second one is not a possibility any more, since a==2 And a<0 can never be true at the same time.
 Example
In> {A==2,c==d} AddTo {b==3 And d==2} Out> {A==2 And b==3 And d==2,c==d And b==3 And d==2}; In> {A==2,c==d} AddTo {b==3, d==2} Out> {A==2 And b==3,A==2 And d==2,c==d And b==3,c==d And d==2};
Differential EquationsÂ¶
In this chapter, some facilities for solving differential equations are described. Currently only simple equations without auxiliary conditions are supported.

OdeSolve
(expr1==expr2)Â¶ general ODE solver
 Param expr1,expr2
expressions containing a function to solve for
This function currently can solve second order homogeneous linear equations with real constant coefficient. The solution is returned with unique constants generated by {UniqueConstant}. The roots of the auxiliary equation are used as the arguments of exponentials. If the roots are complex conjugate pairs, then the solution returned is in the form of exponentials, sines and cosines. First and second derivatives are entered as
y'
,y''
. Higher order derivatives may be entered asy(n)
, wheren
is any positive integer. Example
In> OdeSolve( y'' + y == 0 ) Out> C42*Sin(x)+C43*Cos(x); In> OdeSolve( 2*y'' + 3*y' + 5*y == 0 ) Out> Exp(((3)*x)/4)*(C78*Sin(Sqrt(31/16)*x)+C79*Cos(Sqrt(31/16)*x)); In> OdeSolve( y''  4*y == 0 ) Out> C132*Exp((2)*x)+C136*Exp(2*x); In> OdeSolve( y'' +2*y' + y == 0 ) Out> (C183+C184*x)*Exp(x);
See also
Solve()
,RootsWithMultiples()

OdeTest
(eqn, testsol)Â¶ test the solution of an ODE
 Param eqn
equation to test
 Param testsol
test solution
This function automates the verification of the solution of an ODE. It can also be used to quickly see how a particular equation operates on a function.
 Example
In> OdeTest(y''+y,Sin(x)+Cos(x)) Out> 0; In> OdeTest(y''+2*y,Sin(x)+Cos(x)) Out> Sin(x)+Cos(x);
See also

OdeOrder
(eqn)Â¶ return order of an ODE
 Param eqn
equation
This function returns the order of the differential equation, which is order of the highest derivative. If no derivatives appear, zero is returned.
 Example
In> OdeOrder(y'' + 2*y' == 0) Out> 2; In> OdeOrder(Sin(x)*y(5) + 2*y' == 0) Out> 5; In> OdeOrder(2*y + Sin(y) == 0) Out> 0;
See also

WronskianMatrix
(func, var)Â¶ create the Wronskian matrix
 Param func
an \(n\)dimensional vector of functions
 Param var
a variable to differentiate with respect to
The function
WronskianMatrix()
calculates the Wronskian matrix of \(n\) functions. The Wronskian matrix is created by putting each function as the first element of each column, and filling in the rest of each column by the \((i1)\)th derivative, where \(i\) is the current row. The Wronskian matrix is used to verify that the \(n\) functions are linearly independent, usually solutions to a differential equation. If the determinant of the Wronskian matrix is zero, then the functions are dependent, otherwise they are independent. Example
In> WronskianMatrix({Sin(x),Cos(x),x^4},x); Out> {{Sin(x),Cos(x),x^4},{Cos(x),Sin(x),4*x^3}, {Sin(x),Cos(x),12*x^2}}; In> PrettyForm(%) / \  ( Sin( x ) ) ( Cos( x ) ) / 4 \   \ x /     ( Cos( x ) ) ( ( Sin( x ) ) ) / 3 \   \ 4 * x /     ( ( Sin( x ) ) ) ( ( Cos( x ) ) ) / 2 \   \ 12 * x /  \ /
The last element is a linear combination of the first two, so the determinant is zero:
In> A:=Determinant( WronskianMatrix( {x^4,x^3,2*x^4+3*x^3},x ) ) Out> x^4*3*x^2*(24*x^2+18*x)x^4*(8*x^3+9*x^2)*6*x +(2*x^4+3*x^3)*4*x^3*6*x4*x^6*(24*x^2+18*x)+x^3 *(8*x^3+9*x^2)*12*x^2(2*x^4+3*x^3)*3*x^2*12*x^2; In> Simplify(A) Out> 0;
Propositional logic theorem proverÂ¶

CanProve
(proposition)Â¶ try to prove statement
 Param proposition
an expression with logical operations
Yacas has a small builtin propositional logic theorem prover. It can be invoked with a call to
CanProve()
. An example of a proposition is: â€śif a implies b and b implies c then a implies câ€ť. Yacas supports the following logical operations:Not
negation, read as â€śnotâ€ť
And
conjunction, read as â€śandâ€ť
Or
disjunction, read as â€śorâ€ť
=>
implication, read as â€śimpliesâ€ť
The abovementioned proposition would be represented by the following expression:
( (a=>b) And (b=>c) ) => (a=>c)
Yacas can prove that is correct by applying
CanProve()
to it:In> CanProve(( (a=>b) And (b=>c) ) => (a=>c)) Out> True;
It does this in the following way: in order to prove a proposition \(p\), it suffices to prove that \(\neg p\) is false. It continues to simplify \(\neg p\) using the rules:
\(\neg\neg x \to x\) (eliminate double negation),
\(x\Rightarrow y \to \neg x \vee y\) (eliminate implication),
\(\neg (x \wedge y) \to \neg x \vee \neg y\) (De Morganâ€™s law),
\(\neg (x \vee y) \to \neg x \wedge \neg y\) (De Morganâ€™s law),
\((x \wedge y) \vee z \to (x \vee z) \wedge (y \vee z)\) (distribution),
\(x \vee (y \wedge z) \to (x \vee y) \wedge (x \vee z)\) (distribution),
and the obvious other rules, such as, \(1 \vee x \to 1\) etc. The above rules will translate a proposition into a form:
(p1 Or p2 Or ...) And (q1 Or q2 Or ...) And ...
If any of the clauses is false, the entire expression will be false. In the next step, clauses are scanned for situations of the form: \((p \vee Y) \wedge (\neg p \vee Z) \to (Y \vee Z)\). If this combination \((Y\vee Z)\) is empty, it is false, and thus the entire proposition is false. As a last step, the algorithm negates the result again. This has the added advantage of simplifying the expression further.
 Example
In> CanProve(a Or Not a) Out> True; In> CanProve(True Or a) Out> True; In> CanProve(False Or a) Out> a; In> CanProve(a And Not a) Out> False; In> CanProve(a Or b Or (a And b)) Out> a Or b;
Linear AlgebraÂ¶
This chapter describes the commands for doing linear algebra. They can be used to manipulate vectors, represented as lists, and matrices, represented as lists of lists.

Dot
(t1, t2)Â¶ 
t1
.
t2Â¶ dot product of tensors
 Param t1,t2
tensors (currently only vectors and matrices are supported)
Dot()
returns the dot product (aka inner product) of two tensorst1
andt2
. The last index oft1
and the first index oft2
are contracted. CurrentlyDot()
works only for vectors and matrices. Inner product of two vectors, a matrix with a vector (and vice versa) or two matrices yields respectively a scalar, a vector or a matrix. Example
In> Dot({1,2},{3,4}) Out> 11; In> Dot({{1,2},{3,4}},{5,6}) Out> {17,39}; In> Dot({5,6},{{1,2},{3,4}}) Out> {23,34}; In> Dot({{1,2},{3,4}},{{5,6},{7,8}}) Out> {{19,22},{43,50}};
Or, using the
.
operator:In> {1,2} . {3,4} Out> 11; In> {{1,2},{3,4}} . {5,6} Out> {17,39}; In> {5,6} . {{1,2},{3,4}} Out> {23,34}; In> {{1,2},{3,4}} . {{5,6},{7,8}} Out> {{19,22},{43,50}};
See also
Outer()
,Cross()
,IsScalar()
,IsVector()
,IsMatrix()

CrossProduct
(u, v)Â¶ 
u
X
vÂ¶ cross outer product of vectors
 Param u, v
threedimensional vectors
The cross product of the vectors
u
andv
is returned. Bothu
andv
have to be threedimensional. Example
In> {a,b,c} X {d,e,f}; Out> {b*fc*e,c*da*f,a*eb*d};
See also

Outer
(t1, t2)Â¶ 
t1
o
t2Â¶ outer tensor product
 Param t1,t2
tensors (currently only vectors are supported)
Outer()
returns the outer product of two tensorst1
andt2
. CurrentlyOuter()
work works only for vectors, i.e. tensors of rank 1. The outer product of two vectors yields a matrix. Example
In> Outer({1,2},{3,4,5}) Out> {{3,4,5},{6,8,10}}; In> Outer({a,b},{c,d}) Out> {{a*c,a*d},{b*c,b*d}};
Or, using the
o
operator:In> {1,2} o {3,4,5} Out> {{3,4,5},{6,8,10}}; In> {a,b} o {c,d} Out> {{a*c,a*d},{b*c,b*d}};
See also
Dot()
,Cross()

ZeroVector
(n)Â¶ create a vector with all zeroes
 Param n
length of the vector to return
This command returns a vector of length
n
, filled with zeroes. Example
In> ZeroVector(4) Out> {0,0,0,0};
See also

BaseVector
(k, n)Â¶ base vector
 Param k
index of the base vector to construct
 Param n
dimension of the vector
This command returns the â€śkâ€ťth base vector of dimension â€śnâ€ť. This is a vector of length â€śnâ€ť with all zeroes except for the â€śkâ€ťth entry, which contains a 1.
 Example
In> BaseVector(2,4) Out> {0,1,0,0};
See also

Identity
(n)Â¶ make identity matrix
 Param n
size of the matrix
This commands returns the identity matrix of size â€śnâ€ť by â€śnâ€ť. This matrix has ones on the diagonal while the other entries are zero.
 Example
In> Identity(3) Out> {{1,0,0},{0,1,0},{0,0,1}};
See also

ZeroMatrix
(n)Â¶ make a zero matrix
 Param n
number of rows
 Param m
number of columns
This command returns a matrix with n rows and m columns, completely filled with zeroes. If only given one parameter, it returns the square n by n zero matrix.
 Example
In> ZeroMatrix(3,4) Out> {{0,0,0,0},{0,0,0,0},{0,0,0,0}}; In> ZeroMatrix(3) Out> {{0,0,0},{0,0,0},{0,0,0}};
See also

Diagonal
(A)Â¶ extract the diagonal from a matrix
 Param A
matrix
This command returns a vector of the diagonal components of the matrix {A}.
 Example
In> Diagonal(5*Identity(4)) Out> {5,5,5,5}; In> Diagonal(HilbertMatrix(3)) Out> {1,1/3,1/5};
See also

DiagonalMatrix
(d)Â¶ construct a diagonal matrix
 Param d
list of values to put on the diagonal
This command constructs a diagonal matrix, that is a square matrix whose offdiagonal entries are all zero. The elements of the vector â€śdâ€ť are put on the diagonal.
 Example
In> DiagonalMatrix(1 .. 4) Out> {{1,0,0,0},{0,2,0,0},{0,0,3,0},{0,0,0,4}};
See also

OrthogonalBasis
(W)Â¶ create an orthogonal basis
 Param W
A linearly independent set of row vectors (aka a matrix)
Given a linearly independent set {W} (constructed of rows vectors), this command returns an orthogonal basis {V} for {W}, which means that span(V) = span(W) and {InProduct(V[i],V[j]) = 0} when {i != j}. This function uses the GramSchmidt orthogonalization process.
 Example
In> OrthogonalBasis({{1,1,0},{2,0,1},{2,2,1}}) Out> {{1,1,0},{1,1,1},{1/3,1/3,2/3}};
See also
OrthonormalBasis()
,InProduct()

OrthonormalBasis
(W)Â¶ create an orthonormal basis
 Param W
A linearly independent set of row vectors (aka a matrix)
Given a linearly independent set {W} (constructed of rows vectors), this command returns an orthonormal basis {V} for {W}. This is done by first using {OrthogonalBasis(W)}, then dividing each vector by its magnitude, so as the give them unit length.
 Example
In> OrthonormalBasis({{1,1,0},{2,0,1},{2,2,1}}) Out> {{Sqrt(1/2),Sqrt(1/2),0},{Sqrt(1/3),Sqrt(1/3),Sqrt(1/3)}, {Sqrt(1/6),Sqrt(1/6),Sqrt(2/3)}};
See also
OrthogonalBasis()
,InProduct()
,Normalize()

Normalize
(v)Â¶ normalize a vector
 Param v
a vector
Return the normalized (unit) vector parallel to {v}: a vector having the same direction but with length 1.
 Example
In> v:=Normalize({3,4}) Out> {3/5,4/5}; In> v . v Out> 1;
See also
InProduct()
,CrossProduct()

Transpose
(M)Â¶ get transpose of a matrix
 Param M
a matrix
{Transpose} returns the transpose of a matrix \(M\). Because matrices are just lists of lists, this is a useful operation too for lists.
 Example
In> Transpose({{a,b}}) Out> {{a},{b}};

Determinant
(M)Â¶ determinant of a matrix
 Param M
a matrix
Returns the determinant of a matrix M.
 Example
In> A:=DiagonalMatrix(1 .. 4) Out> {{1,0,0,0},{0,2,0,0},{0,0,3,0},{0,0,0,4}}; In> Determinant(A) Out> 24;

Trace
(M)Â¶ trace of a matrix
 Param M
a matrix
{Trace} returns the trace of a matrix \(M\) (defined as the sum of the elements on the diagonal of the matrix).
 Example
In> A:=DiagonalMatrix(1 .. 4) Out> {{1,0,0,0},{0,2,0,0},{0,0,3,0},{0,0,0,4}}; In> Trace(A) Out> 10;

Inverse
(M)Â¶ get inverse of a matrix
 Param M
a matrix
Inverse returns the inverse of matrix \(M\). The determinant of \(M\) should be nonzero. Because this function uses {Determinant} for calculating the inverse of a matrix, you can supply matrices with nonnumeric (symbolic) matrix elements.
 Example
In> A:=DiagonalMatrix({a,b,c}) Out> {{a,0,0},{0,b,0},{0,0,c}}; In> B:=Inverse(A) Out> {{(b*c)/(a*b*c),0,0},{0,(a*c)/(a*b*c),0}, {0,0,(a*b)/(a*b*c)}}; In> Simplify(B) Out> {{1/a,0,0},{0,1/b,0},{0,0,1/c}};
See also

Minor
(M, i, j)Â¶ get principal minor of a matrix
 Param M
a matrix
 Param i}, {j
positive integers
Minor returns the minor of a matrix around the element \(i, j\). The minor is the determinant of the matrix obtained from \(M\) by deleting the \(i\)th row and the \(j\)th column.
 Example
In> A := {{1,2,3}, {4,5,6}, {7,8,9}}; Out> {{1,2,3},{4,5,6},{7,8,9}}; In> PrettyForm(A); / \  ( 1 ) ( 2 ) ( 3 )     ( 4 ) ( 5 ) ( 6 )     ( 7 ) ( 8 ) ( 9 )  \ / Out> True; In> Minor(A,1,2); Out> 6; In> Determinant({{2,3}, {8,9}}); Out> 6;
See also

CoFactor
(M, i, j)Â¶ cofactor of a matrix
 Param M
a matrix
 Param i}, {j
positive integers
{CoFactor} returns the cofactor of a matrix around the element \(i,j\). The cofactor is the minor times \((1)^(i+j)\).
 Example
In> A := {{1,2,3}, {4,5,6}, {7,8,9}}; Out> {{1,2,3},{4,5,6},{7,8,9}}; In> PrettyForm(A); / \  ( 1 ) ( 2 ) ( 3 )     ( 4 ) ( 5 ) ( 6 )     ( 7 ) ( 8 ) ( 9 )  \ / Out> True; In> CoFactor(A,1,2); Out> 6; In> Minor(A,1,2); Out> 6; In> Minor(A,1,2) * (1)^(1+2); Out> 6;
See also

MatrixPower
(mat, n)Â¶ get nth power of a square matrix
 Param mat
a square matrix
 Param n
an integer
{MatrixPower(mat,n)} returns the {n}th power of a square matrix {mat}. For positive {n} it evaluates dot products of {mat} with itself. For negative {n} the nth power of the inverse of {mat} is returned. For {n}=0 the identity matrix is returned.

SolveMatrix
(M, v)Â¶ solve a linear system
 Param M
a matrix
 Param v
a vector
{SolveMatrix} returns the vector \(x\) that satisfies the equation \(M*x = v\). The determinant of \(M\) should be nonzero.
 Example
In> A := {{1,2}, {3,4}}; Out> {{1,2},{3,4}}; In> v := {5,6}; Out> {5,6}; In> x := SolveMatrix(A, v); Out> {4,9/2}; In> A * x; Out> {5,6};
See also

Sparsity
(matrix)Â¶ get the sparsity of a matrix
 Param matrix
a matrix
The function {Sparsity} returns a number between {0} and {1} which represents the percentage of zero entries in the matrix. Although there is no definite critical value, a sparsity of {0.75} or more is almost universally considered a â€śsparseâ€ť matrix. These type of matrices can be handled in a different manner than â€śfullâ€ť matrices which speedup many calculations by orders of magnitude.
 Example
In> Sparsity(Identity(2)) Out> 0.5; In> Sparsity(Identity(10)) Out> 0.9; In> Sparsity(HankelMatrix(10)) Out> 0.45; In> Sparsity(HankelMatrix(100)) Out> 0.495; In> Sparsity(HilbertMatrix(10)) Out> 0; In> Sparsity(ZeroMatrix(10,10)) Out> 1;
PredicatesÂ¶

IsScalar
(expr)Â¶ test for a scalar
 Param expr
a mathematical object
{IsScalar} returns
True
if {expr} is a scalar,False
otherwise. Something is considered to be a scalar if itâ€™s not a list. Example
In> IsScalar(7) Out> True; In> IsScalar(Sin(x)+x) Out> True; In> IsScalar({x,y}) Out> False;
See also

IsVector
([pred, ]expr)Â¶ test for a vector
 Param expr
expression to test
 Param pred
predicate test (e.g. IsNumber, IsInteger, â€¦)
{IsVector(expr)} returns
True
if {expr} is a vector,False
otherwise. Something is considered to be a vector if itâ€™s a list of scalars. {IsVector(pred,expr)} returnsTrue
if {expr} is a vector and if the predicate test {pred} returnsTrue
when applied to every element of the vector {expr},False
otherwise. Example
In> IsVector({a,b,c}) Out> True; In> IsVector({a,{b},c}) Out> False; In> IsVector(IsInteger,{1,2,3}) Out> True; In> IsVector(IsInteger,{1,2.5,3}) Out> False;
See also

IsMatrix
([pred, ]expr)Â¶ test for a matrix
 Param expr
expression to test
 Param pred
predicate test (e.g. IsNumber, IsInteger, â€¦)
{IsMatrix(expr)} returns
True
if {expr} is a matrix,False
otherwise. Something is considered to be a matrix if itâ€™s a list of vectors of equal length. {IsMatrix(pred,expr)} returnsTrue
if {expr} is a matrix and if the predicate test {pred} returnsTrue
when applied to every element of the matrix {expr},False
otherwise. Example
In> IsMatrix(1) Out> False; In> IsMatrix({1,2}) Out> False; In> IsMatrix({{1,2},{3,4}}) Out> True; In> IsMatrix(IsRational,{{1,2},{3,4}}) Out> False; In> IsMatrix(IsRational,{{1/2,2/3},{3/4,4/5}}) Out> True;
See also

IsSquareMatrix
([pred, ]expr)Â¶ test for a square matrix
 Param expr
expression to test
 Param pred
predicate test (e.g. IsNumber, IsInteger, â€¦)
{IsSquareMatrix(expr)} returns
True
if {expr} is a square matrix,False
otherwise. Something is considered to be a square matrix if itâ€™s a matrix having the same number of rows and columns. {IsMatrix(pred,expr)} returnsTrue
if {expr} is a square matrix and if the predicate test {pred} returnsTrue
when applied to every element of the matrix {expr},False
otherwise. Example
In> IsSquareMatrix({{1,2},{3,4}}); Out> True; In> IsSquareMatrix({{1,2,3},{4,5,6}}); Out> False; In> IsSquareMatrix(IsBoolean,{{1,2},{3,4}}); Out> False; In> IsSquareMatrix(IsBoolean,{{True,False},{False,True}}); Out> True;
See also

IsHermitian
(A)Â¶ test for a Hermitian matrix
 Param A
a square matrix
IsHermitian(A) returns
True
if {A} is Hermitian andFalse
otherwise. \(A\) is a Hermitian matrix iff Conjugate( Transpose \(A\) )=:math:A. If \(A\) is a real matrix, it must be symmetric to be Hermitian. Example
In> IsHermitian({{0,I},{I,0}}) Out> True; In> IsHermitian({{0,I},{2,0}}) Out> False;
See also

IsOrthogonal
(A)Â¶ test for an orthogonal matrix
 Param A
square matrix
{IsOrthogonal(A)} returns
True
if {A} is orthogonal andFalse
otherwise. \(A\) is orthogonal iff \(A\)) = Identity, or equivalently Inverse(\(A\)) = Transpose(\(A\)). Example
In> A := {{1,2,2},{2,1,2},{2,2,1}}; Out> {{1,2,2},{2,1,2},{2,2,1}}; In> PrettyForm(A/3) / \  / 1 \ / 2 \ / 2 \              \ 3 / \ 3 / \ 3 /     / 2 \ / 1 \ / 2 \              \ 3 / \ 3 / \ 3 /     / 2 \ / 2 \ / 1 \              \ 3 / \ 3 / \ 3 /  \ / Out> True; In> IsOrthogonal(A/3) Out> True;

IsDiagonal
(A)Â¶ test for a diagonal matrix
 Param A
a matrix
{IsDiagonal(A)} returns
True
if {A} is a diagonal square matrix andFalse
otherwise. Example
In> IsDiagonal(Identity(5)) Out> True; In> IsDiagonal(HilbertMatrix(5)) Out> False;

IsLowerTriangular
(A)Â¶ test for a lower triangular matrix
 Param A
a matrix
A lower/upper triangular matrix is a square matrix which has all zero entries above/below the diagonal. {IsLowerTriangular(A)} returns
True
if {A} is a lower triangular matrix andFalse
otherwise. {IsUpperTriangular(A)} returnsTrue
if {A} is an upper triangular matrix andFalse
otherwise. Example
In> IsUpperTriangular(Identity(5)) Out> True; In> IsLowerTriangular(Identity(5)) Out> True; In> IsLowerTriangular({{1,2},{0,1}}) Out> False; In> IsUpperTriangular({{1,2},{0,1}}) Out> True; A nonsquare matrix cannot be triangular: In> IsUpperTriangular({{1,2,3},{0,1,2}}) Out> False;
See also

IsSymmetric
(A)Â¶ test for a symmetric matrix
 Param A
a matrix
{IsSymmetric(A)} returns
True
if {A} is symmetric andFalse
otherwise. \(A\) is symmetric iff Transpose (\(A\)) =:math:A. Example
In> A := {{1,0,0,0,1},{0,2,0,0,0},{0,0,3,0,0}, {0,0,0,4,0},{1,0,0,0,5}}; In> PrettyForm(A) / \  ( 1 ) ( 0 ) ( 0 ) ( 0 ) ( 1 )     ( 0 ) ( 2 ) ( 0 ) ( 0 ) ( 0 )     ( 0 ) ( 0 ) ( 3 ) ( 0 ) ( 0 )     ( 0 ) ( 0 ) ( 0 ) ( 4 ) ( 0 )     ( 1 ) ( 0 ) ( 0 ) ( 0 ) ( 5 )  \ / Out> True; In> IsSymmetric(A) Out> True;
See also

IsSkewSymmetric
(A)Â¶ test for a skewsymmetric matrix
 Param A
a square matrix
{IsSkewSymmetric(A)} returns
True
if {A} is skew symmetric andFalse
otherwise. \(A\) is skew symmetric iff \(Transpose(A)\) =:math:A. Example
In> A := {{0,1},{1,0}} Out> {{0,1},{1,0}}; In> PrettyForm(%) / \  ( 0 ) ( 1 )     ( 1 ) ( 0 )  \ / Out> True; In> IsSkewSymmetric(A); Out> True;
See also

IsUnitary
(A)Â¶ test for a unitary matrix
 Param A
a square matrix
This function tries to find out if A is unitary. A matrix \(A\) is orthogonal iff \(A^(1)\) = Transpose( Conjugate(\(A\)) ). This is equivalent to the fact that the columns of \(A\) build an orthonormal system (with respect to the scalar product defined by {InProduct}).
 Example
In> IsUnitary({{0,I},{I,0}}) Out> True; In> IsUnitary({{0,I},{2,0}}) Out> False;
See also

IsIdempotent
(A)Â¶ test for an idempotent matrix
 Param A
a square matrix
{IsIdempotent(A)} returns
True
if {A} is idempotent andFalse
otherwise. \(A\) is idempotent iff \(A^2=A\). Note that this also implies that \(A\) raised to any power is also equal to \(A\). Example
In> IsIdempotent(ZeroMatrix(10,10)); Out> True; In> IsIdempotent(Identity(20)) Out> True; Special matrices
EigenproblemÂ¶

CharacteristicEquation
(matrix, var)Â¶ get characteristic polynomial of a matrix
 Param matrix
a matrix
 Param var
a free variable
CharacteristicEquation returns the characteristic equation of â€śmatrixâ€ť, using â€śvarâ€ť. The zeros of this equation are the eigenvalues of the matrix, Det(matrixI*var);
 Example
In> A:=DiagonalMatrix({a,b,c}) Out> {{a,0,0},{0,b,0},{0,0,c}}; In> B:=CharacteristicEquation(A,x) Out> (ax)*(bx)*(cx); In> Expand(B,x) Out> (b+a+c)*x^2x^3((b+a)*c+a*b)*x+a*b*c;
See also

EigenValues
(matrix)Â¶ get eigenvalues of a matrix
 Param matrix
a square matrix
EigenValues returns the eigenvalues of a matrix. The eigenvalues x of a matrix M are the numbers such that \(M*v=x*v\) for some vector. It first determines the characteristic equation, and then factorizes this equation, returning the roots of the characteristic equation Det(matrixx*identity).
 Example
In> M:={{1,2},{2,1}} Out> {{1,2},{2,1}}; In> EigenValues(M) Out> {3,1};
See also

EigenVectors
(A, eigenvalues)Â¶ get eigenvectors of a matrix
 Param matrix
a square matrix
 Param eigenvalues
list of eigenvalues as returned by {EigenValues}
{EigenVectors} returns a list of the eigenvectors of a matrix. It uses the eigenvalues and the matrix to set up n equations with n unknowns for each eigenvalue, and then calls {Solve} to determine the values of each vector.
 Example
In> M:={{1,2},{2,1}} Out> {{1,2},{2,1}}; In> e:=EigenValues(M) Out> {3,1}; In> EigenVectors(M,e) Out> {{ki2/ 1,ki2},{ki2,ki2}};
See also
Matrix decompositionsÂ¶

Cholesky
(A)Â¶ find the Cholesky decomposition
 Param A
a square positive definite matrix
{Cholesky} returns a upper triangular matrix {R} such that {Transpose(R)*R = A}. The matrix {A} must be positive definite, {Cholesky} will notify the user if the matrix is not. Some families of positive definite matrices are all symmetric matrices, diagonal matrices with positive elements and Hilbert matrices.
 Example
In> A:={{4,2,4,2},{2,10,2,7},{4,2,8,4},{2,7,4,7}} Out> {{4,2,4,2},{2,10,2,7},{4,2,8,4},{2,7,4,7}}; In> R:=Cholesky(A); Out> {{2,1,2,1},{0,3,0,2},{0,0,2,1},{0,0,0,1}}; In> Transpose(R)*R = A Out> True; In> Cholesky(4*Identity(5)) Out> {{2,0,0,0,0},{0,2,0,0,0},{0,0,2,0,0},{0,0,0,2,0},{0,0,0,0,2}}; In> Cholesky(HilbertMatrix(3)) Out> {{1,1/2,1/3},{0,Sqrt(1/12),Sqrt(1/12)},{0,0,Sqrt(1/180)}}; In> Cholesky(ToeplitzMatrix({1,2,3})) In function "Check" : CommandLine(1) : "Cholesky: Matrix is not positive definite"
See also

LU
(A)Â¶ find the LU decomposition
 Param A
square matrix
LU()
performs LU decomposition of a matrix. Example
In> A := {{1,2}, {3,4}} Out> {{1,2},{3,4}} In> {l,u} := LU(A) Out> {{{1,0},{3,1}},{{1,2},{0,2}}} In> IsLowerTriangular(l) Out> True In> IsUpperTriangular(u) Out> True In> l * u Out> {{1,2},{3,4}}
See also
LDU()
,IsLowerTriangular()
,IsUpperTriangular()

LDU
(A)Â¶ find the LDU decomposition
 Param A
square matrix
LDU()
performs LDU decomposition of a matrix. Example
In> A := {{1,2}, {3,4}} Out> {{1,2},{3,4}} In> {l,d,u} := LDU(A) Out> {{{1,0},{3,1}},{{1,0},{0,2}},{{1,2},{0,1}}} In> IsLowerTriangular(l) Out> True In> IsDiagonal(d) Out> True In> IsUpperTriangular(u) Out> True In> l * d * u Out> {{1,2},{3,4}}
See also
LU()
,IsDiagonal()
,IsLowerTriangular()
,IsUpperTriangular()
Special matricesÂ¶

VandermondeMatrix
(vector)Â¶ create the Vandermonde matrix
 Param vector
an \(n\)dimensional vector
The function {VandermondeMatrix} calculates the Vandermonde matrix of a vector. The \((i,j)\)th element of the Vandermonde matrix is defined as \(i^(j1)\).
 Example
In> VandermondeMatrix({1,2,3,4}) Out> {{1,1,1,1},{1,2,3,4},{1,4,9,16},{1,8,27,64}}; In>PrettyForm(%) / \  ( 1 ) ( 1 ) ( 1 ) ( 1 )     ( 1 ) ( 2 ) ( 3 ) ( 4 )     ( 1 ) ( 4 ) ( 9 ) ( 16 )     ( 1 ) ( 8 ) ( 27 ) ( 64 )  \ /

HilbertMatrix
(n)Â¶ create a Hilbert matrix
 Param n,m
positive integers
The function {HilbertMatrix} returns the {n} by {m} Hilbert matrix if given two arguments, and the square {n} by {n} Hilbert matrix if given only one. The Hilbert matrix is defined as {A(i,j) = 1/(i+j1)}. The Hilbert matrix is extremely sensitive to manipulate and invert numerically.
 Example
In> PrettyForm(HilbertMatrix(4)) / \  ( 1 ) / 1 \ / 1 \ / 1 \              \ 2 / \ 3 / \ 4 /     / 1 \ / 1 \ / 1 \ / 1 \                 \ 2 / \ 3 / \ 4 / \ 5 /     / 1 \ / 1 \ / 1 \ / 1 \                 \ 3 / \ 4 / \ 5 / \ 6 /     / 1 \ / 1 \ / 1 \ / 1 \                 \ 4 / \ 5 / \ 6 / \ 7 /  \ /
See also

HilbertInverseMatrix
(n)Â¶ create a Hilbert inverse matrix
 Param n
positive integer
The function {HilbertInverseMatrix} returns the {n} by {n} inverse of the corresponding Hilbert matrix. All Hilbert inverse matrices have integer entries that grow in magnitude rapidly.
 Example
In> PrettyForm(HilbertInverseMatrix(4)) / \  ( 16 ) ( 120 ) ( 240 ) ( 140 )     ( 120 ) ( 1200 ) ( 2700 ) ( 1680 )     ( 240 ) ( 2700 ) ( 6480 ) ( 4200 )     ( 140 ) ( 1680 ) ( 4200 ) ( 2800 )  \ /
See also

ToeplitzMatrix
(N)Â¶ create a Toeplitz matrix
 Param N
an \(n\)dimensional row vector
The function {ToeplitzMatrix} calculates the Toeplitz matrix given an \(n\)dimensional row vector. This matrix has the same entries in all diagonal columns, from upper left to lower right.
 Example
In> PrettyForm(ToeplitzMatrix({1,2,3,4,5})) / \  ( 1 ) ( 2 ) ( 3 ) ( 4 ) ( 5 )     ( 2 ) ( 1 ) ( 2 ) ( 3 ) ( 4 )     ( 3 ) ( 2 ) ( 1 ) ( 2 ) ( 3 )     ( 4 ) ( 3 ) ( 2 ) ( 1 ) ( 2 )     ( 5 ) ( 4 ) ( 3 ) ( 2 ) ( 1 )  \ /

SylvesterMatrix
(poly1, poly2, variable)Â¶ calculate the Sylvester matrix of two polynomials
 Param poly1
polynomial
 Param poly2
polynomial
 Param variable
variable to express the matrix for
The function {SylvesterMatrix} calculates the Sylvester matrix for a pair of polynomials. The Sylvester matrix is closely related to the resultant, which is defined as the determinant of the Sylvester matrix. Two polynomials share common roots only if the resultant is zero.
 Example
In> ex1:= x^2+2*xa Out> x^2+2*xa; In> ex2:= x^2+a*x4 Out> x^2+a*x4; In> A:=SylvesterMatrix(ex1,ex2,x) Out> {{1,2,a,0},{0,1,2,a}, {1,a,4,0},{0,1,a,4}}; In> B:=Determinant(A) Out> 16a^2*a 8*a4*a+a^2 2*a^2164*a; In> Simplify(B) Out> 3*a^2a^3; The above example shows that the two polynomials have common zeros if :math:` a = 3 :math:`.
See also
Operations on polynomialsÂ¶
This chapter contains commands to manipulate polynomials. This includes functions for constructing and evaluating orthogonal polynomials.

Expand
(expr)Â¶ 
Expand
(expr, var) 
Expand
(expr, varlist) transform a polynomial to an expanded form
 Param expr
a polynomial expression
 Param var
a variable
 Param varlist
a list of variables
This command brings a polynomial in expanded form, in which polynomials are represented in the form \(c_0 + c_1x + c_2x^2 + ... + c_nx^n\). In this form, it is easier to test whether a polynomial is zero, namely by testing whether all coefficients are zero. If the polynomial {expr} contains only one variable, the first calling sequence can be used. Otherwise, the second form should be used which explicitly mentions that {expr} should be considered as a polynomial in the variable {var}. The third calling form can be used for multivariate polynomials. Firstly, the polynomial {expr} is expanded with respect to the first variable in {varlist}. Then the coefficients are all expanded with respect to the second variable, and so on.
 Example
In> Expand((1+x)^5) Out> x^5+5*x^4+10*x^3+10*x^2+5*x+1 In> Expand((1+xy)^2, x); Out> x^2+2*(1y)*x+(1y)^2 In> Expand((1+xy)^2, {x,y}) Out> x^2+((2)*y+2)*x+y^22*y+1
See also

Degree
(expr[, var])Â¶ degree of a polynomial
 Param expr
a polynomial
 Param var
a variable occurring in {expr}
This command returns the degree of the polynomial
expr
with respect to the variablevar
. If only one variable occurs inexpr
, the first calling sequence can be used. Otherwise the user should use the second form in which the variable is explicitly mentioned. Example
In> Degree(x^5+x1); Out> 5; In> Degree(a+b*x^3, a); Out> 1; In> Degree(a+b*x^3, x); Out> 3;

Coef
(expr, var, order)Â¶ coefficient of a polynomial
 Param expr
a polynomial
 Param var
a variable occurring in {expr}
 Param order
integer or list of integers
This command returns the coefficient of {var} to the power {order} in the polynomial {expr}. The parameter {order} can also be a list of integers, in which case this function returns a list of coefficients.
 Example
In> e := Expand((a+x)^4,x) Out> x^4+4*a*x^3+(a^2+(2*a)^2+a^2)*x^2+ (a^2*2*a+2*a^3)*x+a^4; In> Coef(e,a,2) Out> 6*x^2; In> Coef(e,a,0 .. 4) Out> {x^4,4*x^3,6*x^2,4*x,1};
See also

Content
(expr)Â¶ content of a univariate polynomial
 Param expr
univariate polynomial
This command determines the content of a univariate polynomial.
 Example
In> poly := 2*x^2 + 4*x; Out> 2*x^2+4*x; In> c := Content(poly); Out> 2*x; In> pp := PrimitivePart(poly); Out> x+2; In> Expand(pp*c); Out> 2*x^2+4*x;
See also

PrimitivePart
(expr)Â¶ primitive part of a univariate polynomial
 Param expr
univariate polynomial
This command determines the primitive part of a univariate polynomial. The primitive part is what remains after the content is divided out. So the product of the content and the primitive part equals the original polynomial.
 Example
In> poly := 2*x^2 + 4*x; Out> 2*x^2+4*x; In> c := Content(poly); Out> 2*x; In> pp := PrimitivePart(poly); Out> x+2; In> Expand(pp*c); Out> 2*x^2+4*x;
See also

LeadingCoef
(poly)Â¶ 
LeadingCoef
(poly, var) leading coefficient of a polynomial
This function returns the leading coefficient of
poly
, regarded as a polynomial in the variablevar
. The leading coefficient is the coefficient of the term of highest degree. If only one variable appears in the expressionpoly
, it is obvious that it should be regarded as a polynomial in this variable and the first calling sequence may be used. Example
In> poly := 2*x^2 + 4*x; Out> 2*x^2+4*x; In> lc := LeadingCoef(poly); Out> 2; In> m := Monic(poly); Out> x^2+2*x; In> Expand(lc*m); Out> 2*x^2+4*x; In> LeadingCoef(2*a^2 + 3*a*b^2 + 5, a); Out> 2; In> LeadingCoef(2*a^2 + 3*a*b^2 + 5, b); Out> 3*a;

Monic
(poly)Â¶ 
Monic
(poly, var) monic part of a polynomial
This function returns the monic part of
poly
, regarded as a polynomial in the variablevar
. The monic part of a polynomial is the quotient of this polynomial by its leading coefficient. So the leading coefficient of the monic part is always one. If only one variable appears in the expressionpoly
, it is obvious that it should be regarded as a polynomial in this variable and the first calling sequence may be used. Example
In> poly := 2*x^2 + 4*x; Out> 2*x^2+4*x; In> lc := LeadingCoef(poly); Out> 2; In> m := Monic(poly); Out> x^2+2*x; In> Expand(lc*m); Out> 2*x^2+4*x; In> Monic(2*a^2 + 3*a*b^2 + 5, a); Out> a^2+(a*3*b^2)/2+5/2; In> Monic(2*a^2 + 3*a*b^2 + 5, b); Out> b^2+(2*a^2+5)/(3*a);
See also

SquareFree
(p)Â¶ return the squarefree part of polynomial
 Param p
a polynomial in {x}
Given a polynomial \(p = p_1^{n_1}\ldots p_m^{n_m}\) with irreducible polynomials \(p_i\), return the squarefree version part (with all the factors having multiplicity 1): \(p_1\ldots p_m\)
 Example
In> Expand((x+1)^5) Out> x^5+5*x^4+10*x^3+10*x^2+5*x+1; In> SquareFree(%) Out> (x+1)/5; In> Monic(%) Out> x+1;
See also
FindRealRoots()
,NumRealRoots()
,MinimumBound()
,MaximumBound()
,Factor()

SquareFreeFactorize
(p, x)Â¶ return squarefree decomposition of polynomial
 Param p
a polynomial in {x}
Given a polynomial \(p\) having squarefree decomposition \(p = p_1^{n_1}\ldots p_m^{n_m}\) where \(p_i\) are squarefree and \(n_{i+1}>n_i\), return the list of pairs (\(p_i\), \(n_i\))
 Example
In> Expand((x+1)^5) Out> x^5+5*x^4+10*x^3+10*x^2+5*x+1 In> SquareFreeFactorize(%,x) Out> {{x+1,5}}
See also

Horner
(expr, var)Â¶ convert a polynomial into the Horner form
This command turns the polynomial
expr
, considered as a univariate polynomial invar
, into the Horner form. A polynomial in normal form is an expression such as \(c_0 + c_1x + \ldots + c_nx^n\). If one converts this polynomial into Horner form, one gets the equivalent expression \((\ldots( c_nx + c_{n1}) x + \ldots + c_1)x + c_0\). Both expression are equal, but the latter form gives a more efficient way to evaluate the polynomial as the powers have disappeared. Example
In> expr1:=Expand((1+x)^4) Out> x^4+4*x^3+6*x^2+4*x+1; In> Horner(expr1,x) Out> (((x+4)*x+6)*x+4)*x+1;
See also

ExpandBrackets
(expr)Â¶ expand all brackets
This command tries to expand all the brackets by repeatedly using the distributive laws \(a(b+c) = ab + ac\) and \((a+b)c = ac + bc\). It goes further than
Expand()
, in that it expands all brackets. Example
In> Expand((ax)*(bx),x) Out> x^2(b+a)*x+a*b; In> Expand((ax)*(bx),{x,a,b}) Out> x^2(b+a)*x+b*a; In> ExpandBrackets((ax)*(bx)) Out> a*bx*b+x^2a*x;
See also

EvaluateHornerScheme
(coeffs, x)Â¶ fast evaluation of polynomials
This function evaluates a polynomial given as a list of its coefficients, using the Horner scheme. The list of coefficients starts with the \(0\)th power.

OrthoP
(n, x)Â¶ 
OrthoP
(n, a, b, x) Legendre and Jacobi orthogonal polynomials
The first calling format with two arguments evaluates the Legendre polynomial of degree
n
at the pointx
. The second form does the same for the Jacobi polynomial with parametersa
andb
, which should be both greater than \(1\).The Jacobi polynomials are orthogonal with respect to the weight function \((1x)^a(1+x)^b\) on the interval \([1,1]\). They satisfy the recurrence relation \(P(n,a,b,x) = \frac{2n+a+b1}{2n+a+b2}\frac{a^2b^2+x(2n+a+b2)(n+a+b)}{2n(n+a+b)}P(n1,a,b,x)  \frac{(n+a1)(n+b1)(2n+a+b)}{n(n+a+b)(2n+a+b2)}P(n2,a,b,x)\) for \(n > 1\), with \(P(0,a,b,x) = 1\), \(P(1,a,b,x) = \frac{ab}{2}+x(1+\frac{a+b}{2})\).

OrthoH
(n, x)Â¶ Hermite orthogonal polynomials
This function evaluates the Hermite polynomial of degree
n
at the pointx
.The Hermite polynomials are orthogonal with respect to the weight function \(\exp(\frac{x^2}{2})\) on the entire real axis. They satisfy the recurrence relation \(H(n,x) = 2xH(n1,x)  2(n1)H(n2,x)\) for \(n > 1\), with \(H(0,x) = 1\), \(H(1,x) = 2x\).
 Example
In> OrthoH(3, x); Out> x*(8*x^212); In> OrthoH(6, 0.5); Out> 31;
See also

OrthoG
(n, a, x)Â¶ Gegenbauer orthogonal polynomials
This function evaluates the Gegenbauer (or ultraspherical) polynomial with parameter
a
and degreen
at the pointx
. The parametera
should be greater than \(\frac{1}{2}\).The Gegenbauer polynomials are orthogonal with respect to the weight function \((1x^2)^{a\frac{1}{2}}\) on the interval \([1,1]\). Hence they are connected to the Jacobi polynomials via \(G(n, a, x) = P(n, a\frac{1}{2}, a\frac{1}{2}, x)\). They satisfy the recurrence relation \(G(n,a,x) = 2(1+\frac{a1}{n})xG(n1,a,x)(1+2\frac{a2}{n})G(n2,a,x)\) for \(n>1\), with \(G(0,a,x) = 1\), \(G(1,a,x) = 2x\).

OrthoL
(n, a, x)Â¶ Laguerre orthogonal polynomials
This function evaluates the Laguerre polynomial with parameter
a
and degreen
at the pointx
. The parametera
should be greater than \(1\).The Laguerre polynomials are orthogonal with respect to the weight function \(x^a\exp(x)\) on the positive real axis. They satisfy the recurrence relation \(L(n,a,x) = (2+\frac{a1x}{n})L(n1,a,x) (1\frac{a1}{n})L(n2,a,x)\) for \(n>1\), with \(L(0,a,x) = 1\), \(L(1,a,x) = a + 1  x\).

OrthoT
(n, x)Â¶ 
OrthoU
(n, x)Â¶ Chebyshev polynomials
These functions evaluate the Chebyshev polynomials of the first kind \(T(n,x)\) and of the second kind \(U(n,x)\), of degree
n
at the pointx
. (The name of this Russian mathematician is also sometimes spelled Tschebyscheff.)The Chebyshev polynomials are orthogonal with respect to the weight function \((1x^2)^{\frac{1}{2}}\). Hence they are a special case of the Gegenbauer polynomials \(G(n,a,x)\), with \(a=0\). They satisfy the recurrence relations \(T(n,x) = 2xT(n1,x)  T(n2,x)\), \(U(n,x) = 2xU(n1,x)  U(n2,x)\) for \(n > 1\), with \(T(0,x) = 1\), \(T(1,x) = x\), \(U(0,x) = 1\), \(U(1,x) = 2x\).
 Example
In> OrthoT(3, x); Out> 2*x*(2*x^21)x; In> OrthoT(10, 0.9); Out> 0.2007474688; In> OrthoU(3, x); Out> 4*x*(2*x^21); In> OrthoU(10, 0.9); Out> 2.2234571776;
See also

OrthoPSum
(c, x)Â¶ 
OrthoPSum
(c, a, b, x) 
OrthoGSum
(c, a, x)Â¶ 
OrthoHSum
(c, x)Â¶ 
OrthoLSum
(c, a, x)Â¶ 
OrthoTSum
(c, x)Â¶ 
OrthoUSum
(c, x)Â¶ sums of series of orthogonal polynomials
These functions evaluate the sum of series of orthogonal polynomials at the point
x
, with given list of coefficientsc
of the series and fixed polynomial parametersa
,b
(if applicable). The list of coefficients starts with the lowest order, so that for exampleOrthoLSum(c, a, x) = c[1] L[0](a,x) + c[2] L[1](a,x) + ... + c[N] L[N1](a,x)
.See pages for specific orthogonal polynomials for more details on the parameters of the polynomials. Most of the work is performed by the internal function
OrthoPolySum()
. The individual polynomials entering the series are not computed, only the sum of the series. Example
In> Expand(OrthoPSum({1,0,0,1/7,1/8}, 3/2, 2/3, x)); Out> (7068985*x^4)/3981312+(1648577*x^3)/995328+ (3502049*x^2)/4644864+(4372969*x)/6967296 +28292143/27869184

OrthoPoly
(name, n, params, x)Â¶ internal function for constructing orthogonal polynomials
This function is used internally to construct orthogonal polynomials. It returns the
n
th polynomial from the familyname
with parametersparams
at the pointx
. All known families are stored in the association list returned by the functionKnownOrthoPoly()
. Thename
serves as key.At the moment the following names are known to yacas:
"Jacobi"
,"Gegenbauer"
,"Laguerre"
,"Hermite"
,"Tscheb1"
, and"Tscheb2"
. The value associated to the key is a pure function that takes two arguments: the ordern
and the extra parametersp
, and returns a list of two lists: the first list contains the coefficients{A,B}
of then=1
polynomial, i.e. \(A+Bx\); the second list contains the coefficients{A,B,C}
in the recurrence relation, i.e. \(P_n = (A+Bx)P_{n1}+CP_{n2}\).Note
There are only 3 coefficients in the second list, because none of the considered polynomials use \(C+Dx\) instead of \(C\) in the recurrence relation. This is assumed in the implementation.
If the argument
x
is numerical, the functionOrthoPolyNumeric()
is called. Otherwise, the functionOrthoPolyCoeffs()
computes a list of coefficients, andEvaluateHornerScheme()
converts this list into a polynomial expression.

OrthoPolySum
(name, c, params, x)Â¶ internal function for computing series of orthogonal polynomials
This function is used internally to compute series of orthogonal polynomials. It is similar to the function
OrthoPoly()
and returns the result of the summation of series of polynomials from the familyname
with parametersparams
at the pointx
, wherec
is the list of coefficients of the series. The algorithm used to compute the series without first computing the individual polynomials is the ClenshawSmith recurrence scheme. (See the algorithms book for explanations.)If the argument
x
is numerical, the functionOrthoPolySumNumeric()
is called. Otherwise, the functionOrthoPolySumCoeffs()
computes the list of coefficients of the resulting polynomial, andEvaluateHornerScheme()
converts this list into a polynomial expression.See also
OrthoPSum()
,OrthoGSum()
,OrthoHSum()
,OrthoLSum()
,OrthoTSum()
,OrthoUSum()
,OrthoPoly()
List operationsÂ¶
Most objects that can be of variable size are represented as lists (linked lists internally). Yacas does implement arrays, which are faster when the number of elements in a collection of objects doesnâ€™t change. Operations on lists have better support in the current system.

Head
(list)Â¶ returns the first element of a list
This function returns the first element of a list. If it is applied to a general expression, it returns the first operand. An error is returned if
list
is an atom. Example
In> Head({a,b,c}) Out> a; In> Head(f(a,b,c)); Out> a;

Tail
(list)Â¶ returns a list without its first element
 Example
In> Tail({a,b,c}) Out> {b,c};

Length
(list)Â¶ 
Length
(string) The length of a list or string
 Example
In> Length({a,b,c}) Out> 3; In> Length("abcdef"); Out> 6;

Map
(fn, list)Â¶ apply an nary function to all entries in a list
This function applies
fn
to every list of arguments to be found inlist
. So the first entry oflist
should be a list containing the first, second, third, â€¦ argument tofn
, and the same goes for the other entries oflist
. The function can either be given as a string or as a pure function (seeApply()
for more information on pure functions). Example
In> Map("+",{{a,b},{c,d}}); Out> {a+c,b+d};
See also

MapSingle
(fn, list)Â¶ apply a unary function to all entries in a list
The function
fn
is successively applied to all entries inlist
, and a list containing the respective results is returned. The function can be given either as a string or as a pure function (seeApply()
for more information on pure functions).The
/@
operator provides a shorthand forMapSingle()
. Example
In> MapSingle("Sin",{a,b,c}); Out> {Sin(a),Sin(b),Sin(c)}; In> MapSingle({{x},x^2}, {a,2,c}); Out> {a^2,4,c^2};

MakeVector
(var, n)Â¶ vector of uniquely numbered variable names
A list of length
n
is generated. The first entry contains the identifiervar
with the number 1 appended to it, the second entry containsvar
with the suffix 2, and so on until the last entry which containsvar
with the numbern
appended to it. Example
In> MakeVector(a,3) Out> {a1,a2,a3};
See also

Select
(pred, list)Â¶ select entries satisfying some predicate
Select()
returns a sublist oflist
which contains all the entries for which the predicatepred
returnsTrue
when applied to this entry. Example
In> Select("IsInteger",{a,b,2,c,3,d,4,e,f}) Out> {2,3,4};

Nth
(list, n)Â¶ return the
n
th element of a listThe entry with index
n
fromlist
is returned. The first entry has index 1. It is possible to pick several entries of the list by takingn
to be a list of indices.More generally,
Nth
returns then
th operand of the expression passed as first argument.An alternative but equivalent form of
Nth(list, n)
islist[n]
. Example
In> lst := {a,b,c,13,19}; Out> {a,b,c,13,19}; In> Nth(lst, 3); Out> c; In> lst[3]; Out> c; In> Nth(lst, {3,4,1}); Out> {c,13,a}; In> Nth(b*(a+c), 2); Out> a+c;

Reverse
(list)Â¶ return the reversed list (without touching the original)
 Param list
list to reverse
This function returns a list reversed, without changing the original list. It is similar to
DestructiveReverse()
, but safer and slower. Example
In> lst:={a,b,c,13,19} Out> {a,b,c,13,19}; In> revlst:=Reverse(lst) Out> {19,13,c,b,a}; In> lst Out> {a,b,c,13,19};
See also

List
(expr1, expr2, ...)Â¶ construct a list
A list is constructed whose first entry is
expr1
, the second entry isexpr2
, and so on. This command is equivalent to the expression{expr1, expr2, ...}
. Example
In> List(); Out> {}; In> List(a,b); Out> {a,b}; In> List(a,{1,2},d); Out> {a,{1,2},d};

UnList
(list)Â¶ convert a list to a function application
This command converts a list to a function application. The first entry of
list
is treated as a function atom, and the following entries are the arguments to this function. So the function referred to in the first element oflist
is applied to the other elements.Note that
list
is evaluated before the function application is formed, but the resulting expression is left unevaluated. The functionsUnList()
andHold()
both stop the process of evaluation. Example
In> UnList({Cos, x}); Out> Cos(x); In> UnList({f}); Out> f(); In> UnList({Taylor,x,0,5,Cos(x)}); Out> Taylor(x,0,5)Cos(x); In> Eval(%); Out> 1x^2/2+x^4/24;

Listify
(expr)Â¶ convert a function application to a list
The parameter
expr
is expected to be a compound object, i.e. not an atom. It is evaluated and then converted to a list. The first entry in the list is the toplevel operator in the evaluated expression and the other entries are the arguments to this operator. Finally, the list is returned. Example
In> Listify(Cos(x)); Out> {Cos,x}; In> Listify(3*a); Out> {*,3,a};

Concat
(list1, list2, ...)Â¶ concatenate lists
The lists
list1
,list2
, â€¦ are evaluated and concatenated. The resulting big list is returned. Example
In> Concat({a,b}, {c,d}); Out> {a,b,c,d}; In> Concat({5}, {a,b,c}, {{f(x)}}); Out> {5,a,b,c,{f(x)}};
See also

Delete
(list, n)Â¶ delete an element from a list
This command deletes the
n
th element fromlist
. The first parameter should be a list, whilen
should be a positive integer less than or equal to the length oflist
. The entry with indexn
is removed (the first entry has index 1), and the resulting list is returned. Example
In> Delete({a,b,c,d,e,f}, 4); Out> {a,b,c,e,f};
See also

Insert
(list, n, expr)Â¶ insert an element into a list
The expression
expr
is inserted just before then
th entry inlist
. The first parameterlist
should be a list, whilen
should be a positive integer less than or equal to the length oflist
plus one. The expressionexpr
is placed between the entries inlist
with indicesn1
andn
. There are two border line cases: ifn
is 1, the expressionexpr
is placed in front of the list (just as by the:()
operator); ifn
equals the length oflist
plus one, the expressionexpr
is placed at the end of the list (just as byAppend()
). In any case, the resulting list is returned. Example
In> Insert({a,b,c,d}, 4, x); Out> {a,b,c,x,d}; In> Insert({a,b,c,d}, 5, x); Out> {a,b,c,d,x}; In> Insert({a,b,c,d}, 1, x); Out> {x,a,b,c,d};
See also

Replace
(list, n, expr)Â¶ replace an entry in a list
The
n
th entry oflist
is replaced by the expressionexpr
. This is equivalent to callingDelete()
andInsert()
in sequence. To be precise, the expressionReplace(list, n, expr)
has the same result as the expressionInsert(Delete(list, n), n, expr)
. Example
In> Replace({a,b,c,d,e,f}, 4, x); Out> {a,b,c,x,e,f};
See also

FlatCopy
(list)Â¶ copy the top level of a list
A copy of
list
is made and returned. The list is not recursed into, only the first level is copied. This is useful in combination with the destructive commands that actually modify lists in place (for efficiency).The following shows a possible way to define a command that reverses a list nondestructively.
 Example
In> reverse(l_IsList) < DestructiveReverse(FlatCopy(l)); Out> True; In> lst := {a,b,c,d,e}; Out> {a,b,c,d,e}; In> reverse(lst); Out> {e,d,c,b,a}; In> lst; Out> {a,b,c,d,e};

Contains
(list, expr)Â¶ test whether a list contains a certain element
This command tests whether
list
contains the expressionexpr
as an entry. It returnsTrue
if it does andFalse
otherwise. Only the top level oflist
is examined. The parameterlist
may also be a general expression, in that case the toplevel operands are tested for the occurrence ofexpr
. Example
In> Contains({a,b,c,d}, b); Out> True; In> Contains({a,b,c,d}, x); Out> False; In> Contains({a,{1,2,3},z}, 1); Out> False; In> Contains(a*b, b); Out> True;

Find
(list, expr)Â¶ get the index at which a certain element occurs
This commands returns the index at which the expression
expr
occurs inlist
. Ifexpr
occurs more than once, the lowest index is returned. Ifexpr
does not occur at all, 1 is returned. Example
In> Find({a,b,c,d,e,f}, d); Out> 4; In> Find({1,2,3,2,1}, 2); Out> 2; In> Find({1,2,3,2,1}, 4); Out> 1;
See also

Append
(list, expr)Â¶ append an entry at the end of a list
The expression
expr
is appended at the end oflist
and the resulting list is returned.Note that due to the underlying data structure, the time it takes to append an entry at the end of a list grows linearly with the length of the list, while the time for prepending an entry at the beginning is constant.
 Example
In> Append({a,b,c,d}, 1); Out> {a,b,c,d,1};
See also

RemoveDuplicates
(list)Â¶ remove any duplicates from a list
This command removes all duplicate elements from a given list and returns the resulting list. To be precise, the second occurrence of any entry is deleted, as are the third, the fourth, etc.
 Example
In> RemoveDuplicates({1,2,3,2,1}); Out> {1,2,3}; In> RemoveDuplicates({a,1,b,1,c,1}); Out> {a,1,b,c};

Swap
(list, i1, i2)Â¶ swap two elements in a list
This command swaps the pair of entries with entries
i1
andi2
inlist
. So the element at indexi1
ends up at indexi2
and the entry ati2
is put at indexi1
. Both indices should be valid to address elements in the list. Then the updated list is returned.Swap()
works also on generic arrays. Example
In> lst := {a,b,c,d,e,f}; Out> {a,b,c,d,e,f}; In> Swap(lst, 2, 4); Out> {a,d,c,b,e,f};
See also

Count
(list, expr)Â¶ count the number of occurrences of an expression
This command counts the number of times that the expression
expr
occurs inlist
and returns this number. Example
In> lst := {a,b,c,b,a}; Out> {a,b,c,b,a}; In> Count(lst, a); Out> 2; In> Count(lst, c); Out> 1; In> Count(lst, x); Out> 0;
See also

FillList
(expr, n)Â¶ fill a list with a certain expression
This command creates a list of length
n
in which all slots contain the expressionexpr
and returns this list. Example
In> FillList(x, 5); Out> {x,x,x,x,x};
See also

Drop
(list, n)Â¶ 
Drop
(list, n) 
Drop
(list, {m, n}) drop a range of elements from a list
This command removes a sublist of
list
and returns a list containing the remaining entries. The first calling sequence drops the firstn
entries inlist
. The second form drops the lastn
entries. The last invocation drops the elements with indicesm
throughn
. Example
In> lst := {a,b,c,d,e,f,g}; Out> {a,b,c,d,e,f,g}; In> Drop(lst, 2); Out> {c,d,e,f,g}; In> Drop(lst, 3); Out> {a,b,c,d}; In> Drop(lst, {2,4}); Out> {a,e,f,g};

Take
(list, n)Â¶ 
Take
(list, n) 
Take
(list, {m, n}) take a sublist from a list, dropping the rest
This command takes a sublist of
list
, drops the rest, and returns the selected sublist. The first calling sequence selects the firstn
entries inlist
. The second form takes the lastn
entries. The last invocation selects the sublist beginning with entry numberm
and ending with then
th entry. Example
In> lst := {a,b,c,d,e,f,g}; Out> {a,b,c,d,e,f,g}; In> Take(lst, 2); Out> {a,b}; In> Take(lst, 3); Out> {e,f,g}; In> Take(lst, {2,4}); Out> {b,c,d};

Partition
(list, n)Â¶ partition a list in sublists of equal length
This command partitions
list
into nonoverlapping sublists of lengthn
and returns a list of these sublists. The firstn
entries inlist
form the first partition, the entries from positionn+1
up to2n
form the second partition, and so on. Ifn
does not divide the length oflist
, the remaining entries will be thrown away. Ifn
equals zero, an empty list is returned. Example
In> Partition({a,b,c,d,e,f,}, 2); Out> {{a,b},{c,d},{e,f}}; In> Partition(1 .. 11, 3); Out> {{1,2,3},{4,5,6},{7,8,9}};
See also

Flatten
(expression, operator)Â¶ flatten expression w.r.t. some operator
Flatten()
flattens an expression with respect to a specific operator, converting the result into a list. This is useful for unnesting an expression.Flatten()
is typically used in simple simplification schemes. Example
In> Flatten(a+b*c+d, "+"); Out> {a,b*c,d}; In> Flatten({a,{b,c},d}, "List"); Out> {a,b,c,d};
See also

UnFlatten
(list, operator, identity)Â¶ inverse operation of
Flatten()
UnFlatten()
is the inverse operation ofFlatten()
. Given a list, it can be turned into an expression representing for instance the addition of these elements by callingUnFlatten()
with+
as argument to operator, and 0 as argument to identity (0 is the identity for addition, since a+0=a). For multiplication the identity element would be 1. Example
In> UnFlatten({a,b,c},"+",0) Out> a+b+c; In> UnFlatten({a,b,c},"*",1) Out> a*b*c;
See also

Type
(expr)Â¶ return the type of an expression
The type of the expression
expr
is represented as a string and returned. So, ifexpr
is a list, the string"List"
is returned. In general, the toplevel operator ofexpr
is returned. If the argumentexpr
is an atom, the result is the empty string""
. Example
In> Type({a,b,c}); Out> "List"; In> Type(a*(b+c)); Out> "*"; In> Type(123); Out> "";

NrArgs
(expr)Â¶ return number of toplevel arguments
This function evaluates to the number of toplevel arguments of the expression
expr
. The argumentexpr
may not be an atom, since that would lead to an error. Example
In> NrArgs(f(a,b,c)) Out> 3; In> NrArgs(Sin(x)); Out> 1; In> NrArgs(a*(b+c)); Out> 2;

VarList
(expr)Â¶ 
VarListArith
(expr)Â¶ 
VarListSome
(expr, list)Â¶ list of variables appearing in an expression
The command
VarList()
returns a list of all variables that appear in the expressionexpr
. The expression is traversed recursively.The command
VarListSome()
looks only at arguments of functions in thelist
. All other functions are considered opaque (as if they do not contain any variables) and their arguments are not checked. For example,VarListSome(a + Sin(bc))
will return{a, b, c}
, butVarListSome(a*Sin(bc), {*})
will not look at arguments ofSin()
and will return{a,Sin(bc)}
. HereSin(bc)
is considered a variable because the functionSin()
does not belong tolist
.The command â€śfunc:VarListArith returns a list of all variables that appear arithmetically in the expression
expr
. This is implemented throughVarListSome()
by restricting to the arithmetic functions+
,
,*
,/
. Arguments of other functions are not checked.Note that since the operators
+
and
are prefix as well as infix operators, it is currently required to useAtom("+")
to obtain the unevaluated atom+
. Example
In> VarList(Sin(x)) Out> {x}; In> VarList(x+a*y) Out> {x,a,y}; In> VarListSome(x+a*y, {Atom("+")}) Out> {x,a*y}; In> VarListArith(x+y*Cos(Ln(x)/x)) Out> {x,y,Cos(Ln(x)/x)} In> VarListArith(x+a*y^21) Out> {x,a,y^2};
See also
IsFreeOf()
,IsVariable()
,FuncList()
,HasExpr()
,HasFunc()

FuncList
(expr)Â¶ list of functions used in an expression
The command
FuncList()
returns a list of all function atoms that appear in the expressionexpr
. The expression is recursively traversed. Example
In> FuncList(x+y*Cos(Ln(x)/x)) Out> {+,*,Cos,/,Ln};

FuncListArith
(expr)Â¶ list of functions used in an expression
FuncListArith()
is defined throughFuncListSome()
to look only at arithmetic operations+
,
,*
,/
. Example
In> FuncListArith(x+y*Cos(Ln(x)/x)) Out> {+,*,Cos};

FuncListSome
(expr, list)Â¶ list of functions used in an expression
The command
FuncListSome()
does the same asFuncList()
, except it only looks at arguments of a givenlist
of functions. All other functions become opaque (as if they do not contain any other functions). For example,FuncList(a + Sin(bc))
will see that the expression has a{}
operation and return {{+,Sin,}}, butFuncListSome(a + Sin(bc), {+})
will not look at arguments ofSin()
and will return{+,Sin}
.Note that since the operators
+
and
are prefix as well as infix operators, it is currently required to useAtom("+")
to obtain the unevaluated atom+
. Example
In> FuncListSome({a+b*2,c/d},{List}) Out> {List,+,/};

PrintList
(list[, padding])Â¶ print list with padding
Prints
list
and inserts thepadding
string between each pair of items of the list. Items of the list which are strings are printed without quotes, unlikeWrite()
. Items of the list which are themselves lists are printed inside braces{}
. If padding is not specified, standard one is used â€ś, â€ť (comma, space). Example
In> PrintList({a,b,{c, d}}, `` .. ``) Out> `` a .. b .. { c .. d}``;
See also

Table
(body, var, from, to, step)Â¶ evaluate while some variable ranges over interval
This command generates a list of values from
body
, by assigning variablevar
values fromfrom
up toto
, incrementingstep
each time. So, the variablevar
first gets the valuefrom
, and the expressionbody
is evaluated. Then the valuefrom``+``step
is assigned tovar
and the expressionbody
is again evaluated. This continues, incrementingvar
withstep
on every iteration, untilvar
exceedsto
. At that moment, all the results are assembled in a list and this list is returned. Example
In> Table(i!, i, 1, 9, 1); Out> {1,2,6,24,120,720,5040,40320,362880}; In> Table(i, i, 3, 16, 4); Out> {3,7,11,15}; In> Table(i^2, i, 10, 1, 1); Out> {100,81,64,49,36,25,16,9,4,1};
See also
For()
,MapSingle()
, ..:,TableForm()

TableForm
(list)Â¶ print each entry in a list on a line
This functions writes out the list
list
in a better readable form, by printing every element in the list on a separate line. Example
In> TableForm(Table(i!, i, 1, 10, 1)); 1 2 6 24 120 720 5040 40320 362880 3628800 Out> True;
See also
Destructive operationsÂ¶
Destructive commands run faster than their nondestructive counterparts because the latter copy the list before they alter it.

DestructiveAppend
(list, expr)Â¶ destructively append an entry to a list
This is the destructive counterpart of
Append()
. This command yields the same result as the corresponding call toAppend()
, but the original list is modified. So if a variable is bound tolist
, it will now be bound to the list with the expressionexpr
inserted. Example
In> lst := {a,b,c,d}; Out> {a,b,c,d}; In> Append(lst, 1); Out> {a,b,c,d,1}; In> lst Out> {a,b,c,d}; In> DestructiveAppend(lst, 1); Out> {a,b,c,d,1}; In> lst; Out> {a,b,c,d,1};

DestructiveDelete
(list, n)Â¶ delete an element destructively from a list
This is the destructive counterpart of :func`Delete`. This command yields the same result as the corresponding call to
Delete()
, but the original list is modified. So if a variable is bound tolist
, it will now be bound to the list with then
th entry removed. Example
In> lst := {a,b,c,d,e,f}; Out> {a,b,c,d,e,f}; In> Delete(lst, 4); Out> {a,b,c,e,f}; In> lst; Out> {a,b,c,d,e,f}; In> DestructiveDelete(lst, 4); Out> {a,b,c,e,f}; In> lst; Out> {a,b,c,e,f};
See also

DestructiveInsert
(list, n, expr)Â¶ insert an element destructively into a list
This is the destructive counterpart of
Insert()
. This command yields the same result as the corresponding call toInsert()
, but the original list is modified. So if a variable is bound tolist
, it will now be bound to the list with the expressionexpr
inserted. Example
In> lst := {a,b,c,d}; Out> {a,b,c,d}; In> Insert(lst, 2, x); Out> {a,x,b,c,d}; In> lst; Out> {a,b,c,d}; In> DestructiveInsert(lst, 2, x); Out> {a,x,b,c,d}; In> lst; Out> {a,x,b,c,d};
See also

DestructiveReplace
(list, n, expr)Â¶ replace an entry destructively in a list
 Param list
list of which an entry should be replaced
 Param n
index of entry to replace
 Param expr
expression to replace the
n
th entry with
This is the destructive counterpart of
Replace()
. This command yields the same result as the corresponding call toReplace()
, but the original list is modified. So if a variable is bound tolist
, it will now be bound to the list with the expressionexpr
inserted. Example
In> lst := {a,b,c,d,e,f}; Out> {a,b,c,d,e,f}; In> Replace(lst, 4, x); Out> {a,b,c,x,e,f}; In> lst; Out> {a,b,c,d,e,f}; In> DestructiveReplace(lst, 4, x); Out> {a,b,c,x,e,f}; In> lst; Out> {a,b,c,x,e,f};
See also

DestructiveReverse
(list)Â¶ reverse a list destructively
This command reverses
list
in place, so that the original is destroyed. This means that any variable bound tolist
will now have an undefined content, and should not be used any more. The reversed list is returned. Example
In> lst := {a,b,c,13,19}; Out> {a,b,c,13,19}; In> revlst := DestructiveReverse(lst); Out> {19,13,c,b,a}; In> lst; Out> {a};
See also
Set operationsÂ¶

Intersection
(l1, l2)Â¶ return the intersection of two lists
The intersection of the lists
l1
andl2
is determined and returned. The intersection contains all elements that occur in both lists. The entries in the result are listed in the same order as inl1
. If an expression occurs multiple times in bothl1
andl2
, then it will occur the same number of times in the result. Example
In> Intersection({a,b,c}, {b,c,d}); Out> {b,c}; In> Intersection({a,e,i,o,u}, {f,o,u,r,t,e,e,n}); Out> {e,o,u}; In> Intersection({1,2,2,3,3,3}, {1,1,2,2,3,3}); Out> {1,2,2,3,3};
See also

Union
(l1, l2)Â¶ return the union of two lists
The union of the lists
l1
andl2
is determined and returned. The union contains all elements that occur in one or both of the lists. In the resulting list, any element will occur only once. Example
In> Union({a,b,c}, {b,c,d}); Out> {a,b,c,d}; In> Union({a,e,i,o,u}, {f,o,u,r,t,e,e,n}); Out> {a,e,i,o,u,f,r,t,n}; In> Union({1,2,2,3,3,3}, {2,2,3,3,4,4}); Out> {1,2,3,4};
See also

Difference
(l1, l2)Â¶ return the difference of two lists
The difference of the lists
l1
andl2
is determined and returned. The difference contains all elements that occur inl1
but not inl2
. The order of elements inl1
is preserved. If a certain expression occursn1
times in the first list andn2
times in the second list, it will occurn1n2
times in the result ifn1
is greater thann2
and not at all otherwise. Example
In> Difference({a,b,c}, {b,c,d}); Out> {a}; In> Difference({a,e,i,o,u}, {f,o,u,r,t,e,e,n}); Out> {a,i}; In> Difference({1,2,2,3,3,3}, {2,2,3,4,4}); Out> {1,3,3};
See also
Associative mapÂ¶

Assoc
(key, alist)Â¶ return element stored in association list
The association list
alist
is searched for an entry stored with indexkey
. If such an entry is found, it is returned. Otherwise the atomEmpty
is returned.Association lists are represented as a list of twoentry lists. The first element in the twoentry list is the key, the second element is the value stored under this key.
The call
Assoc(key, alist)
can (probably more intuitively) be accessed asalist[key]
. Example
In> writer := {}; Out> {}; In> writer[``Iliad``] := ``Homer``; Out> True; In> writer[``Henry IV``] := ``Shakespeare``; Out> True; In> writer[``Ulysses``] := ``James Joyce``; Out> True; In> Assoc(``Henry IV``, writer); Out> {``Henry IV``,``Shakespeare``}; In> Assoc(``War and Peace``, writer); Out> Empty;
See also
AssocIndices()
,[]()
,:=()
,AssocDelete()

AssocIndices
(alist)Â¶ return the keys in an association list
All the keys in the association list
alist
are assembled in a list and this list is returned. Example
In> writer := {}; Out> {}; In> writer[``Iliad``] := ``Homer``; Out> True; In> writer[``Henry IV``] := ``Shakespeare``; Out> True; In> writer[``Ulysses``] := ``James Joyce``; Out> True; In> AssocIndices(writer); Out> {``Iliad``,``Henry IV``,``Ulysses``};
See also

AssocDelete
(alist, key)Â¶ 
AssocDelete
(alist, {key, value}) delete an entry in an association list
The key {
key
} in the association listalist
is deleted. (The list itself is modified.) If the key was found and successfully deleted, returnsTrue
, otherwise if the given key was not found, the function returnsFalse
.The second, longer form of the function deletes the entry that has both the specified key and the specified value. It can be used for two purposes:
to make sure that we are deleting the right value;
if several values are stored on the same key, to delete the specified entry (see the last example).
At most one entry is deleted.
 Example
In> writer := {}; Out> {}; In> writer[``Iliad``] := ``Homer``; Out> True; In> writer[``Henry IV``] := ``Shakespeare``; Out> True; In> writer[``Ulysses``] := ``James Joyce``; Out> True; In> AssocDelete(writer, ``Henry IV``) Out> True; In> AssocDelete(writer, ``Henry XII``) Out> False; In> writer Out> {{``Ulysses``,``James Joyce``}, {``Iliad``,``Homer``}}; In> DestructiveAppend(writer, {``Ulysses``, ``Dublin``}); Out> {{``Iliad``,``Homer``},{``Ulysses``,``James Joyce``}, {``Ulysses``,``Dublin``}}; In> writer[``Ulysses``]; Out> ``James Joyce``; In> AssocDelete(writer,{``Ulysses``,``James Joyce``}); Out> True; In> writer Out> {{``Iliad``,``Homer``},{``Ulysses``,``Dublin``}};
See also
SortingÂ¶

BubbleSort
(list, compare)Â¶ sort a list
This command returns
list
after it is sorted usingcompare
to compare elements. The functioncompare
should accept two arguments, which will be elements oflist
, and compare them. It should returnTrue
if in the sorted list the second argument should come after the first one, andFalse
otherwise.The function
BubbleSort()
uses the socalled bubble sort algorithm to do the sorting by swapping elements that are out of order. This algorithm is easy to implement, though it is not particularly fast. The sorting time is proportional to \(n^2\) where \(n\) is the length of the list. Example
In> BubbleSort({4,7,23,53,2,1}, "<"); Out> {2,1,4,7,23,53};
See also

HeapSort
(list, compare)Â¶ sort a list
This command returns
list
after it is sorted usingcompare
to compare elements. The functioncompare
should accept two arguments, which will be elements oflist
, and compare them. It should returnTrue
if in the sorted list the second argument should come after the first one, andFalse
otherwise.The function
HeapSort()
uses theheapsort algorithm
and is much faster for large lists. The sorting time is proportional to \(n\ln(n)\) where \(n\) is the length of the list. Example
In> HeapSort({4,7,23,53,2,1}, ``>``); Out> {53,23,7,4,1,2};
See also
Stack and queue operationsÂ¶

Push
(stack, expr)Â¶ add an element on top of a stack
This is part of a simple implementation of a stack, internally represented as a list. This command pushes the expression
expr
on top of the stack, and returns the stack afterwards. Example
In> stack := {}; Out> {}; In> Push(stack, x); Out> {x}; In> Push(stack, x2); Out> {x2,x}; In> PopFront(stack); Out> x2;
See also

Pop
(stack, n)Â¶ remove an element from a stack
This is part of a simple implementation of a stack, internally represented as a list. This command removes the element with index
n
from the stack and returns this element. The top of the stack is represented by the index 1. Invalid indices, for example indices greater than the number of element on the stack, lead to an error. Example
In> stack := {}; Out> {}; In> Push(stack, x); Out> {x}; In> Push(stack, x2); Out> {x2,x}; In> Push(stack, x3); Out> {x3,x2,x}; In> Pop(stack, 2); Out> x2; In> stack; Out> {x3,x};
See also

PopFront
(stack)Â¶ remove an element from the top of a stack
This is part of a simple implementation of a stack, internally represented as a list. This command removes the element on the top of the stack and returns it. This is the last element that is pushed onto the stack.
 Example
In> stack := {}; Out> {}; In> Push(stack, x); Out> {x}; In> Push(stack, x2); Out> {x2,x}; In> Push(stack, x3); Out> {x3,x2,x}; In> PopFront(stack); Out> x3; In> stack; Out> {x2,x};

PopBack
(stack)Â¶ remove an element from the bottom of a stack
This is part of a simple implementation of a stack, internally represented as a list. This command removes the element at the bottom of the stack and returns this element. Of course, the stack should not be empty.
 Example
In> stack := {}; Out> {}; In> Push(stack, x); Out> {x}; In> Push(stack, x2); Out> {x2,x}; In> Push(stack, x3); Out> {x3,x2,x}; In> PopBack(stack); Out> x; In> stack; Out> {x3,x2};
See also
Global stackÂ¶
The functions below operate on a global stack, currently implemented as a list
that is not accessible externally (it is protected through
LocalSymbols()
).

GlobalPop
()Â¶ 
GlobalPop
(var) restore variables using a global stack
GlobalPop()
removes the last pushed value from the stack. If a variable name is given, the variable is assigned, otherwise the popped value is returned. If the global stack is empty, an error message is printed.See also

GlobalPush
(expr)Â¶ save variables using a global stack
 Example
In> GlobalPush(3) Out> 3; In> GlobalPush(Sin(x)) Out> Sin(x); In> GlobalPop(x) Out> Sin(x); In> GlobalPop(x) Out> 3; In> x Out> 3;
See also
GraphsÂ¶

Graph
(edges)Â¶ 
Graph
(vertices, edges) construct a graph

Vertices
(g)Â¶ return list of graph vertices

Edges
(g)Â¶ return list of graph edges
See also

AdjacencyList
(g)Â¶ adjacency list
 Param g
graph
Return adjacency list of graph
g
.See also

AdjacencyMatrix
(g)Â¶ adjacency matrix
 Param g
graph
Return adjacency matrix of graph
g
.See also

BFS
(g, f)Â¶ 
BFS
(g, v, f) traverse graph in breadthfirst order
Traverse graph
g
in breadthfirst order, starting fromv
if provided, or from the first vertex.f
is called for every visited vertex.

DFS
(g, f)Â¶ 
DFS
(g, v, f) traverse graph in depthfirst order
Traverse graph
g
in depthfirst order, starting fromv
if provided, or from the first vertex.f
is called for every visited vertex.
Functional operatorsÂ¶
These operators can help the user to program in the style of functional programming languages such as Miranda or Haskell.

item
:
listÂ¶ 
list
:
item 
list
:
list 
string
:
string prepend or append item to list, or concatenate lists or strings
 Example
In> a:b:c:{} Out> {a,b,c}; In> "This":"Is":"A":"String" Out> "ThisIsAString";
See also

fn
@
arglistÂ¶ apply a function
This function is a shorthand for
Apply()
. It applies the functionfn
to the argument(s) inarglist
and returns the result.fn
can either be a string containing the name of a function or a pure function. Example
In> "Sin" @ a Out> Sin(a); In> {{a},Sin(a)} @ a Out> Sin(a); In> "f" @ {a,b} Out> f(a,b);
See also

fn
/@
listÂ¶ apply a function to all entries in a list
This function is a shorthand for
MapSingle()
. It successively applies the functionfn
to all the entries inlist
and returns a list containing the results. The parameterfn
can either be a string containing the name of a function or a pure function. Example
In> "Sin" /@ {a,b} Out> {Sin(a),Sin(b)}; In> {{a},Sin(a)*a} /@ {a,b} Out> {Sin(a)*a,Sin(b)*b};
See also

n
..
mÂ¶ construct a list of consecutive integers
This command returns the list
{n, n+1, n+2, ..., m}
. Ifm
is smaller thann
, the empty list is returned.Note
The
..
operator should be surrounded by spaces to keep the parser happy. So one should write1 .. 4
instead of1..4
.

NFunction
(newname, funcname, arglist)Â¶ make wrapper for numeric functions
This function will define a function named
newname()
with the same arguments as an existing function namedfuncname()
. The new function will evaluate and return the expressionfuncname(arglist)
only when all items in the argument listarglist
are numbers, and return unevaluated otherwise. This can be useful e.g. when plotting functions defined through other yacas routines that cannot return unevaluated. If the numerical calculation does not return a number (for example, it might return the atomInfinity
for some arguments), then the new function will returnUndefined
. Example
In> f(x) := N(Sin(x)); Out> True; In> NFunction("f1", "f", {x}); Out> True; In> f1(a); Out> f1(a); In> f1(0); Out> 0;
Suppose we need to define a complicated function
t()
which cannot be evaluated unless the argument is a number:In> t(x) := If(x<=0.5, 2*x, 2*(1x)); Out> True; In> t(0.2); Out> 0.4; In> t(x); In function "If" : bad argument number 1 (counting from 1) CommandLine(1) : Invalid argument
Then, we can use
NFunction()
to define a wrappert1()
aroundt()
which will not try to evaluatet()
unless the argument is a number:In> NFunction("t1", "t", {x}) Out> True; In> t1(x); Out> t1(x); In> t1(0.2); Out> 0.4;
Now we can plot the function.
In> Plot2D(t1(x), 0.1: 1.1) Out> True;
See also
Control flow functionsÂ¶
Evaluation controlÂ¶

MaxEvalDepth
(n)Â¶ set the maximum evaluation depth
Use this command to set the maximum evaluation depth to
n
. The default value is 1000.The point of having a maximum evaluation depth is to catch any infinite recursion. For example, after the definition
f(x) := f(x)
, evaluating the expressionf(x)
would callf(x)
, which would callf(x)
, etc. The interpreter will halt if the maximum evaluation depth is reached. Also indirect recursion, e.g. the pair of definitionsf(x) := g(x)
andg(x) := f(x)
, will be caught.An example of an infinite recursion, caught because the maximum evaluation depth is reached:
In> f(x) := f(x) Out> True; In> f(x) Error on line 1 in file [CommandLine] Max evaluation stack depth reached. Please use MaxEvalDepth to increase the stack size as needed.
However, a long calculation may cause the maximum evaluation depth to be reached without the presence of infinite recursion. The function
MaxEvalDepth()
is meant for these cases:In> 10 # g(0) < 1; Out> True; In> 20 # g(n_IsPositiveInteger) < \ 2 * g(n1); Out> True; In> g(1001); Error on line 1 in file [CommandLine] Max evaluation stack depth reached. Please use MaxEvalDepth to increase the stack size as needed. In> MaxEvalDepth(10000); Out> True; In> g(1001); Out> 21430172143725346418968500981200036211228096234 1106721488750077674070210224987224498639675763139171 6255189345835106293650374290571384628087196915514939 7149607869135549648461970842149210124742283755908364 3060929499671638825347975351183310878921541258291423 92955373084335320859663305248773674411336138752;

Hold
(expr)Â¶ keep expression unevaluated
The expression
expr
is returned unevaluated. This is useful to prevent the evaluation of a certain expression in a context in which evaluation normally takes place. Example
In> Echo({ Hold(1+1), "=", 1+1 }); 1+1 = 2 Out> True;

Eval
(expr)Â¶ force evaluation of expression
This function explicitly requests an evaluation of the expression
expr
, and returns the result of this evaluation. Example
In> a := x; Out> x; In> x := 5; Out> 5; In> a; Out> x; In> Eval(a); Out> 5;
The variable
a
is bound tox
, andx
is bound to 5. Hence evaluatinga
will givex
. Only when an extra evaluation ofa
is requested, the value 5 is returned. Note that the behavior would be different if we had exchanged the assignments. If the assignmenta := x
were given whilex
had the value 5, the variablea
would also get the value 5 because the assignment operator:=()
evaluates the righthand side.
Conditional executionÂ¶

If
(pred, then[, else])Â¶ branch point
This command implements a branch point. The predicate
pred
is evaluated, which should result in eitherTrue
orFalse
. In the first case, the expressionthen
is evaluated and returned. If the predicate yieldsFalse
, the expressionelse
(if present) is evaluated and returned. If there is noelse
branch, theIf()
expression returnsFalse
.The sign function is defined to be 1 if its argument is positive and 1 if its argument is negative. A possible implementation is:
In> mysign(x) := If (IsPositiveReal(x), 1, 1); Out> True; In> mysign(Pi); Out> 1; In> mysign(2.5); Out> 1;
Note that this will give incorrect results, if
x
cannot be numerically approximated:In> mysign(a); Out> 1;
Hence a better implementation would be:
In> mysign(_x)_IsNumber(N(x)) < If(IsPositiveReal(x), 1, 1); Out> True;
LoopsÂ¶

While
(pred) exprÂ¶ loop while a condition is met
Keep on evaluating
expr
whilepred
evaluates toTrue
. More precisely,While()
evaluates the predicatepred
, which should evaluate to eitherTrue
orFalse
. If the result isTrue
, the expressionexpr
is evaluated and then the predicatepred
is evaluated again. If it is stillTrue
, the expressionsexpr
andpred
are again evaluated and so on untilpred
evaluates toFalse
. At that point, the loop terminates andWhile()
returnsTrue
.In particular, if
pred
immediately evaluates toFalse
, the body is never executed.While()
is the fundamental looping construct on which all other loop commands are based. It is equivalent to thewhile
command in the programming language C. Example
In> x := 0; Out> 0; In> While (x! < 10^6) [ Echo({x, x!}); x++; ]; 0 1 1 1 2 2 3 6 4 24 5 120 6 720 7 5040 8 40320 9 362880 Out> True;

Until
(pred) exprÂ¶ loop until a condition is met
Keep on evaluating
expr
untilpred
becomesTrue
. More precisely,Until()
first evaluates the expressionbody
. Then the predicatepred
is evaluated, which should yield eitherTrue
orFalse
. In the latter case, the expressionsexpr
andpred
are again evaluated and this continues as long as â€śpredâ€ť isFalse
. As soon aspred
yieldsTrue
, the loop terminates andUntil()
returnsTrue
.The main difference with
While()
is thatUntil()
always evaluatesexpr
at least once, butWhile()
may not evaluate it at all. Besides, the meaning of the predicate is reversed:While()
stops ifpred
isFalse
whileUntil()
stops ifpred
isTrue
. The commandUntil(pred) expr;
is equivalent topred; While(Not pred) body;
. In fact, the implementation ofUntil()
is based on the internal commandWhile()
. TheUntil()
command can be compared to thedo ... while
construct in the programming language C. Example
In> x := 0; Out> 0; In> Until (x! > 10^6) [ Echo({x, x!}); x++; ]; 0 1 1 1 2 2 3 6 4 24 5 120 6 720 7 5040 8 40320 9 362880 Out> True;

For
(init, pred, incr) exprÂ¶ Cstyle
for
loopThis commands implements a C style
for
loop. First of all, the expressioninit
is evaluated. Then the predicatepred
is evaluated, which should returnTrue
orFalse
. Next, the loop is executed as long as the predicate yieldsTrue
. One traversal of the loop consists of the subsequent evaluations ofexpr
,incr
, andpred
. Finally,True
is returned.This command is most often used in a form such as
For(i=1, i<=10, i++) expr
, which evaluatesexpr
withi
subsequently set to 1, 2, 3, 4, 5, 6, 7, 8, 9, and 10.The expression
For(init, pred, incr) expr
is equivalent toinit; While(pred) [expr; incr;]
. Example
In> For (i:=1, i<=10, i++) Echo({i, i!}); 1 1 2 2 3 6 4 24 5 120 6 720 7 5040 8 40320 9 362880 10 3628800 Out> True;

ForEach
(var, list) exprÂ¶ loop over all entries in list
The expression
expr
is evaluated multiple times. The first time,var
has the value of the first element of â€ślistâ€ť, then it gets the value of the second element and so on.ForEach()
returnsTrue
. Example
In> ForEach(i,{2,3,5,7,11}) Echo({i, i!}); 2 2 3 6 5 120 7 5040 11 39916800 Out> True;
See also

Function
() func(args)Â¶ 
Function
(funcname, {args}) body declare or define a function
This command can be used to define a new function with named arguments.
The number of arguments of the new function and their names are determined by the list
args
. If the ellipsis...
follows the last atom inargs
, a function with a variable number of arguments is declared (usingRuleBaseListed()
). Note that the ellipsis cannot be the only element ofargs
and must be preceded by an atom.A function with variable number of arguments can take more arguments than elements in
args
; in this case, it obtains its last argument as a list containing all extra arguments.The short form of the
Function()
call merely declares aRuleBase()
for the new function but does not define any function body. This is a convenient shorthand forRuleBase()
andRuleBaseListed()
, when definitions of the function are to be supplied by rules. If the new function has been already declared with the same number of arguments (with or without variable arguments),Function()
returns false and does nothing.The second, longer form of the
Function()
call declares a function and also defines a function body. It is equivalent to a single rule such asfuncname(_arg1, _arg2) < body
. The rule will be declared at precedence 1025. Any previous rules associated withfuncname
(with the same arity) will be discarded. More complicated functions (with more than one body) can be defined by adding more rules. Example
This will declare a new function with two or more arguments, but define no rules for it. This is equivalent to
RuleBase ("f1", {x, y, ...})
:In> Function() f1(x,y,...); Out> True; In> Function() f1(x,y); Out> False;
This defines a function
FirstOf
which returns the first element of a list. Equivalent definitions would beFirstOf(_list) < list[1]
orFirstOf(list) := list[1]
:In> Function("FirstOf", {list}) list[1]; Out> True; In> FirstOf({a,b,c}); Out> a;
The following function will print all arguments to a string:
In> Function("PrintAll",{x, ...}) If(IsList(x), PrintList(x), ToString()Write(x)); Out> True; In> PrintAll(1): Out> " 1"; In> PrintAll(1,2,3); Out> " 1 2 3";
See also
TemplateFunction()
,Rule()
,RuleBase()
,RuleBaseListed()
,:=()
,Retract()

Macro
() func(args)Â¶ 
Macro
(funcname, {args}) body declare or define a macro
This does the same as
Function()
, but for macros. One can define a macro easily with this function, instead of having to useDefMacroRuleBase()
. Example
The following example defines a looping function
In> Macro("myfor",{init,pred,inc,body}) [@init;While(@pred)[@body;@inc;];True;]; Out> True; In> a:=10 Out> 10;
Here this new macro
myfor
is used to loop, using a variablea
from the calling environmentIn> myfor(i:=1,i<10,i++,Echo(a*i)) 10 20 30 40 50 60 70 80 90 Out> True; In> i Out> 10;
See also

Apply
(fn, arglist)Â¶ apply a function to arguments
This function applies the function
fn
to the arguments inarglist
and returns the result. The first parameterfn
can either be a string containing the name of a function or a pure function. Pure functions, modeled after lambdaexpressions, have the form{varlist,body}
, wherevarlist
is the list of formal parameters. Upon application, the formal parameters are assigned the values inarglist
(the second parameter ofApply()
) and thebody
is evaluated.Another way to define a pure function is with the Lambda construct. Here, instead of passing in
{varlist,body}
, one can pass inLambda(varlist,body)
. Lambda has the advantage that its arguments are not evaluated (using lists can have undesirable effects because lists are evaluated). Lambda can be used everywhere a pure function is expected, in principle, because the functionApply()
is the only function dealing with pure functions. So all places where a pure function can be passed in will also accept Lambda.An shorthand for
Apply()
is provided by the@()
operator. Example
In> Apply("+", {5,9}); Out> 14; In> Apply({{x,y}, xy^2}, {Cos(a), Sin(a)}); Out> Cos(a)Sin(a)^2; In> Apply(Lambda({x,y}, xy^2), {Cos(a), Sin(a)}); Out> Cos(a)Sin(a)^2 In> Lambda({x,y}, xy^2) @ {Cos(a), Sin(a)} Out> Cos(a)Sin(a)^2
See also

MapArgs
(expr, fn)Â¶ apply a function to all toplevel arguments
Every toplevel argument in
expr
is substituted by the result of applyingfn
to this argument. Herefn
can be either the name of a function or a pure function (seeApply()
for more information on pure functions). Example
In> MapArgs(f(x,y,z),"Sin"); Out> f(Sin(x),Sin(y),Sin(z)); In> MapArgs({3,4,5,6}, {{x},x^2}); Out> {9,16,25,36};
See also

Subst
(from, to) exprÂ¶ perform a substitution
This function substitutes every occurrence of
from
inexpr
byto
. This is a syntactical substitution: only places wherefrom
occurs as a subexpression are affected. Example
In> Subst(x, Sin(y)) x^2+x+1; Out> Sin(y)^2+Sin(y)+1; In> Subst(a+b, x) a+b+c; Out> x+c; In> Subst(b+c, x) a+b+c; Out> a+b+c;
The explanation for the last result is that the expression
a+b+c
is internally stored as(a+b)+c
. Hencea+b
is a subexpression, butb+c
is not.See also

WithValue
(var, val, expr)Â¶ 
WithValue
(varlist, vallist, expr) temporary assignment during an evaluation
First, the expression
val
is assigned to the variablevar
. Then, the expressionexpr
is evaluated and returned. Finally, the assignment is reversed so that the variablevar
has the same value as it had beforeWithValue()
was evaluated.The second calling sequence assigns the first element in the list of values to the first element in the list of variables, the second value to the second variable, etc.
 Example
In> WithValue(x, 3, x^2+y^2+1); Out> y^2+10; In> WithValue({x,y}, {3,2}, x^2+y^2+1); Out> 14;

expression
/:
patternsÂ¶ local simplification rules
Sometimes you have an expression, and you want to use specific simplification rules on it that are not done by default. This can be done with the
/:
and the/::
operators. Suppose we have the expression containing things such asLn(a*b)
, and we want to change these intoLn(a)+Ln(b)
, the easiest way to do this is using the/:
operator, as follows:In> Sin(x)*Ln(a*b) Out> Sin(x)*Ln(a*b); In> % /: { Ln(_x*_y) < Ln(x)+Ln(y) } Out> Sin(x)*(Ln(a)+Ln(b));
A whole list of simplification rules can be built up in the list, and they will be applied to the expression on the left hand side of
/:
.The forms the patterns can have are one of:
pattern < replacement {pattern,replacement} {pattern,postpredicate,replacement}
Note that for these local rules,
<
should be used instead of<
which would be used in a global rule.The
/:
operator traverses an expression much asSubst()
does, that is, top down, trying to apply the rules from the beginning of the list of rules to the end of the list of rules. If the rules cannot be applied to an expression, it will try subexpressions of that expression and so on.It might be necessary sometimes to use the
/::
operator, which repeatedly applies the/:
operator until the result doesnâ€™t change any more. Caution is required, since rules can contradict each other, which could result in an infinite loop. To detect this situation, just use/:
repeatedly on the expression. The repetitive nature should become apparent. Example
In> Sin(u)*Ln(a*b) /: {Ln(_x*_y) < Ln(x)+Ln(y)} Out> Sin(u)*(Ln(a)+Ln(b)); In> Sin(u)*Ln(a*b) /:: { a < 2, b < 3 } Out> Sin(u)*Ln(6);
See also
PredicatesÂ¶
A predicate is a function that returns a boolean value, i.e. True
or
False
. Predicates are often used in patterns, For instance, a rule
that only holds for a positive integer would use a pattern such as
{n_IsPositiveInteger}.

e1 != e2
test for â€śnot equalâ€ť
 Param e1}, {e2
expressions to be compared
Both expressions are evaluated and compared. If they turn out to be equal, the result is
False
. Otherwise, the result isTrue
. The expression {e1 != e2} is equivalent to {Not(e1 = e2)}. Example
In> 1 != 2; Out> True; In> 1 != 1; Out> False;
See also
=()

e1 = e2
test for equality of expressions
 Param e1, e2
expressions to be compared
Both expressions are evaluated and compared. If they turn out to be equal, the result is
True
. Otherwise, the result isFalse
. The function {Equals} does the same. Note that the test is on syntactic equality, not mathematical equality. Hence even if the result isFalse
, the expressions can still be mathematically equal; see the examples below. Put otherwise, this function tests whether the two expressions would be displayed in the same way if they were printed. Example
In> e1 := (x+1) * (x1); Out> (x+1)*(x1); In> e2 := x^2  1; Out> x^21; In> e1 = e2; Out> False; In> Expand(e1) = e2; Out> True;
See also
=()
,Equals()

Not
(expr)Â¶ 
Not
expr logical negation
 Param expr
a boolean expression
Not returns the logical negation of the argument expr. If
expr
isFalse
it returnsTrue
, and ifexpr
isTrue
, {Not expr} returnsFalse
. If the argument is neitherTrue
norFalse
, it returns the entire expression with evaluated arguments. Example
In> Not True Out> False; In> Not False Out> True; In> Not(a) Out> Not a;
See also
And()
,Or()

a1 And a2
logical conjunction
This function returns
True
if all arguments are true. The {And} operation is â€ślazyâ€ť, i.e. it returnsFalse
as soon as aFalse
argument is found (from left to right). If an argument other thanTrue
orFalse
is encountered a new {And} expression is returned with all arguments that didnâ€™t evaluate toTrue
orFalse
yet. Example
In> True And False Out> False; In> And(True,True) Out> True; In> False And a Out> False; In> True And a Out> And(a); In> And(True,a,True,b) Out> b And a;
See also
Or()
,Not()

a1 Or a2
logical disjunction
This function returns
True
if an argument is encountered that is true (scanning from left to right). The {Or} operation is â€ślazyâ€ť, i.e. it returnsTrue
as soon as aTrue
argument is found (from left to right). If an argument other thanTrue
orFalse
is encountered, an unevaluated {Or} expression is returned with all arguments that didnâ€™t evaluate toTrue
orFalse
yet. Example
In> True Or False Out> True; In> False Or a Out> Or(a); In> Or(False,a,b,True) Out> True;
See also
And()
,Not()

IsFreeOf
(var, expr)Â¶ test whether expression depends on variable
 Param expr
expression to test
 Param var
variable to look for in â€śexprâ€ť
This function checks whether the expression â€śexprâ€ť (after being evaluated) depends on the variable â€śvarâ€ť. It returns
False
if this is the case andTrue
otherwise. The second form test whether the expression depends on any of the variables named in the list. The result isTrue
if none of the variables appear in the expression andFalse
otherwise. Example
In> IsFreeOf(x, Sin(x)); Out> False; In> IsFreeOf(y, Sin(x)); Out> True; In> IsFreeOf(x, D(x) a*x+b); Out> True; In> IsFreeOf({x,y}, Sin(x)); Out> False; The third command returns :data:`True` because the expression {D(x) a*x+b} evaluates to {a}, which does not depend on {x}.
See also

IsZeroVector
(list)Â¶ test whether list contains only zeroes
 Param list
list to compare against the zero vector
The only argument given to {IsZeroVector} should be a list. The result is
True
if the list contains only zeroes andFalse
otherwise. Example
In> IsZeroVector({0, x, 0}); Out> False; In> IsZeroVector({xx, 1  D(x) x}); Out> True;
See also

IsNonObject
(expr)Â¶ test whether argument is not an {Object()}
 Param expr
the expression to examine
This function returns
True
if â€śexprâ€ť is not of the form {Object(â€¦)} andFalse
otherwise.

IsEven
(n)Â¶ test for an even integer
 Param n
integer to test
This function tests whether the integer â€śnâ€ť is even. An integer is even if it is divisible by two. Hence the even numbers are 0, 2, 4, 6, 8, 10, etc., and 2, 4, 6, 8, 10, etc.
 Example
In> IsEven(4); Out> True; In> IsEven(1); Out> False;
See also
IsOdd()
,IsInteger()

IsOdd
(n)Â¶ test for an odd integer
 Param n
integer to test
This function tests whether the integer â€śnâ€ť is odd. An integer is odd if it is not divisible by two. Hence the odd numbers are 1, 3, 5, 7, 9, etc., and 1, 3, 5, 7, 9, etc.
 Example
In> IsOdd(4); Out> False; In> IsOdd(1); Out> True;
See also
IsEven()
,IsInteger()

IsEvenFunction
(expression, variable)Â¶ Return true if function is an even function, False otherwise
 Param expression
mathematical expression
 Param variable
variable
These functions return
True
if yacas can determine that the function is even or odd respectively. Even functions are defined to be functions that have the property: \(f(x) = f(x)\) And odd functions have the property: \(f(x) = f(x)\). \(\sin(x)\) is an example of an odd function, and \(cos(x)\) is an example of an even function.Note
One can decompose a function into an even and an odd part \(f(x) = f_{even}(x) + f_{odd}(x)\) where \(f_{even}(x) = \frac{f(x)+f(x)}{2}\) and \(f_{odd}(x) = \frac{f(x)f(x)}{2}\)

IsFunction
(expr)Â¶ test for a composite object
This function tests whether
expr
is a composite object, i.e. not an atom. This includes not only obvious functions such asf(x)
, but also expressions such asx+5
and lists. Example
In> IsFunction(x+5); Out> True; In> IsFunction(x); Out> False;

IsAtom
(expr)Â¶ test for an atom
This function tests whether
expr
is an atom. Numbers, strings, and variables are all atoms. Example
In> IsAtom(x+5); Out> False; In> IsAtom(5); Out> True;
See also

IsString
(expr)Â¶ test for an string
 Param expr
expression to test
This function tests whether â€śexprâ€ť is a string. A string is a text within quotes, e.g. {â€śduhâ€ť}.
 Example
In> IsString("duh"); Out> True; In> IsString(duh); Out> False;
See also

IsNumber
(expr)Â¶ test for a number
 Param expr
expression to test
This function tests whether â€śexprâ€ť is a number. There are two kinds of numbers, integers (e.g. 6) and reals (e.g. 2.75 or 6.0). Note that a complex number is represented by the {Complex} function, so {IsNumber} will return
False
. Example
In> IsNumber(6); Out> True; In> IsNumber(3.25); Out> True; In> IsNumber(I); Out> False; In> IsNumber("duh"); Out> False;
See also
IsAtom()
,IsString()
,IsInteger()
,IsPositiveNumber()
,IsNegativeNumber()
,Complex()

IsList
(expr)Â¶ test for a list
 Param expr
expression to test
This function tests whether â€śexprâ€ť is a list. A list is a sequence between curly braces, e.g. {{2, 3, 5}}.
 Example
In> IsList({2,3,5}); Out> True; In> IsList(2+3+5); Out> False;
See also

IsNumericList
({list})Â¶ test for a list of numbers
 Param {list}
a list
Returns
True
when called on a list of numbers or expressions that evaluate to numbers using {N()}. ReturnsFalse
otherwise.See also

IsBound
(var)Â¶ test for a bound variable
 Param var
variable to test
This function tests whether the variable â€śvarâ€ť is bound, i.e. whether it has been assigned a value. The argument â€śvarâ€ť is not evaluated.
 Example
In> IsBound(x); Out> False; In> x := 5; Out> 5; In> IsBound(x); Out> True;
See also

IsBoolean
(expression)Â¶ test for a Boolean value
 Param expression
an expression
IsBoolean returns True if the argument is of a boolean type. This means it has to be either True, False, or an expression involving functions that return a boolean result, e.g. {=}, {>}, {<}, {>=}, {<=}, {!=}, {And}, {Not}, {Or}.
 Example
In> IsBoolean(a) Out> False; In> IsBoolean(True) Out> True; In> IsBoolean(a And b) Out> True;

IsNegativeNumber
(n)Â¶ test for a negative number
 Param n
number to test
{IsNegativeNumber(n)} evaluates to
True
if \(n\) is (strictly) negative, i.e. if \(n<0\). If {n} is not a number, the functions returnFalse
. Example
In> IsNegativeNumber(6); Out> False; In> IsNegativeNumber(2.5); Out> True;

IsNegativeInteger
(n)Â¶ test for a negative integer
 Param n
integer to test
This function tests whether the integer {n} is (strictly) negative. The negative integers are 1, 2, 3, 4, 5, etc. If {n} is not a integer, the function returns
False
. Example
In> IsNegativeInteger(31); Out> False; In> IsNegativeInteger(2); Out> True;

IsPositiveNumber
(n)Â¶ test for a positive number
 Param n
number to test
{IsPositiveNumber(n)} evaluates to
True
if \(n\) is (strictly) positive, i.e. if \(n>0\). If {n} is not a number the function returnsFalse
. Example
In> IsPositiveNumber(6); Out> True; In> IsPositiveNumber(2.5); Out> False;

IsPositiveInteger
(n)Â¶ test for a positive integer
 Param n
integer to test
This function tests whether the integer {n} is (strictly) positive. The positive integers are 1, 2, 3, 4, 5, etc. If {n} is not a integer, the function returns
False
. Example
In> IsPositiveInteger(31); Out> True; In> IsPositiveInteger(2); Out> False;

IsNotZero
(n)Â¶ test for a nonzero number
 Param n
number to test
{IsNotZero(n)} evaluates to
True
if {n} is not zero. In case {n} is not a number, the function returnsFalse
. Example
In> IsNotZero(3.25); Out> True; In> IsNotZero(0); Out> False;

IsNonZeroInteger
(n)Â¶ test for a nonzero integer
 Param n
integer to test
This function tests whether the integer {n} is not zero. If {n} is not an integer, the result is
False
. Example
In> IsNonZeroInteger(0) Out> False; In> IsNonZeroInteger(2) Out> True;
See also

IsInfinity
(expr)Â¶ test for an infinity
 Param expr
expression to test
This function tests whether {expr} is an infinity. This is only the case if {expr} is either {Infinity} or {Infinity}.
 Example
In> IsInfinity(10^1000); Out> False; In> IsInfinity(Infinity); Out> True;
See also
Integer()

IsPositiveReal
(expr)Â¶ test for a numerically positive value
 Param expr
expression to test
This function tries to approximate â€śexprâ€ť numerically. It returns
True
if this approximation is positive. In case no approximation can be found, the function returnsFalse
. Note that roundoff errors may cause incorrect results. Example
In> IsPositiveReal(Sin(1)3/4); Out> True; In> IsPositiveReal(Sin(1)6/7); Out> False; In> IsPositiveReal(Exp(x)); Out> False; The last result is because {Exp(x)} cannot be numerically approximated if {x} is not known. Hence Yacas can not determine the sign of this expression.
See also

IsNegativeReal
(expr)Â¶ test for a numerically negative value
 Param expr
expression to test
This function tries to approximate {expr} numerically. It returns
True
if this approximation is negative. In case no approximation can be found, the function returnsFalse
. Note that roundoff errors may cause incorrect results. Example
In> IsNegativeReal(Sin(1)3/4); Out> False; In> IsNegativeReal(Sin(1)6/7); Out> True; In> IsNegativeReal(Exp(x)); Out> False; The last result is because {Exp(x)} cannot be numerically approximated if {x} is not known. Hence Yacas can not determine the sign of this expression.
See also

IsConstant
(expr)Â¶ test for a constant
 Param expr
some expression
{IsConstant} returns
True
if the expression is some constant or a function with constant arguments. It does this by checking that no variables are referenced in the expression. {Pi} is considered a constant. Example
In> IsConstant(Cos(x)) Out> False; In> IsConstant(Cos(2)) Out> True; In> IsConstant(Cos(2+x)) Out> False;
See also
IsNumber()
,IsInteger()
,VarList()

IsGaussianInteger
(z)Â¶ test for a Gaussian integer
 Param z
a complex or real number
This function returns
True
if the argument is a Gaussian integer andFalse
otherwise. A Gaussian integer is a generalization of integers into the complex plane. A complex number \(a+b*I\) is a Gaussian integer if and only if \(a\) and \(b\) are integers. Example
In> IsGaussianInteger(5) Out> True; In> IsGaussianInteger(5+6*I) Out> True; In> IsGaussianInteger(1+2.5*I) Out> False;
See also

MatchLinear
(x, expr)Â¶ match an expression to a polynomial of degree one in a variable
 Param x
variable to express the univariate polynomial in
 Param expr
expression to match
{MatchLinear} tries to match an expression to a linear (degree less than two) polynomial. The function returns
True
if it could match, and it stores the resulting coefficients in the variables â€ś{a}â€ť and â€ś{b}â€ť as a side effect. The function calling this predicate should declare local variables â€ś{a}â€ť and â€ś{b}â€ť for this purpose. {MatchLinear} tries to match to constant coefficients which donâ€™t depend on the variable passed in, trying to find a form â€ś{a*x+b}â€ť with â€ś{a}â€ť and â€ś{b}â€ť not depending on {x} if {x} is given as the variable. Example
In> MatchLinear(x,(R+1)*x+(T1)) Out> True; In> {a,b}; Out> {R+1,T1}; In> MatchLinear(x,Sin(x)*x+(T1)) Out> False;
See also

HasExpr
(expr, x)Â¶ check for expression containing a subexpression
 Param expr
an expression
 Param x
a subexpression to be found
 Param list
list of function atoms to be considered â€śtransparentâ€ť
The command {HasExpr} returns
True
if the expression {expr} contains a literal subexpression {x}. The expression is recursively traversed. The command {HasExprSome} does the same, except it only looks at arguments of a given {list} of functions. All other functions become â€śopaqueâ€ť (as if they do not contain anything). {HasExprArith} is defined through {HasExprSome} to look only at arithmetic operations {+}, {}, {*}, {/}. Note that since the operators â€ś{+}â€ť and â€ś{}â€ť are prefix as well as infix operators, it is currently required to use {Atom(â€ś+â€ť)} to obtain the unevaluated atom â€ś{+}â€ť. Example
In> HasExpr(x+y*Cos(Ln(z)/z), z) Out> True; In> HasExpr(x+y*Cos(Ln(z)/z), Ln(z)) Out> True; In> HasExpr(x+y*Cos(Ln(z)/z), z/Ln(z)) Out> False; In> HasExprArith(x+y*Cos(Ln(x)/x), z) Out> False; In> HasExprSome({a+b*2,c/d},c/d,{List}) Out> True; In> HasExprSome({a+b*2,c/d},c,{List}) Out> False;
See also

HasFunc
(expr, func)Â¶ check for expression containing a function
 Param expr
an expression
 Param func
a function atom to be found
 Param list
list of function atoms to be considered â€śtransparentâ€ť
The command {HasFunc} returns
True
if the expression {expr} contains a function {func}. The expression is recursively traversed. The command {HasFuncSome} does the same, except it only looks at arguments of a given {list} of functions. Arguments of all other functions become â€śopaqueâ€ť (as if they do not contain anything). {HasFuncArith} is defined through {HasFuncSome} to look only at arithmetic operations {+}, {}, {*}, {/}. Note that since the operators â€ś{+}â€ť and â€ś{}â€ť are prefix as well as infix operators, it is currently required to use {Atom(â€ś+â€ť)} to obtain the unevaluated atom â€ś{+}â€ť. Example
In> HasFunc(x+y*Cos(Ln(z)/z), Ln) Out> True; In> HasFunc(x+y*Cos(Ln(z)/z), Sin) Out> False; In> HasFuncArith(x+y*Cos(Ln(x)/x), Cos) Out> True; In> HasFuncArith(x+y*Cos(Ln(x)/x), Ln) Out> False; In> HasFuncSome({a+b*2,c/d},/,{List}) Out> True; In> HasFuncSome({a+b*2,c/d},*,{List}) Out> False;
See also
ConstantsÂ¶
Yacasspecific constantsÂ¶

%
previous result
%
evaluates to the previous result on the command line.%
is a global variable that is bound to the previous result from the command line. Using%
will evaluate the previous result. (This uses the functionality offered by the {SetGlobalLazyVariable} command).Typical examples are
Simplify(%)
andPrettyForm(%)
to simplify and show the result in a nice form respectively. Example
In> Taylor(x,0,5)Sin(x) Out> xx^3/6+x^5/120; In> PrettyForm(%) 3 5 x x x   +  6 120
See also

EndOfFile
Â¶ endoffile marker
End of file marker when reading from file. If a file contains the expression {EndOfFile;} the operation will stop reading the file at that point.
Mathematical constantsÂ¶

True
Â¶ 
False
Â¶ boolean constants representing true and false
True
andFalse
are typically a result of boolean expressions such as2 < 3
orTrue And False
.
See also
And()
, Or()
, Not()

Infinity
Â¶ constant representing mathematical infinity
Infinity
represents infinitely large values. It can be the result of certain calculations.Note that for most analytic functions yacas understands
Infinity
as a positive number. ThusInfinity*2
will returnInfinity
, anda < Infinity
will evaluate toTrue
. Example
In> 2*Infinity Out> Infinity; In> 2<Infinity Out> True;

Pi
Â¶ mathematical constant, \(\pi\)
The constant represents the number Ď€. It is available symbolically as
Pi
or numerically throughN(Pi)
.This is a cached constant which is recalculated only when precision is increased.
 Example
In> Sin(3*Pi/2) Out> 1; In> Pi+1 Out> Pi+1; In> N(Pi) Out> 3.14159265358979323846;
See also

Undefined
Â¶ constant signifying an undefined result
Undefined
is a token that can be returned by a function when it considers its input to be invalid or when no meaningful answer can be given. The result is then undefined.Most functions also return
Undefined
when evaluated on it. Example
In> 2*Infinity Out> Infinity; In> 0*Infinity Out> Undefined; In> Sin(Infinity); Out> Undefined; In> Undefined+2*Exp(Undefined); Out> Undefined;
See also

GoldenRatio
Â¶ the golden ratio
The constant represents the golden ratio
\[\phi := \frac{1+\sqrt{5}}{2} = 1.6180339887\ldots\]It is available symbolically as
GoldenRatio
or numerically throughN(GoldenRatio)
.This is a cached constant which is recalculated only when precision is increased.
 Example
In> x:=GoldenRatio  1 Out> GoldenRatio1; In> N(x) Out> 0.6180339887; In> N(1/GoldenRatio) Out> 0.6180339887; In> V(N(GoldenRatio,20)); CachedConstant: Info: constant GoldenRatio is being recalculated at precision 20 Out> 1.6180339887498948482;
See also

Catalan
Â¶ Catalanâ€™s constant
The constant represents the Catalanâ€™s constant
\[G := \beta(2) = \sum_{n=0}^\infty\frac{1^n}{(2n+1)^2}=0.9159655941\ldots\]It is available symbolically as
Catalan
or numerically throughN(Catalan)
.This is a cached constant which is recalculated only when precision is increased.
 Example
In> N(Catalan) Out> 0.9159655941; In> DirichletBeta(2) Out> Catalan; In> V(N(Catalan,20)) CachedConstant: Info: constant Catalan is being recalculated at precision 20 Out> 0.91596559417721901505;
See also

gamma
Â¶ Eulerâ€“Mascheroni constant \(\gamma\)
The constant represents the Eulerâ€“Mascheroni constant
\[\gamma := \lim_{n\to\infty}\left(\ln(n)+\sum_{k=1}^n\frac{1}{k}\right)=0.5772156649\ldots\]It is available symbolically as
gamma
or numerically throughN(gamma)
.This is a cached constant which is recalculated only when precision is increased.
Note
Eulerâ€™s \(\Gamma(x)\) function is the capitalized
Gamma()
in yacas. Example
In> gamma+Pi Out> gamma+Pi; In> N(gamma+Pi) Out> 3.7188083184; In> V(N(gamma,20)) CachedConstant: Info: constant gamma is being recalculated at precision 20 GammaConstNum: Info: used 56 iterations at working precision 24 Out> 0.57721566490153286061;
See also
VariablesÂ¶

var
:=
exprÂ¶ 
var[i]
:=
expr 
varlist
:=
exprlist 
fn
:=
expr assign a variable or a list; define a function
var := expr {var1, var2, â€¦} := {expr1, expr2, â€¦} var[i] := expr fn(arg1, arg2, â€¦) := expr
 Param var
atom, variable which should be assigned
 Param expr
expression to assign to the variable or body of function
 Param i
index (can be integer or string)
 Param fn
atom, name of a new function to define
 Param arg1, arg2
atoms, names of arguments of the new function {fn}
The
:=()
operator can be used in a number of ways. In all cases, some sort of assignment or definition takes place. The first form is the most basic one. It evaluates the expression on the righthand side and assigns it to the variable named on the lefthand side. The lefthand side is not evaluated. The evaluated expression is also returned. The second form is a small extension, which allows one to do multiple assignments. The first entry in the list on the righthand side is assigned to the first variable mentioned in the lefthand side, the second entry on the righthand side to the second variable on the lefthand side, etc. The list on the righthand side must have at least as many entries as the list on the lefthand side. Any excess entries are silently ignored. The result of the expression is the list of values that have been assigned. The third form allows one to change an entry in the list. If the index â€śiâ€ť is an integer, the â€śiâ€ťth entry in the list is changed to the expression on the righthand side. It is assumed that the length of the list is at least â€śiâ€ť. If the index â€śiâ€ť is a string, then â€śvarâ€ť is considered to be an associative list (sometimes called hash table), and the key â€śiâ€ť is paired with the value â€śexpâ€ť. In both cases, the righthand side is evaluated before the assignment and the result of the assignment isTrue
. The last form defines a function. For example, the assignment {fn(x) := x^2} removes any rules previously associated with {fn(x)} and defines the rule {fn(_x) <â€“ x^2}. Note that the lefthand side may take a different form if {fn} is defined to be a prefix, infix or bodied function. This case is special since the righthand side is not evaluated immediately, but only when the function {fn} is used. If this takes time, it may be better to force an immediate evaluation with {Eval} (see the last example). If the expression on the right hand side begins with {Eval()}, then it will be evaluated before defining the new function. A variant of the function definition can be used to make a function accepting a variable number of arguments. The last argumentSimple assignment:
In> a := Sin(x) + 3; Out> Sin(x)+3; In> a; Out> Sin(x)+3;
Multiple assignments:
In> {a,b,c} := {1,2,3}; Out> {1,2,3}; In> a; Out> 1; In> b+c; Out> 5;
Assignment to a list:
In> xs := { 1,2,3,4,5 }; Out> {1,2,3,4,5}; In> xs[3] := 15; Out> True; In> xs; Out> {1,2,15,4,5};
Building an associative list:
In> alist := {}; Out> {}; In> alist["cherry"] := "red"; Out> True; In> alist["banana"] := "yellow"; Out> True; In> alist["cherry"]; Out> "red"; In> alist; Out> {{"banana","yellow"},{"cherry","red"}};
Defining a function:
In> f(x) := x^2; Out> True; In> f(3); Out> 9; In> f(Sin(a)); Out> Sin(a)^2;
Defining a function with variable number of arguments:
In> f(x, ...) := If(IsList(x),Sum(x),x); Out> True; In> f(2); Out> 2; In> f(1,2,3); Out> 6;
Defining a new infix operator:
In> Infix("*&*",10); Out> True; In> x1 *&* x2 := x1/x2 + x2/x1; Out> True; In> Sin(a) *&* Cos(a); Out> Tan(1)+Cos(1)/Sin(1); In> Clear(a); Out> True; In> Sin(a) *&* Exp(a); Out> Sin(a)/Exp(a)+Exp(a)/Sin(a);
In the following example, it may take some time to compute the Taylor expansion. This has to be done every time the function {f} is called:
In> f(a) := Taylor(x,0,25) Sin(x); Out> True; In> f(1); Out> xx^3/6+x^5/120x^7/5040+x^9/362880 x^11/39916800+x^13/6227020800x^15/ 1307674368000+x^17/355687428096000x^19/ 121645100408832000+x^21/51090942171709440000 x^23/25852016738884976640000+x^25 /15511210043330985984000000; In> f(2); Out> xx^3/6+x^5/120x^7/5040+x^9/362880 x^11/39916800+x^13/6227020800x^15 /1307674368000+x^17/355687428096000x^19/ 121645100408832000+x^21/51090942171709440000 x^23/25852016738884976640000+x^25/ 15511210043330985984000000;
The remedy is to evaluate the Taylor expansion immediately. Now the expansion is computed only once:
In> f(a) := Eval(Taylor(x,0,25) Sin(x)); Out> True; In> f(1); Out> xx^3/6+x^5/120x^7/5040+x^9/362880 x^11/39916800+x^13/6227020800x^15/ 1307674368000+x^17/355687428096000x^19/ 121645100408832000+x^21/51090942171709440000 x^23/25852016738884976640000+x^25 /15511210043330985984000000; In> f(2); Out> xx^3/6+x^5/120x^7/5040+x^9/362880 x^11/39916800+x^13/6227020800x^15 /1307674368000+x^17/355687428096000x^19/ 121645100408832000+x^21/51090942171709440000 x^23/25852016738884976640000+x^25/ 15511210043330985984000000;

Set
(var, exp)Â¶ assignment
 Param var
variable which should be assigned
 Param exp
expression to assign to the variable
The expression â€śexpâ€ť is evaluated and assigned it to the variable named â€śvarâ€ť. The first argument is not evaluated. The value True is returned. The statement {Set(var, exp)} is equivalent to {var := exp}, but the {:=} operator has more uses, e.g. changing individual entries in a list.
 Example
In> Set(a, Sin(x)+3); Out> True; In> a; Out> Sin(x)+3;

Clear
(var, ...)Â¶ undo an assignment
 Param var
name of the variable to be cleared
All assignments made to the variables listed as arguments are undone. From now on, all these variables remain unevaluated (until a subsequent assignment is made). The result of the expression is True.
 Example
In> a := 5; Out> 5; In> a^2; Out> 25; In> Clear(a); Out> True; In> a^2; Out> a^2;

Local
(var, ...)Â¶ declare new local variables
 Param var
name of the variable to be declared as local
All variables in the argument list are declared as local variables. The arguments are not evaluated. The value
True
is returned. By default, all variables in Yacas are global. This means that the variable has the same value everywhere. But sometimes it is useful to have a private copy of some variable, either to prevent the outside world from changing it or to prevent accidental changes to the outside world. This can be achieved by declaring the variable local. Now only expressions within theProg()
block (or its syntactic equivalent, the[]
block) can access and change it. Functions called within this block cannot access the local copy unless this is specifically allowed withUnFence()
. Example
In> a := 3; Out> 3; In> [ a := 4; a; ]; Out> 4; In> a; Out> 4; In> [ Local(a); a := 5; a; ]; Out> 5; In> a; Out> 4;
In the first block,
a
is not declared local and hence defaults to be a global variable. Indeed, changing the variable inside the block also changes the value ofa
outside the block. However, in the second blocka
is defined to be local and now the value outside the block stays the same, even thougha
is assigned the value 5 inside the block.See also
LocalSymbols()
,Prog()
,[]()
,UnFence()

var
++
Â¶ increment variable
 Param var
variable to increment
The variable with name
var
is incremented, i.e. the number 1 is added to it. The expressionx++
is equivalent to the assignmentx := x + 1
, except that the assignment returns the new value ofx
whilex++
always returnsTrue
. In this respect, Yacasâ€™++
differs from the corresponding operator in the programming language C. Example
In> x := 5; Out> 5; In> x++; Out> True; In> x; Out> 6;

var

Â¶ decrement variable
 Param var
variable to decrement
The variable with name
var
is decremented, i.e. the number 1 is subtracted from it. The expressionx
is equivalent to the assignmentx := x  1
, except that the assignment returns the new value ofx
whilex
always returnsTrue
. In this respect, Yacasâ€™
differs from the corresponding operator in the programming language C. Example
In> x := 5; Out> 5; In> x; Out> True; In> x; Out> 4;

Object
("pred", expr)Â¶ create an incomplete type
 Param pred
name of the predicate to apply
 Param expr
expression on which
pred
should be applied
This function returns â€śobjâ€ť as soon as â€śpredâ€ť returns
True
when applied on â€śobjâ€ť. This is used to declare socalled incomplete types. Example
In> a := Object("IsNumber", x); Out> Object("IsNumber",x); In> Eval(a); Out> Object("IsNumber",x); In> x := 5; Out> 5; In> Eval(a); Out> 5;
See also

SetGlobalLazyVariable
(var, value)Â¶ global variable is to be evaluated lazily
 Param var
variable (held argument)
 Param value
value to be set to (evaluated before it is assigned)
SetGlobalLazyVariable()
enforces that a global variable will reevaluate when used. This functionality doesnâ€™t survive ifClear(var)
is called afterwards. Places where this is used include the global variables%
andI
. The use of lazy in the name stems from the concept of lazy evaluation. The object the global variable is bound to will only be evaluated when called. The {SetGlobalLazyVariable} property only holds once: after that, the result of evaluation is stored in the global variable, and it wonâ€™t be reevaluated again:In> SetGlobalLazyVariable(a,Hold(Taylor(x,0,30)Sin(x))) Out> True
Then the first time you call
a
it evaluatesTaylor(...)
and assigns the result toa
. The next time you calla
it immediately returns the result.SetGlobalLazyVariable()
is called for%
each time%
changes. The following example demonstrates the sequence of execution:In> SetGlobalLazyVariable(test,Hold(Write("hello"))) Out> True
The text â€śhelloâ€ť is not written out to screen yet. However, evaluating the variable
test
forces the expression to be evaluated:In> test = "hello" Out> True
 Example
In> Set(a,Hold(2+3)) Out> True In> a Out> 2+3 In> SetGlobalLazyVariable(a,Hold(2+3)) Out> True In> a Out> 5

UniqueConstant
()Â¶ create a unique identifier
This function returns a unique constant atom each time you call it. The atom starts with a C character, and a unique number is appended to it.
 Example
In> UniqueConstant() Out> C9 In> UniqueConstant() Out> C10
See also

LocalSymbols
(var1, var2, ...) exprÂ¶ create unique local symbols with given prefix
 Param var1, var2, ..
atoms, symbols to be made local
 Param expr
expression to execute
Given the symbols passed as the first arguments to
LocalSymbols()
, a set of unique local symbols will be created, typically of the form$<symbol><number>
, wheresymbol
was the symbol entered by the user, andnumber
is a unique number. This scheme is used to ensure that a generated symbol can not accidentally be entered by a user. This is useful in cases where a guaranteed free variable is needed, for example, in the macrolike functions (For()
,While()
etc.). Example
In> LocalSymbols(a,b)a+b Out> :math:`a6+ :math:`b6;
See also
Input/outputÂ¶
This chapter contains commands to use for input and output. All output commands write to the same destination stream, called the â€ścurrent outputâ€ť. This is initially the screen, but may be redirected by some commands. Similarly, most input commands read from the â€ścurrent inputâ€ť stream, which can also be redirected. The exception to this rule are the commands for reading script files, which simply read a specified file.

FullForm
(expr)Â¶ print an expression in LISPformat
 Param expr
expression to be printed in LISPformat
Evaluates â€śexprâ€ť, and prints it in LISPformat on the current output. It is followed by a newline. The evaluated expression is also returned. This can be useful if you want to study the internal representation of a certain expression.
 Example
In> FullForm(a+b+c); (+ (+ a b )c ) Out> a+b+c; In> FullForm(2*I*b^2); (* (Complex 0 2 )(^ b 2 )) Out> Complex(0,2)*b^2;
The first example shows how the expression \(a+b+c\) is internally represented. In the second example, \(2i\) is first evaluated to
Complex(0,2)
before the expression is printed.See also
LispRead()
,Listify()
,Unlist()

Echo
(item)Â¶ 
Echo
(items) highlevel printing routine
 Param item
the item to be printed
 Param items
a list of items to be printed
If passed a single item, {Echo} will evaluate it and print it to the current output, followed by a newline. If {item} is a string, it is printed without quotation marks. If there is one argument, and it is a list, {Echo} will print all the entries in the list subsequently to the current output, followed by a newline. Any strings in the list are printed without quotation marks. All other entries are followed by a space. {Echo} can be called with a variable number of arguments, they will all be printed, followed by a newline. {Echo} always returns
True
. Example
In> Echo(5+3); 8 Out> True; In> Echo({"The square of two is ", 2*2}); The square of two is 4 Out> True; In> Echo("The square of two is ", 2*2); The square of two is 4 Out> True; Note that one must use the second calling format if one wishes to print a list: In> Echo({a,b,c}); a b c Out> True; In> Echo({{a,b,c}}); {a,b,c} Out> True;
See also

PrettyForm
(expr)Â¶ print an expression nicely with ASCII art
 Param expr
an expression
PrettyForm()
renders an expression in a nicer way, using ascii art. This is generally useful when the result of a calculation is more complex than a simple number. Example
In> Taylor(x,0,9)Sin(x) Out> xx^3/6+x^5/120x^7/5040+x^9/362880; In> PrettyForm(%) 3 5 7 9 x x x x x   +    +  6 120 5040 362880 Out> True;
See also
EvalFormula()
,PrettyPrinter'Set()

EvalFormula
(expr)Â¶ print an evaluation nicely with ASCII art
 Param expr
an expression
Show an evaluation in a nice way, using
PrettyPrinter'Set()
to show â€input = outputâ€™. Example
In> EvalFormula(Taylor(x,0,7)Sin(x)) 3 5 x x Taylor( x , 0 , 5 , Sin( x ) ) = x   +  6 120
See also

TeXForm
(expr)Â¶ export expressions to LaTeX
 Param expr
an expression to be exported
TeXForm()
returns a string containing LaTeX representation of the yacas expressionexpr
. Currently the exporter handles most expression types but not all.

CForm
(expr)Â¶ export expression to C code
 Param expr
expression to be exported
CForm()
returns a string containing C code that attempts to implement the yacas expressionexpr
. Currently the exporter handles most expression types but not all.

IsCFormable
(expr)Â¶ 
IsCFormable
(expr, funclist) check possibility to export expression to C code
 Param expr
expression to be exported (this argument is not evaluated)
 Param funclist
list of â€śallowedâ€ť function atoms
IsCFormable()
returnsTrue
if the yacas expressionexpr
can be exported into C code. This is a check whether the C exporterCForm()
can be safely used on the expression. A yacas expression is considered exportable if it contains only functions that can be translated into C (e.g.UnList()
cannot be exported). All variables and constants are considered exportable. The verbose option prints names of functions that are not exportable. The second calling format ofIsCFormable()
can be used to allow certain function names that will be available in the C code. Example
In> IsCFormable(Sin(a1)+2*Cos(b1)) Out> True; In> V(IsCFormable(1+func123(b1))) IsCFormable: Info: unexportable function(s): func123 Out> False;
This returned
False
because the functionfunc123()
is not available in C. We can explicitly allow this function and then the expression will be considered exportable:In> IsCFormable(1+func123(b1), {func123}) Out> True;

Write
(expr, ...)Â¶ lowlevel printing routine
 Param expr
expression to be printed
The expression
expr
is evaluated and written to the current output. Note thatWrite()
accepts an arbitrary number of arguments, all of which are written to the current output (see second example).Write()
always returnsTrue
. Example
In> Write(1); 1Out> True; In> Write(1,2); 1 2Out> True;
Write does not write a newline, so the
Out>
prompt immediately follows the output ofWrite()
.See also

WriteString
(string)Â¶ lowlevel printing routine for strings
 Param string
the string to be printed
The expression
string
is evaluated and written to the current output without quotation marks. The argument should be a string.WriteString()
always returnsTrue
. Example
In> Write("Hello, world!"); "Hello, world!"Out> True; In> WriteString("Hello, world!"); Hello, world!Out> True;
This example clearly shows the difference between
Write()
andWriteString()
. Note thatWrite()
andWriteString()
do not write a newline, so theOut>
prompt immediately follows the output.

Space
()Â¶ 
Space
(n) print one or more spaces
 Param n
the number of spaces to print
Space()
prints one space on the current output. The second form printsn
spaces on the current output. The result is alwaysTrue
. Example
In> Space(5); Out> True;

NewLine
()Â¶ 
NewLine
(n) print one or more newline characters
 Param n
the number of newline characters to print
NewLine()
prints a newline character on the current output. The second form printsn
newlines on the current output. The result is alwaysTrue
. Example
In> NewLine(); Out> True;

FromFile
(name) bodyÂ¶ connect current input to a file
 Param name
name of the file to read
 Param body
expression to be evaluated
The current input is connected to the file
name
. Then the expressionbody
is evaluated. If some functions inbody
try to read from current input, they will read from the filename
. Finally, the file is closed and the result of evaluatingbody
is returned. Example
Suppose that the file
foo
contains2 + 5;
:In> FromFile("foo") res := Read(); Out> 2+5; In> FromFile("foo") res := ReadToken(); Out> 2;
See also

FromString
(str) bodyÂ¶ connect current input to a string
 Param str
a string containing the text to parse
 Param body
expression to be evaluated
The commands in
body
are executed, but every read is done from the stringstr
. The result of evaluatingbody
is returned. Example
In> FromString("2+5; this is never read") res := Read(); Out> 2+5; In> FromString("2+5; this is never read") res := Eval(Read()); Out> 7;
See also

ToFile
(name) bodyÂ¶ connect current output to a file
 Param name
name of the file to write the result to
 Param body
expression to be evaluated
The current output is connected to the file
name
. Then the expressionbody
is evaluated. Everything that the commands inbody
prints ends up in the filename
. Finally, the file is closed and the result of evaluatingbody
is returned. If the file is opened again, the old contents will be overwritten. This is a limitation ofToFile()
: one cannot append to a file that has already been created. Example
Here is how one can create a file with C code to evaluate an expression:
In> ToFile("expr1.c") WriteString(CForm(Sqrt(xy)*Sin(x))); Out> True;
The file
expr1.c
was created in the current working directory and it contains the linesqrt(xy)*sin(x)
.As another example, take a look at the following command:
In> [ Echo("Result:"); PrettyForm(Taylor(x,0,9) Sin(x)); ]; Result: 3 5 7 9 x x x x x   +    +  6 120 5040 362880 Out> True;
Now suppose one wants to send the output of this command to a file. This can be achieved as follows:
In> ToFile("out") [ Echo("Result:"); PrettyForm(Taylor(x,0,9) Sin(x)); ]; Out> True;
After this command the file
out
contains:Result: 3 5 7 9 x x x x x   +    +  6 120 5040 362880
See also
FromFile()
,ToString()
,Echo()
,Write()
,WriteString()
,PrettyForm()
,Taylor()

ToString
() bodyÂ¶ connect current output to a string
 Param body
expression to be evaluated
The commands in
body
are executed. Everything that is printed, byEcho()
for instance, is collected in a string and this string is returned. Example
In> str := ToString() [ WriteString("The square of 8 is "); Write(8^2); ]; Out> "The square of 8 is 64";
See also

Read
()Â¶ read an expression from current input
Read an expression from the current input, and return it unevaluated. When the end of an input file is encountered, the token atom {EndOfFile} is returned.
 Example
In> FromString("2+5;") Read(); Out> 2+5; In> FromString("") Read(); Out> EndOfFile;
See also

ToStdout
() bodyÂ¶ select initial output stream for output
 Param body
expression to be evaluated
When using
ToString()
orToFile()
, it might happen that something needs to be written to the (initial) standard output (typically the screen).ToStdout()
can be used to select this stream.

ReadCmdLineString
(prompt)Â¶ read an expression from command line and return in string
 Param prompt
string representing the prompt shown on screen
This function allows for interactive input similar to the command line. When using this function, the history from the command line is also available. The result is returned in a string, so it still needs to be parsed. This function will typically be used in situations where one wants a custom readevalprint loop.
 Example
The following defines a function that when invoked keeps asking for an expression (the read step), and then takes the derivative of it (the eval step) and then uses
PrettyForm()
to display the result (the print step):In> ReEvPr() := \ In> While(True) [ \ In> PrettyForm(Deriv(x) \ In> FromString(ReadCmdLineString("Deriv> "):";")Read()); \ In> ]; Out> True;
Then one can invoke the command, from which the following interaction might follow:
In> ReEvPr() Deriv> Sin(a^2*x/b) / 2 \  a * x  2 Cos   * a * b \ b /  2 b Deriv> Sin(x) Cos( x ) Deriv>
See also

LispRead
()Â¶ read expressions in LISP syntax
LispRead()
reads an expression in the LISP syntax from the current input, and returns it unevaluated. When the end of an input file is encountered, the special token atomEndOfFile
is returned. The yacas expressiona+b
is written in the LISP syntax as(+ a b)
. The advantage of this syntax is that it is less ambiguous than the infix operator grammar that yacas uses by default. Example
In> FromString("(+ a b)") LispRead(); Out> a+b; In> FromString("(List (Sin x) ( (Cos x)))") \ LispRead(); Out> {Sin(x),Cos(x)}; In> FromString("(+ a b)")LispRead() Out> a+b;
See also
FromFile()
,FromString()
,Read()
,ReadToken()
,FullForm()
,LispReadListed()

LispReadListed
()Â¶ read expressions in LISP syntax
LispReadListed()
reads a LISP expression and returns it in a list, instead of the form usual to yacas (expressions). The result can be thought of as applyingListify()
toLispRead()
. The functionLispReadListed()
is more useful for reading arbitrary LISP expressions, because the first object in a list can be itself a list (this is never the case for yacas expressions where the first object in a list is always a function atom). Example
In> FromString("(+ a b)")LispReadListed() Out> {+,a,b};
See also
FromFile()
,FromString()
,Read()
,ReadToken()
,FullForm()
,LispRead()

ReadToken
()Â¶ read a token from current input
Read a token from the current input, and return it unevaluated. The returned object is a Yacas atom (not a string). When the end of an input file is encountered, the token atom {EndOfFile} is returned. A token is for computer languages what a word is for human languages: it is the smallest unit in which a command can be divided, so that the semantics (that is the meaning) of the command is in some sense a combination of the semantics of the tokens. Hence {a := foo} consists of three tokens, namely {a}, {:=}, and {foo}. The parsing of the string depends on the syntax of the language. The part of the kernel that does the parsing is the â€śtokenizerâ€ť. Yacas can parse its own syntax (the default tokenizer) or it can be instructed to parse XML or C++ syntax using the directives {DefaultTokenizer} or {XmlTokenizer}. Setting a tokenizer is a global action that affects all {ReadToken} calls.
 Example
In> FromString("a := Sin(x)") While((tok := ReadToken()) != EndOfFile) Echo(tok); a := Sin ( x ) Out> True;
We can read some junk too:
In> FromString("$3")ReadToken(); Out> $;
The result is an atom with the string representation
$
. Yacas assumes that$
is an operator symbol yet to be defined. The3
will be in the next token. (The results will be different if a nondefault tokenizer is selected.)See also
FromFile()
,FromString()
,Read()
,LispRead()
,DefaultTokenizer()

Load
(name)Â¶ evaluate all expressions in a file
 Param name
name of the file to load
The file
name
is opened. All expressions in the file are read and evaluated.Load()
always returnsTrue
.See also
Use()
,DefLoad()
,DefaultDirectory()
,FindFile()

Use
(name)Â¶ load a file, but not twice
 Param name
name of the file to load
If the file
name
has been loaded before, either by an earlier call toUse()
or via theDefLoad()
mechanism, nothing happens. Otherwise all expressions in the file are read and evaluated.Use()
always returnsTrue
. The purpose of this function is to make sure that the file will at least have been loaded, but is not loaded twice.

DefLoad
(name)Â¶ load a
.def
file Param name
name of the file (without the
.def
suffix)
The suffix
.def
is appended toname
and the file with this name is loaded. It should contain a list of functions, terminated by a closing brace\}
(the endoflist delimiter). This tells the system to load the filename
as soon as the user calls one of the functions named in the file (if not done so already). This allows for faster startup times, since not all of the rules databases need to be loaded, just the descriptions on which files to load for which functions.

FindFile
(name)Â¶ find a file in the current path
 Param name
string, name of the file or directory to find
The result of this command is the full path to the file that would be opened when the command {Load(name)} would be invoked. This means that the input directories are subsequently searched for a file called â€śnameâ€ť. If such a file is not found, {FindFile} returns an empty string. {FindFile(â€śâ€ť)} returns the name of the default directory (the first one on the search path).
See also
Load()
,DefaultDirectory()

PatchLoad
(name)Â¶ execute commands between
<?
and?>
in file Param name
string, name of the file to â€śpatchâ€ť
PatchLoad()
loads in a file and outputs the contents to the current output. The file can contain blocks delimited by<?
and?>
. The piece of text between such delimiters is treated as a separate file with yacas instructions, which is then loaded and executed. All output of write statements in that block will be written to the same current output. This is similar to the way PHP works. You can have a static text file with dynamic content generated by yacas.See also

Nl
()Â¶ the newline character
This function returns a string with one element in it, namely a newline character. This may be useful for building strings to send to some output in the end.
 Example
In> WriteString("First line" : Nl() : "Second line" : Nl()); First line Second line Out> True;
See also

V
(expression)Â¶ set verbose output mode
 Param expression
expression to be evaluated in verbose mode
V()
will evaluate the expression in verbose mode. Various parts of yacas can show extra information about the work done while doing a calculation when usingV()
. In verbose mode,InVerboseMode()
will returnTrue
, otherwise it will returnFalse
. Example
In> OldSolve({x+2==0},{x}) Out> {{2}}; In> V(OldSolve({x+2==0},{x})) Entering OldSolve From x+2==0 it follows that x = 2 x+2==0 simplifies to True Leaving OldSolve Out> {{2}}; In> InVerboseMode() Out> False In> V(InVerboseMode()) Out> True
See also

InVerboseMode
()Â¶ check for verbose output mode
In verbose mode,
InVerboseMode()
will returnTrue
, otherwise it will returnFalse
. Example
In> InVerboseMode() Out> False In> V(InVerboseMode()) Out> True
See also
Echo()
,N()
,OldSolve()
,V()

XmlExplodeTag
(xmltext)Â¶ convert XML strings to tag objects
 Param xmltext
string containing some XML tokens
{XmlExplodeTag} parses the first XML token in {xmltext} and returns a Yacas expression. The following subset of XML syntax is supported currently:
{<TAG [options]>} â€“ an opening tag
{</TAG [options]>} â€“ a closing tag
{<TAG [options] />} â€“ an open/close tag
plain (nontag) text
The tag options take the form {paramname=â€ťvalueâ€ť}.
If given an XML tag, {XmlExplodeTag} returns a structure of the form {XmlTag(name,params,type)}. In the returned object, {name} is the (capitalized) tag name, {params} is an assoc list with the options (key fields capitalized), and type can be either â€śOpenâ€ť, â€śCloseâ€ť or â€śOpenCloseâ€ť.
If given a plain text string, the same string is returned.
 Example
In> XmlExplodeTag("some plain text") Out> "some plain text"; In> XmlExplodeTag("<a name=\"blah blah\" align=\"left\">") Out> XmlTag("A",{{"ALIGN","left"}, {"NAME","blah blah"}},"Open"); In> XmlExplodeTag("</p>") Out> XmlTag("P",{},"Close"); In> XmlExplodeTag("<br/>") Out> XmlTag("BR",{},"OpenClose");
See also

XmlTokenizer
()Â¶ select the default syntax tokenizer for parsing the input
A â€śtokenizerâ€ť is an internal routine in the kernel that parses the input into Yacas expressions. This affects all input typed in by a user at the prompt and also the input redirected from files or strings using {FromFile} and {FromString} and read using {Read} or {ReadToken}. The Yacas environment currently supports some experimental tokenizers for various syntaxes. {DefaultTokenizer} switches to the tokenizer used for default Yacas syntax. {XmlTokenizer} switches to an XML syntax. Note that setting the tokenizer is a global side effect. One typically needs to switch back to the default tokenizer when finished reading the special syntax. Care needs to be taken when kernel errors are raised during a nondefault tokenizer operation (as with any global change in the environment). Errors need to be caught with the {TrapError} function. The error handler code should reinstate the default tokenizer, or else the user will be unable to continue the session (everything a user types will be parsed using a nondefault tokenizer). When reading XML syntax, the supported formats are the same as those of {XmlExplodeTag}. The parser does not validate anything in the XML input. After an XML token has been read in, it can be converted into an Yacas expression with {XmlExplodeTag}. Note that when reading XML, any plain text between tags is returned as one token. Any malformed XML will be treated as plain text.
 Example
In> [XmlTokenizer(); q:=ReadToken(); \ DefaultTokenizer();q;] <a> Out> <a>;
Note that:
after switching to {XmlTokenizer} the {In>} prompt disappeared; the user typed {<a>} and the {Out>} prompt with the resulting expression appeared.
The resulting expression is an atom with the string representation {<a>}; it is not a string.
See also
OMRead()
, TrapError()
, XmlExplodeTag()
,
ReadToken()
, FromFile()
, FromString()

DefaultTokenizer
()Â¶ select the default syntax tokenizer for parsing the input
A â€śtokenizerâ€ť is an internal routine in the kernel that parses the input into Yacas expressions. This affects all input typed in by a user at the prompt and also the input redirected from files or strings using {FromFile} and {FromString} and read using {Read} or {ReadToken}. The Yacas environment currently supports some experimental tokenizers for various syntaxes. {DefaultTokenizer} switches to the tokenizer used for default Yacas syntax. {XmlTokenizer} switches to an XML syntax. Note that setting the tokenizer is a global side effect. One typically needs to switch back to the default tokenizer when finished reading the special syntax. Care needs to be taken when kernel errors are raised during a nondefault tokenizer operation (as with any global change in the environment). Errors need to be caught with the {TrapError} function. The error handler code should reinstate the default tokenizer, or else the user will be unable to continue the session (everything a user types will be parsed using a nondefault tokenizer). When reading XML syntax, the supported formats are the same as those of {XmlExplodeTag}. The parser does not validate anything in the XML input. After an XML token has been read in, it can be converted into an Yacas expression with {XmlExplodeTag}. Note that when reading XML, any plain text between tags is returned as one token. Any malformed XML will be treated as plain text.
See also
OMRead()
, TrapError()
, XmlExplodeTag()
,
ReadToken()
, FromFile()
, FromString()

OMForm
(expression)Â¶ convert Yacas expression to OpenMath
 Param expression
expression to convert
{OMForm} prints an OpenMath representation of the input parameter {expression} to standard output. If a Yacas symbol does not have a mapping defined by {OMDef}, it is translated to and from OpenMath as the OpenMath symbol in the CD â€śyacasâ€ť with the same name as it has in Yacas.
 Example
In> str:=ToString()OMForm(2+Sin(a*3)) Out> "<OMOBJ> <OMA> <OMS cd="arith1" name="plus"/> <OMI>2</OMI> <OMA> <OMS cd="transc1" name="sin"/> <OMA> <OMS cd="arith1" name="times"/> <OMV name="a"/> <OMI>3</OMI> </OMA> </OMA> </OMA> </OMOBJ> "; In> FromString(str)OMRead() Out> 2+Sin(a*3); In> OMForm(NotDefinedInOpenMath(2+3)) <OMOBJ> <OMA> <OMS cd="yacas" name="NotDefinedInOpenMath"/> <OMA> <OMS cd="arith1" name="plus"/> <OMI>2</OMI> <OMI>3</OMI> </OMA> </OMA> </OMOBJ> Out> True
See also

OMRead
()Â¶ read OpenMath expression and convert to Yacas
 Param expression
expression to convert
{OMRead} reads an OpenMath expression from standard input and returns a normal Yacas expression that matches the input OpenMath expression. If a Yacas symbol does not have a mapping defined by {OMDef}, it is translated to and from OpenMath as the OpenMath symbol in the CD â€śyacasâ€ť with the same name as it has in Yacas.
 Example
In> str:=ToString()OMForm(2+Sin(a*3)) Out> "<OMOBJ> <OMA> <OMS cd="arith1" name="plus"/> <OMI>2</OMI> <OMA> <OMS cd="transc1" name="sin"/> <OMA> <OMS cd="arith1" name="times"/> <OMV name="a"/> <OMI>3</OMI> </OMA> </OMA> </OMA> </OMOBJ> "; In> FromString(str)OMRead() Out> 2+Sin(a*3);
See also

OMDef
(yacasForm, cd, name)Â¶ define translations from Yacas to OpenMath and viceversa.
 Param yacasForm
string with the name of a Yacas symbol, or a Yacas expression
 Param cd
OpenMath Content Dictionary for the symbol
 Param name
OpenMath name for the symbol
 Param yacasToOM
rule for translating an application of that symbol in Yacas into an OpenMath expression
 Param omToYacas
rule for translating an OpenMath expression into an application of this symbol in Yacas
{OMDef} defines the translation rules for symbols between the Yacas representation and {OpenMath}. The first parameter, {yacasForm}, can be a string or an expression. The difference is that when giving an expression only the {omToYacas} translation is defined, and it uses the exact expression given. This is used for {OpenMath} symbols that must be translated into a whole subexpression in Yacas, such as {set1:emptyset} which gets translated to an empty list as follows: In> OMDef( {}, â€śset1â€ť,â€ťemptysetâ€ť ) Out> True In> FromString(â€ś<OMOBJ><OMS cd=â€ťset1â€ť name=â€ťemptysetâ€ť/></OMOBJ> â€ś)OMRead() Out> {} In> IsList(%) Out> True Otherwise, a symbol that is not inside an application (OMA) gets translated to the Yacas atom with the given name: In> OMDef( â€śEmptySetâ€ť, â€śset1â€ť,â€ťemptysetâ€ť ) Warning: the mapping for set1:emptyset was already defined as {} , but is redefined now as EmptySet Out> True In> FromString(â€ś<OMOBJ><OMS cd=â€ťset1â€ť name=â€ťemptysetâ€ť/></OMOBJ> â€ś)OMRead() Out> EmptySet The definitions for the symbols in the Yacas library are in the
*.rep
script subdirectories. In those modules for which the mappings are defined, there is a file called {om.ys} that contains the {OMDef} calls. Those files are loaded in {openmath.rep/om.ys}, so any new file must be added to the list there, at the end of the file. A rule is represented as a list of expressions. Since both OM and Yacas expressions are actually lists, the syntax is the same in both directions. There are two template forms that are expanded before the translation:{$}: this symbol stands for the translation of the symbol applied in the original expression.
{_path}: a path into the original expression (list) to extract an element, written as an underscore applied to an integer or a list of integers. Those integers are indexes into expressions, and integers in a list are applied recursively starting at the original expression. For example, {_2} means the second parameter of the expression, while {_{3,2,1}} means the first parameter of the second parameter of the third parameter of the original expression.
They can appear anywhere in the rule as expressions or subexpressions.
Finally, several alternative rules can be specified by joining them with the {} symbol, and each of them can be annotated with a postpredicate applied with the underscore {_} symbol, in the style of Yacasâ€™ simplification rules. Only the first alternative rule that matches is applied, so the more specific rules must be written first.
There are special symbols recognized by {OMForm} to output {OpenMath} constructs that have no specific parallel in Yacas, such as an OpenMath symbol having a {CD} and {name}: Yacas symbols have only a name. Those special symbols are:
{OMS(cd, name)}: {<OMS cd=â€ťcdâ€ť name=â€ťnameâ€ť>}
{OMA(f x y â€¦)}: {<OMA>f x y â€¦</OMA>}
{OMBIND(binderSymbol, bvars, expression)}: {<OMBIND>binderSymbol bvars expression</OMBIND>}, where {bvars} must be produced by using {OMBVAR(â€¦)}.
{OMBVAR(x y â€¦)}: {<OMBVAR>x y â€¦</OMBVAR>}
{OME(â€¦)}: {<OME>â€¦</OME>}
When translating from OpenMath to Yacas, we just store unknown symbols as {OMS(â€ścdâ€ť, â€śnameâ€ť)}. This way we donâ€™t have to bother defining bogus symbols for concepts that Yacas does not handle, and we can evaluate expressions that contain them.
 Example
In> OMDef( "Sqrt" , "arith1", "root", { :math:`, _1, 2 }, :math:`(_1)_(_2=2)  (_1^(1/_2)) ); Out> True In> OMForm(Sqrt(3)) <OMOBJ> <OMA> <OMS cd="arith1" name="root"/> <OMI>3</OMI> <OMI>2</OMI> </OMA> </OMOBJ> Out> True In> FromString("<OMOBJ><OMA><OMS cd=\"arith1\" name=\"root\"/><OMI>16</OMI><OMI>2</OMI></OMA></OMOBJ> ")OMRead() Out> Sqrt(16) In> FromString("<OMOBJ><OMA><OMS cd=\"arith1\" name=\"root\"/><OMI>16</OMI><OMI>3</OMI></OMA></OMOBJ> ")OMRead() Out> 16^(1/3) In> OMDef("Limit", "limit1", "limit", \ { :math:`, _2, OMS("limit1", "under"), OMBIND(OMS("fns1", "lambda"), OMBVAR(_1), _4) }_(_3=Left) \ { :math:`, _2, OMS("limit1", "above"), OMBIND(OMS("fns1", "lambda"), OMBVAR(_1), _4) }_(_3=Right) \ { :math:`, _2, OMS("limit1", "both_sides"), OMBIND(OMS("fns1", "lambda"), OMBVAR(_1), _3) }, \ { :math:`, _{3,2,1}, _1, Left, _{3,3}}_(_2=OMS("limit1", "below")) \ {$, _{3,2,1}, _1, Right, _{3,3}}_(_2=OMS("limit1", "above")) \ {$, _{3,2,1}, _1, _{3,3}} \ ); In> OMForm(Limit(x,0) Sin(x)/x) <OMOBJ> <OMA> <OMS cd="limit1" name="limit"/> <OMI>0</OMI> <OMS cd="limit1" name="both_sides"/> <OMBIND> <OMS cd="fns1" name="lambda"/> <OMBVAR> <OMV name="x"/> </OMBVAR> <OMA> <OMS cd="arith1" name="divide"/> <OMA> <OMS cd="transc1" name="sin"/> <OMV name="x"/> </OMA> <OMV name="x"/> </OMA> </OMBIND> </OMA> </OMOBJ> Out> True In> OMForm(Limit(x,0,Right) 1/x) <OMOBJ> <OMA> <OMS cd="limit1" name="limit"/> <OMI>0</OMI> <OMS cd="limit1" name="above"/> <OMBIND> <OMS cd="fns1" name="lambda"/> <OMBVAR> <OMV name="x"/> </OMBVAR> <OMA> <OMS cd="arith1" name="divide"/> <OMI>1</OMI> <OMV name="x"/> </OMA> </OMBIND> </OMA> </OMOBJ> Out> True In> FromString(ToString()OMForm(Limit(x,0,Right) 1/x))OMRead() Out> Limit(x,0,Right)1/x In> % Out> Infinity
PlottingÂ¶

Plot2D
(expr[, x0:x1][, option=value[, ...]])Â¶ 
Plot2D
({expr1, expr2, ..., exprn}[, x0:x1][, option=value[, ...]]) adaptive twodimensional plotting
 Param f(x)
unevaluated expression containing one variables (function to be plotted)
 Param list
list of functions to plot
 Param a}, {b
numbers, plotting range in the \(x\) coordinate
 Param option
atom, option name
 Param value
atom, number or string (value of option)
The routine
Plot2D()
performs adaptive plotting of one or several functions of one variable in the specified range. The result is presented as a line given by the equation \(y=f(x)\). Several functions can be plotted at once. Various plotting options can be specified. Output can be directed to a plotting program (the default is to use {data}) to a list of values. The function parameter {f(x)} must evaluate to a yacas expression containing at most one variable. (The variable does not have to be called {x}.) Also, {N(f(x))} must evaluate to a real (not complex) numerical value when given a numerical value of the argument {x}. If the function {f(x)} does not satisfy these requirements, an error is raised. Several functions may be specified as a list and they do not have to depend on the same variable, for example, {{f(x), g(y)}}. The functions will be plotted on the same graph using the same coordinate ranges. If you have defined a function which accepts a number but does not accept an undefined variable, {Plot2D} will fail to plot it. Use {NFunction} to overcome this difficulty. Data files are created in a temporary directory {/tmp/plot.tmp/} unless otherwise requested. File names and other information is printed if {InVerboseMode()} returnsTrue
on using {V()}. The current algorithm uses NewtonCotes quadratures and some heuristics for error estimation (see <yacasdoc://Algo/3/1/>). The initial grid of {points+1} points is refined between any grid points \(x0\), \(x1\) if the integral \(Integrate(x,a,b)f(x)\) is not approximated to the given precision by the existing grid. Default plotting range is {5:5}. Range can also be specified as {x= 5:5} (note the mandatory space separating â€ś{=}â€ť and â€ś{}â€ť); currently the variable name {x} is ignored in this case. Options are of the form {option=value}. Currently supported option names are: â€śpointsâ€ť, â€śprecisionâ€ť, â€śdepthâ€ť, â€śoutputâ€ť, â€śfilenameâ€ť, â€śyrangeâ€ť. Option values are either numbers or special unevaluated atoms such as {data}. If you need to use the names of these atoms in your script, strings can be used. Several option/value pairs may be specified (the function {Plot2D} has a variable number of arguments).{yrange}: the range of ordinates to use for plotting, e.g. {yrange=0:20}. If no range is specified, the default is usually to leave the choice to the plotting backend.
{points}: initial number of points (default 23) â€“ at least that many points will be plotted. The initial grid of this many points will be adaptively refined.
{precision}: graphing precision (default \(10^(6)\)). This is interpreted as the relative precision of computing the integral of \(f(x)Min(f(x))\) using the grid points. For a smooth, nonoscillating function this value should be roughly 1/(number of screen pixels in the plot).
{depth}: max. refinement depth, logarithmic (default 5) â€“ means there will be at most \(2^depth\) extra points per initial grid point.
{output}: name of the plotting backend. Supported names: {data} (default). The {data} backend will return the data as a list of pairs such as {{{x1,y1}, {x2,y2}, â€¦}}.
{filename}: specify name of the created data file. For example: {filename=â€ťdata1.txtâ€ť}. The default is the name {â€śoutput.dataâ€ť}. Note that if several functions are plotted, the data files will have a number appended to the given name, for example {data.txt1}, {data.txt2}.
Other options may be supported in the future.
The current implementation can deal with a singularity within the plotting range only if the function {f(x)} returns {Infinity}, {Infinity} or {Undefined} at the singularity. If the function {f(x)} generates a numerical error and fails at a singularity, {Plot2D} will fail if one of the grid points falls on thez singularity. (All grid points are generated by bisection so in principle the endpoints and the {points} parameter could be chosen to avoid numerical singularities.)
See also

Plot3DS
(expr[, option=value[, ...]])Â¶ 
Plot3DS
({expr1, expr2, ..., exprn}[, option=value[, ...]]) threedimensional (surface) plotting
The routine
Plot3DS()
performs adaptive plotting of a function of two variables in the specified ranges. The result is presented as a surface given by the equation \(z=f(x,y)\). Several functions can be plotted at once, by giving a list of functions. Various plotting options can be specified. Output can be directed to a plotting program (the default is to use {data}), to a list of values. The function parameter {f(x,y)} must evaluate to a Yacas expression containing at most two variables. (The variables do not have to be called {x} and {y}.) Also, {N(f(x,y))} must evaluate to a real (not complex) numerical value when given numerical values of the arguments {x}, {y}. If the function {f(x,y)} does not satisfy these requirements, an error is raised. Several functions may be specified as a list but they have to depend on the same symbolic variables, for example, {{f(x,y), g(y,x)}}, but not {{f(x,y), g(a,b)}}. The functions will be plotted on the same graph using the same coordinate ranges. If you have defined a function which accepts a number but does not accept an undefined variable, {Plot3DS} will fail to plot it. Use {NFunction} to overcome this difficulty. Data files are created in a temporary directory {/tmp/plot.tmp/} unless otherwise requested. File names and other information is printed if {InVerboseMode()} returnsTrue
on using {V()}. The current algorithm uses NewtonCotes cubatures and some heuristics for error estimation (see <yacasdoc://Algo/3/1/>). The initial rectangular grid of {xpoints+1}*{ypoints+1} points is refined within any rectangle where the integral of \(f(x,y)\) is not approximated to the given precision by the existing grid. Default plotting range is {5:5} in both coordinates. A range can also be specified with a variable name, e.g. {x= 5:5} (note the mandatory space separating â€ś{=}â€ť and â€ś{}â€ť). The variable name {x} should be the same as that used in the function {f(x,y)}. If ranges are not given with variable names, the first variable encountered in the function {f(x,y)} is associated with the first of the two ranges. Options are of the form {option=value}. Currently supported option names are â€śpointsâ€ť, â€śxpointsâ€ť, â€śypointsâ€ť, â€śprecisionâ€ť, â€śdepthâ€ť, â€śoutputâ€ť, â€śfilenameâ€ť, â€śxrangeâ€ť, â€śyrangeâ€ť, â€śzrangeâ€ť. Option values are either numbers or special unevaluated atoms such as {data}. If you need to use the names of these atoms in your script, strings can be used (e.g. {output=â€ťdataâ€ť}). Several option/value pairs may be specified (the function {Plot3DS} has a variable number of arguments).{xrange}, {yrange}: optionally override coordinate ranges. Note that {xrange} is always the first variable and {yrange} the second variable, regardless of the actual variable names.
{zrange}: the range of the \(z\) axis to use for plotting, e.g. {zrange=0:20}. If no range is specified, the default is usually to leave the choice to the plotting backend. Automatic choice based on actual values may give visually inadequate plots if the function has a singularity.
{points}, {xpoints}, {ypoints}: initial number of points (default 10 each) â€“ at least that many points will be plotted in each coordinate. The initial grid of this many points will be adaptively refined. If {points} is specified, it serves as a default for both {xpoints} and {ypoints}; this value may be overridden by {xpoints} and {ypoints} values.
{precision}: graphing precision (default \(0.01\)). This is interpreted as the relative precision of computing the integral of \(f(x,y)Min(f(x,y))\) using the grid points. For a smooth, nonoscillating function this value should be roughly 1/(number of screen pixels in the plot).
{depth}: max. refinement depth, logarithmic (default 3) â€“ means there will be at most \(2^depth\) extra points per initial grid point (in each coordinate).
{output}: name of the plotting backend. Supported names: {data} (default). The {data} backend will return the data as a list of triples such as {{{x1, y1, z1}, {x2, y2, z2}, â€¦}}.
Other options may be supported in the future.
The current implementation can deal with a singularity within the plotting range only if the function {f(x,y)} returns {Infinity}, {Infinity} or {Undefined} at the singularity. If the function {f(x,y)} generates a numerical error and fails at a singularity, {Plot3DS} will fail only if one of the grid points falls on the singularity. (All grid points are generated by bisection so in principle the endpoints and the {xpoints}, {ypoints} parameters could be chosen to avoid numerical singularities.)
The {filename} option is optional if using graphical backends, but can be used to specify the location of the created data file.
 Example
In> Plot3DS(a*b^2) Out> True; In> V(Plot3DS(Sin(x)*Cos(y),x=0:20, y=0:20,depth=3)) CachedConstant: Info: constant Pi is being recalculated at precision 10 CachedConstant: Info: constant Pi is being recalculated at precision 11 Plot3DS: using 1699 points for function Sin(x)*Cos(y) Plot3DS: max. used 8 subdivisions for Sin(x)*Cos(y) Plot3DS'datafile: created file '/tmp/plot.tmp/data1' Out> True;
See also
String manipulationÂ¶

StringMid'Set
(index, substring, string)Â¶ change a substring
 Param index
index of substring to get
 Param substring
substring to store
 Param string
string to store substring in
Set (change) a part of a string. It leaves the original alone, returning a new changed copy.
 Example
In> StringMid'Set(3,"XY","abcdef") Out> "abXYef";
See also

StringMid'Get
(index, length, string)Â¶ retrieve a substring
 Param index
index of substring to get
 Param length
length of substring to get
 Param string
string to get substring from
{StringMidâ€™Get} returns a part of a string. Substrings can also be accessed using the {[]} operator.
 Example
In> StringMid'Get(3,2,"abcdef") Out> "cd"; In> "abcdefg"[2 .. 4] Out> "bcd";
See also

Atom
("string")Â¶ convert string to atom
 Param â€śstringâ€ť
a string
Returns an atom with the string representation given as the evaluated argument. Example: {Atom(â€śfooâ€ť);} returns {foo}.
 Example
In> Atom("a") Out> a;
See also

String
(atom)Â¶ convert atom to string
 Param atom
an atom
{String} is the inverse of {Atom}: turns {atom} into {â€śatomâ€ť}.
 Example
In> String(a) Out> "a";
See also

ConcatStrings
(strings)Â¶ concatenate strings
 Param strings
one or more strings
Concatenates strings.
 Example
In> ConcatStrings("a","b","c") Out> "abc";
See also

PatchString
(string)Â¶ execute commands between
<?
and?>
in strings Param string
a string to patch
This function does the same as
PatchLoad()
, but it works on a string instead of on the contents of a text file. SeePatchLoad()
for more details. Example
In> PatchString("Two plus three is <? Write(2+3); ?> "); Out> "Two plus three is 5 ";
See also
Random numbersÂ¶
Simple interfaceÂ¶
Advanced interfaceÂ¶

RngCreate
()Â¶ 
RngCreate
(seed) 
RngCreate
([seed=seed][, engine=engine][, dist=dist]) 
RngCreate
({seed, engine, dist}) create a pseudorandom generator
RngCreate()
returns a list which is a wellformed RNG object. Its value should be saved in a variable and used to callRng()
andRngSeed()
.Engines:
default
advanced
Distributions:
default
(the same asflat
)flat
(uniform)gauss
(normal)

RngSeed
(r, seed)Â¶ (re)seed pseudorandom number generator
RngSeed()
reinitializes the RNG objectr
with the seed valueseed
. The seed value should be a positive integer.
See also

Rng
(r)Â¶ generate pseudorandom number
Rng(r)()
returns a floatingpoint random number between 0 and 1 and updates the RNG objectr
. (Currently, the Gaussian option makes a RNG return a complex random number instead of a real random number.)See also
Auxilliary functionsÂ¶

RandomIntegerMatrix
(rows, cols, from, to)Â¶ generate a matrix of random integers
This function generates a
rows x cols
matrix of random integers. All entries lie betweenfrom
andto
, including the boundaries, and are uniformly distributed in this interval. Example
In> PrettyForm( RandomIntegerMatrix(5,5,2^10,2^10) ) / \  ( 506 ) ( 749 ) ( 574 ) ( 674 ) ( 106 )     ( 301 ) ( 151 ) ( 326 ) ( 56 ) ( 277 )     ( 777 ) ( 761 ) ( 161 ) ( 918 ) ( 417 )     ( 518 ) ( 127 ) ( 136 ) ( 797 ) ( 406 )     ( 679 ) ( 854 ) ( 78 ) ( 503 ) ( 772 )  \ /
See also

RandomIntegerVector
(n, from, to)Â¶ generate a vector of random integers
This function generates a list with
n
random integers. All entries lie betweenfrom
andto
, including the boundaries, and are uniformly distributed in this interval. Example
In> RandomIntegerVector(4,3,3) Out> {0,3,2,2};
See also

RandomPoly
(var, deg, coefmin, coefmax)Â¶ construct a random polynomial
RandomPoly()
generates a random polynomial in the variablevar
, of degreedeg
, with integer coefficients ranging fromcoefmin
tocoefmax
(inclusive). The coefficients are uniformly distributed in this interval, and are independent of each other. Example
In> RandomPoly(x,3,10,10) Out> 3*x^3+10*x^24*x6; In> RandomPoly(x,3,10,10) Out> 2*x^38*x^2+8;
See also
Probability and StatisticsÂ¶
ProbabilityÂ¶
DistributionsÂ¶
Each distribution is represented as an entity. For each distribution known to
the system the consistency of parameters is checked. If the parameters for a
distribution are invalid, the functions return Undefined
. For example,
NormalDistribution(a,1)
evaluates to Undefined
, because of
negative variance.

BernoulliDistribution
(p)Â¶ Bernoulli distribution
 Param p
number, probability of an event in a single trial
A random variable has a Bernoulli distribution with probability
p
if it can be interpreted as an indicator of an event, wherep
is the probability to observe the event in a single trial. Numerical value ofp
must satisfy0 < p < 1
.See also

BinomialDistribution
(p, n)Â¶ binomial distribution
 Param p
number, probability to observe an event in single trial
 Param n
number of trials
Suppose we repeat a trial
n
times, the probability to observe an event in a single trial isp
and outcomes in all trials are mutually independent. Then the number of trials when the event occurred is distributed according to the binomial distribution. The probability of that isBinomialDistribution(p,n)
. Numerical value ofp
must satisfy0 < p < 1
. Numerical value ofn
must be a positive integer.See also

ChiSquareDistribution
(m)Â¶

DiscreteUniformDistribution
(a, b)Â¶

ExponentialDistribution
(l)Â¶

GeometricDistribution
(p)Â¶

NormalDistribution
(m, s2)Â¶

PoissonDistribution
(l)Â¶

tDistribution
(m)Â¶ Studentâ€™s \(t\) distribution
 Param m
number of degrees of freedom
FunctionsÂ¶

PDF
(dist, x)Â¶ probability density function
 Param dist
a distribution type
 Param x
a value of random variable
If
dist
is a discrete distribution, thenPDF()
returns the probability for a random variable with distributiondist
to take a value ofx
. Ifdist
is a continuous distribution, thenPDF
returns the density function at pointx
.See also
StatisticsÂ¶

ChiSquareTest
(observed, expected, params)Â¶ Pearsonâ€™s ChiSquare test
 Param observed
list of observed frequencies
 Param expected
list of expected frequencies
 Param params
number of estimated parameters
Chisquared test is intended to find out if our sample was drawn from a given distribution or not. To find this out, one has to calculate observed frequencies into certain intervals and expected ones. To calculate expected frequency the formula \(n_i=n p_i\) must be used, where \(p_i\) is the probability measure of \(i\)th interval, and \(n\) is the total number of observations. If any of the parameters of the distribution were estimated, this number is given as
params
. The function returns a list of three local substitution rules. First of them contains the test statistic, the second contains the value of the parameters, and the last one contains the degrees of freedom. The test statistic is distributed asChiSquareDistribution()
.
Special functionsÂ¶

Gamma
(x)Â¶ 
Note
Eulerâ€™s constant is represented by
gamma
in yacas. Example
In> Gamma(1.3) Out> Gamma(1.3); In> N(Gamma(1.3),30) Out> 0.897470696306277188493754954771; In> Gamma(1.5) Out> Sqrt(Pi)/2; In> N(Gamma(1.5),30); Out> 0.88622692545275801364908374167;
See also
()
,gamma

Zeta
(x)Â¶ 
 Example
In> Precision(30) Out> True; In> Zeta(1) Out> Infinity; In> Zeta(1.3) Out> Zeta(1.3); In> N(Zeta(1.3)) Out> 3.93194921180954422697490751058798; In> Zeta(2) Out> Pi^2/6; In> N(Zeta(2)); Out> 1.64493406684822643647241516664602;
See also
()

Bernoulli
(n)Â¶ 
Bernoulli
(n, x)

Euler
(n)Â¶ 
Euler
(n, x) Euler numbers and Euler polynomials
 Example
In> Euler(6) Out> 61; In> A:=Euler(5,x) Out> (x1/2)^5+(10*(x1/2)^3)/4+(25*(x1/2))/16; In> Simplify(A) Out> (2*x^55*x^4+5*x^21)/2;
See also

LambertW
(x)Â¶ Lambertâ€™s Wfunction
 Example
In> LambertW(0) Out> 0; In> N(LambertW(0.24/Sqrt(3*Pi))) Out> 0.0851224014;
See also
Number theoryÂ¶
This chapter describes functions that are of interest in number theory. These functions typically operate on integers. Some of these functions work quite slowly.

IsPrime
(n)Â¶ test for a prime number
 Param n
integer to test

IsComposite
(n)Â¶ test for a composite number
 Param n
positive integer

IsCoprime
(m, n)Â¶ test if integers are coprime
 Param m
positive integer
 Param n
positive integer
 Param list
list of positive integers

IsSquareFree
(n)Â¶ test for a squarefree number
 Param n
positive integer

IsPrimePower
(n)Â¶ test for a power of a prime number
 Param n
integer to test

NextPrime
(i)Â¶ generate a prime following a number
 Param i
integer value

IsTwinPrime
(n)Â¶ test for a twin prime
 Param n
positive integer

IsIrregularPrime
(n)Â¶ test for an irregular prime
 Param n
positive integer

IsCarmichaelNumber
(n)Â¶ test for a Carmichael number
 Param n
positive integer

Factors
(x)Â¶ factorization
 Param x
integer or univariate polynomial

IsAmicablePair
(m, n)Â¶ test for a pair of amicable numbers
 Param m
positive integer
 Param n
positive integer

Factor
(x)Â¶ factorization, in pretty form
 Param x
integer or univariate polynomial

Divisors
(n)Â¶ number of divisors
 Param n
positive integer

DivisorsSum
(n)Â¶ the sum of divisors
 Param n
positive integer

ProperDivisors
(n)Â¶ the number of proper divisors
 Param n
positive integer

ProperDivisorsSum
(n)Â¶ the sum of proper divisors
 Param n
positive integer

Moebius
(n)Â¶ the Moebius function
 Param n
positive integer

CatalanNumber
(n)Â¶ return the
n
th Catalan Number Param n
positive integer

FermatNumber
(n)Â¶ return the
n
th Fermat Number Param n
positive integer

HarmonicNumber
(n)Â¶ return the
n
th Harmonic Number Param n
positive integer
 Param r
positive integer

StirlingNumber1
(n, m)Â¶ return the
n,m
th Stirling Number of the first kind Param n
positive integers
 Param m
positive integers

StirlingNumber1
(n, m) return the
n,m
th Stirling Number of the second kind Param n
positive integer
 Param m
positive integer

DivisorsList
(n)Â¶ the list of divisors
 Param n
positive integer

SquareFreeDivisorsList
(n)Â¶ the list of squarefree divisors
 Param n
positive integer

MoebiusDivisorsList
(n)Â¶ the list of divisors and Moebius values
 Param n
positive integer

SumForDivisors
(var, n, expr)Â¶ loop over divisors
 Param var
atom, variable name
 Param n
positive integer
 Param expr
expression depending on
var

RamanujanSum
(k, n)Â¶ compute the Ramanujanâ€™s sum
 Param k
positive integer
 Param n
positive integer
This function computes the Ramanujanâ€™s sum, i.e. the sum of the
n
th powers of thek
th primitive roots of the unit:\[\sum_{l=1}^k\frac{\exp(2ln\pi\imath)}{k}\]where \(l\) runs thought the integers between 1 and
k1
that are coprime to \(l\). The computation is done by using the formula in T. M. Apostol, <i>Introduction to Analytic Theory</i> (SpringerVerlag), Theorem 8.6.Todo
check the definition

PAdicExpand
(n, p)Â¶ padic expansion
 Param n
number or polynomial to expand
 Param p
base to expand in

IsQuadraticResidue
(m, n)Â¶ functions related to finite groups
 Param m
integer
 Param n
odd positive integer

GaussianFactors
(z)Â¶ factorization in Gaussian integers
 Param z
Gaussian integer

GaussianNorm
(z)Â¶ norm of a Gaussian integer
 Param z
Gaussian integer

IsGaussianUnit
(z)Â¶ test for a Gaussian unit
 Param z
a Gaussian integer

IsGaussianPrime
(z)Â¶ test for a Gaussian prime
 Param z
a complex or real number

GaussianGcd
(z, w)Â¶ greatest common divisor in Gaussian integers
 Param z
Gaussian integer
 Param w
Gaussian integer
Numerical methodsÂ¶

NIntegrate
(x, x0, x1) exprÂ¶ numerical integration
 Param x
integration variable
 Param x0
lower integration limit
 Param x1
upper integration limit
 Param expr
integrand
Numerically integrate
expr
overx
fromx0
tox1
.See also
PhysicsÂ¶
Assorted physicsrelated functions
Quantum PhysicsÂ¶

ClebschGordan
({j1, m1}, {j2, m2}, {J, M})Â¶ ClebschGordan coefficient
Calculates the ClebschGordan coefficient \(\langle j_1m_1j_2m_2\vert JM\rangle\)
DebuggingÂ¶

TraceStack
(expression)Â¶ show calling stack after an error occurs
TraceStack()
shows the calling stack after an error occurred. It shows the last few items on the stack, not to flood the screen. These are usually the only items of interest on the stack. This is probably by far the most useful debugging function in yacas. It shows the last few things it did just after an error was generated somewhere.For each stack frame, it shows if the function evaluated was a builtin function or a userdefined function, and for the userdefined function, the number of the rule it is trying whether it was evaluating the pattern matcher of the rule, or the body code of the rule.
This functionality is not offered by default because it slows down the evaluation code.
Here is an example of a function calling itself recursively, causing yacas to flood its stack:
In> f(x):=f(Sin(x)) Out> True; In> TraceStack(f(2)) Debug> 982 : f (Rule # 0 in body) Debug> 983 : f (Rule # 0 in body) Debug> 984 : f (Rule # 0 in body) Debug> 985 : f (Rule # 0 in body) Debug> 986 : f (Rule # 0 in body) Debug> 987 : f (Rule # 0 in body) Debug> 988 : f (Rule # 0 in body) Debug> 989 : f (Rule # 0 in body) Debug> 990 : f (Rule # 0 in body) Debug> 991 : f (Rule # 0 in body) Debug> 992 : f (Rule # 0 in body) Debug> 993 : f (Rule # 0 in body) Debug> 994 : f (Rule # 0 in body) Debug> 995 : f (User function) Debug> 996 : Sin (Rule # 0 in pattern) Debug> 997 : IsList (Internal function) Error on line 1 in file [CommandLine] Max evaluation stack depth reached. Please use MaxEvalDepth to increase the stack size as needed.
See also

TraceExp
(expr)Â¶ evaluate with tracing enabled
The expression â€śexprâ€ť is evaluated with the tracing facility turned on. This means that every subexpression, which is evaluated, is shown before and after evaluation. Before evaluation, it is shown in the form {TrEnter(x)}, where {x} denotes the subexpression being evaluated. After the evaluation the line {TrLeave(x,y)} is printed, where {y} is the result of the evaluation. The indentation shows the nesting level.
Note that this command usually generates huge amounts of output. A more specific form of tracing (eg. {TraceRule}) is probably more useful for all but very simple expressions.
 Example
In> TraceExp(2+3); TrEnter(2+3); TrEnter(2); TrLeave(2, 2); TrEnter(3); TrLeave(3, 3); TrEnter(IsNumber(x)); TrEnter(x); TrLeave(x, 2); TrLeave(IsNumber(x),True); TrEnter(IsNumber(y)); TrEnter(y); TrLeave(y, 3); TrLeave(IsNumber(y),True); TrEnter(True); TrLeave(True, True); TrEnter(MathAdd(x,y)); TrEnter(x); TrLeave(x, 2); TrEnter(y); TrLeave(y, 3); TrLeave(MathAdd(x,y),5); TrLeave(2+3, 5); Out> 5;
See also

TraceRule
(template) exprÂ¶ turn on tracing for a particular function
 Param template
template showing the operator to trace
 Param expr
expression to evaluate with tracing on
The tracing facility is turned on for subexpressions of the form â€śtemplateâ€ť, and the expression â€śexprâ€ť is evaluated. The template â€śtemplateâ€ť is an example of the function to trace on. Specifically, all subexpressions with the same toplevel operator and arity as â€śtemplateâ€ť are shown. The subexpressions are displayed before (indicated with {TrEnter}) and after ({TrLeave}) evaluation. In between, the arguments are shown before and after evaluation ({TrArg}). Only functions defined in scripts can be traced.
This is useful for tracing a function that is called from within another function. This way you can see how your function behaves in the environment it is used in.
 Example
In> TraceRule(x+y) 2+3*5+4; TrEnter(2+3*5+4); TrEnter(2+3*5); TrArg(2, 2); TrArg(3*5, 15); TrLeave(2+3*5, 17); TrArg(2+3*5, 17); TrArg(4, 4); TrLeave(2+3*5+4, 21); Out> 21;
See also
MiscellaneousÂ¶

Time
(expr)Â¶ measure the time taken by a function
 Param expr
any expression
The function
Time()
evaluates the expressionexpr
and prints the time in seconds needed for the evaluation. The time is printed to the current output stream. The builtin functionGetTime()
is used for timing.The result is the â€śuser timeâ€ť as reported by the OS, not the real (â€śwall clockâ€ť) time. Therefore, any CPUintensive processes running alongside yacas will not significantly affect the result of
Time()
. Example
In> Time(N(MathLog(1000),40)) 0.34 seconds taken Out> 6.9077552789821370520539743640530926228033;
See also

SystemCall
(str)Â¶ pass a command to the shell
The command contained in the string
str
is executed by the underlying operating system. The return value ofSystemCall()
isTrue
orFalse
according to the exit code of the command.The
SystemCall()
function is not allowed in the body of theSecure()
command.In a UNIX environment, the command
SystemCall("ls")
would print the contents of the current directory:In> SystemCall("ls") AUTHORS COPYING ChangeLog ... (truncated to save space) Out> True;
The standard UNIX command
test
returns success or failure depending on conditions. For example, the following command will check if a directory exists:In> SystemCall("test d scripts/") Out> True;
Check that a file exists:
In> SystemCall("test f COPYING") Out> True; In> SystemCall("test f nosuchfile.txt") Out> False;
See also
Programming in YacasÂ¶
This part of the manual is a somewhat indepth explanation of the Yacas programming language and environment. It assumes that you have worked through the introductory tutorial. You should consult the function reference about how to use the various Yacas functions mentioned here.
This document should get you started programming in Yacas. There are some basic explanations and handson tutorials.
The Yacas architectureÂ¶
Yacas is designed as a small core engine that interprets a library of scripts. The core engine provides the syntax parser and a number of hardwired functions, such as {Set()} or {MathExp()} which cannot be redefined by the user. The script library resides in the scripts directory â€ś{scripts/}â€ť and contains higherlevel definitions of functions and constants. The library scripts are on equal footing with any code the user executes interactively or any files the user loads.
Generally, all core functions have plain names and almost all are not â€śbodiedâ€ť or infix operators. The file {corefunctions.h} in the source tree lists declarations of all kernel functions callable from Yacas; consult it for reference. For many of the core functions, the script library already provides convenient aliases. For instance, the addition operator â€ś{+}â€ť is defined in the script {scripts/standard} while the actual addition of numbers is performed through the builtin function {MathAdd}.
Startup, scripts and {.def} filesÂ¶
When Yacas is first started or restarted, it executes the script {yacasinit.ys} in the scripts directory. This script may load some other scripts. In order to start up quickly, Yacas does not execute all other library scripts at first run or at restart. It only executes the file {yacasinit.ys} and all {.def} files in the scripts. The {.def} files tell the system where it can find definitions for various library functions. Library is divided into â€śpackagesâ€ť stored in â€śrepositoryâ€ť directories. For example, the function {ArcTan} is defined in the {stdfuncs} package; the library file is {stdfuncs.rep/}{code.ys} and the {.def} file is {stdfuncs.rep}{/code.ys.def}. The function {ArcTan} mentioned in the {.def} file, therefore Yacas will know to load the package {stdfuncs} when the user invokes {ArcTan}. This way Yacas knows where to look for any given function without actually loading the file where the function is defined.
There is one exception to the strategy of delayed loading of the library scripts. Namely, the syntax definitions of infix, prefix, postfix and bodied functions, such as {Infix(â€ś*â€ť,4)} cannot be delayed (it is currently in the file {stdopers.ys}). If it were delayed, the Yacas parser would encounter {1+2} (typed by the user) and generate a syntax error before it has a chance to load the definition of the operator â€ś{+}â€ť.
Object typesÂ¶
Yacas supports two basic kinds of objects: atoms and compounds. Atoms are (integer or real, arbitraryprecision) numbers such as {2.71828}, symbolic variables such as {A3} and character strings. Compounds include functions and expressions, e.g. {Cos(ab)} and lists, e.g. {{1+a,2+b,3+c}}.
The type of an object is returned by the builtin function {Type}, for example:
In> Type(a);
Out> "";
In> Type(F(x));
Out> "F";
In> Type(x+y);
Out> "+";
In> Type({1,2,3});
Out> "List";
Internally, atoms are stored as strings and compounds as lists. (The Yacas lexical analyzer is casesensitive, so {List} and {list} are different atoms.) The functions {String()} and {Atom()} convert between atoms and strings. A Yacas list {{1,2,3}} is internally a list {(List 1 2 3)} which is the same as a function call {List(1,2,3)} and for this reason the â€śtypeâ€ť of a list is the string {â€śListâ€ť}. During evaluation, atoms can be interpreted as numbers, or as variables that may be bound to some value, while compounds are interpreted as function calls.
Note that atoms that result from an {Atom()} call may be invalid and never evaluate to anything. For example, {Atom(3X)} is an atom with string representation â€ś3Xâ€ť but with no other properties.
Currently, no other lowestlevel objects are provided by the core engine besides numbers, atoms, strings, and lists. There is, however, a possibility to link some externally compiled code that will provide additional types of objects. Those will be available in Yacas as â€śgeneric objects.â€ť For example, fixedsize arrays are implemented in this way.
Yacas evaluation schemeÂ¶
Evaluation of an object is performed either explicitly by the builtin command {Eval()} or implicitly when assigning variables or calling functions with the object as argument (except when a function does not evaluate that argument). Evaluation of an object can be explicitly inhibited using {Hold()}. To make a function not evaluate one of its arguments, a {HoldArg(funcname, argname)} must be declared for that function.
Internally, all expressions are either atoms or lists (perhaps nested). Use {FullForm()} to see the internal form of an expression. A Yacas list expression written as {{a, b}} is represented internally as {(List a b)}, equivalently to a function call {List(a,b)}.
Evaluation of an atom goes as follows: if the atom is bound locally as a variable, the object it is bound to is returned, otherwise, if it is bound as a global variable then that is returned. Otherwise, the atom is returned unevaluated. Note that if an atom is bound to an expression, that expression is considered as final and is not evaluated again.
Internal lists of atoms are generally interpreted in the following way: the first atom of the list is some command, and the atoms following in the list are considered the arguments. The engine first tries to find out if it is a builtin command (core function). In that case, the function is executed. Otherwise, it could be a userdefined function (with a â€śrule databaseâ€ť), and in that case the rules from the database are applied to it. If none of the rules are applicable, or if no rules are defined for it, the object is returned unevaluated.
Application of a rule to an expression transforms it into a different expression to which other rules may be applicable. Transformation by matching rules continues until no more rules are applicable, or until a â€śterminatingâ€ť rule is encountered. A â€śterminatingâ€ť rule is one that returns {Hold()} or {UnList()} of some expression. Calling these functions gives an unevaluated expression because it terminates the process of evaluation itself.
The main properties of this scheme are the following. When objects are assigned to variables, they generally are evaluated (except if you are using the {Hold()} function) because assignment {var := value} is really a function call to {Set(var, value)} and this function evaluates its second argument (but not its first argument). When referencing that variable again, the object which is its value will not be reevaluated. Also, the default behavior of the engine is to return the original expression if it could not be evaluated. This is a desired behavior if evaluation is used for simplifying expressions.
One major design flaw in Yacas (one that other functional languages like LISP also have) is that when some expression is reevaluated in another environment, the local variables contained in the expression to be evaluated might have a different meaning. In this case it might be useful to use the functions {LocalSymbols} and {TemplateFunction}. Calling
LocalSymbols(a,b)
a*b;
results in â€ś{a}â€ť and â€ś{b}â€ť in the multiplication being substituted with unique symbols that can not clash with other variables that may be used elsewhere. Use {TemplateFunction} instead of {Function} to define a function whose parameters should be treated as unique symbols.
Consider the following example:
In> f1(x):=Apply("+",{x,x});
Out> True
The function {f1} simply adds its argument to itself. Now calling this function with some argument:
In> f1(Sin(a))
Out> 2*Sin(a)
yields the expected result. However, if we pass as an argument an expression containing the variable {x}, things go wrong:
In> f1(Sin(x))
Out> 2*Sin(Sin(x))
This happens because within the function, {x} is bound to {Sin(x)}, and since it is passed as an argument to {Apply} it will be reevaluated, resulting in {Sin(Sin(x))}. {TemplateFunction} solves this by making sure the arguments can not collide like this (by using {LocalSymbols}:
In> TemplateFunction("f2",{x}) Apply("+",{x,x});
Out> True
In> f2(Sin(a))
Out> 2*Sin(a)
In> f2(Sin(x))
Out> 2*Sin(x)
In general one has to be careful when functions like {Apply}, {Map} or {Eval} (or derivatives) are used.
RulesÂ¶
Rules are special properties of functions that are applied when the function object is being evaluated. A function object could have just one rule bound to it; this is similar to a â€śsubroutineâ€ť having a â€śfunction bodyâ€ť in usual procedural languages. However, Yacas function objects can also have several rules bound to them. This is analogous of having several alternative â€śfunction bodiesâ€ť that are executed under different circumstances. This design is more suitable for symbolic manipulations.
A function is identified by its name as returned by {Type} and the number of arguments, or â€śarityâ€ť. The same name can be used with different arities to define different functions: {f(x)} is said to â€śhave arity 1â€ť and {f(x,y)} has arity 2. Each of these functions may possess its own set of specific rules, which we shall call a â€śrule databaseâ€ť of a function.
Each function should be first declared with the builtin command {RuleBase} as follows:
RuleBase("FunctionName",{argument list});
So, a new (and empty) rule database for {f(x,y)} could be created by typing {RuleBase(â€śfâ€ť,{x,y})}. The names for the arguments â€śxâ€ť and â€śyâ€ť here are arbitrary, but they will be globally stored and must be later used in descriptions of particular rules for the function {f}. After the new rulebase declaration, the evaluation engine of Yacas will begin to really recognize {f} as a function, even though no function body or equivalently no rules have been defined for it yet.
The shorthand operator {:=} for creating user functions that we illustrated in the tutorial is actually defined in the scripts and it makes the requisite call to the {RuleBase()} function. After a {RuleBase()} call you can specify parsing properties for the function; for example, you could make it an infix or bodied operator.
Now we can add some rules to the rule database for a function. A rule simply states that if a specific function object with a specific arity is encountered in an expression and if a certain predicate is true, then Yacas should replace this function with some other expression. To tell Yacas about a new rule you can use the builtin {Rule} command. This command is what does the real work for the somewhat more aesthetically pleasing {â€¦ # â€¦ <â€“ â€¦} construct we have seen in the tutorial. You do not have to call {RuleBase()} explicitly if you use that construct.
Here is the general syntax for a {Rule()} call:
Rule("foo", arity, precedence, pred) body;
This specifies that for function {foo} with given {arity} ({foo(a,b)} has arity 2), there is a rule that if {pred} is true, then {body} should be evaluated, and the original expression replaced by the result. Predicate and body can use the symbolic names of arguments that were declared in the {RuleBase} call.
All rules for a given function can be erased with a call to {Retract(funcname, arity)}. This is useful, for instance, when too many rules have been entered in the interactive mode. This call undefines the function and also invalidates the {RuleBase} declaration.
You can specify that function arguments are not evaluated before they are bound to the parameter: {HoldArg(â€śfooâ€ť,a)} would then declare that the a arguments in both {foo(a)} and {foo(a,b)} should not be evaluated before bound to {a}. Here the argument name {a} should be the same as that used in the {RuleBase()} call when declaring these functions. Inhibiting evaluation of certain arguments is useful for procedures performing actions based partly on a variable in the expression, such as integration, differentiation, looping, etc., and will be typically used for functions that are algorithmic and procedural by nature.
Rulebased programming normally makes heavy use of recursion and it is important to control the order in which replacement rules are to be applied. For this purpose, each rule is given a precedence. Precedences go from low to high, so all rules with precedence 0 will be tried before any rule with precedence 1.
You can assign several rules to one and the same function, as long as some of the predicates differ. If none of the predicates are true, the function is returned with its arguments evaluated.
This scheme is slightly slower for ordinary functions that just have
one rule (with the predicate True
), but it is a desired behavior for
symbolic manipulation. You can gradually build up your own functions,
incrementally testing their properties.
Examples of using rulesÂ¶
As a simple illustration, here are the actual {RuleBase()} and {Rule()} calls needed to define the factorial function:
In> RuleBase("f",{n});
Out> True;
In> Rule("f", 1, 10, n=0) 1;
Out> True;
In> Rule("f", 1, 20, IsInteger(n) And n>0) n*f(n1);
Out> True;
This definition is entirely equivalent to the one in the tutorial. {f(4)} should now return 24, while {f(a)} should return just {f(a)} if {a} is not bound to any value.
The {Rule} commands in this example specified two rules for function
{f} with arity 1: one rule with precedence 10 and predicate {n=0}, and
another with precedence 20 and the predicate that returns True
only
if {n} is a positive integer. Rules with lowest precedence get
evaluated first, so the rule with precedence 10 will be tried before
the rule with precedence 20. Note that the predicates and the body use
the name â€śnâ€ť declared by the {RuleBase()} call.
After declaring {RuleBase()} for a function, you could tell the parser to treat this function as a postfix operator:
In> Postfix("f");
Out> True;
In> 4 f;
Out> 24;
There is already a function {Function} defined in the standard scripts that allows you to construct simple functions. An example would be
Function ("FirstOf", {list}) list[1] ;
which simply returns the first element of a list. This could also have been written as
Function("FirstOf", {list})
[
list[1] ;
];
As mentioned before, the brackets {[ ]} are also used to combine multiple operations to be performed one after the other. The result of the last performed action is returned.
Finally, the function {FirstOf} could also have been defined by typing
FirstOf(list):=list[1] ;
Structured programming and control flowÂ¶
Some functions useful for control flow are already defined in Yacasâ€™s standard library. Letâ€™s look at a possible definition of a looping function {ForEach}. We shall here consider a somewhat simpleminded definition, while the actual {ForEach} as defined in the standard script â€ścontrolflowâ€ť is a little more sophisticated.
Function("ForEach",{foreachitem,
foreachlist,foreachbody})
[
Local(foreachi,foreachlen);
foreachlen:=Length(foreachlist);
foreachi:=0;
While (foreachi < foreachlen)
[
foreachi++;
MacroLocal(foreachitem);
MacroSet(foreachitem,
foreachlist[foreachi]);
Eval(foreachbody);
];
];
Bodied("ForEach");
UnFence("ForEach",3);
HoldArg("ForEach",foreachitem);
HoldArg("ForEach",foreachbody);
Functions like this should probably be defined in a separate file. You can load such a file with the command {Load(â€śfileâ€ť)}. This is an example of a macrolike function. Letâ€™s first look at the last few lines. There is a {Bodied(â€¦)} call, which states that the syntax for the function {ForEach()} is {ForEach(item,{list}) body;} â€“ that is, the last argument to the command {ForEach} should be outside its brackets. {UnFence(â€¦)} states that this function can use the local variables of the calling function. This is necessary, since the body to be evaluated for each item will probably use some local variables from that surrounding.
Finally, {HoldArg(â€śfunctionâ€ť,argument)} specifies that the argument â€ś{argument}â€ť should not be evaluated before being bound to that variable. This holds for {foreachitem} and {foreachbody}, since {foreachitem} specifies a variable to be set to that value, and {foreachbody} is the expression that should be evaluated after that variable is set.
Inside the body of the function definition there are calls to {Local(â€¦)}. {Local()} declares some local variable that will only be visible within a block {[ â€¦ ]}. The command {MacroLocal()} works almost the same. The difference is that it evaluates its arguments before performing the action on it. This is needed in this case, because the variable {foreachitem} is bound to a variable to be used as the loop iterator, and it is the variable it is bound to that we want to make local, not {foreachitem} itself. {MacroSet()} works similarly: it does the same as {Set()} except that it also first evaluates the first argument, thus setting the variable requested by the user of this function. The {Macro}â€¦ functions in the builtin functions generally perform the same action as their nonmacro versions, apart from evaluating an argument it would otherwise not evaluate.
To see the function in action, you could type:
ForEach(i,{1,2,3}) [Write(i); NewLine();];
This should print 1, 2 and 3, each on a new line.
Note: the variable names â€śforeachâ€¦â€ť have been chosen so they wonâ€™t get confused with normal variables you use. This is a major design flaw in this language. Suppose there was a local variable {foreachitem}, defined in the calling function, and used in {foreachbody}. These two would collide, and the interpreter would use only the last defined version. In general, when writing a function that calls {Eval()}, it is a good idea to use variable names that can not collide with userâ€™s variables. This is generally the single largest cause of bugs when writing programs in Yacas. This issue should be addressed in the future.
Additional syntactic sugarÂ¶
The parser is extended slightly to allow for fancier constructs.
Lists, e.g. {{a,b}}. This then is parsed into the internal notation {(List a b)} , but will be printed again as {{a,b};}
Statement blocks such as {[} statement1 {;} statement2{;];}. This is parsed into a Lisp object {(Prog} {(}statement1 {)} {(}statement2 {))}, and printed out again in the proper form.
Object argument accessors in the form of {expr[ index ]}. These are mapped internally to {Nth(expr,index)}. The value of {index}=0 returns the operator of the object, {index}=1 the first argument, etc. So, if {expr} is {foo(bar)}, then {expr[0]} returns {foo}, and {expr[1]} returns {bar}. Since lists of the form {{â€¦}} are essentially the same as {List(â€¦)}, the same accessors can be used on lists.
Function blocks such as
While (i < 10) [ Write(i); i:=i+1; ];
The expression directly following the {While(â€¦)} block is added as a last argument to the {While(â€¦)} call. So {While(a)b;} is parsed to the internal form {(While a b).}
This scheme allows coding the algorithms in an almost Clike syntax.
Strings are generally represented with quotes around them, e.g. â€śthis is a stringâ€ť. Backslash {} in a string will unconditionally add the next character to the string, so a quote can be added with {â€ś} (a backslashquote sequence).
Using â€śMacro rulesâ€ť (e.g. {NFunction})Â¶
The Yacas language allows to have rules whose definitions are generated at runtime. In other words, it is possible to write rules (or â€śfunctionsâ€ť) that, as a sideeffect, will define other rules, and those other rules will depend on some parts of the expression the original function was applied to.
This is accomplished using functions {MacroRuleBase}, {MacroRule}, {MacroRulePattern}. These functions evaluate their arguments (including the rule name, predicate and body) and define the rule that results from this evaluation.
Normal, â€śnonMacroâ€ť calls such as {Rule()} will not evaluate their arguments and this is a desired feature. For example, suppose we defined a new predicate like this,
RuleBase("IsIntegerOrString, {x});
Rule("IsIntegerOrString", 1, 1, True)
IsInteger(x) And IsString(x);
If the {Rule()} call were to evaluate its arguments, then the â€śbodyâ€ť
argument, {IsInteger(x) And IsString(x)}, would be evaluated to
False
since {x} is an atom, so we would have defined the predicate
to be always False
, which is not at all what we meant to do. For
this reason, the {Rule} calls do not evaluate their arguments.
Consider however the following situation. Suppose we have a function {f(arglist)} where {arglist} is its list of arguments, and suppose we want to define a function {Nf(arglist)} with the same arguments which will evaluate {f(arglist)} and return only when all arguments from {arglist} are numbers, and return unevaluated {Nf(arglist)} otherwise. This can of course be done by a usual rule such as
Rule("Nf", 3, 0, IsNumericList({x,y,z}))
< "f" @ {x,y,z};
Here {IsNumericList} is a predicate that checks whether all elements of a given list are numbers. (We deliberately used a {Rule} call instead of an easiertoread {<â€“} operator to make it easier to compare with what follows.)
However, this will have to be done for every function {f} separately. We would like to define a procedure that will define {Nf}, given any function {f}. We would like to use it like this:
NFunction("Nf", "f", {x,y,z});
After this function call we expect to be able to use the function {Nf}.
Here is how we could naively try to implement {NFunction} (and fail):
NFunction(new'name, old'name, arg'list) := [
MacroRuleBase(new'name, arg'list);
MacroRule(new'name, Length(arg'list), 0,
IsNumericList(arg'list)
)
new'name @ arg'list;
];
Now, this just does not do anything remotely right. {MacroRule}
evaluates its arguments. Since {argâ€™list} is an atom and not a list of
numbers at the time we are defining this, {IsNumericList(argâ€™list)}
will evaluate to False
and the new rule will be defined with a
predicate that is always False
, i.e. it will be never applied.
The right way to figure this out is to realize that the {MacroRule} call evaluates all its arguments and passes the results to a {Rule} call. So we need to see exactly what {Rule()} call we need to produce and then we need to prepare the arguments of {MacroRule} so that they evaluate to the right values. The {Rule()} call we need is something like this:
Rule("actual new name", <actual # of args>, 0,
IsNumericList({actual arg list})
) "actual new name" @ {actual arg list};
Note that we need to produce expressions such as {â€śnew nameâ€ť @ argâ€™list} and not results of evaluation of these expressions. We can produce these expressions by using {UnList()}, e.g.
UnList({Atom("@"), "Sin", {x}})
produces
"Sin" @ {x};
but not {Sin(x)}, and
UnList({IsNumericList, {1,2,x}})
produces the expression
IsNumericList({1,2,x});
which is not further evaluated.
Here is a second version of {NFunction()} that works:
NFunction(new'name, old'name, arg'list) := [
MacroRuleBase(new'name, arg'list);
MacroRule(new'name, Length(arg'list), 0,
UnList({IsNumericList, arg'list})
)
UnList({Atom("@"), old'name, arg'list});
];
Note that we used {Atom(â€ś@â€ť)} rather than just the bare atom {@} because {@} is a prefix operator and prefix operator names as bare atoms do not parse (they would be confused with applications of a prefix operator to what follows).
Finally, there is a more concise (but less general) way of defining {NFunction()} for functions with known number of arguments, using the backquoting mechanism. The backquote operation will first substitute variables in an expression, without evaluating anything else, and then will evaluate the resulting expression a second time. The code for functions of just one variable may look like this:
N1Function(new'name, old'name) :=
`( @new'name(x_IsNumber) < @old'name(x) );
This executes a little slower than the above version, because the backquote needs to traverse the expression twice, but makes for much more readable code.
Macro expansionÂ¶
Yacas supports macro expansion (backquoting). An expression can be
backquoted by putting a \`
in front of it. Within the backquoted
expression, all atoms that have a @
in front of them get replaced
with the value of that atom (treated as a variable), and then the
resulting expression is evaluated:
In> x:=y
Out> y
In> `(@x:=2)
Out> 2
In> x
Out> y
In> y
Out> 2
This is useful in cases where within an expression one subexpression is not evaluated. For instance, transformation rules can be built dynamically, before being declared. This is a particularly powerful feature that allows a programmer to write programs that write programs. The idea is borrowed from Lisp.
As the above example shows, there are similarities with the
Macro...
functions, that serve the same purpose for specific
expressions. For example, for the above code, one could also have
called MacroSet
:
In> MacroSet(x,3)
Out> True;
In> x
Out> y;
In> y
Out> 3;
The difference is that MacroSet
, and in general the Macro...
functions, are faster than their backquoted counterparts. This is
because with backquoting, first a new expression is built before it
is evaluated. The advantages of backquoting are readability and
flexibility (the number of Macro...
functions is limited, whereas
backquoting can be used anywhere).
When an @
operator is placed in front of a function call, the
function call is replaced:
In> plus:=Add
Out> Add;
In> `(@plus(1,2,3))
Out> 6;
Application of pure functions is also possible by using macro expansion:
In> pure:={{a,b},a+b};
Out> {{a,b},a+b};
In> ` @pure(2,3);
Out> 5;
Pure (nameless) functions are useful for declaring a temporary function, that has functionality depending on the current environment it is in, or as a way to call driver functions. In the case of drivers (interfaces to specific functionality), a variable can be bound to a function to be evaluated to perform a specific task. That way several drivers can be around, with one bound to the variables holding the functions that will be called.
Scope of variable bindingsÂ¶
When setting variables or retrieving variable values, variables are automatically bound global by default. You can explicitly specify variables to be local to a block such as a function body; this will make them invisible outside the block. Blocks have the form {[} statement1{;} statement2{;} {]} and local variables are declared by the {Local()} function.
When entering a block, a new stack frame is pushed for the local variables; it means that the code inside a block doesnâ€™t see the local variables of the caller either! You can tell the interpreter that a function should see local variables of the calling environment; to do this, declare UnFence(funcname, arity) on that function.
Evaluation of expressionsÂ¶
When programming in some language, it helps to have a mental model of what goes on behind the scenes when evaluating expressions, or in this case simplifying expressions.
This section aims to explain how evaluation (and simplification) of expressions works internally, in