Yacas user's function reference

DefaultDirectory , PrettyPrinter , Help , HistorySize .

Startup configuration

Yacas allows you to configure a few things at startup. The file ~/.yacasrc is written in the Yacas language and will be executed when Yacas is run. The following functions can be useful in the ~/.yacasrc file.


DefaultDirectory -- add directory to path for Yacas scripts

Internal function
Calling format:
DefaultDirectory(path)

Parameters:
path -- a string containing a full path where yacas script files reside

Description:
When loading files, yacas is also allowed to look in the folder "path". path will be prepended to the file name before trying to load the file. This means that "path" should end with a forward slash (under Unix-like operating systems).

Yacas first tries to load a file from the current directory, and otherwise it tries to load from directories defined with this function, in the order they are defined. Note there will be at least one directory specified at start-up time, defined during compilation. This is the directory Yacas searches for the initialization scripts and standard scripts.

Examples:
In> DefaultDirectory("/home/user/myscripts/");
Out> True;

See also:
Load , Use , DefLoad , FindFile .


PrettyPrinter -- set routine to use as pretty-printer

Standard library
Calling format:
PrettyPrinter(printer)

Parameters:
printer -- a string containing the name of a function that can "pretty-print" an expression

Description:
This function sets up the function printer to print out the results on the command line. This can be reset to the internal printer with PrettyPrinter().

Currently implemented prettyprinters are: PrettyForm, TeXForm, Print and DefaultPrint.

Examples:
In> Taylor(x,0,5)Sin(x)
Out> x-x^3/6+x^5/120;
In> PrettyPrinter("PrettyForm");

True

In> Taylor(x,0,5)Sin(x)

     3    5
    x    x
x - -- + ---
    6    120

In> PrettyPrinter();
Out> True;
In> Taylor(x,0,5)Sin(x)
Out> x-x^3/6+x^5/120;

See also:
PrettyForm , Write .*CMD MaxEvalDepth -- set depth of recursion stack
Internal function
Calling format:
MaxEvalDepth(n)
Parameters:
n -- integer
Description:
Sets the maximum depth of recursive function call. An error message is printed when too many recursive calls are executed, and this function can be used to increase or decrease the limit as necessary.


Help -- get documentation for some command

Standard library
Calling format:
Help()
Help(function)

Parameters:
function -- a string containing the name of a function to show help for

Description:
When help is requested by the user, by typing ?function or ??, the functions Help() (for ??) and Help(function) (for ?function) are called. By default, lynx is used as a browser (another recommended text-only browser is links). The help resides in the subdirectory documentation/ under the directory the math scripts were installed in. So the help files can be found using FindFile.

The function Help is auxiliary and should not be used to actually get online help.

Examples:
To use netscape for browsing help, enter the following commands:

Help(_f) <-- SystemCall("netscape " :
  FindFile("documentation/ref.html"):"#":f);
Help() := SystemCall("netscape " :
  FindFile("documentation/books.html"));

See also:
SystemCall , FindFile .


HistorySize -- set size of history file

Internal function
Calling format:
HistorySize(n)

Parameters:
n -- number of lines to store in history file

Description:
When exiting, yacas saves the command line history to a file ~/.yacas_history. By default it will only save the last 50 lines, to save space on the hard disk. This can be overridden with this function. Passing -1 tells the system to save all lines.

Examples:
In> HistorySize(200)
Out> True;
In> quit


+, -, *, /, ^ , Div, Mod , Gcd , Lcm , <<, >> , FromBase, ToBase , Precision , GetPrecision , N , Rationalize , IsPrime , IsComposite , IsCoprime , IsSquareFree , IsPrimePower , NextPrime , IsTwinPrime , IsIrregularPrime , IsCarmichaelNumber , Factors , IsAmicablePair , Factor , Divisors , DivisorsSum , ProperDivisors , ProperDivisorsSum , Moebius , CatalanNumber , FermatNumber , HarmonicNumber , StirlingNumber1 , StirlingNumber2 , IntLog , IntNthRoot , PAdicExpand , ContFrac , ContFracList, ContFracEval , GuessRational, NearRational , Decimal , TruncRadian , Floor , Ceil , Round , Pslq .

Arithmetic and other operations on numbers

Besides the usual arithmetical operations, Yacas defines some more advanced operations on numbers. Many of them also work on polynomials.


+, -, *, /, ^ -- arithmetic operations

Standard library
Calling format:
x+y  (precedence 6)
+x
x-y  (precedence 5)
-x
x*y  (precedence 3)
x/y  (precedence 3)
x^y  (precedence 2)

Parameters:
x and y -- objects for which arithmetic operations are defined

Description:
These are the basic arithmetic operations. They can work on integers, rational numbers, complex numbers, vectors, matrices and lists.

These operators are implemented in the standard math library (as opposed to being built-in). This means that they can be extended by the user.

Examples:
In> 2+3
Out> 5;
In> 2*3
Out> 6;


Div, Mod -- division with remainder

Standard library
Calling format:
Div(x,y)
Mod(x,y)

Parameters:
x, y -- integers or univariate polynomials

Description:
Div performs integer division and Mod returns the remainder after division. Div and Mod are also defined for polynomials.

If Div(x,y) returns "a" and Mod(x,y) equals "b", then these numbers satisfy x=a*y+b and 0<=b<y.

Examples:
In> Div(5,3)
Out> 1;
In> Mod(5,3)
Out> 2;

See also:
Gcd , Lcm .


Gcd -- greatest common divisor

Standard library
Calling format:
Gcd(n,m)
Gcd(list)

Parameters:
n, m -- integers or Gaussian integers or univariate polynomials

list -- a list of all integers or all univariate polynomials

Description:
This function returns the greatest common divisor of "n" and "m". The gcd is the largest number that divides "n" and "m". It is also known as the highest common factor (hcf). The library code calls MathGcd, which is an internal function. This function implements the "binary Euclidean algorithm" for determining the greatest common divisor:

Routine for calculating Gcd(n,m)

This is a rather fast algorithm on computers that can efficiently shift integers. When factoring Gaussian integers, a slower recursive algorithm is used.

If the second calling form is used, Gcd will return the greatest common divisor of all the integers or polynomials in "list". It uses the identity

Gcd(a,b,c)=Gcd(Gcd(a,b),c).

Examples:
In> Gcd(55,10)
Out> 5;
In> Gcd({60,24,120})
Out> 12;
In> Gcd( 7300 + 12*I, 2700 + 100*I)
Out> Complex(-4,4);

See also:
Lcm .


Lcm -- least common multiple

Standard library
Calling format:
Lcm(n,m)
Lcm(list)

Parameters:
n, m -- integers or univariate polynomials list -- list of integers

Description:
This command returns the least common multiple of "n" and "m" or all of the integers in the list list. The least common multiple of two numbers "n" and "m" is the lowest number which is an integer multiple of both "n" and "m". It is calculated with the formula

Lcm(n,m)=Div(n*m,Gcd(n,m)).

This means it also works on polynomials, since Div, Gcd and multiplication are also defined for them.

Examples:
In> Lcm(60,24)
Out> 120;
In> Lcm({3,5,7,9})
Out> 315;

See also:
Gcd .


<<, >> -- shift operators

Standard library
Calling format:
n<<m
n>>m

Parameters:
n, m -- integers

Description:
These operators shift integers to the left or to the right. They are similar to the C shift operators. These are sign-extended shifts, so they act as multiplication or division by powers of 2.

Examples:
In> 1 << 10
Out> 1024;
In> -1024 >> 10
Out> -1;


FromBase, ToBase -- conversion from/to non-decimal base

Internal function
Calling format:
FromBase(base,number)
ToBase(base,number)

Parameters:
base -- integer, base to write the numbers in

number -- integer, number to write out in the base representation

Description:
FromBase converts "number", written in base "base", to base 10. ToBase converts "number", written in base 10, to base "base".

These functions use the p-adic expansion capabilities of the built-in arbitrary precision math libraries.

Examples:
In> FromBase(2,111111)
Out> 63;
In> ToBase(16,255)
Out> ff;

The first command writes the binary number 111111 in decimal base. The second command converts 255 (in decimal base) to hexadecimal base.

See also:
PAdicExpand .


Precision -- set the precision

Internal function
Calling format:
Precision(n)

Parameters:
n -- integer, new precision

Description:
This command sets the number of binary digits to be used in calculations. All subsequent floating point operations will allow for at least n digits after the decimal point.

When the precision is changed, all variables containing previosly calculated values remain unchanged. The Precision function only makes all further calculations proceed with a different precision.

Examples:
In> Precision(10)
Out> True;
In> N(Sin(1))
Out> 0.8414709848;
In> Precision(20)
Out> True;
In> x:=N(Sin(1))
Out> 0.84147098480789650665;
In> GetPrecision()
Out> 20;
In> [ Precision(10); x; ]
Out> 0.84147098480789650665;
In> x+0
Out> 0.8414709848;

See also:
GetPrecision , N .


GetPrecision -- get the current precision

Internal function
Calling format:
GetPrecision()

Description:
This command returns the current precision, as set by Precision.

Examples:
In> GetPrecision();
Out> 10;
In> Precision(20);
Out> True;
In> GetPrecision();
Out> 20;

See also:
Precision , N .


N -- compute numerical approximation

Standard library
Calling format:
N(expr)
N(expr, prec)

Parameters:
expr -- expression to evaluate

prec -- integer, precision to use

Description:
This function forces Yacas to give a numerical approximation to the expression "expr", using "prec" digits if the second calling sequence is used, and the precision as set by SetPrecision otherwise. This overrides the normal behaviour, in which expressions are kept in symbolic form (eg. Sqrt(2) instead of 1.41421).

Application of the N operator will make Yacas calculate floating point representations of functions whenever possible. In addition, the variable Pi is bound to the value of Pi calculated at the current precision. (This value is a "cached constant", so it is not recalculated each time N is used, unless the precision is increased.)

Examples:
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:
Precision , GetPrecision , Pi , CachedConstant .


Rationalize -- convert floating point numbers to fractions

Standard library
Calling format:
Rationalize(expr)

Parameters:
expr -- an expression containing real numbers

Description:
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.

Examples:
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:
IsRational .


IsPrime -- test for a prime number

Standard library
Calling format:
IsPrime(n)

Parameters:
n -- integer to test

Description:
This command checks whether "n", which should be a positive integer, is a prime number. A number is a prime number if it is only divisible by 1 and itself. As a special case, 1 is not a prime number.

This function essentially checks for all integers between 2 and the square root of "n" whether they divide "n", and hence may take a long time for large numbers.

Examples:
In> IsPrime(1)
Out> False;
In> IsPrime(2)
Out> True;
In> IsPrime(10)
Out> False;
In> IsPrime(23)
Out> True;
In> Select("IsPrime", 1 .. 100)
Out> {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,
  53,59,61,67,71,73,79,83,89,97};

See also:
IsPrimePower , Factors .


IsComposite -- test for a composite number

Standard library
Calling format:
IsComposite(n)

Parameters:
n -- positive integer

Description:
This function is the logical negation of IsPrime, except for the number 1, which is neither prime nor composite.

Examples:
In> IsComposite(1)
Out> False;
In> IsComposite(7)
Out> False;
In> IsComposite(8)
Out> True;
In> Select(IsComposite,1...20)
Out> {4,6,8,9,10,12,14,15,16,18,20};

See also:
IsPrime .


IsCoprime -- test if integers are coprime

Standard library
Calling format:
IsCoprime(m,n)
IsCoprime(list)
Parameters:
m,n -- positive integers

list -- list of positive integers

Description:
This function returns True if the given pair or list of integers are coprime, also called relatively prime. A pair or list of numbers are coprime if they share no common factors.

Examples:
In> IsCoprime({3,4,5,8})
Out> False;
In> IsCoprime(15,17)
Out> True;

See also:
Prime .


IsSquareFree -- test for a square free number

Standard library
Calling format:
IsSquareFree(n)

Parameters:
n -- positive integer

Description:
This function uses the Moebius function to tell if the given number is square free, which means it has distinct prime factors. If Mobius(n)!=0, then n is square free. All prime numbers are trivially square free.

Examples:
In> IsSquareFree(37)
Out> True;
In> IsSquareFree(4)
Out> False;
In> IsSquareFree(16)
Out> False;
In> IsSquareFree(18)
Out> False;

See also:
Moebius .


IsPrimePower -- test for a power of a prime number

Standard library
Calling format:
IsPrimePower(n)

Parameters:
n -- integer to test

Description:
This command tests whether "n", which should be a positive integer, is a prime power, that is whether it is of the form p^m, with "p" prime and "m" an integer.

This function essentially checks for all integers between 2 and the square root of "n" for the largest divisor, and then tests whether "n" is a power of this divisor. So it will take a long time for large numbers.

Examples:
In> IsPrimePower(9)
Out> True;
In> IsPrimePower(10)
Out> False;
In> Select("IsPrimePower", 1 .. 50)
Out> {2,3,4,5,7,8,9,11,13,16,17,19,23,25,27,
  29,31,32,37,41,43,47,49};

See also:
IsPrime , Factors .


NextPrime -- generate a prime following a number

Standard library
Calling format:
NextPrime(i)

Parameters:
i -- integer value

Description:
The function finds the smallest prime number that is greater than the given integer value.

The routine generates "candidate numbers" using the formula n+2*Mod(-n,3) where n is an odd number (this generates the sequence 5, 7, 11, 13, 17, 19, ...) and IsPrime() to test whether the next candidate number is in fact prime.

Example:
In> NextPrime(5)
Out> 7;

See also:
IsPrime .


IsTwinPrime -- test for a twin prime

Standard library
Calling format:
IsTwinPrime(n)
Parameters:
n -- positive integer

Description:
This function returns True if n is a twin prime. By definition, a twin prime is a prime number n such that n+2 is also a prime number.

Examples:
In> IsTwinPrime(101)
Out> True;
In> IsTwinPrime(7)
Out> False;
In> Select(IsTwinPrime, 1...100)
Out> {3,5,11,17,29,41,59,71};

See also:
IsPrime .


IsIrregularPrime -- test for an irregular prime

Standard library
Calling format:
IsIrregularPrime(n)

Parameters:
n -- positive integer

Description:
This function returns True if n is an irregular prime. A prime number n is irregular if and only if n divides the numerator of a Bernoulli number B[2*i], where 2*i+1<n. Small irregular primes are quite rare; the only irregular primes under 100 are 37, 59 and 67. Asymptotically, roughly 40% of primes are irregular.

Examples:
In> IsIrregularPrime(5)
Out> False;
In> Select(IsIrregularPrime,1...100)
Out> {37,59,67};

See also:
IsPrime .


IsCarmichaelNumber -- test for a Carmichael number

Standard library
Calling format:
IsCarmichaelNumber(n)

Parameters:
n -- positive integer

Description:
This fuction returns True if n is a Carmichael number, also called an absolute pseudoprime. They have the property that b^(n-1)%n==1 for all b satisfying Gcd(b,n)==1. These numbers cannot be proved composite by Fermat's little theorem. Because the previous property is extremely slow to test, the following equivalent property is tested by Yacas: for all prime factors p[i] of n, (n-1)%(p[i]-1)==0 and n must be square free. Also, Carmichael numbers must be odd and have at least three prime factors. Although these numbers are rare (there are only 43 that are less than a million), it has recently been proven that there are infinitely many of them.

Examples:
In> IsCarmichaelNumber(561)
Out> True;
In> Time(Select(IsCarmichaelNumber,1 .. 10000))
504.19 seconds taken
Out> {561,1105,1729,2465,2821,6601,8911};

See also:
IsSquareFree , IsComposite .


Factors -- factorization

Standard library
Calling format:
Factors(x)

Parameters:
x -- integer or univariate polynomial

Description:
This function decomposes the integer number x into a product of numbers. Alternatively, if x is a univariate polynomial, it is decomposed in irreducible polynomials.

The factorization is returned as a list of pairs. The first member of each pair is the factor, while the second member denotes the power to which this factor should be raised. So the factorization x=p1^n1*...*p9^n9 is returned as {{p1,n1}, ..., {p9,n9}}.

Examples:
In> Factors(24);
Out> {{2,3},{3,1}};
In> Factors(2*x^3 + 3*x^2 - 1);
Out> {{2,1},{x+1,2},{x-1/2,1}};

See also:
Factor , IsPrime .


IsAmicablePair -- test for a pair of amicable numbers

Standard library
Calling format:
IsAmicablePair(m,n)

Parameters:
m, n -- positive integers

Description:
This function tests if a pair of numbers are amicable. A pair of numbers m, n has this property if the sum of the proper divisors of m is n and the sum of the proper divisors of n is m.

Examples:
In> IsAmicablePair(200958394875, 209194708485 )
Out> True;
In> IsAmicablePair(220, 284)
Out> True;

See also:
ProperDivisorsSum .


Factor -- factorization, in pretty form

Standard library
Calling format:
Factors(x)

Parameters:
x -- integer or univariate polynomial

Description:
This function factorizes "x", similarly to Factors, but it shows the result in a nicer human readable format.

Examples:
In> PrettyForm(Factor(24));

 3
2  * 3

Out> True;
In> PrettyForm(Factor(2*x^3 + 3*x^2 - 1));

             2   /     1 \
2 * ( x + 1 )  * | x - - |
                 \     2 /

Out> True;

See also:
Factors , IsPrime , PrettyForm .


Divisors -- number of divisors

Standard library
Calling format:
Divisors(n)
Parameters:
n -- positive integer

Description:
Divisors returns the number of positive divisors of a number. A number is prime if and only if it has two divisors, 1 and itself.

Examples:
In> Divisors(180)
Out> 18;
In> Divisors(37)
Out> 2;

See also:
DivisorsSum , ProperDivisors , ProperDivisorsSum , Moebius .


DivisorsSum -- the sum of divisors

Standard library
Calling format:
DivisorsSum(n)
Parameters:
n -- positive integer

Description:
DivisorsSum returns the sum all numbers that divide it. A number n is prime if and only if the sum of its divisors are n+1.

Examples:
In> DivisorsSum(180)
Out> 546;
In> DivisorsSum(37)
Out> 38;

See also:
DivisorsSum , ProperDivisors , ProperDivisorsSum , Moebius .


ProperDivisors -- the number of proper divisors

Standard library
Calling format:
ProperDivisors(n)
Parameters:
n -- positive integer

Description:
ProperDivisors returns the number of proper divisors, i.e Divisors(n)-1, since n is not counted. An integer n is prime if and only if it has 1 proper divisor.

Examples:
In> ProperDivisors(180)
Out> 17;
In> ProperDivisors(37)
Out> 1;

See also:
DivisorsSum , ProperDivisors , ProperDivisorsSum , Moebius .


ProperDivisorsSum -- the sum of proper divisors

Standard library
Calling format:
ProperDivisorsSum(n)
Parameters:
n -- positive integer

Description:
ProperDivisorsSum returns the sum of proper divisors, i.e. ProperDivisors(n)-n, since n is not counted. n is prime if and only if ProperDivisorsSum(n)==1.

Examples:
In> ProperDivisorsSum(180)
Out> 366;
In> ProperDivisorsSum(37)
Out> 1;

See also:
DivisorsSum , ProperDivisors , ProperDivisorsSum , Moebius .


Moebius -- the Moebius function

Standard library
Calling format:
Moebius(n)
Parameters:
n -- positive integer

Description:
The Moebius function is 0 when a prime factor is repeated (which means it is not square-free) and is (-1)^r if n has r distinct factors. Also, Moebius(1)==1.

Examples:
In> Moebius(10)
Out> 1;
In> Moebius(11)
Out> -1;
In> Moebius(12)
Out> 0;
In> Moebius(13)
Out> -1;

See also:
DivisorsSum , ProperDivisors , ProperDivisorsSum , Moebius .


CatalanNumber -- return the nth Catalan Number

Standard library
Calling format:
CatalanNumber(n)
Parameters:
n -- positive integer

Description:
This function returns the n-th Catalan number, defined as Bin(2*n,n)/(n+1).

Examples:
In> CatalanNumber(10)
Out> 16796;
In> CatalanNumber(5)
Out> 42;

See also:
Bin .


FermatNumber -- return the nth Fermat Number

Standard library
Calling format:
FermatNumber(n)
Parameters:
n -- positive integer

Description:
This function returns the n-th Fermat number, which is defined as 2^2^n+1.

Examples:
In> FermatNumber(7)
Out> 340282366920938463463374607431768211457;

See also:
Factor .


HarmonicNumber -- return the nth Harmonic Number

Standard library
Calling format:
HarmonicNumber(n)
HarmonicNumber(n,r)
Parameters:
n, r -- positive integers

Description:
This function returns the n-th Harmonic number, which is defined as Sum(k,1,n,1/k). If given a second argument, the Harmonic number of order r is returned, which is defined as Sum(k,1,n,k^(-r)).

Examples:
In> HarmonicNumber(10)
Out> 7381/2520;
In> HarmonicNumber(15)
Out> 1195757/360360;
In> HarmonicNumber(1)
Out> 1;
In> HarmonicNumber(4,3)
Out> 2035/1728;

See also:
Sum .


StirlingNumber1 -- return the n,mth Stirling Number of the first kind

Standard library
Calling format:
StirlingNumber1(n,m)
Parameters:
n, m -- positive integers

Description:
This function returns the signed Stirling Number of the first kind. All Stirling Numbers are integers. If m>n, then StirlingNumber1 returns 0.

Examples:
In> StirlingNumber1(10,5)
Out> -269325;
In> StirlingNumber1(3,6)
Out> 0;

See also:
StirlingNumber2 .


StirlingNumber2 -- return the n,mth Stirling Number of the second kind

Standard library
Calling format:
StirlingNumber1(n,m)
Parameters:
n, m -- positive integers

Description:
This function returns the Stirling Number of the second kind. All Stirling Numbers are positive integers. If m>n, then StirlingNumber2 returns 0.

Examples:
In> StirlingNumber2(3,6)
Out> 0;
In> StirlingNumber2(10,4)
Out> 34105;

See also:
StirlingNumber1 .


IntLog -- integer part of logarithm

Standard library
Calling format:
IntLog(n, base)

Parameters:
n, base -- positive integers

Description:
IntLog calculates the integer part of the logarithm of n in base base. The algorithm uses only integer math and may be faster than computing

Ln(n)/Ln(base)

with multiple precision floating-point math and rounding off to get the integer part.

This function can also be used to quickly count the digits in a given number.

Examples:
Count the number of bits:
In> IntLog(257^8, 2)
Out> 64;

Count the number of decimal digits:
In> IntLog(321^321, 10)
Out> 804;

See also:
IntNthRoot , Div , Mod , Ln .


IntNthRoot -- integer part of n-th root

Standard library
Calling format:
IntNthRoot(x, n)

Parameters:
x, n -- positive integers

Description:
IntNthRoot calculates the integer part of the n-th root of x. The algorithm uses only integer math and may be faster than computing x^(1/n) with floating-point and rounding.

This function is used to test numbers for prime powers.

Example:
In> IntNthRoot(65537^111, 37)
Out> 281487861809153;

See also:
IntLog , MathPower , IsPrimePower .


PAdicExpand -- p-adic expansion

Standard library
Calling format:
PAdicExpand(n, p)

Parameters:
n -- number or polynomial to expand

p -- base to expand in

Description:
This command computes the p-adic expansion of "n". In other words, "n" is expanded in powers of "p". The argument "n" can be either an integer or a univariate polynomial. The base "p" should be of the same type.

Examples:
In> PrettyForm(PAdicExpand(1234, 10));

               2     3
3 * 10 + 2 * 10  + 10  + 4

Out> True;
In> PrettyForm(PAdicExpand(x^3, x-1));

                             2            3
3 * ( x - 1 ) + 3 * ( x - 1 )  + ( x - 1 )  + 1

Out> True;

See also:
Mod , ContFrac , FromBase , ToBase .


ContFrac -- continued fraction expansion

Standard library
Calling format:
ContFrac(x)
ContFrac(x, depth)

Parameters:
x -- number or polynomial to expand in continued fractions

depth -- integer, maximum required depth of result

Description:
This command returns the continued fraction expansion of x, which should be either a floating point number or a polynomial. If depth is not specified, it defaults to 6. The remainder is denoted by rest.

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.

Examples:
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:
ContFracList , NearRational , GuessRational , PAdicExpand , N .


ContFracList, ContFracEval -- manipulate continued fractions

Standard library
Calling format:
ContFracList(frac)
ContFracList(frac, depth)
ContFracEval(list)
ContFracEval(list, rest)

Parameters:
frac -- a number to be expanded

depth -- desired number of terms

list -- a list of coefficients

rest -- expression to put at the end of the continued fraction

Description:
The function ContFracList computes terms of the continued fraction representation of a rational number frac. It returns a list of terms of length depth. If depth is not specified, it returns all terms.

The function ContFracEval converts a list of coefficients into a continued fraction expression. The optional parameter rest specifies the symbol to put at the end of the expansion. If it is not given, the result is the same as if rest=0.

Examples:
In> A:=ContFracList(33/7 + 0.000001)
Out> {4,1,2,1,1,20409,2,1,13,2,1,4,1,1,3,3,2};
In> ContFracEval(Take(A, 5))
Out> 33/7;
In> ContFracEval(Take(A,3), remainder)
Out> 1/(1/(remainder+2)+1)+4;

See also:
ContFrac , GuessRational .


GuessRational, NearRational -- find optimal rational approximations

Standard library
Calling format:
GuessRational(x)
GuessRational(x, digits)
NearRational(x)
NearRational(x, digits)

Parameters:
x -- a number to be approximated

digits -- desired number of decimal digits

Description:
The functions GuessRational(x) and NearRational(x) attempt to find "optimal" rational approximations to a given value x. The approximations are "optimal" in the sense of having smallest numerators and denominators among all rational numbers close to x. This is done by computing a continued fraction representation of x and truncating it at a suitably chosen term. Both functions return a rational number which is an approximation of x.

Unlike the function Rationalize() which converts floating-point numbers to rationals without loss of precision, the functions GuessRational() and NearRational() are intended to find the best rational that is approximately equal to a given value.

The function GuessRational() is useful if you have obtained a floating-point representation of a rational number and you know approximately how many digits its exact representation should contain. This function takes an optional second parameter digits which limits the number of decimal digits in the denominator of the resulting rational number. If this parameter is not given, it defaults to half the current precision. This function truncates the continuous fraction expansion when it encounters an unusually large value (see example). This procedure does not always give the "correct" rational number; a rule of thumb is that the floating-point number should have at least as many digits as the combined number of digits in the numerator and the denominator of the correct rational number.

The function NearRational(x) is useful if one needs to approximate a given value, i.e. to find an "optimal" rational number that lies in a certain small interval around a certain value x. This function takes an optional second parameter digits which has slightly different meaning: it specifies the number of digits of precision of the approximation; in other words, the difference between x and the resulting rational number should be at most one digit of that precision. The parameter digits also defaults to half of the current precision.

Examples:
Start with a rational number and obtain a floating-point approximation:
In> x:=N(956/1013)
Out> 0.9437314906
In> Rationalize(x)
Out> 4718657453/5000000000;
In> V(GuessRational(x))
GuessRational: using 10 terms of the
  continued fraction
Out> 956/1013;
In> ContFracList(x)
Out> {0,1,16,1,3,2,1,1,1,1,508848,3,1,2,1,2,2};
The first 10 terms of this continued fraction correspond to the correct continued fraction for the original rational number.
In> NearRational(x)
Out> 218/231;
This function found a different rational number closeby because the precision was not high enough.
In> NearRational(x, 10)
Out> 956/1013;

See also:
ContFrac , ContFracList , Rationalize .


Decimal -- decimal representation of a rational

Standard library
Calling format:
Decimal(frac)

Parameters:
frac -- a rational number

Description:
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.

Examples:
In> Decimal(1/22)
Out> {0,0,{4,5}};
In> N(1/22,30)
Out> 0.045454545454545454545454545454;

See also:
N .


TruncRadian -- remainder modulo 2*Pi

Standard library
Calling format:
TruncRadian(r)

Parameters:
r -- a number

Description:
TruncRadian calculates Mod(r,2*Pi), returning a value between 0 and 2*Pi. This function is used in the trigonometry functions, just before doing a numerical calculation using a Taylor series. It greatly speeds up the calculation if the value passed is a large number.

The library uses the formula

TruncRadian(r)=r-Floor(r/(2*Pi))*2*Pi,

where r and 2*Pi are calculated with twice the precision used in the environment to make sure there is no rounding error in the significant digits.

Examples:
In> 2*Pi()
Out> 6.283185307;
In> TruncRadian(6.28)
Out> 6.28;
In> TruncRadian(6.29)
Out> 0.0068146929;

See also:
Sin , Cos , Tan .


Floor -- round a number downwards

Standard library
Calling format:
Floor(x)

Parameters:
x -- a number

Description:
This function returns Floor(x), the largest integer smaller than or equal to x.

Examples:
In> Floor(1.1)
Out> 1;
In> Floor(-1.1)
Out> -2;

See also:
Ceil , Round .


Ceil -- round a number upwards

Standard library
Calling format:
Ceil(x)

Parameters:
x -- a number

Description:
This function returns Ceil(x), the smallest integer larger than or equal to x.

Examples:
In> Ceil(1.1)
Out> 2;
In> Ceil(-1.1)
Out> -1;

See also:
Floor , Round .


Round -- round a number to the nearest integer

Standard library
Calling format:
Round(x)

Parameters:
x -- a number

Description:
This function returns the integer closest to x. Half-integers (i.e. numbers of the form n+0.5, with n an integer) are rounded upwards.

Examples:
In> Round(1.49)
Out> 1;
In> Round(1.51)
Out> 2;
In> Round(-1.49)
Out> -1;
In> Round(-1.51)
Out> -2;

See also:
Floor , Ceil .


Pslq -- search for integer relations between reals

Standard library
Calling format:
Pslq(xlist,precision)

Parameters:
xlist -- list of numbers

precision -- required number of digits precision of calculation

Description:
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] + ... + a[n]*x[n]=0. The list of integer coefficients is returned.

The numbers in "xlist" must evaluate to floating point numbers if the N operator is applied on them.

Example:
In> Pslq({ 2*Pi+3*Exp(1), Pi, Exp(1) },20)
Out> {1,-2,-3};

Note: in this example the system detects correctly that 1*(2*Pi+3*e)+(-2)*Pi+(-3)*e=0.

See also:
N .


Sin, Cos, Tan , ArcSin, ArcCos, ArcTan , Exp , Ln , Sqrt , Abs , Sign , Complex , Re , Im , I , Conjugate , Arg , RootsOfUnity , !, !!, ***, Subfactorial , Bin , Eulerian , Add , Sum , Average , Factorize , Min , Max , IsZero , IsRational , Numer , Denom , Commutator , Taylor , InverseTaylor , ReversePoly , BigOh , Newton , D , Curl , Diverge , Integrate , Simplify , RadSimp , Rationalize , Solve , SuchThat , Eliminate , PSolve , Pi() , Random, RandomSeed , RngCreate, RngSeed, Rng , Limit , TrigSimpCombine , LagrangeInterpolant , Fibonacci .

Calculus and elementary functions

In this chapter, some facilities for doing calculus are described. These include functions implementing differentiation, integration, standard mathematical functions, and solving of equations.


Sin, Cos, Tan -- trigonometric functions

Standard library
Calling format:
Sin(x)
Cos(x)
Tan(x)

Parameters:
x -- argument to the function, in radians

Description:
These functions represent the trigonometric functions sine, cosine, and tangent respectively. Yacas leaves them alone even if x is a number, trying to keep the result as exact as possible. The floating point approximations of these functions can be forced by using the N function.

Yacas knows some trigonometric identities, so it can simplify to exact results even if N is not used. This is the case, for instance, when the argument is a multiple of Pi/6 or Pi/4.

These functions are threaded, meaning that if the argument x is a list, the function is applied to all entries in the list.

Examples:
In> Sin(1)
Out> Sin(1);
In> N(Sin(1),20)
Out> 0.84147098480789650665;
In> Sin(Pi/4)
Out> Sqrt(2)/2;

See also:
ArcSin , ArcCos , ArcTan , N , Pi .


ArcSin, ArcCos, ArcTan -- inverse trigonometric functions

Standard library
Calling format:
ArcSin(x)
ArcCos(x)
ArcTan(x)

Parameters:
x -- argument to the function

Description:
These functions represent the inverse trigonometric functions. For instance, the value of ArcSin(x) is the number y such that Sin(y) equals x.

Note that the number y is not unique. For instance, Sin(0) and Sin(Pi) both equal 0, so what should ArcSin(0) be? In Yacas, it is agreed that the value of ArcSin(x) should be in the interval [-Pi/2, Pi/2]. The same goes for ArcTan(x). However, ArcCos(x) is in the interval [0,Pi].

Usually, Yacas leaves these functions alone unless it is forced to do a numerical evaluation by the N function. If the argument is -1, 0, or 1 however, Yacas will simplify the expression. If the argument is complex, the expression will be rewritten using the Ln function.

These functions are threaded, meaning that if the argument x is a list, the function is applied to all entries in the list.

Examples:
In> ArcSin(1)
Out> Pi/2;

In> ArcSin(1/3)
Out> ArcSin(1/3);
In> Sin(ArcSin(1/3))
Out> 1/3;

In> N(ArcSin(0.75))
Out> 0.848062;
In> N(Sin(%))
Out> 0.7499999477;

See also:
Sin , Cos , Tan , N , Pi , Ln .


Exp -- exponential function

Standard library
Calling format:
Exp(x)

Parameters:
x -- argument to the function

Description:
This function calculates e raised to the power x, where e is the mathematic constant 2.71828... One can use Exp(1) to represent e.

This function is threaded, meaning that if the argument x is a list, the function is applied to all entries in the list.

Examples:
In> Exp(0)
Out> 1;
In> Exp(I*Pi)
Out> -1;
In> N(Exp(1))
Out> 2.7182818284;

See also:
Ln , Sin , Cos , Tan , N .


Ln -- natural logarithm

Standard library
Calling format:
Ln(x)

Parameters:
x -- argument to the function

Description:
This function calculates the natural logarithm of "x". This is the inverse function of the exponential function, Exp, i.e. Ln(x)=y implies that Exp(y)=x. For complex arguments, the imaginary part of the logarithm is in the interval (- Pi, Pi]. This is compatible with the branch cut of Arg.

This function is threaded, meaning that if the argument x is a list, the function is applied to all entries in the list.

Examples:
In> Ln(1)
Out> 0;
In> Ln(Exp(x))
Out> x;
In> D(x) Ln(x)
Out> 1/x;

See also:
Exp , Arg .


Sqrt -- square root

Standard library
Calling format:
Sqrt(x)

Parameters:
x -- argument to the function

Description:
This function calculates the square root of "x". If the result is not rational, the call is returned unevaluated unless a numerical approximation is forced with the N function. This function can also handle negative and complex arguments.

This function is threaded, meaning that if the argument x is a list, the function is applied to all entries in the list.

Examples:
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);

See also:
Exp , ^ , N .


Abs -- absolute value or modulus

Standard library
Calling format:
Abs(x)

Parameters:
x -- argument to the function

Description:
This function returns the absolute value (also called the modulus) of "x". If "x" is positive, the absolute value is "x" itself; if "x" is negative, the absolute value is "-x". For complex "x", the modulus is the "r" in the polar decomposition x=r*Exp(I*phi).

This function is connected to the Sign function by the identity "Abs(x) * Sign(x) = x" for real "x".

This function is threaded, meaning that if the argument x is a list, the function is applied to all entries in the list.

Examples:
In> Abs(2);
Out> 2;
In> Abs(-1/2);
Out> -1/2;
In> Abs(3+4*I);
Out> 5;

See also:
Sign , Arg .


Sign -- sign of a number

Standard library
Calling format:
Sign(x)

Parameters:
x -- argument to the function

Description:
This function returns the sign of the real number x. It is "1" for positive numbers and "-1" for negative numbers. Somewhat arbitrarily, Sign(0) is defined to be 1.

This function is connected to the Abs function by the identity Abs(x)*Sign(x)=x for real x.

This function is threaded, meaning that if the argument x is a list, the function is applied to all entries in the list.

Examples:
In> Sign(2)
Out> 1;
In> Sign(-3)
Out> -1;
In> Sign(0)
Out> 1;
In> Sign(-3) * Abs(-3)
Out> -3;

See also:
Arg , Abs .


Complex -- construct a complex number

Standard library
Calling format:
Complex(r, c)

Parameters:
r -- real part

c -- imaginary part

Description:
This function represents the complex number "r + I*c", where "I" is the imaginary unit. It is the standard representation used in Yacas to represent complex numbers. Both "r" and "c" are supposed to be real.

Note that, at the moment, many functions in Yacas assume that all numbers are real unless it is obvious that it is a complex number. Hence Im(Sqrt(x)) evaluates to 0 which is only true for nonnegative "x".

Examples:
In> I
Out> Complex(0,1);
In> 3+4*I
Out> Complex(3,4);
In> Complex(-2,0)
Out> -2;

See also:
Re , Im , I , Abs , Arg .


Re -- real part of a complex number

Standard library
Calling format:
Re(x)

Parameters:
x -- argument to the function

Description:
This function returns the real part of the complex number "x".

Examples:
In> Re(5)
Out> 5;
In> Re(I)
Out> 0;
In> Re(Complex(3,4))
Out> 3;

See also:
Complex , Im .


Im -- imaginary part of a complex number

Standard library
Calling format:
Im(x)

Parameters:
x -- argument to the function

Description:
This function returns the imaginary part of the complex number "x".

Examples:
In> Im(5)
Out> 0;
In> Im(I)
Out> 1;
In> Im(Complex(3,4))
Out> 4;

See also:
Complex , Re .


I -- imaginary unit

Standard library
Calling format:
I

Description:
This symbol represents the imaginary unit, which equals the square root of -1. It evaluates to Complex(0,1).

Examples:
In> I
Out> Complex(0,1);
In> I = Sqrt(-1)
Out> True;

See also:
Complex .


Conjugate -- complex conjugate

Standard library
Calling format:
Conjugate(x)

Parameters:
x -- argument to the function

Description:
This function returns the complex conjugate of "x". The complex conjugate of a+I*b is a-I*b. This function assumes that all unbound variables are real.

Examples:
In> Conjugate(2)
Out> 2;
In> Conjugate(Complex(a,b))
Out> Complex(a,-b);

See also:
Complex , Re , Im .


Arg -- argument of a complex number

Standard library
Calling format:
Arg(x)

Parameters:
x -- argument to the function

Description:
This function returns the argument of "x". The argument is the angle with the positive real axis in the Argand diagram, or the angle "phi" in the polar representation r*Exp(I*phi) of "x". The result is in the range (-Pi, Pi], that is, excluding -Pi but including Pi. The argument of 0 is Undefined.

Examples:
In> Arg(2)
Out> 0;
In> Arg(-1)
Out> Pi;
In> Arg(1+I)
Out> Pi/4;

See also:
Abs , Sign .


RootsOfUnity -- find the n complex roots of unity

Standard library
Calling format:
RootsOfUnity(n)

Parameters:
n -- positive integer

Description:
This function returns the list of n roots of unity. The first element of this list is the primitive n-th root of unity, and the last element is simply 1.

Examples:
In> RootsOfUnity(3)
Out> {Complex(-1/2,Sqrt(3/4)),Complex(-1/2,-Sqrt(3/4)),1};
In> RootsOfUnity(1)
Out> {1};
In> RootsOfUnity(2)
Out> {-1,1};

See also:
I , Complex .


!, !!, ***, Subfactorial -- factorial and related functions

Standard library
Calling format:
n!
n!!
a *** b
Subfactorial(m)

Parameters:
m -- integer n -- integer, half-integer, or list a, b -- numbers

Description:
The factorial function n! calculates the factorial of integer or half-integer numbers. For nonnegative integers, n! :=n*(n-1)*(n-2)*...*1. The factorial of half-integers 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*(n-2)*(n-4)*.... 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 a*(a+1)*... which is terminated at the least integer not greater than b. The arguments a and b do not have to be integers; for integer arguments, a *** b = b! /(a-1)!. 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 non-letter 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 LnGammaNum() to evaluate logarithms of such factorials to desired precision.

Examples:
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 .


Bin -- binomial coefficients

Standard library
Calling format:
Bin(n, m)

Parameters:
n, m -- integers

Description:
This function calculates the binomial coefficient "n" above "m", which equals

n! /(m! *(n-m)!)

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.

Examples:
In> Bin(10, 4)
Out> 210;
In> 10! / (4! * 6!)
Out> 210;

See also:
! , Eulerian .


Eulerian -- Eulerian numbers

Standard library
Calling format:
Eulerian(n,m)

Parameters:
n, m --- integers

Description:
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)*(k-j+1)^n)

.

Examples:
In> Eulerian(6,2)
Out> 302;
In> Eulerian(10,9)
Out> 1;

See also:
Bin .


Add -- find sum of a list of values

Standard library
Calling format:
Add(val1, val2, ...)
Add({list})

Parameters:
val1, val2 -- epressions

{list} -- list of expressions to add

Description:
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.

Examples:
In> Add(1,4,9);
Out> 14;
In> Add(1 .. 10);
Out> 55;

See also:
Average .


Sum -- find sum of a sequence

Standard library
Calling format:
Sum(var, from, to, body)

Parameters:
var -- variable to iterate over

from -- integer value to iterate from

to -- integer value to iterate up to

body -- expression to evaluate for each iteration

Description:
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.

Examples:
In> Sum(i, 1, 3, i^2);
Out> 14;

See also:
Factorize .


Average -- average of a list of values

Standard library
Calling format:
Average(list)

Parameters:
list -- list of values to average

Description:
This command calculates the (arithmetical) average of all the entries in "list", which is the sum of all entries divided by the number of entries.

Examples:
In> Average({1,2,3,4,5});
Out> 3;
In> Average({2,6,7});
Out> 5;

See also:
Add .


Factorize -- product of a list of values

Standard library
Calling format:
Factorize(list)
Factorize(var, from, to, body)

Parameters:
list -- list of values to multiply

var -- variable to iterate over

from -- integer value to iterate from

to -- integer value to iterate up to

body -- expression to evaluate for each iteration

Description:
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".

Examples:
In> Factorize({1,2,3,4});
Out> 24;
In> Factorize(i, 1, 4, i);
Out> 24;

See also:
Sum , Apply .


Min -- minimum of a number of values

Standard library
Calling format:
Min(x,y)
Min(list)

Parameters:
x, y -- pair of values to determine the minimum of

list -- list of values from which the minimum is sought

Description:
This function returns the minimum value of its argument(s). If the first calling sequence is used, the smaller of "x" and "y" is returned. If one uses the second form, the smallest of the entries in "list" is returned. In both cases, this function can only be used with numerical values and not with symbolic arguments.

Examples:
In> Min(2,3);
Out> 2;
In> Min({5,8,4});
Out> 4;

See also:
Max , Sum , Average .


Max -- maximum of a number of values

Standard library
Calling format:
Max(x,y)
Max(list)

Parameters:
x, y -- pair of values to determine the maximum of

list -- list of values from which the maximum is sought

Description:
This function returns the maximum value of its argument(s). If the first calling sequence is used, the larger of "x" and "y" is returned. If one uses the second form, the largest of the entries in "list" is returned. In both cases, this function can only be used with numerical values and not with symbolic arguments.

Examples:
In> Max(2,3);
Out> 3;
In> Max({5,8,4});
Out> 8;

See also:
Min , Sum , Average .


IsZero -- test whether argument is zero

Standard library
Calling format:
IsZero(n)

Parameters:
n -- number to test

Description:
IsZero(n) evaluates to True if "n" is zero. In case "n" is not a number, the function returns False.

Examples:
In> IsZero(3.25)
Out> False;
In> IsZero(0)
Out> True;
In> IsZero(x)
Out> False;

See also:
IsNumber , IsNotZero .


IsRational -- test whether argument is a rational

Standard library
Calling format:
IsRational(expr)

Parameters:
expr -- expression to test

Description:
This commands tests whether the expression "expr" is a rational number. This is the case if the top-level operator of "expr" is /.

Examples:
In> IsRational(5)
Out> False;
In> IsRational(2/7)
Out> True;
In> IsRational(a/b)
Out> True;
In> IsRational(x + 1/x)
Out> False;

See also:
Numer , Denom .


Numer -- numerator of an expression

Standard library
Calling format:
Numer(expr)

Parameters:
expr -- expression to determine numerator of

Description:
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. If "expr" is neither rational nor numeric, the function returns unevaluated.

Examples:
In> Numer(2/7)
Out> 2;
In> Numer(a / x^2)
Out> a;
In> Numer(5)
Out> 5;

See also:
Denom , IsRational , IsNumber .


Denom -- denominator of an expression

Standard library
Calling format:
Denom(expr)

Parameters:
expr -- expression to determine denominator of

Description:
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 returns 1. If "expr" is neither rational nor numeric, the function returns unevaluated.

Examples:
In> Denom(2/7)
Out> 7;
In> Denom(a / x^2)
Out> x^2;
In> Denom(5)
Out> 1;

See also:
Numer , IsRational , IsNumber .


Commutator -- commutator of two objects

Standard library
Calling format:
Commutator(a, b)

Parameters:
a, b -- two objects whose commutator should be computed

Description:
This command computes the commutator of 'a" and "b", i.e. the expression "a b - b a". For numbers and other objects for which multiplication is commutative, the commutator is zero. But this is not necessarily the case for matrices.

Examples:
In> Commutator(2,3)
Out> 0;
In> PrettyPrinter("PrettyForm");

True

In> A := { {0,x}, {0,0} }

/              \
| ( 0 ) ( x )  |
|              |
| ( 0 ) ( 0 )  |
\              /

In> B := { {y,0}, {0,z} }

/              \
| ( y ) ( 0 )  |
|              |
| ( 0 ) ( z )  |
\              /

In> Commutator(A,B)

/                          \
| ( 0 ) ( x * z - y * x )  |
|                          |
| ( 0 ) ( 0 )              |
\                          /


Taylor -- univariate Taylor series expansion

Standard library
Calling format:
Taylor(var, at, order) expr

Parameters:
var -- variable

at -- point to get Taylor series around

order -- order of approximation

expr -- expression to get Taylor series for

Description:
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".

Examples:
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 -- Taylor expansion of inverse

Standard library
Calling format:
InverseTaylor(var, at, order) expr

Parameters:
var -- variable

at -- point to get inverse Taylor series around

order -- order of approximation

expr -- expression to get inverse Taylor series for

Description:
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.

Examples:
In> PrettyPrinter("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(exp1-exp2)

0

See also:
ReversePoly , Taylor , BigOh .


ReversePoly -- solve h(f(x))=g(x)+O(x^n) for h

Standard library
Calling format:
ReversePoly(f, g, var, newvar, degree)

Parameters:
f, g -- functions of "var"

var -- a variable

newvar -- a new variable to express the result in

degree -- the degree of the required solution

Description:
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 "degree-1". 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".

Examples:
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*(x-1)^7)/131072+(791*(x-1)^6)
/32768 +(-119*(x-1)^5)/4096+(37*(x-1)^4)
/1024+(-3*(x-1)^3)/64+(x-1)^2/16;

See also:
InverseTaylor , Taylor , BigOh .


BigOh -- drop all terms of a certain order in a polynomial

Standard library
Calling format:
BigOh(poly, var, degree)

Parameters:
poly -- a univariate polynomial

var -- a free variable

degree -- positive integer

Description:
This function drops all terms of order "degree" or higher in "poly", which is a polynomial in the variable "var".

Examples:
In> BigOh(1+x+x^2+x^3,x,2)
Out> x+1;

See also:
Taylor , InverseTaylor .


Newton -- solve an equation numerically with Newton's method

Standard library
Calling format:
Newton(expr, var, initial, accuracy)
Newton(expr, var, initial, accuracy,min,max)

Parameters:
expr -- an expression to find a zero for

var -- free variable to adjust to find a zero

initial -- initial value for "var" to use in the search

accuracy -- minimum required accuracy of the result

min -- minimum value for "var" to use in the search

max -- maximum value for "var" to use in the search

Description:
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.

Examples:
In> Newton(Sin(x),x,3,0.0001)
Out> 3.1415926535;
In> Newton(x^2-1,x,2,0.0001,-5,5)
Out> 1;
In> Newton(x^2+1,x,2,0.0001,-5,5)
Out> Fail;

See also:
Solve , NewtonNum .


D -- differentiation

Standard library
Calling format:
D(var) expr
D(list) expr
D(var,n) expr

Parameters:
var -- variable

list -- a list of variables

expr -- expression to take derivatives of

n -- order of derivative

Description:
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 the 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.

Examples:
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 -- curl of a vector field

Standard library
Calling format:
Curl(vector, basis)

Parameters:
vector -- vector field to take the curl of

basis -- list of variables forming the basis

Description:
This function takes the curl of the vector field "vector" with respect to the variables "basis". 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]
}
Both "vector" and "basis" should be lists of length 3.

Example:
In> Curl({x*y,x*y,x*y},{x,y,z})
Out> {x,-y,y-x};

See also:
D , Diverge .


Diverge -- divergence of a vector field

Standard library
Calling format:
Diverge(vector, basis)

Parameters:
vector -- vector field to calculate the divergence of

basis -- list of variables forming the basis

Description:
This function calculates the divergence of the vector field "vector" with respect to the variables "basis". The divergence is defined as

Diverge(f,x) = D(x[1]) f[1] + ...
    + D(x[n]) f[n],
where n is the length of the lists "vector" and "basis". These lists should have equal length.

Example:
In> Diverge({x*y,x*y,x*y},{x,y,z})
Out> y+x;

See also:
D , Curl .


Integrate -- integration

Standard library
Calling format:
Integrate(var, x1, x2) expr
Integrate(var) expr

Parameters:
var -- atom, variable to integrate over

x1 -- first point of definite integration

x2 -- second point of definite integration

expr -- expression to integrate

Description:
This function integrates the expression expr with respect to the variable var. The first calling format is used to perform definite integration: the integration is carried out from var=x1 to var=x2". The second form is for indefinite integration.

Some simple integration rules have currently been implemented. Polynomials, quotients of polynomials, the functions Sin, Cos, Exp, and Ln, and products of these functions with polynomials can be integrated.

Examples:
In> Integrate(x,a,b) Cos(x)
Out> Sin(b)-Sin(a);
In> Integrate(x) Cos(x)
Out> Sin(x)+C9;

See also:
D , UniqueConstant .


Simplify -- try to simplify an expression

Standard library
Calling format:
Simplify(expr)

Parameters:
expr -- expression to simplify

Description:
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.

Examples:
In> a*b*a^2/b-a^3
Out> (b*a^3)/b-a^3;
In> Simplify(a*b*a^2/b-a^3)
Out> 0;

See also:
TrigSimpCombine , RadSimp .


RadSimp -- simplify expression with nested radicals

Standard library
Calling format:
RadSimp(expr)

Parameters:
expr -- an expression containing nested radicals

Description:
This function tries to write the expression "expr" as a sum of roots of integers: Sqrt(e1)+Sqrt(e2)+..., where e1, e2 and so on are natural numbers. The expression "expr" may not contain free variables.

It does this by trying all possible combinations for e1, e2, ... Every possibility is numerically evaluated using N and compared with the numerical evaluation of "expr". If the approximations are equal (up to a certain margin), this possibility is returned. Otherwise, the expression is returned unevaluated.

Note that due to the use of numerical approximations, there is a small chance that the expression returned by RadSimp is close but not equal to expr. The last example underneath illustrates this problem. Furthermore, if the numerical value of expr is large, the number of possibilities becomes exorbitantly big so the evaluation may take very long.

Examples:
In> RadSimp(Sqrt(9+4*Sqrt(2)))
Out> Sqrt(8)+1;
In> RadSimp(Sqrt(5+2*Sqrt(6)) \
  +Sqrt(5-2*Sqrt(6)))
Out> Sqrt(12);
In> RadSimp(Sqrt(14+3*Sqrt(3+2
*Sqrt(5-12*Sqrt(3-2*Sqrt(2))))))
Out> Sqrt(2)+3;

But this command may yield incorrect results:

In> RadSimp(Sqrt(1+10^(-6)))
Out> 1;

See also:
Simplify , N .


Rationalize -- convert floating point numbers to fractions

Standard library
Calling format:
Rationalize(expr)

Parameters:
expr -- an expression containing real numbers

Description:
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.

Examples:
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:
IsRational .


Solve -- solve one or more algebraic equations

Standard library
Calling format:
Solve(eq, var)
Solve(eqlist, varlist)

Parameters:
eq -- single identity equation

var -- single variable

eqlist -- list of identity equations

varlist -- list of variables

Description:
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.

Examples:
In> Solve(a+x*y==z,x)
Out> (z-a)/y;
In> Solve({a*x+y==0,x+z==0},{x,y})
Out> {{-z,z*a}};

This means that "x = (z-a)/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 Solve cannot solve:

In> Solve({x^2-x == y^2-y,x^2-x == y^3+y},{x,y});
Out> {};

See also:
SuchThat , Eliminate , PSolve , == .


SuchThat -- find a value which makes some expression zero

Standard library
Calling format:
SuchThat(expr, var)

Parameters:
expr -- expression to make zero

var -- variable (or subexpression) to solve for

Description:
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.

Examples:
In> SuchThat(a+b*x, x)
Out> (-a)/b;
In> SuchThat(Cos(a)+Cos(b)^2, Cos(b))
Out> Cos(a)^(1/2);
In> Expand(a*x+b*x+c, x)
Out> (a+b)*x+c;
In> SuchThat(%, x)
Out> (-c)/(a+b);

See also:
Solve , Subst , Simplify .


Eliminate -- substitute and simplify

Standard library
Calling format:
Eliminate(var, value, expr)

Parameters:
var -- variable (or subexpression) to substitute

value -- new value of "var"

expr -- expression in which the substitution should take place

Description:
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.

Examples:
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:
SuchThat , Subst , Simplify .


PSolve -- solve a polynomial equation

Standard library
Calling format:
PSolve(poly, var)

Parameters:
poly -- a polynomial in "var"

var -- a variable

Description:
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 one-entry 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.

Examples:
In> PSolve(b*x+a,x)
Out> -a/b;
In> PSolve(c*x^2+b*x+a,x)
Out> {(Sqrt(b^2-4*c*a)-b)/(2*c),(-(b+
Sqrt(b^2-4*c*a)))/(2*c)};

See also:
Solve , Factor .


Pi() -- numerical approximation of Pi

Internal function
Calling format:
Pi()

Description:
This commands returns the value of the mathematical constant pi at the current precision, as set by Precision. Usually this function should not be called directly. The constant Pi can (and should) be used to represent the exact value of pi, as it is recognized by the simplification rules. When the function N is invoked on an expression, Pi will be replaced with the value returned by Pi().

Examples:
In> Pi()
Out> 3.14159265358979323846;
In> Sin(3*Pi/2)
Out> -1;
In> Sin(3*Pi()/2)
Out> Sin(4.7123889804);
In> Precision(35)
Out> True;
In> Pi()
Out> 3.14159265358979323846264338327950288;

See also:
N , Pi , Precision .


Random, RandomSeed -- (pseudo-)random number generator

Standard library
Calling format:
Random()
RandomSeed(init)

*PARAMS init -- positive integer, initial random seed

Description:
The function Random returns a random number, uniformly distributed in the interval between 0 and 1. The same sequence of random numbers is generated in every Yacas session.

The random number generator can be initialized by calling RandomSeed with an integer value. Each seed value will result in the same sequence of pseudo-random numbers.

See also:
RandomInteger , RandomPoly , Rng .


RngCreate, RngSeed, Rng -- manipulate random number generators as objects

Standard library
Calling format:
RngCreate()
RngCreate(init)
RngCreate(option=value,...)
RngSeed(r, init)
Rng(r)

Parameters:
init -- integer, initial seed value

option -- atom, option name

value -- atom, option value

r -- a list, RNG object

Description:
These commands are an object-oriented interface to (pseudo-)random number generators (RNGs).

RngCreate returns a list which is a well-formed RNG object. Its value should be saved in a variable and used to call Rng and RngSeed.

Rng(r) returns a floating-point random number between 0 and 1 and updates the RNG object r. (Currently, the Gaussian option makes a RNG return a complex random number instead of a real random number.)

RngSeed(r,init) re-initializes the RNG object r with the seed value init. The seed value should be a positive integer.

The RngCreate function accepts several options as arguments. Currently the following options are available:

If the initial seed is not specified, the value of 76544321 will be used.

The gauss option will create a RNG object that generates pairs of Gaussian distributed random numbers as a complex random number. The real and the imaginary parts of this number are independent random numbers taken from a Gaussian (i.e. "normal") distribution with unit variance.

Note that unlike the global Random function, the RNG objects created with RngCreate are independent RNGs and do not affect each other. They generate independent streams of pseudo-random numbers. However, the Random function is slightly faster.

Examples:
In> r1:=RngCreate(seed=1,dist=gauss)
Out> {"GaussianRNGDist","RNGEngine'LCG'2",{1}}
In> Rng(r1)
Out> Complex(-1.6668466417,0.228904004);
In> Rng(r1);
Out> Complex(0.0279296109,-0.5382405341);
The second RNG gives a uniform distribution (default option) but uses a more complicated algorithm:
In> [r2:=RngCreate(engine=advanced);Rng(r2);]
Out> 0.3653615377;
The generator r1 can be re-initialized with seed 1 again to obtain the same sequence:
In> RngSeed(r1, 1)
Out> True;
In> Rng(r1)
Out> Complex(-1.6668466417,0.228904004);


See also:
Random .


Limit -- limit of an expression

Standard library
Calling format:
Limit(var, val) expr
Limit(var, val, dir) expr

Parameters:
var -- a variable

val -- a number

dir -- a direction (Left or Right)

expr -- an expression

Description:
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.

Examples:
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;


TrigSimpCombine -- combine products of trigonometric functions

Standard library
Calling format:
TrigSimpCombine(expr)

Parameters:
expr -- expression to simplify

Description:
This function applies the product rules of trigonometry, e.g. Cos(u)*Sin(v)=1/2*(Sin(v-u)+Sin(v+u)). As a result, all products of the trigonometric functions Cos and Sin 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 instance Integrate, to bring down the expression into a simpler form that hopefully can be integrated easily.

Examples:
In> PrettyPrinter("PrettyForm");

True

In> TrigSimpCombine(Cos(a)^2+Sin(a)^2)

1

In> TrigSimpCombine(Cos(a)^2-Sin(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:
Simplify , Integrate , Expand , Sin , Cos , Tan .


LagrangeInterpolant -- polynomial interpolation

Standard library
Calling format:
LagrangeInterpolant(xlist, ylist, var)

Parameters:
xlist -- list of argument values

ylist -- list of function values

var -- free variable for resulting polynomial

Description:
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.

Examples:
In> f := LagrangeInterpolant({0,1,2}, \
  {0,1,1}, x);
Out> (x*(x-1))/2-x*(x-2);
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("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:
Subst .


Fibonacci -- Fibonacci sequence

Standard library
Calling format:
Fibonacci(n)

Parameters:
n -- an integer

Description:
This command calculates and returns the "n"-th Fibonacci number.

The Fibonacci sequence is 1, 1, 2, 3, 5, 8, 13, 21, ... where every number is the sum of the two preceding numbers. Formally, it is defined by F(1)=1, F(2)=1, and F(n+1)=F(n)+F(n-1), where F(n) denotes the n-th Fibonacci number.

Examples:
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};


Gamma, GammaNum , Zeta, ZetaNum , Bernoulli, BernoulliArray , Euler , LambertW, LambertWNum , gamma , GoldenRatio , Catalan .

Special functions

In this chapter, special and transcendental mathematical functions are described.


Gamma, GammaNum -- Euler's Gamma function

Standard library
Calling format:
Gamma(x)
GammaNum(number)

Parameters:
x -- expression

number -- expression that can be evaluated to a number

Description:
Gamma(x) is an interface to Euler's Gamma function Gamma(x). It returns exact values on integer and half-integer arguments. GammaNum(x) or equivalently N(Gamma(x) takes a numeric parameter and always returns a floating-point number in the current precision.

Note that Euler's constant gamma<=>0.57722 is the lowercase gamma in Yacas.

Examples:
In> Precision(30)
Out> True;
In> Gamma(1.3)
Out> Gamma(1.3);
In> N(%)
Out> 0.897470696306277188493754954771;
In> Gamma(1.5)
Out> Sqrt(Pi)/2;
In> GammaNum(1.5);
Out> 0.88622692545275801364908374167;

See also:
! , N , gamma .


Zeta, ZetaNum -- Riemann's Zeta function

Standard library
Calling format:
Zeta(x)
ZetaNum(number)

Parameters:
x -- expression

number -- expression that can be evaluated to a number

Description:
Zeta(x) is an interface to Riemann's Zeta function zeta(s). It returns exact values on integer and half-integer arguments. ZetaNum(x) or equivalently N(Zeta(x) takes a numeric parameter and always returns a floating-point number in the current precision.

Examples:
In> Precision(30)
Out> True;
In> Zeta(1)
Out> Infinity;
In> Zeta(1.3)
Out> Zeta(1.3);
In> N(%)
Out> 3.93194921180954422697490751058798;
In> Zeta(2)
Out> Pi^2/6;
In> ZetaNum(2);
Out> 1.64493406684822643647241516664602;

See also:
! , N .


Bernoulli, BernoulliArray -- Bernoulli numbers and polynomials

Standard library
Calling format:
Bernoulli(index)
BernoulliArray(index)
Bernoulli(index, x)

Parameters:
x -- expression that will be the variable in the polynomial

index -- expression that can be evaluated to an integer

Description:
Bernoulli(n) evaluates the n-th Bernoulli number. Bernoulli(n, x) returns the n-th Bernoulli polynomial in the variable x. The polynomial is returned in the Horner form.

An auxiliary function BernoulliArray(n) might be useful too: it returns an array (of type GenericArray) of Bernoulli numbers up to n. The array is 1-based, so that the n-th Bernoulli number is BernoulliArray(n)[n+1].

Example:
In> Bernoulli(20);
Out> -174611/330;
In> Bernoulli(4, x);
Out> ((x-2)*x+1)*x^2-1/30;

See also:
Gamma , Zeta .


Euler -- Euler numbers and polynomials

Standard library
Calling format:
Euler(index)
Euler(index,x)

Parameters:
x -- expression that will be the variable in the polynomial

index -- expression that can be evaluated to an integer

Description:
Euler(n) evaluates the n-th Euler number. Euler(n,x) returns the n-th Euler polynomial in the variable x.

Examples:
In> Euler(6)
Out> -61;
In> Euler(5,x)
Out> (x-1/2)^5+(-10*(x-1/2)^3)/4+(25*(x-1/2))/16;
In> Simplify(%)
Out> (2*x^5-5*x^4+5*x^2-1)/2;

See also:
Bin .


LambertW, LambertWNum -- Lambert's W function

Standard library
Calling format:
LambertW(x)
LambertWNum(x)
Parameters:
x -- expression, argument of the function

Description:
Lambert's W function is (a multiple-valued, complex function) defined for any (complex) z by

W(z)*Exp(W(z))=z.

This function is sometimes useful to represent solutions of transcendental equations. For example, the equation Ln(x)=3*x can be "solved" by writing x= -3*W(-1/3). It is also possible to take a derivative or integrate this function "explicitly".

For real arguments x, W(x) is real if x>= -Exp(-1).

LambertWNum is an auxiliary function that computes the numerical value of the principal branch of Lambert's W function for real arguments x>= -Exp(-1) to current precision.

Examples:
In> LambertW(0)
Out> 0;
In> N(LambertW(-0.24/Sqrt(3*Pi)))
Out> -0.0851224014;

See also:
Exp .


gamma -- Euler's constant gamma

Standard library
Calling format:
N(gamma)
gamma()

Description:
These functions compute Euler's constant gamma<=>0.57722...

The constant is available symbolically as gamma or numerically as a function gamma(). This is a "cached constant" which is recalculated only when precision is increased. The numerical value of the constant can also be obtained as N(gamma). The low-level numerical computations are performed by the routine GammaConstNum.

Note that Euler's Gamma function Gamma(x) is the capitalized Gamma in Yacas.

Examples:
In> gamma+Pi
Out> gamma+Pi;
In> N(%)
Out> 3.7188083184;
In> [Precision(20);V(gamma());]
CachedConstant: Info: constant gamma is being
  recalculated at precision 20 
GammaConstNum: Info: used 56 iterations at
  working precision 24 
Out> 0.57721566490153286061;

See also:
Gamma , N , CachedConstant .


GoldenRatio -- the Golden Ratio

Standard library
Calling format:
N(GoldenRatio)
GoldenRatio()

Description:
These functions compute the Golden Ratio GoldenRatio<=>1.6180339887<=>(1+Sqrt(5))/2.

The constant is available symbolically as GoldenRatio or numerically as a function GoldenRatio(). This is a "cached constant" which is recalculated only when precision is increased. The numerical value of the constant can also be obtained as N(GoldenRatio).

Examples:
In> GoldenRatio - 1
Out> GoldenRatio-1;
In> N(%)
Out> 0.6180339887;
In> N(1/GoldenRatio)
Out> 0.6180339887;
In> [Precision(20);V(GoldenRatio());]
CachedConstant: Info: constant GoldenRatio is being recalculated at precision 20 
Out> 1.6180339887498948482;

See also:
N , CachedConstant .


Catalan -- Catalan's Constant

Standard library
Calling format:
N(Catalan)
Catalan()

Description:
These functions compute Catalan's Constant Catalan<=>0.9159655941.

The constant is available symbolically as Catalan or numerically as a function Catalan(). This is a "cached constant" which is recalculated only when precision is increased. The numerical value of the constant can also be obtained as N(Catalan). The low-level numerical computations are performed by the routine CatalanConstNum.

Examples:
In> N(Catalan)
Out> 0.9159655941;
In> DirichletBeta(2)
Out> Catalan;
In> [Precision(20);V(Catalan());]
CachedConstant: Info: constant Catalan is being recalculated at precision 20
Out> 0.91596559417721901505;

See also:
N , CachedConstant .


LeviCivita , Permutations , InProduct , CrossProduct , ZeroVector , BaseVector , Identity , ZeroMatrix , DiagonalMatrix , OrthogonalBasis , OrthonormalBasis , IsMatrix , Normalize , Transpose , Determinant , Trace , Inverse , Minor , CoFactor , SolveMatrix , CharacteristicEquation , EigenValues , EigenVectors , IsHermitian , IsOrthogonal , IsSymmetric , IsSkewSymmetric , IsUnitary , IsIdempotent , JacobianMatrix , VandermondeMatrix , HessianMatrix , WronskianMatrix , SylvesterMatrix .

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.


LeviCivita -- totally anti-symmetric Levi-Civita symbol

Standard library
Calling format:
LeviCivita(list)

Parameters:
list -- a list of integers 1 .. n in some order

Description:
LeviCivita implements the Levi-Civita symbol. This is generally useful for tensor calculus. 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.

Examples:
In> LeviCivita({1,2,3})
Out> 1;
In> LeviCivita({2,1,3})
Out> -1;
In> LeviCivita({2,2,3})
Out> 0;

See also:
Permutations .


Permutations -- get all permutations of a list

Standard library
Calling format:
Permutations(list)

Parameters:
list -- a list of elements

Description:
Permutations returns a list with all the permutations of the original list.

Examples:
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:
LeviCivita .


InProduct -- inner product of vectors

Standard library
Calling format:
InProduct(a,b)
a . b (prec. 3)

Parameters:
a, b -- vectors of equal length

Description:
The inner product of the two vectors "a" and "b" is returned. The vectors need to have the same size.

Examples:
In> {a,b,c} . {d,e,f};
Out> a*d+b*e+c*f;

See also:
CrossProduct .


CrossProduct -- outer product of vectors

Standard library
Calling format:
CrossProduct(a,b)
a X b  (prec. 3)

Parameters:
a, b -- three-dimensional vectors

Description:
The outer product (also called the cross product) of the vectors "a" and "b" is returned. The result is perpendicular to both "a" and "b" and its length is the product of the lengths of the vectors. Both "a" and "b" have to be three-dimensional.

Examples:
In> {a,b,c} X {d,e,f};
Out> {b*f-c*e,c*d-a*f,a*e-b*d};

See also:
InProduct .


ZeroVector -- create a vector with all zeroes

Standard library
Calling format:
ZeroVector(n)

Parameters:
n -- length of the vector to return

Description:
This command returns a vector of length "n", filled with zeroes.

Examples:
In> ZeroVector(4)
Out> {0,0,0,0};

See also:
BaseVector , ZeroMatrix , IsZeroVector .


BaseVector -- base vector

Standard library
Calling format:
BaseVector(k, n)

Parameters:
k -- index of the base vector to construct

n -- dimension of the vector

Description:
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.

Examples:
In> BaseVector(2,4)
Out> {0,1,0,0};

See also:
ZeroVector , Identity .


Identity -- make identity matrix

Standard library
Calling format:
Identity(n)

Parameters:
n -- size of the matrix

Description:
This commands returns the identity matrix of size "n" by "n". This matrix has ones on the diagonal while the other entries are zero.

Examples:
In> Identity(3)
Out> {{1,0,0},{0,1,0},{0,0,1}};

See also:
BaseVector , ZeroMatrix , DiagonalMatrix .


ZeroMatrix -- make a zero matrix

Standard library
Calling format:
ZeroMatrix(n, m)

Parameters:
n -- number of rows

m -- number of columns

Description:
This command returns a matrix with "n" rows and "m" columns, completely filled with zeroes.

Examples:
In> ZeroMatrix(3,4)
Out> {{0,0,0,0},{0,0,0,0},{0,0,0,0}};

See also:
ZeroVector , Identity .


DiagonalMatrix -- construct a diagonal matrix

Standard library
Calling format:
DiagonalMatrix(d)

Parameters:
d -- list of values to put on the diagonal

Description:
This command constructs a diagonal matrix, that is a square matrix whose off-diagonal entries are all zero. The elements of the vector "d" are put on the diagonal.

Examples:
In> DiagonalMatrix(1 .. 4)
Out> {{1,0,0,0},{0,2,0,0},{0,0,3,0},{0,0,0,4}};

See also:
Identity , ZeroMatrix .


OrthogonalBasis -- create an orthogonal basis

Standard library
Calling format:
OrthogonalBasis(W)

Parameters:
W - A linearly independent set of row vectors (aka a matrix)

Description:
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 Gram-Schmidt orthogonalization process.

Examples:
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 -- create an orthonormal basis

Standard library
Calling format:
OrthonormalBasis(W)

Parameters:
W - A linearly independent set of row vectors (aka a matrix)

Description:
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.

Examples:
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 .


IsMatrix -- test for a matrix

Standard library
Calling format:
IsMatrix(M)

Parameters:
M -- a mathematical object

Description:
IsMatrix returns True if M is a matrix, False otherwise. Something is considered to be a matrix if it is a list and all the entries of this list are themselves lists.

Examples:
In> IsMatrix(ZeroMatrix(3,4))
Out> True;
In> IsMatrix(ZeroVector(4))
Out> False;
In> IsMatrix(3)
Out> False;

See also:
IsVector .


Normalize -- normalize a vector

Standard library
Calling format:
Normalize(v)

Parameters:
v -- a vector

Description:
Return the normalized (unit) vector parallel to v: a vector having the same direction but with length 1.

Examples:
In> Normalize({3,4})
Out> {3/5,4/5};
In> % . %
Out> 1;

See also:
InProduct , CrossProduct .


Transpose -- get transpose of a matrix

Standard library
Calling format:
Transpose(M)

Parameters:
M -- a matrix

Description:
Transpose returns the transpose of a matrix M. Because matrices are just lists of lists, this is a useful operation too for lists.

Examples:
In> Transpose({{a,b}})
Out> {{a},{b}};


Determinant -- determinant of a matrix

Standard library
Calling format:
Determinant(M)

Parameters:
M -- a matrix

Description:
Returns the determinant of a matrix M.

Examples:
In> DiagonalMatrix(1 .. 4)
Out> {{1,0,0,0},{0,2,0,0},{0,0,3,0},{0,0,0,4}};
In> Determinant(%)
Out> 24;


Trace -- trace of a matrix

Standard library
Calling format:
Trace(M)

Parameters:
M -- a matrix

Description:
Trace returns the trace of a matrix M (defined as the sum of the elements on the diagonal of the matrix).

Examples:
In> DiagonalMatrix(1 .. 4)
Out> {{1,0,0,0},{0,2,0,0},{0,0,3,0},{0,0,0,4}};
In> Trace(%)
Out> 10;


Inverse -- get inverse of a matrix

Standard library
Calling format:
Inverse(M)

Parameters:
M -- a matrix

Description:
Inverse returns the inverse of matrix M. The determinant of M should be non-zero. Because this function uses Determinant for calculating the inverse of a matrix, you can supply matrices with non-numeric (symbolic) matrix elements.

Examples:
In> DiagonalMatrix({a,b,c})
Out> {{a,0,0},{0,b,0},{0,0,c}};
In> Inverse(%)
Out> {{(b*c)/(a*b*c),0,0},{0,(a*c)/(a*b*c),0},
{0,0,(a*b)/(a*b*c)}};
In> Simplify(%)
Out> {{1/a,0,0},{0,1/b,0},{0,0,1/c}};

See also:
Determinant .


Minor -- get principal minor of a matrix

Standard library
Calling format:
Minor(M,i,j)

Parameters:
M -- a matrix

i, j - positive integers

Description:
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.

Examples:
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 , Determinant , Inverse .


CoFactor -- cofactor of a matrix

Standard library
Calling format:
CoFactor(M,i,j)

Parameters:
M -- a matrix

i, j - positive integers

Description:
CoFactor returns the cofactor of a matrix around the element ( i, j). The cofactor is the minor times (-1)^(i+j).

Examples:
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:
Minor , Determinant , Inverse .


SolveMatrix -- solve a linear system

Standard library
Calling format:
SolveMatrix(M,v)

Parameters:
M -- a matrix

v -- a vector

Description:
SolveMatrix returns the vector x that satisfies the equation M*x=v. The determinant of M should be non-zero.

Examples:
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:
Inverse , Solve , PSolve , Determinant .


CharacteristicEquation -- get characteristic polynomial of a matrix

Standard library
Calling format:
CharacteristicEquation(matrix,var)

Parameters:
matrix -- a matrix

var -- a free variable

Description:
CharacteristicEquation returns the characteristic equation of "matrix", using "var". The zeros of this equation are the eigenvalues of the matrix, Det(matrix-I*var);

Examples:
In> DiagonalMatrix({a,b,c})
Out> {{a,0,0},{0,b,0},{0,0,c}};
In> CharacteristicEquation(%,x)
Out> (a-x)*(b-x)*(c-x);
In> Expand(%,x)
Out> (b+a+c)*x^2-x^3-((b+a)*c+a*b)*x+a*b*c;

See also:
EigenValues , EigenVectors .


EigenValues -- get eigenvalues of a matrix

Standard library
Calling format:
EigenValues(matrix)

Parameters:
matrix -- a square matrix

Description:
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(matrix-x*identity).

Examples:
In> M:={{1,2},{2,1}}
Out> {{1,2},{2,1}};
In> EigenValues(M)
Out> {3,-1};

See also:
EigenVectors , CharacteristicEquation .


EigenVectors -- get eigenvectors of a matrix

Standard library
Calling format:
EigenVectors(A,eigenvalues)

Parameters:
matrix -- a square matrix

eigenvalues -- list of eigenvalues as returned by EigenValues

Description:
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.

Examples:
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:
EigenValues , CharacteristicEquation .


IsHermitian -- test for a Hermitian matrix

Standard library
Calling format:
IsHermitian(A)

Parameters:
A -- a square matrix

Description:
IsHermitian(A) returns True if A is Hermitian and False otherwise. A is a Hermitian matrix iff Conjugate( Transpose A )= A. If A is a real matrix, it must be symmetric to be Hermitian.

Examples:
In> IsHermitian({{0,I},{-I,0}})
Out> True;
In> IsHermitian({{0,I},{2,0}})
Out> False;

See also:
IsUnitary .


IsOrthogonal -- test for an orthogonal matrix

Standard library
Calling format:
IsOrthogonal(A)

Parameters:
A -- square matrix

Description:
IsOrthogonal(A) returns True if A is orthogonal and False otherwise. A is orthogonal iff A*Transpose( A) = Identity, or equivalently Inverse( A) = Transpose( A).

Examples:
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;


IsSymmetric -- test for a symmetric matrix

Standard library
Calling format:
IsSymmetric(A)

Parameters:
A -- a square matrix

Description:
IsSymmetric(A) returns True if A is symmetric and False otherwise. A is symmetric iff Transpose ( A) = A. All Hermitian matrices are symmetric.

Examples:
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:
IsHermitian , IsSkewSymmetric .


IsSkewSymmetric -- test for a skew-symmetric matrix

Standard library
Calling format:
IsSkewSymmetric(A)

Parameters:
A -- a square matrix

Description:
IsSkewSymmetric(A) returns True if A is skew symmetric and False otherwise. A is skew symmetic iff Transpose A =-A.

Examples:
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:
IsSymmetric , IsHermitian .


IsUnitary -- test for a unitary matrix

Standard library
Calling format:
IsUnitary(A)

Parameters:
A -- a square matrix

Description:
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).

Examples:
In> IsUnitary({{0,I},{-I,0}})
Out> True;
In> IsUnitary({{0,I},{2,0}})
Out> False;

See also:
IsHermitian , IsSymmetric .


IsIdempotent -- test whether a matrix is idempotent

Standard library
Calling format:
IsIdempotent(A)

Parameters:
A -- a square matrix

Description:
IsIdempotent(A) returns True if A is idempotent and False otherwise. A is idempotent iff A^2 = A. Note that this also implies that A to any power is A.

Examples:
In> IsIdempotent(ZeroMatrix(10,10));
Out> True;
In> IsIdempotent(Identity(20))
Out> True;


JacobianMatrix -- calculate the Jacobian matrix of n functions in n variables

Standard library
Calling format:
JacobianMatrix(functions,variables)

Parameters:
functions -- An n dimensional vector of functions

variables -- An n dimensional vector of variables

Description:
The function JacobianMatrix calculates the Jacobian matrix of n functions in n variables.

The ijth element of the Jacobian matrix is defined as the derivative of ith function with respect to the jth variable.

Examples:
In> JacobianMatrix( {Sin(x),Cos(y)}, {x,y} ); 
Out> {{Cos(x),0},{0,-Sin(y)}};
In> PrettyForm(%)
/                                 \
| ( Cos( x ) ) ( 0 )              |
|                                 |
| ( 0 )        ( -( Sin( y ) ) )  |
\                                 /


VandermondeMatrix -- calculate the Vandermonde matrix

Standard library
Calling format:
VandermondeMatrix(vector)
Parameters:
vector -- An n dimensional vector

Description:
The function VandermondeMatrix calculates the Vandermonde matrix of a vector.

The ijth element of the Vandermonde matrix is defined as i^(j-1).

Examples:
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 )  |
\                            /


HessianMatrix -- calculate the Hessian matrix

Standard library
Calling format:
HessianMatrix(function,var)
Parameters:
function -- An function in n variables

var -- An n dimensian vector of variables

Description:
The function HessianMatrix calculates the Hessian matrix of a vector.

The ijth element of the Hessian matrix is defined as Deriv(var[i])Deriv(var[j])function. If the third order mixed partials are continuous, then the Hessian matrix is symmetric.

The Hessian matrix is used in the second derivative test to discern if a critical point is a local maximum, local minimum or a saddle point.

Examples:
In> HessianMatrix(3*x^2-2*x*y+y^2-8*y, {x,y} )
Out> {{6,-2},{-2,2}};
In> PrettyForm(%)
/                \
| ( 6 )  ( -2 )  |
|                |
| ( -2 ) ( 2 )   |
\                /


WronskianMatrix -- calculate the Wronskian matrix

Standard library
Calling format:
WronskianMatrix(func,var)
Parameters:
func -- An n dimensional vector of functions

var -- A variable to differentiate with respect to

Description:
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 ( i-1)-th derivative, where i is the current row.

The Wronskian matrix is used to verify if 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.

Examples:
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> 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*x-4*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(%)
Out> 0;


SylvesterMatrix -- calculate the Sylvester matrix of two polynomials

Standard library
Calling format:
SylvesterMatrix(poly1,poly2,variable)

Parameters:
poly1 -- polynomial

poly2 -- polynomial

variable -- variable to express the matrix for

Description:
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.

Examples:
In> ex1:= x^2+2*x-a
Out> x^2+2*x-a;
In> ex2:= x^2+a*x-4
Out> x^2+a*x-4;
In> SylvesterMatrix(ex1,ex2,x)
Out> {{1,2,-a,0},{0,1,2,-a},
  {1,a,-4,0},{0,1,a,-4}};
In> Determinant(%)
Out> 16-a^2*a- -8*a-4*a+a^2- -2*a^2-16-4*a;
In> Simplify(%)
Out> 3*a^2-a^3;

The above example shows that the two polynomials have common zeros if a=3.

See also:
Determinant , Simplify , Solve , PSolve .


Expand , Degree , Coef , Content , PrimitivePart , LeadingCoef , Monic , RandomPoly , Horner , ExpandBrackets , EvaluateHornerScheme , OrthoP , OrthoH , OrthoG , OrthoL , OrthoT, OrthoU , OrthoPSum, OrthoHSum, OrthoLSum, OrthoGSum, OrthoTSum, OrthoUSum , OrthoPoly , OrthoPolySum , SquareFree , FindRealRoots , NumRealRoots , MinimumBound , MaximumBound .

Polynomials

This chapter contains commands to manipulate polynomials. This includes functions for constructing and evaluating orthogonal polynomials.


Expand -- put polynomial in expanded form

Standard library
Calling format:
Expand(expr)
Expand(expr, var)
Expand(expr, varlist)

Parameters:
expr -- a polynomial expression

var -- a variable

varlist -- a list of variables

Description:
This command brings a polynomial in expanded form, in which polynomials are represented in the form c0+c1*x+c2*x^2+...+c[n]*x^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.

Examples:
In> PrettyPrinter("PrettyForm");

True

In> Expand((1+x)^5);

 5        4         3         2
x  + 5 * x  + 10 * x  + 10 * x  + 5 * x + 1

In> Expand((1+x-y)^2, x);

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

In> Expand((1+x-y)^2, {x,y});

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

See also:
ExpandBrackets .


Degree -- degree of a polynomial

Standard library
Calling format:
Degree(expr)
Degree(expr, var)

Parameters:
expr -- a polynomial

var -- a variable occurring in "expr"

Description:
This command returns the degree of the polynomial "expr" with respect to the variable "var". The degree is the highest power of "var" occurring in the polynomial. If only one variable occurs in "expr", the first calling sequence can be used. Otherwise the user should use the second form in which the variable is explicitly mentioned.

Examples:
In> Degree(x^5+x-1);
Out> 5;
In> Degree(a+b*x^3, a);
Out> 1;
In> Degree(a+b*x^3, x);
Out> 3;

See also:
Expand , Coef .


Coef -- coefficient of a polynomial

Standard library
Calling format:
Coef(expr, var, order)

Parameters:
expr -- a polynomial

var -- a variable occurring in "expr"

order -- integer or list of integers

Description:
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.

Examples:
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:
Expand , Degree , LeadingCoef .


Content -- content of a univariate polynomial

Standard library
Calling format:
Content(expr)

Parameters:
expr -- univariate polynomial

Description:
This command determines the content of a univariate polynomial. The content is the greatest common divisor of all the terms in the polynomial. Every polynomial can be written as the product of the content with the primitive part.

Examples:
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 , Gcd .


PrimitivePart -- primitive part of a univariate polynomial

Standard library
Calling format:
PrimitivePart(expr)

Parameters:
expr -- univariate polynomial

Description:
This command determines the primitive part of a univariate polynomial. The primitive part is what remains after the content (the greatest common divisor of all the terms) is divided out. So the product of the content and the primitive part equals the original polynomial.

Examples:
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:
Content .


LeadingCoef -- leading coefficient of a polynomial

Standard library
Calling format:
LeadingCoef(poly)
LeadingCoef(poly, var)

Parameters:
poly -- a polynomial

var -- a variable

Description:
This function returns the leading coefficient of "poly", regarded as a polynomial in the variable "var". The leading coefficient is the coefficient of the term of highest degree. If only one variable appears in the expression "poly", it is obvious that it should be regarded as a polynomial in this variable and the first calling sequence may be used.

Examples:
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;

See also:
Coef , Monic .


Monic -- monic part of a polynomial

Standard library
Calling format:
Monic(poly)
Monic(poly, var)

Parameters:
poly -- a polynomial

var -- a variable

Description:
This function returns the monic part of "poly", regarded as a polynomial in the variable "var". 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 expression "poly", it is obvious that it should be regarded as a polynomial in this variable and the first calling sequence may be used.

Examples:
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:
LeadingCoef .


RandomPoly -- construct a random polynomial

Standard library
Calling format:
RandomPoly(var,deg,coefmin,coefmax)

Parameters:
var -- free variable for resulting univariate polynomial

deg -- degree of resulting univariate polynomial

coefmin -- minimum value for coefficients

coefmax -- maximum value for coefficients

Description:
RandomPoly generates a random polynomial in variable "var", of degree "deg", with integer coefficients ranging from "coefmin" to "coefmax" (inclusive). The coefficients are uniformly distributed in this interval, and are independent of each other.

Examples:
In> RandomPoly(x,3,-10,10)
Out> 3*x^3+10*x^2-4*x-6;
In> RandomPoly(x,3,-10,10)
Out> -2*x^3-8*x^2+8;

See also:
Random , RandomIntegerVector .


Div and Mod for polynomials

Standard library
Div and Mod are also defined for polynomials.

See also:
Div , Mod .


Horner -- convert polynomial into Horner form

Standard library
Calling format:
Horner(expr, var)

Parameters:
expr -- a polynomial in "var"

var -- a variable

Description:
This command turns the polynomial "expr", considered as a univariate polynomial in "var", into Horner form. A polynomial in normal form is an expression such as

c[0]+c[1]*x+...+c[n]*x^n.

If one converts this polynomial into Horner form, one gets the equivalent expression

(...(c[n]*x+c[n-1])*x+...+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.

Examples:
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:
Expand , ExpandBrackets , EvaluateHornerScheme .


ExpandBrackets -- expand all brackets

Standard library
Calling format:
ExpandBrackets(expr)

Parameters:
expr -- an expression

Description:
This command tries to expand all the brackets by repeatedly using the distributive laws a*(b+c)=a*b+a*c and (a+b)*c=a*c+b*c. It goes further than Expand, in that it expands all brackets.

Examples:
In> Expand((a-x)*(b-x),x)
Out> x^2-(b+a)*x+a*b;
In> Expand((a-x)*(b-x),{x,a,b})
Out> x^2-(b+a)*x+b*a;
In> ExpandBrackets((a-x)*(b-x))
Out> a*b-x*b+x^2-a*x;

See also:
Expand .


EvaluateHornerScheme -- fast evaluation of polynomials

Standard library
Calling format:
EvaluateHornerScheme(coeffs,x)

Parameters:
coeffs -- a list of coefficients

x -- expression

Description:
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.

Example:
In> EvaluateHornerScheme({a,b,c,d},x)
Out> a+x*(b+x*(c+x*d));

See also:
Horner .


OrthoP -- Legendre and Jacobi orthogonal polynomials

Standard library
Calling format:
OrthoP(n, x);
OrthoP(n, a, b, x);

Parameters:
n -- degree of polynomial

x -- point to evaluate polynomial at

a, b -- parameters for Jacobi polynomial

Description:
The first calling format with two arguments evaluates the Legendre polynomial of degree n at the point x. The second form does the same for the Jacobi polynomial with parameters a and b, which should be both greater than -1.

The Jacobi polynomials are orthogonal with respect to the weight function (1-x)^a*(1+x)^b on the interval [-1,1]. They satisfy the recurrence relation

P(n,a,b,x)=(2*n+a+b-1)/(2*n+a+b-2)*

(a^2-b^2+x*(2*n+a+b-2)*(n+a+b))/(2*n*(n+a+b))*P(n-1,a,b,x)

-((n+a-1)*(n+b-1)*(2*n+a+b))/(n*(n+a+b)*(2*n+a+b-2))*P(n-2,a,b,x)

for n>1, with P(0,a,b,x)=1,

P(1,a,b,x)=(a-b)/2+x*(1+(a+b)/2).

Legendre polynomials are a special case of Jacobi polynomials with the specific parameter values a=b=0. So they form an orthogonal system with respect to the weight function identically equal to 1 on the interval [-1,1], and they satisfy the recurrence relation

P(n,x)=(2*n-1)*x/(2*n)*P(n-1,x)-(n-1)/n*P(n-2,x)

for n>1, with P(0,x)=1, P(1,x)=x.

Most of the work is performed by the internal function OrthoPoly.

Examples:
In> PrettyPrinter("PrettyForm");

True

In> OrthoP(3, x);

    /      2     \
    | 5 * x    3 |
x * | ------ - - |
    \   2      2 /

In> OrthoP(3, 1, 2, x);

1       /     / 21 * x   7 \   7 \
- + x * | x * | ------ - - | - - |
2       \     \   2      2 /   2 /

In> Expand(%)

      3        2
21 * x  - 7 * x  - 7 * x + 1
----------------------------
             2

In> OrthoP(3, 1, 2, 0.5);

-0.8124999999

See also:
OrthoPSum , OrthoG , OrthoPoly .


OrthoH -- Hermite orthogonal polynomials

Standard library
Calling format:
OrthoH(n, x);

Parameters:
n -- degree of polynomial

x -- point to evaluate polynomial at

Description:
This function evaluates the Hermite polynomial of degree n at the point x.

The Hermite polynomials are orthogonal with respect to the weight function Exp(-x^2/2) on the entire real axis. They satisfy the recurrence relation

H(n,x)=2*x*H(n-1,x)-2*(n-1)*H(n-2,x)

for n>1, with H(0,x)=1, H(1,x)=2*x.

Most of the work is performed by the internal function OrthoPoly.

Examples:
In> OrthoH(3, x);
Out> x*(8*x^2-12);
In> OrthoH(6, 0.5);
Out> 31;

See also:
OrthoHSum , OrthoPoly .


OrthoG -- Gegenbauer orthogonal polynomials

Standard library
Calling format:
OrthoG(n, a, x);

Parameters:
n -- degree of polynomial

a -- parameter

x -- point to evaluate polynomial at

Description:
This function evaluates the Gegenbauer (or ultraspherical) polynomial with parameter a and degree n at the point x. The parameter a should be greater than -1/2.

The Gegenbauer polynomials are orthogonal with respect to the weight function (1-x^2)^(a-1/2) on the interval [-1,1]. Hence they are connected to the Jacobi polynomials via

G(n,a,x)=P(n,a-1/2,a-1/2,x).

They satisfy the recurrence relation

G(n,a,x)=2*(1+(a-1)/n)*x*G(n-1,a,x)

-(1+2*(a-2)/n)*G(n-2,a,x)

for n>1, with G(0,a,x)=1, G(1,a,x)=2*x.

Most of the work is performed by the internal function OrthoPoly.

Examples:
In> OrthoG(5, 1, x);
Out> x*((32*x^2-32)*x^2+6);
In> OrthoG(5, 2, -0.5);
Out> 2;

See also:
OrthoP , OrthoT , OrthoU , OrthoGSum , OrthoPoly .


OrthoL -- Laguerre orthogonal polynomials

Standard library
Calling format:
OrthoL(n, a, x);

Parameters:
n -- degree of polynomial

a -- parameter

x -- point to evaluate polynomial at

Description:
This function evaluates the Laguerre polynomial with parameter a and degree n at the point x. The parameter a 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+(a-1-x)/n)*L(n-1,a,x)

-(1-(a-1)/n)*L(n-2,a,x)

for n>1, with L(0,a,x)=1, L(1,a,x)=a+1-x.

Most of the work is performed by the internal function OrthoPoly.

Examples:
In> OrthoL(3, 1, x);
Out> x*(x*(2-x/6)-6)+4;
In> OrthoL(3, 1/2, 0.25);
Out> 1.2005208334;

See also:
OrthoLSum , OrthoPoly .


OrthoT, OrthoU -- Tschebyscheff polynomials

Standard library
Calling format:
OrthoT(n, x);
OrthoU(n, x);

Parameters:
n -- degree of polynomial

x -- point to evaluate polynomial at

Description:
These functions evaluate the Tschebyscheff polynomials of the first kind T(n,x) and of the second kind U(n,x), of degree "n" at the point "x". (The name of this Russian mathematician is also sometimes spelled "Chebyshev".)

The Tschebyscheff polynomials are orthogonal with respect to the weight function (1-x^2)^(-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)=2*x*T(n-1,x)-T(n-2,x),

U(n,x)=2*x*U(n-1,x)-U(n-2,x)

for n>1, with T(0,x)=1, T(1,x)=x, U(0,x)=1, U(1,x)=2*x.

Tschebyscheff polynomials are evaluated using fast (but numerically unstable) recurrence relations

T(2*n,x)=2*T(n,x)^2-1,

T(2*n+1,x)=2*T(n+1,x)*T(n,x)-x,

U(2*n,x)=2*T(n,x)*U(n,x)-1,

U(2*n+1,x)=2*T(n+1,x)*U(n,x).

This allows to compute T(n,x) and U(n,x) in time logarithmic in n. Note that the functions return the polynomials in a sparse unexpanded form.

Warning: because of numerical instability of this algorithm, polynomials of very large orders on floating-point arguments should be evaluated with increased precision.

Examples:
In> OrthoT(3, x);
Out> 2*x*(2*x^2-1)-x;
In> OrthoT(10, 0.9);
Out> -0.2007474688;
In> OrthoU(3, x);
Out> 4*x*(2*x^2-1);
In> OrthoU(10, 0.9);
Out> -2.2234571776;

Here is an example numerical calculation where the loss of precision is catastrophic:

In> OrthoT(10000000000001, 0.9)
Out> 0.1851470834;
In> Precision(20);
Out> True;
In> OrthoT(10000000000001, 0.9)
Out> -0.79727552022438356731;

See also:
OrthoG , OrthoTSum , OrthoUSum , OrthoPoly .


OrthoPSum, OrthoHSum, OrthoLSum, OrthoGSum, OrthoTSum, OrthoUSum -- sums of series of orthogonal polynomials

Standard library
Calling format:
OrthoPSum(c, x);
OrthoPSum(c, a, b, x);
OrthoHSum(c, x);
OrthoLSum(c, a, x);
OrthoGSum(c, a, x);
OrthoTSum(c, x);
OrthoUSum(c, x);

Parameters:
c -- list of coefficients

a, b -- parameters of specific polynomials

x -- point to evaluate polynomial at

Description:
These functions evaluate the sum of series of orthogonal polynomials at the point x, with given list of coefficients c of the series and fixed polynomial parameters a, b (if applicable).

The list of coefficients starts with the lowest order, so that for example OrthoLSum(c, a, x) = c[1] L[0](a,x) + c[2] L[1](a,x) + ... + c[N] L[N-1](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.

Examples:
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;

See also:
OrthoP , OrthoG , OrthoH , OrthoL , OrthoT , OrthoU , OrthoPolySum .


OrthoPoly -- internal function for constructing orthogonal polynomials

Standard library
Calling format:
OrthoPoly(name, n, par, x)

Parameters:
name -- string containing name of orthogonal family

n -- degree of the polynomial

par -- list of values for the parameters

x -- point to evaluate at

Description:
This function is used internally to construct orthogonal polynomials. It returns the n-th polynomial from the family name with parameters par at the point x.

All known families are stored in the association list KnownOrthoPoly. The name 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 order n and the extra parameters p, and returns a list of two lists: the first list contains the coefficients A,B of the n=1 polynomial, i.e. A+B*x; the second list contains the coefficients A,B,C in the recurrence relation, i.e. P[n]=(A+B*x)*P[n-1]+C*P[n-2]. (There are only 3 coefficients in the second list, because none of the polynomials use C+D*x instead of C in the recurrence relation. This is assumed in the implementation!)

If the argument x is numerical, the function OrthoPolyNumeric is called. Otherwise, the function OrthoPolyCoeffs computes a list of coefficients, and EvaluateHornerScheme converts this list into a polynomial expression.

See also:
OrthoP , OrthoG , OrthoH , OrthoL , OrthoT , OrthoU , OrthoPolySum .


OrthoPolySum -- internal function for computing series of orthogonal polynomials

Standard library
Calling format:
OrthoPolySum(name, c, par, x)

Parameters:
name -- string containing name of orthogonal family

c -- list of coefficients

par -- list of values for the parameters

x -- point to evaluate at

Description:
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 family name with parameters par at the point x, where c is the list of coefficients of the series.

The algorithm used to compute the series without first computing the individual polynomials is the Clenshaw-Smith recurrence scheme. (See the algorithms book for explanations.)

If the argument x is numerical, the function OrthoPolySumNumeric is called. Otherwise, the function OrthoPolySumCoeffs computes the list of coefficients of the resulting polynomial, and EvaluateHornerScheme converts this list into a polynomial expression.

See also:
OrthoPSum , OrthoGSum , OrthoHSum , OrthoLSum , OrthoTSum , OrthoUSum , OrthoPoly .


SquareFree -- Return square-free part of polynom p=p(x) in x

Standard library
Calling format:
SquareFree(p)

Parameters:
p - a polynom in x

Description:
Given a polynom

p=p[1]^n[1]*...*p[m]^n[m]

with irreducible polynoms p[i], return the square-free version part (with all the factors having multiplicity 1):

p[1]*...*p[m]

Examples:
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 .


FindRealRoots -- Find the real roots of a polynom p=p(x) in x

Standard library
Calling format:
FindRealRoots(p)

Parameters:
p - a polynom in x

Description:
Return a list with the real roots of p. It tries to find the real-valued roots, and thus requires numeric floating point calculations. The precision of the result can be improved by increasing the calculation precision.

Examples:
In> p:=Expand((x+3.1)^5*(x-6.23))
Out> x^6+9.27*x^5-0.465*x^4-300.793*x^3-
1394.2188*x^2-2590.476405*x-1783.5961073;
In> FindRealRoots(p)
Out> {-3.1,6.23};

See also:
SquareFree , NumRealRoots , MinimumBound , MaximumBound , Factor .


NumRealRoots -- Return the number of real roots of a polynom p=p(x) in x

Standard library
Calling format:
NumRealRoots(p)

Parameters:
p - a polynom in x

Description:
Returns the number of real roots of a polynom p.

Examples:
In> NumRealRoots(x^2-1)
Out> 2;
In> NumRealRoots(x^2+1)
Out> 0;

See also:
FindRealRoots , SquareFree , MinimumBound , MaximumBound , Factor .


MinimumBound -- Return a lower bound on the absolute value of the real roots of a polynom p=p(x) in x


MaximumBound -- Return an upper bound on the absolute value of the real roots of a polynom p=p(x) in x

Standard library
Calling format:
MinimumBound(p)

MaximumBound(p)

Parameters:
p - a polynom in x

Description:
Return minimum and maximum boubds for the absolute values of the real roots of a polynom p. The polynom has to be converted to one with rational coefficients first, and be made square-free.

Examples:
In> p:=SquareFree(Rationalize((x-3.1)*(x+6.23)))
Out> (-40000*x^2-125200*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:
SquareFree , NumRealRoots , FindRealRoots , Factor .


Head , Tail , Length , Map , MapSingle , RandomIntegerVector , MakeVector , Select , Nth , DestructiveReverse , List , UnList , Listify , Concat , Delete , Insert , DestructiveDelete , DestructiveInsert , Replace , DestructiveReplace , FlatCopy , Contains , Find , Append , DestructiveAppend , RemoveDuplicates , Push , Pop , PopFront , PopBack , Swap , Count , Intersection , Union , Difference , FillList , Drop , Take , Partition , Assoc , AssocIndices , AssocDelete , Flatten , UnFlatten , Type , NrArgs , VarList, VarListArith, VarListSome , FuncList, FuncListArith, FuncListSome , BubbleSort, HeapSort , PrintList , Table , TableForm , GlobalPop, GlobalPush .

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 -- the first element of a list

Internal function
Calling format:
Head(list)

Parameters:
list -- a list

Description:
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.

Examples:
In> Head({a,b,c})
Out> a;
In> Head(f(a,b,c));
Out> a;

See also:
Tail , Length .


Tail -- returns a list without its first element

Internal function
Calling format:
Tail(list)

Parameters:
list -- a list

Description:
This function returns "list" without its first element.

Examples:
In> Tail({a,b,c})
Out> {b,c};

See also:
Head , Length .


Length -- the length of a list or string

Internal function
Calling format:
Length(object)

Parameters:
object -- a list, array or string

Description:
Length returns the length of a list. This function also works on strings and arrays.

Examples:
In> Length({a,b,c})
Out> 3;
In> Length("abcdef");
Out> 6;

See also:
Head , Tail , Nth , Count .


Map -- apply an n-ary function to all entries in a list

Standard library
Calling format:
Map(fn, list)

Parameters:
fn -- function to apply

list -- list of lists of arguments

Description:
This function applies "fn" to every list of arguments to be found in "list". So the first entry of "list" should be a list containing the first, second, third, ... argument to "fn", and the same goes for the other entries of "list". The function can either be given as a string or as a pure function.

Examples:
In> MapSingle("Sin",{a,b,c});
Out> {Sin(a),Sin(b),Sin(c)};
In> Map("+",{{a,b},{c,d}});
Out> {a+c,b+d};

See also:
MapSingle , MapArgs .


MapSingle -- apply a unary function to all entries in a list

Standard library
Calling format:
MapSingle(fn, list)

Parameters:
fn -- function to apply

list -- list of arguments

Description:
The function "fn" is successively applied to all entries in "list", and a list containing the respective results is returned. The function can be given either as a string or as a pure function.

The /@ operator provides a shorthand for MapSingle.

Examples:
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};

See also:
Map , MapArgs , /@ .


RandomIntegerVector -- generate a vector of random integers

Standard library
Calling format:
RandomIntegerVector(nr, from, to)

Parameters:
nr -- number of integers to generate

from -- lower bound

to -- upper bound

Description:
This function generates a list with "nr" random integers. All entries lie between "from" and "to", including the boundaries, and are uniformly distributed in this interval.

Examples:
In> RandomIntegerVector(4,-3,3)
Out> {0,3,2,-2};

See also:
Random , RandomPoly .


MakeVector -- vector of uniquely numbered variable names

Standard library
Calling format:
MakeVector(var,n)

Parameters:
var -- free variable

n -- length of the vector

Description:
A list of length "n" is generated. The first entry contains the identifier "var" with the number 1 appended to it, the second entry contains "var" with the suffix 2, and so on until the last entry which contains "var" with the number "n" appended to it.

Examples:
In> MakeVector(a,3)
Out> {a1,a2,a3};

See also:
RandomIntegerVector , ZeroVector .


Select -- select entries satisfying some predicate

Standard library
Calling format:
Select(pred, list)

Parameters:
pred -- a predicate

list -- a list of elements to select from

Description:
Select returns a sublist of "list" which contains all the entries for which the predicate "pred" returns True when applied to this entry.

Examples:
In> Select("IsInteger",{a,b,2,c,3,d,4,e,f})
Out> {2,3,4};

See also:
Length , Find , Count .


Nth -- return the n-th element of a list

Internal function
Calling format:
Nth(list, n)

Parameters:
list -- list to choose from

n -- index of entry to pick

Description:
The entry with index "n" from "list" is returned. The first entry has index 1. It is possible to pick several entries of the list by taking "n" to be a list of indices.

More generally, Nth returns the n-th operand of the expression passed as first argument.

An alternative but equivalent form of Nth(list, n) is list[n].

Examples:
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;

See also:
Select , Nth .


DestructiveReverse -- reverse a list destructively

Internal function
Calling format:
DestructiveReverse(list)

Parameters:
list -- list to reverse

Description:
This command reverses "list" in place, so that the original is destroyed. This means that any variable bound to "list" will now be bound to the reversed list. The reversed list is also returned.

Destructive commands are faster than their nondestructive counterparts. Strangely, there is no nondestructive command to reverse a list. Use FlatCopy and DestructiveReverse to achieve this.

Examples:
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:
FlatCopy .


List -- construct a list

Internal function
Calling format:
List(expr1, expr2, ...)

Parameters:
expr1, expr2 -- expressions making up the list

Description:
A list is constructed whose first entry is "expr1", the second entry is "expr2", and so on. This command is equivalent to the expression "expr1, expr2, ...".

Examples:
In> List();
Out> {};
In> List(a,b);
Out> {a,b};
In> List(a,{1,2},d);
Out> {a,{1,2},d};

See also:
UnList , Listify .


UnList -- convert a list to a function application

Internal function
Calling format:
UnList(list)

Parameters:
list -- list to be converted

Description:
This command converts a list to a function application. The first entry of "list" is treated as a function, and the following entries are the arguments to this function. So the function refered to in the first element of "list" 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 functions UnList() and Hold() both stop the process of evaluation.

Examples:
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> 1-x^2/2+x^4/24;

See also:
List , Listify , Hold .


Listify -- convert a function application to a list

Internal function
Calling format:
Listify(expr)

Parameters:
expr -- expression to be converted

Description:
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 top-level operator in the evaluated expression and the other entries are the arguments to this operator. Finally, the list is returned.

Examples:
In> Listify(Cos(x));
Out> {Cos,x};
In> Listify(3*a);
Out> {*,3,a};

See also:
List , UnList , IsAtom .


Concat -- concatenate lists

Internal function
Calling format:
Concat(list1, list2, ...)

Parameters:
list1, list2, ... -- lists to concatenate

Description:
The lists "list1", "list2", ... are evaluated and concatenated. The resulting big list is returned.

Examples:
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:
ConcatStrings , : , Insert .


Delete -- delete an element from a list

Internal function
Calling format:
Delete(list, n)

Parameters:
list -- list from which an element should be removed

n -- index of the element to remove

Description:
This command deletes the n-th element from "list". The first parameter should be a list, while "n" should be a positive integer less than or equal to the length of "list". The entry with index "n" is removed (the first entry has index 1), and the resulting list is returned.

Examples:
In> Delete({a,b,c,d,e,f}, 4);
Out> {a,b,c,e,f};

See also:
DestructiveDelete , Insert , Replace .


Insert -- insert an element into a list

Internal function
Calling format:
Insert(list, n, expr)

Parameters:
list -- list in which "expr" should be inserted

n -- index at which to insert

expr -- expression to insert in "list"

Description:
The expression "expr" is inserted just before the n-th entry in "list". The first parameter "list" should be a list, while "n" should be a positive integer less than or equal to the length of "list" plus one. The expression "expr" is placed between the entries in "list" with entries "n-1" and "n". There are two border line cases: if "n" is 1, the expression "expr" is placed in front of the list (just as by the : operator); if "n" equals the length of "list" plus one, the expression "expr" is placed at the end of the list (just as by Append). In any case, the resulting list is returned.

Examples:
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:
DestructiveInsert , : , Append , Delete , Remove .


DestructiveDelete -- delete an element destructively from a list

Internal function
Calling format:
DestructiveDelete(list, n)

Parameters:
list -- list from which an element should be removed

n -- index of the element to remove

Description:
This is the destructive counterpart of 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 to "list", it will now be bound to the list with the n-th entry removed.

Destructive commands run faster than their nondestructive counterparts because the latter copy the list before they alter it.

Examples:
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:
Delete , DestructiveInsert , DestructiveReplace .


DestructiveInsert -- insert an element destructively into a list

Internal function
Calling format:
DestructiveInsert(list, n, expr)

Parameters:
list -- list in which "expr" should be inserted

n -- index at which to insert

expr -- expression to insert in "list"

Description:
This is the destructive counterpart of Insert. This command yields the same result as the corresponding call to Insert, but the original list is modified. So if a variable is bound to "list", it will now be bound to the list with the expression "expr" inserted.

Destructive commands run faster than their nondestructive counterparts because the latter copy the list before they alter it.

Examples:
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:
Insert , DestructiveDelete , DestructiveReplace .


Replace -- replace an entry in a list

Internal function
Calling format:
Replace(list, n, expr)

Parameters:
list -- list of which an entry should be replaced

n -- index of entry to replace

expr -- expression to replace the n-th entry with

Description:
The n-th entry of "list" is replaced by the expression "expr". This is equivalent to calling Delete and Insert in sequence. To be precise, the expression Replace(list, n, expr) has the same result as the expression Insert(Delete(list, n), n, expr).

Examples:
In> Replace({a,b,c,d,e,f}, 4, x);
Out> {a,b,c,x,e,f};

See also:
Delete , Insert , DestructiveReplace .


DestructiveReplace -- replace an entry destructively in a list

Internal function
Calling format:
DestructiveReplace(list, n, expr)

Parameters:
list -- list of which an entry should be replaced

n -- index of entry to replace

expr -- expression to replace the n-th entry with

Description:
This is the destructive counterpart of Replace. This command yields the same result as the corresponding call to Replace, but the original list is modified. So if a variable is bound to "list", it will now be bound to the list with the expression "expr" inserted.

Destructive commands run faster than their nondestructive counterparts because the latter copy the list before they alter it.

Examples:
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:
Replace , DestructiveDelete , DestructiveInsert .


FlatCopy -- copy the top level of a list

Internal function
Calling format:
FlatCopy(list)

Parameters:
list -- list to be copied

Description:
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).

Examples:
The following shows a possible way to define a command that reverses a list nondestructively.

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 -- test whether a list contains a certain element

Standard library
Calling format:
Contains(list, expr)

Parameters:
list -- list to examine

expr -- expression to look for in "list"

Description:
This command tests whether "list" contains the expression "expr" as an entry. It returns True if it does and False otherwise. Only the top level of "list" is examined. The parameter "list" may also be a general expression, in that case the top-level operands are tested for the occurence of "expr".

Examples:
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;

See also:
Find , Count .


Find -- get the index at which a certain element occurs

Standard library
Calling format:
Find(list, expr)

Parameters:
list -- the list to examine

expr -- expression to look for in "list"

Description:
This commands returns the index at which the expression "expr" occurs in "list". If "expr" occurs more than once, the lowest index is returned. If "expr" does not occur at all, -1 is returned.

Examples:
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:
Contains .


Append -- append an entry at the end of a list

Standard library
Calling format:
Append(list, expr)

Parameters:
list -- list to append "expr" to

expr -- expression to append to the list

Description:
The expression "expr" is appended at the end of "list" 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.

Examples:
In> Append({a,b,c,d}, 1);
Out> {a,b,c,d,1};

See also:
Concat , : , DestructiveAppend .


DestructiveAppend -- destructively append an entry to a list

Internal function
CALL
DestructiveAppend(list, expr)

Parameters:
list -- list to append "expr" to

expr -- expression to append to the list

Description:
This is the destructive counterpart of Append. This command yields the same result as the corresponding call to Append, but the original list is modified. So if a variable is bound to "list", it will now be bound to the list with the expression "expr" inserted.

Destructive commands run faster than their nondestructive counterparts because the latter copy the list before they alter it.

Examples:
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};

See also:
Concat , : , Append .


RemoveDuplicates -- remove any duplicates from a list

Standard library
Calling format:
RemoveDuplicates(list)

Parameters:
list -- list to act on

Description:
This command returns "list" after all duplicates are removed. To be precise, the second occurence of any entry is deleted, as are the third, the fourth, etcetera.

Examples:
In> RemoveDuplicates({1,2,3,2,1});
Out> {1,2,3};
In> RemoveDuplicates({a,1,b,1,c,1});
Out> {a,1,b,c};


Push -- add an element on top of a stack

Standard library
Calling format:
Push(stack, expr)

Parameters:
stack -- a list (which serves as the stack container)

expr -- expression to push on "stack"

Description:
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.

Examples:
In> stack := {};
Out> {};
In> Push(stack, x);
Out> {x};
In> Push(stack, x2);
Out> {x2,x};
In> PopFront(stack);
Out> x2;

See also:
Pop , PopFront , PopBack .


Pop -- remove an element from a stack

Standard library
Calling format:
Pop(stack, n)

Parameters:
stack -- a list (which serves as the stack container)

n -- index of the element to remove

Description:
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.

Examples:
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:
Push , PopFront , PopBack .


PopFront -- remove an element from the top of a stack

Standard library
Calling format:
PopFront(stack)

Parameters:
stack -- a list (which serves as the stack container)

Description:
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.

Examples:
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};

See also:
Push , Pop , PopBack .


PopBack -- remove an element from the bottom of a stack

Standard library
Calling format:
PopBack(stack)

Parameters:
stack -- a list (which serves as the stack container)

Description:
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.

Examples:
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:
Push , Pop , PopFront .


Swap -- swap two elements in a list

Standard library
Calling format:
Swap(list, i1, i2)

Parameters:
list -- the list in which a pair of entries should be swapped

i1, i2 -- indices of the entries in "list" to swap

Description:
This command swaps the pair of entries with entries "i1" and "i2" in "list". So the element at index "i1" ends up at index "i2" and the entry at "i2" is put at index "i1". Both indices should be valid to address elements in the list. Then the updated list is returned.

Swap() works also on generic arrays.

Examples:
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:
Replace , DestructiveReplace , ArrayCreate .


Count -- count the number of occurrences of an expression

Standard library
Calling format:
Count(list, expr)

Parameters:
list -- the list to examine

expr -- expression to look for in "list"

Description:
This command counts the number of times that the expression "expr" occurs in "list" and returns this number.

Examples:
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:
Length , Select , Contains .


Intersection -- return the intersection of two lists

Standard library
Calling format:
Intersection(l1, l2)

Parameters:
l1, l2 -- two lists

Description:
The intersection of the lists "l1" and "l2" 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 in "l1". If an expression occurs multiple times in both "l1" and "l2", then it will occur the same number of times in the result.

Examples:
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 , Difference .


Union -- return the union of two lists

Standard library
Calling format:
Union(l1, l2)

Parameters:
l1, l2 -- two lists

Description:
The union of the lists "l1" and "l2" 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.

Examples:
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:
Intersection , Difference .


Difference -- return the difference of two lists

Standard library
Calling format:
Difference(l1, l2)

Parameters:
l1, l2 -- two lists

Description:
The difference of the lists "l1" and "l2" is determined and returned. The difference contains all elements that occur in "l1" but not in "l2". The order of elements in "l1" is preserved. If a certain expression occurs "n1" times in the first list and "n2" times in the second list, it will occur "n1-n2" times in the result if "n1" is greater than "n2" and not at all otherwise.

Examples:
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:
Intersection , Union .


FillList -- fill a list with a certain expression

Standard library
Calling format:
FillList(expr, n)

Parameters:
expr -- expression to fill the list with

n -- the length of the list to construct

Description:
This command creates a list of length "n" in which all slots contain the expression "expr" and returns this list.

Examples:
In> FillList(x, 5);
Out> {x,x,x,x,x};

See also:
MakeVector , ZeroVector , RandomIntegerVector .


Drop -- drop a range of elements from a list

Standard library
Calling format:
Drop(list, n)
Drop(list, -n)
Drop(list, {m,n})

Parameters:
list -- list to act on

n, m -- positive integers describing the entries to drop

Description:
This command removes a sublist of "list" and returns a list containing the remaining entries. The first calling sequence drops the first "n" entries in "list". The second form drops the last "n" entries. The last invocation drops the elements with indices "m" through "n".

Examples:
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};

See also:
Take , Select , Remove .


Take -- take a sublist from a list, dropping the rest

Standard library
Calling format:
Take(list, n)
Take(list, -n)
Take(list, {m,n})

Parameters:
list -- list to act on

n, m -- positive integers describing the entries to drop

Description:
This command takes a sublist of "list", drops the rest, and returns the selected sublist. The first calling sequence selects the first "n" entries in "list". The second form takes the last "n" entries. The last invocation selects the sublist beginning with entry number "m" and ending with the "n"-th entry.

Examples:
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};

See also:
Drop , Select , Remove .


Partition -- partition a list in sublists of equal length

Standard library
Calling format:
Partition(list, n)

Parameters:
list -- list to partition

n -- length of partitions

Description:
This command partitions "list" into non-overlapping sublists of length "n" and returns a list of these sublists. The first "n" entries in "list" form the first partition, the entries from position "n+1" upto "2n" form the second partition, and so on. If "n" does not divide the length of "list", the remaining entries will be thrown away. If "n" equals zero, an empty list is returned.

Examples:
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:
Take , Permutations .


Assoc -- return element stored in association list

Standard library
Calling format:
Assoc(key, alist)

Parameters:
key -- string, key under which element is stored

alist -- association list to examine

Description:
The association list "alist" is searched for an entry stored with index "key". If such an entry is found, it is returned. Otherwise the atom Empty is returned.

Association lists are represented as a list of two-entry lists. The first element in the two-entry 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 as alist[key].

Examples:
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 -- return the keys in an association list

Standard library
Calling format:
AssocIndices(alist)

Parameters:
alist -- association list to examine

Description:
All the keys in the association list "alist" are assembled in a list and this list is returned.

Examples:
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:
Assoc , AssocDelete .


AssocDelete -- delete an entry in an association list

Standard library
Calling format:
AssocDelete(alist, "key")
AssocDelete(alist, {key, value})

Parameters:
alist -- association list

"key" -- string, association key

value -- value of the key to be deleted

Description:
The key "key" in the association list alist is deleted. (The list itself is modified.) If the key was found and successfully deleted, returns True, otherwise if the given key was not found, the function returns False.

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:

At most one entry is deleted.

Examples:
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:
Assoc , AssocIndices .


Flatten -- flatten expression w.r.t. some operator

Standard library
Calling format:
Flatten(expression,operator)

Parameters:
expression -- an expression

operator -- string with the contents of an infix operator.

Description:
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.

Examples:
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 .


UnFlatten -- inverse operation of Flatten

Standard library
Calling format:
UnFlatten(list,operator,identity)

Parameters:
list -- list of objects the operator is to work on

operator -- infix operator

identity -- identity of the operator

Description:
UnFlatten is the inverse operation of Flatten. Given a list, it can be turned into an expression representing for instance the addition of these elements by calling UnFlatten 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.

Examples:
In> UnFlatten({a,b,c},"+",0)
Out> a+b+c;
In> UnFlatten({a,b,c},"*",1)
Out> a*b*c;

See also:
Flatten .


Type -- return the type of an expression

Internal function
Calling format:
Type(expr)

Parameters:
expr -- expression to examine

Description:
The type of the expression "expr" is represented as a string and returned. So, if "expr" is a list, the string "List" is returned. In general, the top-level operator of "expr" is returned. If the argument "expr" is an atom, the result is the empty string "".

Examples:
In> Type({a,b,c});
Out> "List";
In> Type(a*(b+c));
Out> "*";
In> Type(123);
Out> "";

See also:
IsAtom , NrArgs .


NrArgs -- return number of top-level arguments

Standard library
Calling format:
NrArgs(expr)

Parameters:
expr -- expression to examine

Description:
This function evaluates to the number of top-level arguments of the expression "expr". The argument "expr" may not be an atom, since that would lead to an error.

Examples:
In> NrArgs(f(a,b,c))
Out> 3;
In> NrArgs(Sin(x));
Out> 1;
In> NrArgs(a*(b+c));
Out> 2;

See also:
Type , Length .


VarList, VarListArith, VarListSome -- list of variables appearing in an expression

Standard library
Calling format:
VarList(expr)
VarListArith(expr)
VarListSome(expr, list)

Parameters:
expr -- an expression

list -- a list of function atoms

Description:
The command VarList(expr) returns a list of all variables that appear in the expression expr. The expression is traversed recursively.

The command VarListSome looks only at arguments of functions in the list. 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(b-c)) will return {a, b, c}, but VarListSome(a*Sin(b-c), {*}) will not look at arguments of Sin() and will return {a,Sin(b-c)}. Here Sin(b-c) is considered a "variable" because the function Sin does not belong to list.

The command VarListArith returns a list of all variables that appear arithmetically in the expression expr. This is implemented through VarListSome by resticting 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 use Atom("+") to obtain the unevaluated atom "+".

Examples:
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^2-1)
Out> {x,a,y^2};

See also:
IsFreeOf , IsVariable , FuncList , HasExpr , HasFunc .


FuncList, FuncListArith, FuncListSome -- list of functions used in an expression

Standard library
Calling format:
FuncList(expr)
FuncListArith(expr)
FuncListSome(expr, list)

Parameters:
expr -- an expression

list -- list of function atoms to be considered "transparent"

Description:
The command FuncList(expr) returns a list of all function atoms that appear in the expression expr. The expression is recursively traversed.

The command FuncListSome(expr, list) 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 any other functions). For example, FuncListSome(a + Sin(b-c)) will see that the expression has a "-" operation and return {+,Sin,-}, but FuncListSome(a + Sin(b-c), {+}) will not look at arguments of Sin() and will return {+,Sin}.

FuncListArith is defined through FuncListSome 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 "+".

Examples:
In> FuncList(x+y*Cos(Ln(x)/x))
Out> {+,*,Cos,/,Ln};
In> FuncListArith(x+y*Cos(Ln(x)/x))
Out> {+,*,Cos};
In> FuncListSome({a+b*2,c/d},{List})
Out> {List,+,/};

See also:
VarList , HasExpr , HasFunc .


BubbleSort, HeapSort -- sort a list

Standard library
Calling format:
BubbleSort(list, compare)
HeapSort(list, compare)

Parameters:
list -- list to sort

compare -- function used to compare elements of list

Description:
This command returns list after it is sorted using compare to compare elements. The function compare should accept two arguments, which will be elements of list, and compare them. It should return True if in the sorted list the second argument should come after the first one, and False otherwise.

The function BubbleSort uses the so-called "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.

The function HeapSort uses a recursive algorithm "heapsort" and is much faster for large lists. The sorting time is proportional to n*Ln(n) where n is the length of the list.

Examples:
In> BubbleSort({4,7,23,53,-2,1}, "<");
Out> {-2,1,4,7,23,53};
In> HeapSort({4,7,23,53,-2,1}, ">");
Out> {53,23,7,4,1,-2};


PrintList -- print list with padding

Standard library
Calling format:
PrintList(list)
PrintList(list, padding);

Parameters:
list -- a list to be printed

padding -- (optional) a string

Description:
Prints list and inserts the padding string between each pair of items of the list. Items of the list which are strings are printed without quotes, unlike Write(). Items of the list which are themselves lists are printed inside braces {}. If padding is not specified, a standard one is used (comma, space).

Examples:
In> PrintList({a,b,{c, d}}, " .. ")
Out> " a ..  b .. { c ..  d}";

See also:
Write , WriteString .


Table -- evaluate while some variable ranges over interval

Standard library
Calling format:
Table(body, var, from, to, step)

Parameters:
body -- expression to evaluate multiple times

var -- variable to use as loop variable

from -- initial value for "var"

to -- final value for "var"

step -- step size with which "var" is incremented

Description:
This command generates a list of values from "body", by assigning variable "var" values from "from" upto "to", incrementing "step" each time. So, the variable "var" first gets the value "from", and the expression "body" is evaluated. Then the value "from"+"step" is assigned to "var" and the expression "body" is again evaluated. This continues, incrementing "var" with "step" on every iteration, until "var" exceeds "to". At that moment, all the results are assembled in a list and this list is returned.

Examples:
In> Table(i!, i, 1, 10, 1);
Out> {1,2,6,24,120,720,5040,40320,362880,3628800};
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 -- print each entry in a list on a line

Standard library
Calling format:
TableForm(list)

Parameters:
list -- list to print

Description:
This functions writes out "list" in a nicer readable form, by printing every element in the list on a seperate line.

Examples:
In> TableForm(Table(i!, i, 1, 10, 1));
1
 2
 6
 24
 120
 720
 5040
 40320
 362880
 3628800
Out> True;

See also:
PrettyForm , Echo , Table .


GlobalPop, GlobalPush -- save/restore variables using a global stack

Standard library
Calling format:
GlobalPop(var)
GlobalPop()
GlobalPush(expr)

Parameters:
var -- atom, name of variable to restore from the stack

expr -- expression, value to save on the stack

Description:
These functions operate with a global stack, currently implemented as a list GlobalStack.

GlobalPush stores a value on the 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.

Examples:
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:
Push , PopFront .


: , @ , /@ , .. , NFunction , Where , AddTo .

Functional operators

These operators can help the user to program in the style of functional programming languages such as Miranda or Haskell.


: -- prepend item to list, or concatenate strings

Standard library
Calling format:
item : list (prec. 7)
string1 : string2 (prec. 7)

Parameters:
item -- an item to be prepended to a list

list -- a list

string1 -- a string

string2 -- a string

Description:
The first form prepends "item" as the first entry to the list "list". The second form concatenates the strings "string1" and "string2".

Examples:
In> a:b:c:{}
Out> {a,b,c};
In> "This":"Is":"A":"String"
Out> "ThisIsAString";

See also:
Concat , ConcatStrings .


@ -- apply a function

Standard library
Calling format:
fn @ arglist (prec. 60)

Parameters:
fn -- function to apply

arglist -- single argument, or a list of arguments

Description:
This function is a shorthand for Apply. It applies the function "fn" to the argument(s) in "arglist" and returns the result. The first parameter "fn" can either be a string containing the name of a function or a pure function.

Examples:
In> "Sin" @ a
Out> Sin(a);
In> {{a},Sin(a)} @ a
Out> Sin(a);
In> "f" @ {a,b}
Out> f(a,b);

See also:
Apply .


/@ -- apply a function to all entries in a list

Standard library
Calling format:
fn /@ list (prec. 60)

Parameters:
fn -- function to apply

list -- list of arguments

Description:
This function is a shorthand for MapSingle. It successively applies the function "fn" to all the entries in "list" and returns a list contains the results. The parameter "fn" can either be a string containing the name of a function or a pure function.

Examples:
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:
MapSingle , Map , MapArgs .


.. -- construct a list of consecutive integers

Standard library
Calling format:
n .. m (prec. 60)

Parameters:
n -- integer. the first entry in the list

m -- integer, the last entry in the list

Description:
This command returns the list {n, n+1, n+2, ..., m}. If m is smaller than n, the empty list is returned. Note that the .. operator should be surrounded by spaces to keep the parser happy, if "n" is a number. So one should write "1 .. 4" instead of "1..4".

Example:
In> 1 .. 4
Out> {1,2,3,4};

See also:
Table .


NFunction -- make wrapper for numeric functions

Standard library
Calling format:
NFunction("newname","funcname", {arglist})

Parameters:
"newname" -- name of new function

"funcname" -- name of an existing function

arglist -- symbolic list of arguments

Description:
This function will define a function named "newname" with the same arguments as an existing function named "funcname". The new function will evaluate and return the expression "funcname(arglist)" only when all items in the argument list arglist are numbers, and return unevaluated otherwise.

This can be useful when plotting functions defined through other Yacas routines that cannot return unevaluated.

Example:
Suppose we need to define a complicated function t(x) which cannot be evaluated unless x is a number:

In> t(x) := If(x<=0.5, 2*x, 2*(1-x));
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 wrapper t1(x) around t(x) which will not try to evaluate t(x) unless x 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:
MacroRule .


Where -- substitute result into expression

Standard library
Calling format:
expr Where x==v
expr Where x1==v1 And x2==v2 And ...
expr Where {x1==v1 And x2==v2,x1==v3
  And x2==v4,...}

Parameters:
expr - expression to evaluate

x - variable to set

v - value to substitute for variable

Description:
The operator Where fills in values for variables, in its simplest form. It accepts sets of variable/value pairs defined as

var1==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 through Solve.

Examples:
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};

See also:
Solve , AddTo .


AddTo -- add an equation to a set of equations or set of set of equations

Standard library
Calling format:
eq1 AddTo eq2

Parameters:
eq - (set of) set of equations

Description:
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.

Examples:
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};

See also:
Where , Solve .


MaxEvalDepth , Hold , Eval , While , Until , If , SystemCall , Function , Use , For , ForEach , Apply , MapArgs , Subst , WithValue , /:, /:: , SetHelpBrowser , TraceStack , TraceExp , TraceRule .

Control flow functions


MaxEvalDepth -- set the maximum evaluation depth

Internal function
Calling format:
MaxEvalDepth(n)

Parameters:
n -- new maximum evalution depth

Description:
Use this command to set the maximum evaluation depth to the integer "n". The default value is 1000. The function MaxEvalDepth returns True.

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 expression f(x) would call f(x), which would call f(x), etcetera. The interpreter will halt if the maximum evaluation depth is reached. Also indirect recursion, e.g. the pair of definitions f(x) := g(x) and g(x) := f(x), will be caught.

Examples:
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(n-1);
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 -- keep expression unevaluated

Internal function
Calling format:
Hold(expr)

Parameters:
expr -- expression to keep unevaluated

Description:
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.

The function UnList() also leaves its result unevaluated. Both functions stop the process of evaluation (no more rules will be applied).

Examples:
In> Echo({ Hold(1+1), "=", 1+1 });
 1+1 = 2
Out> True;

See also:
Eval , HoldArg , UnList .


Eval -- force evaluation of expression

Internal function
Calling format:
Eval(expr)

Parameters:
expr -- expression to evaluate

Description:
This function explicitly requests an evaluation of the expression "expr", and returns the result of this evaluation.

Examples:
In> a := x;
Out> x;
In> x := 5;
Out> 5;
In> a;
Out> x;
In> Eval(a);
Out> 5;

The variable a is bound to x, and x is bound to 5. Hence evaluating a will give x. Only when an extra evaluation of a is requested, the value 5 is returned.

Note that the behaviour would be different if we had exchanged the assignments. If the assignment a := x were given while x had the value 5, the variable a would also get the value 5 because the assignment operator := evaluates the right-hand side.

See also:
Hold , HoldArg , := .


While -- loop while a condition is met

Internal function
Calling format:
While(pred) body

Parameters:
pred -- predicate deciding whether to keep on looping

body -- expression to loop over

Description:
Keep on evaluating "body" while "pred" evaluates to True. More precisely, While evaluates the predicate "pred", which should evaluate to either True or False. If the result is True, the expression "body" is evaluated and then the predicate "pred" is again evaluated. If it is still True, the expressions "body" and "pred" are again evaluated and so on until "pred" evaluates to False. At that point, the loop terminates and While returns True.

In particular, if "pred" immediately evaluates to False, the body is never executed. While is the fundamental looping construct on which all other loop commands are based. It is equivalent to the while command in the programming language C.

Examples:
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;

See also:
Until , For .


Until -- loop until a condition is met

Standard library
Calling format:
Until(pred) body

Parameters:
pred -- predicate deciding whether to stop

body -- expression to loop over

Description:
Keep on evaluating "body" until "pred" becomes True. More precisely, Until first evaluates the expression "body". Then the predicate "pred" is evaluated, which should yield either True or False. In the latter case, the expressions "body" and "pred" are again evaluated and this continues as long as "pred" is False. As soon as "pred" yields True, the loop terminates and Until returns True.

The main difference with While is that Until always evaluates the body at least once, but While may not evaluate the body at all. Besides, the meaning of the predicate is reversed: While stops if "pred" is False while Until stops if "pred" is True. The command Until(pred) body; is equivalent to pred; While(Not pred) body;. In fact, the implementation of Until is based on the internal command While. The Until command can be compared to the do ... while construct in the programming language C.

Examples:
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;

See also:
While , For .


If -- branch point

Internal function
Calling format:
If(pred, then)
If(pred, then, else)

Parameters:
pred -- predicate to test

then -- expression to evaluate if "pred" is True

else -- expression to evaluate if "pred" is False

Description:
This command implements a branch point. The predicate "pred" is evaluated, which should result in either True or False. In the first case, the expression "then" is evaluated and returned. If the predicate yields False, the expression "else" (if present) is evaluated and returned. If there is no "else" branch (ie. if the first calling sequence is used), the If expression returns False.

Examples:
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;


SystemCall -- pass a command to the shell

Internal function
Calling format:
SystemCall(str)

Parameters:
str -- string containing the command to call

Description:
The command contained in the string "str" is executed by the underlying Operating System. The return value of SystemCall is True.

This command is not allowed in the body of the Secure command and will lead to an error.

Examples:
In a UNIX environment, the command SystemCall("ls") would list the contents of the current directory.

See also:
Secure .


Function -- declare or define a function

Standard library
Calling format:
Function() func(arglist)
Function() func(arglist, ...)
Function("op", {arglist}) body
Function("op", {arglist, ...}) body

Parameters:
func(args) -- function declaration, e.g. f(x,y)

"op" -- string, name of the function

{arglist} -- list of atoms, formal arguments to the function

... -- literal ellipsis symbol "..." used to denote a variable number of arguments

body -- expression comprising the body of the function

Description:
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 arglist. If the ellipsis "..." follows the last atom in arglist, a function with a variable number of arguments is declared (using RuleBaseListed). Note that the ellipsis cannot be the only element of arglist and must be preceded by an atom.

A function with variable number of arguments can take more arguments than elements in arglist; in this case, it obtains its last argument as a list containing all extra arguments.

The short form of the Function call merely declares a RuleBase for the new function but does not define any function body. This is a convenient shorthand for RuleBase and RuleBaseListed, 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 as op(_arg1, _arg2) <-- body. The rule will be declared at precedence 1025. Any previous rules associated with "op" (with the same arity) will be discarded. More complicated functions (with more than one body) can be defined by adding more rules.

Examples:
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 be FirstOf(_list) <-- list[1] or FirstOf(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 .


Use -- load a file, but not twice

Internal function
Calling format:
Use(name)

Parameters:
name -- name of the file to load

Description:
If the file "name" has been loaded before, either by an earlier call to Use or via the DefLoad mechanism, nothing happens. Otherwise all expressions in the file are read and evaluated. Use always returns True.

The purpose of this function is to make sure that the file will at least have been loaded, but is not loaded twice.

See also:
Load , DefLoad , DefaultDirectory .


For -- C-style for loop

Standard library
Calling format:
For(init, pred, incr) body

Parameters:
init -- expression for performing the initialization

pred -- predicate deciding whether to continue the loop

incr -- expression to increment the counter

body -- expression to loop over

Description:
This commands implements a C style for loop. First of all, the expression "init" is evaluated. Then the predicate "pred" is evaluated, which should return True or False. Next the loop is executed as long as the predicate yields True. One traversion of the loop consists of the subsequent evaluations of "body", "incr", and "pred". Finally, the value True is returned.

This command is most often used in a form such as For(i=1, i<=10, i++) body, which evaluates body with i subsequently set to 1, 2, 3, 4, 5, 6, 7, 8, 9, and 10.

The expression For(init, pred, incr) body is equivalent to init; While(pred) [body; incr;].

Examples:
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;

See also:
While , Until , ForEach .


ForEach -- loop over all entries in list

Standard library
Calling format:
ForEach(var, list) body

Parameters:
var -- looping variable

list -- list of values to assign to "var"

body -- expression to evaluate with different values of "var"

Description:
The expression "body" 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 returns True.

Examples:
 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:
For .


Apply -- apply a function to arguments

Standard library
Calling format:
Apply(fn, arglist)

Parameters:
fn -- function to apply

arglist -- list of arguments

Description:
This function applies the function "fn" to the arguments in "arglist" and returns the result. The first parameter "fn" can either be a string containing the name of a function or a pure function. Pure functions, modelled after lambda-expressions, have the form "varlist,body", where "varlist" is the list of formal parameters. Upon application, the formal paramaters are assigned the values in "arglist" (the second parameter of Apply) and the "body" is evaluated

An shorthand for Apply is provided by the @ operator.

Examples:
In> Apply("+", {5,9});
Out> 14;
In> Apply({{x,y}, x-y^2}, {Cos(a), Sin(a)});
Out> Cos(a)-Sin(a)^2;

See also:
Map , MapSingle , @ .


MapArgs -- apply a function to all top-level arguments

Standard library
Calling format:
MapArgs(expr, fn)

Parameters:
expr -- an expression to work on

fn -- an operation to perform on each argument

Description:
Every top-level argument in "expr" is substituted by the result of applying "fn" to this argument. Here "fn" can be either the name of a function or a pure function.

Examples:
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:
MapSingle , Map , Apply .


Subst -- perform a substitution

Standard library
Calling format:
Subst(from, to) expr

Parameters:
from -- expression to be substituted

to -- expression to substitute for "from"

expr -- expression in which the substitution takes place

Description:
This function substitutes every occurence of "from" in "expr" by "to". This is a syntactical substitution: only places where "from" occurs as a subexpression are affected.

Examples:
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. Hence a+b is a subexpression, but b+c is not.

See also:
WithValue , /: .


WithValue -- temporary assignment during an evaluation

Standard library
Calling format:
WithValue(var, val, expr)
WithValue({var,...}, {val,...}, expr)

Parameters:
var -- variable to assign to

val -- value to be assigned to "var"

expr -- expression to evaluate with "var" equal to "val"

Description:
First, the expression "val" is assigned to the variable "var". Then, the expression "expr" is evaluated and returned. Finally, the assignment is reversed so that the variable "var" has the same value as it had before WithValue 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, etcetera.

Examples:
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;

See also:
Subst , /: .


/:, /:: -- local simplification rules

Standard library
Calling format:
expression /: patterns
expressions /:: patterns
(prec. 10000)

Parameters:
expression -- an expression

patterns -- a list of patterns

Description:
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 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:

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 as Subst does, that is, top down, trying to apply the rules from the begining 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.

Examples:
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:
Subst .


SetHelpBrowser -- set the HTML browser to use for help

Standard library
Calling format:
SetHelpBrowser(helpbrowser)

Parameters:
helpbrowser -- string containing a html browser to use for help

Description:
This function sets the help browser you want to use to browse the help online. It calls the help browser with the html page as first argument. The default value is lynx. If you want to use a different browser by default it suffices to create a file ~/.yacasrc and add a line to set the browser in there.

Examples:
In> SetHelpBrowser("netscape")
Out> "netscape";
In> ??

See also:
Help .


TraceStack -- show calling stack after an error occurs

Internal function
Calling format:
TraceStack(expression)

Parameters:
expression -- an expression to evaluate

Description:
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 built-in function or a user-defined function, and for the user-defined 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.

Examples:
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 , TraceRule .


TraceExp -- evaluate with tracing enabled

Internal function
Calling format:
TraceExp(expr)

Parameters:
expr -- expression to trace

Description:
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 forn 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.

Examples:
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:
TraceStack , TraceRule .


TraceRule -- turn on tracing for a particular function

Internal function
Calling format:
TraceRule(template) expr

Parameters:
template -- template showing the operator to trace

expr -- expression to evaluate with tracing on

Description:
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 top-level 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.

Examples:
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:
TraceStack , TraceExp .


< , > , <= , >= , != , = , Not , And , Or , IsFreeOf , IsZeroVector , IsNonObject , IsEven , IsOdd , IsFunction , IsAtom , IsString , IsNumber , IsList , IsNumericList , IsBound , IsBoolean , IsNegativeNumber , IsNegativeInteger , IsPositiveNumber , IsPositiveInteger , IsNotZero , IsNonZeroInteger , IsInfinity , IsPositiveReal , IsNegativeReal , IsConstant , IsGaussianInteger , IsGaussianPrime , MatchLinear , HasExpr, HasExprArith, HasExprSome , HasFunc, HasFuncArith, HasFuncSome .

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.


< -- test for "less than"

Standard library
Calling format:
e1 < e2
(prec. 9)

Parameters:
e1, e2 -- expressions to be compared

Description:
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 is False 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 returns True), or the quotient of two numbers, or an infinity (i.e. IsInfinity returns True).

Examples:
In> 2 < 5;
Out> True;
In> Cos(1) < 5;
Out> Cos(1)<5;
In> N(Cos(1)) < 5;
Out> True

See also:
IsNumber , IsInfinity , N .


> -- test for "greater than"

Standard library
Calling format:
e1 > e2
(prec. 9)

Parameters:
e1, e2 -- expressions to be compared

Description:
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 is False 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 returns True), or the quotient of two numbers, or an infinity (i.e. IsInfinity returns True).

Examples:
In> 2 > 5;
Out> False;
In> Cos(1) > 5;
Out> Cos(1)>5;
In> N(Cos(1)) > 5;
Out> False

See also:
IsNumber , IsInfinity , N .


<= -- test for "less or equal"

Standard library
Calling format:
e1 <= e2
(prec. 9)

Parameters:
e1, e2 -- expressions to be compared

Description:
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 is False 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 returns True), or the quotient of two numbers, or an infinity (i.e. IsInfinity returns True).

Examples:
In> 2 <= 5;
Out> True;
In> Cos(1) <= 5;
Out> Cos(1)<=5;
In> N(Cos(1)) <= 5;
Out> True

See also:
IsNumber , IsInfinity , N .


>= -- test for "greater or equal"

Standard library
Calling format:
e1 >= e2
(prec. 9)

Parameters:
e1, e2 -- expressions to be compared

Description:
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 is False 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 returns True), or the quotient of two numbers, or an infinity (i.e. IsInfinity returns True).

Examples:
In> 2 >= 5;
Out> False;
In> Cos(1) >= 5;
Out> Cos(1)>=5;
In> N(Cos(1)) >= 5;
Out> False

See also:
IsNumber , IsInfinity , N .


!= -- test for "not equal"

Standard library
Calling format:
e1 != e2
(prec. 9)

Parameters:
e1, e2 -- expressions to be compared

Description:
Both expressions are evaluated and compared. If they turn out to be equal, the result is False. Otherwise, the result is True.

The expression e1 != e2 is equivalent to Not(e1 = e2).

Examples:
In> 1 != 2;
Out> True;
In> 1 != 1;
Out> False;

See also:
= .


= -- test for equality of expressions

Standard library
Calling format:
e1 = e2
(prec. 9)

Parameters:
e1, e2 -- expressions to be compared

Description:
Both expressions are evaluated and compared. If they turn out to be equal, the result is True. Otherwise, the result is False. The function Equals does the same.

Note that the test is on syntactic equality, not mathematical equality. Hence even if the result is False, 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.

Examples:
In> e1 := (x+1) * (x-1);
Out> (x+1)*(x-1);
In> e2 := x^2 - 1;
Out> x^2-1;

In> e1 = e2;
Out> False;
In> Expand(e1) = e2;
Out> True;

See also:
!= , Equals .


Not -- logical negation

Internal function
Calling format:
Not expr

Parameters:
expr -- a boolean expression

Description:
Not returns the logical negation of the argument expr. If expr is False it returns True, and if expr is True, Not expr returns False. If the argument is neither True nor False, it returns the entire expression with evaluated arguments.

Examples:
In> Not True
Out> False;
In> Not False
Out> True;
In> Not(a)
Out> Not a;

See also:
And , Or .


And -- logical conjunction

Internal function
Calling format:
a1 And a2
(prec. 100)
And(a1, a2, a3, ..., aN)

Parameters:
a1, ..., aN -- boolean values (may evaluate to True or False)

Description:
This function returns True if all arguments are true. The And operation is "lazy", i.e. it returns False as soon as a False argument is found (from left to right). If an argument other than True or False is encountered a new And expression is returned with all arguments that didn't evaluate to True or False yet.

Examples:
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 .


Or -- logical disjunction

Internal function
Calling format:
a1 Or a2
(prec. 101)
Or(a1, a2, a3, ..., aN)

Parameters:
a1, ..., aN -- boolean expressions (may evaluate to True or False)

Description:
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 returns True as soon as a True argument is found (from left to right). If an argument other than True or False is encountered, an unevaluated Or expression is returned with all arguments that didn't evaluate to True or False yet.

Examples:
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 -- test whether expression depends on variable

Standard library
Calling format:
IsFreeOf(var, expr)
IsFreeOf({var, ...}, expr)

Parameters:
expr -- expression to test

var -- variable to look for in "expr"

Description:
This function checks whether the expression "expr" (after being evaluated) depends on the variable "var". It returns False if this is the case and True otherwise.

The second form test whether the expression depends on any of the variables named in the list. The result is True if none of the variables appear in the expression and False otherwise.

Examples:
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 True because the expression D(x) a*x+b evaluates to a, which does not depend on x.

See also:
Contains .


IsZeroVector -- test whether list contains only zeroes

Standard library
Calling format:
IsZeroVector(list)

Parameters:
list -- list to compare against the zero vector

Description:
The only argument given to IsZeroVector should be a list. The result is True if the list contains only zeroes and False otherwise.

Examples:
In> IsZeroVector({0, x, 0});
Out> False;
In> IsZeroVector({x-x, 1 - D(x) x});
Out> True;

See also:
IsList , ZeroVector .


IsNonObject -- test whether argument is not an Object()

Standard library
Calling format:
IsNonObject(expr)

Parameters:
expr -- the expression to examine

Description:
This function returns True if "expr" is not of the form Object(...) and False otherwise.

Bugs
In fact, the result is always True.

See also:
Object .


IsEven -- test for an even integer

Standard library
Calling format:
IsEven(n)

Parameters:
n -- integer to test

Description:
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, etcetera, and -2, -4, -6, -8, -10, etcetera.

Examples:
In> IsEven(4);
Out> True;
In> IsEven(-1);
Out> False;

See also:
IsOdd , IsInteger .


IsOdd -- test for an odd integer

Standard library
Calling format:
IsOdd(n)

Parameters:
n -- integer to test

Description:
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, etcetera, and -1, -3, -5, -7, -9, etcetera.

Examples:
In> IsOdd(4);
Out> False;
In> IsOdd(-1);
Out> True;

See also:
IsEven , IsInteger .


IsFunction -- test for a composite object

Internal function
Calling format:
IsFunction(expr)

Parameters:
expr -- expression to test

Description:
This function tests whether "expr" is a composite object, i.e. not an atom. This includes not only obvious functions such as f(x), but also expressions such as x+5 and lists.

Examples:
In> IsFunction(x+5);
Out> True;
In> IsFunction(x);
Out> False;

See also:
IsAtom , IsList , Type .


IsAtom -- test for an atom

Internal function
Calling format:
IsAtom(expr)

Parameters:
expr -- expression to test

Description:
This function tests whether "expr" is an atom. Numbers, strings, and variables are all atoms.

Examples:
In> IsAtom(x+5);
Out> Falso;
In> IsAtom(5);
Out> True;

See also:
IsFunction , IsNumber , IsString .


IsString -- test for an string

Internal function
Calling format:
IsString(expr)

Parameters:
expr -- expression to test

Description:
This function tests whether "expr" is a string. A string is a text within quotes, eg. "duh".

Examples:
In> IsString("duh");
Out> True;
In> IsString(duh);
Out> False;

See also:
IsAtom , IsNumber .


IsNumber -- test for a number

Internal function
Calling format:
IsNumber(expr)

Parameters:
expr -- expression to test

Description:
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.

Examples:
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 -- test for a list

Internal function
Calling format:
IsList(expr)

Parameters:
expr -- expression to test

Description:
This function tests whether "expr" is a list. A list is a sequence between curly braces, e.g. {2, 3, 5}.

Examples:
In> IsList({2,3,5});
Out> True;
In> IsList(2+3+5);
Out> False;

See also:
IsFunction .


IsNumericList -- test for a list of numbers

Standard library
Calling format:
IsNumericList({list})

Parameters:
{list} -- a list

Description:
Returns True when called on a list of numbers or expressions that evaluate to numbers using N(). Returns False otherwise.

See also:
N , IsNumber .


IsBound -- test for a bound variable

Internal function
Calling format:
IsBound(var)

Parameters:
var -- variable to test

Description:
This function tests whether the variable "var" is bound, ie. whether it has been assigned a value. The argument "var" is not evaluated.

Examples:
In> IsBound(x);
Out> False;
In> x := 5;
Out> 5;
In> IsBound(x);
Out> True;

See also:
IsAtom .


IsBoolean -- test for a Boolean value

Standard library
Calling format:
IsBoolean(expression)

Parameters:
expression -- an expression

Description:
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.

Examples:
In> IsBoolean(a)
Out> False;
In> IsBoolean(True)
Out> True;
In> IsBoolean(a And b)
Out> True;

See also:
True , False .


IsNegativeNumber -- test for a negative number

Standard library
Calling format:
IsNegativeNumber(n)

Parameters:
n -- number to test

Description:
IsNegativeNumber(n) evaluates to True if n is (strictly) negative, i.e. if n<0. If n is not a number, the functions return False.

Examples:
In> IsNegativeNumber(6);
Out> False;
In> IsNegativeNumber(-2.5);
Out> True;

See also:
IsNumber , IsPositiveNumber , IsNotZero , IsNegativeInteger , IsNegativeReal .


IsNegativeInteger -- test for a negative integer

Standard library
Calling format:
IsNegativeInteger(n)

Parameters:
n -- integer to test

Description:
This function tests whether the integer n is (strictly) negative. The negative integers are -1, -2, -3, -4, -5, etcetera. If n is not a integer, the function returns False.

Examples:
In> IsNegativeInteger(31);
Out> False;
In> IsNegativeInteger(-2);
Out> True;

See also:
IsPositiveInteger , IsNonZeroInteger , IsNegativeNumber .


IsPositiveNumber -- test for a positive number

Standard library
Calling format:
IsPositiveNumber(n)

Parameters:
n -- number to test

Description:
IsPositiveNumber(n) evaluates to True if n is (strictly) positive, i.e. if n>0. If n is not a number the function returns False.

Examples:
In> IsPositiveNumber(6);
Out> True;
In> IsPositiveNumber(-2.5);
Out> False;

See also:
IsNumber , IsNegativeNumber , IsNotZero , IsPositiveInteger , IsPositiveReal .


IsPositiveInteger -- test for a positive integer

Standard library
Calling format:
IsPositiveInteger(n)

Parameters:
n -- integer to test

Description:
This function tests whether the integer n is (strictly) positive. The positive integers are 1, 2, 3, 4, 5, etcetera. If n is not a integer, the function returns False.

Examples:
In> IsPositiveInteger(31);
Out> True;
In> IsPositiveInteger(-2);
Out> False;

See also:
IsNegativeInteger , IsNonZeroInteger , IsPositiveNumber .


IsNotZero -- test for a nonzero number

Standard library
Calling format:
IsNotZero(n)

Parameters:
n -- number to test

Description:
IsNotZero(n) evaluates to True if n is not zero. In case n is not a number, the function returns False.

Examples:
In> IsNotZero(3.25);
Out> True;
In> IsNotZero(0);
Out> False;

See also:
IsNumber , IsPositiveNumber , IsNegativeNumber , IsNonZeroInteger .


IsNonZeroInteger -- test for a nonzero integer

Standard library
Calling format:
IsNonZeroInteger(n)

Parameters:
n -- integer to test

Description:
This function tests whether the integer n is not zero. If n is not an integer, the result is False.

Examples:
In> IsNonZeroInteger(0)
Out> False;
In> IsNonZeroInteger(-2)
Out> True;

See also:
IsPositiveInteger , IsNegativeInteger , IsNotZero .


IsInfinity -- test for an infinity

Standard library
Calling format:
IsInfinity(expr)

Parameters:
expr -- expression to test

Description:
This function tests whether expr is an infinity. This is only the case if expr is either Infinity or -Infinity.

Examples:
In> IsInfinity(10^1000);
Out> False;
In> IsInfinity(-Infinity);
Out> True;

See also:
Integer .


IsPositiveReal -- test for a numerically positive value

Standard library
Calling format:
IsPositiveReal(expr)

Parameters:
expr -- expression to test

Description:
This function tries to approximate "expr" numerically. It returns True if this approximation is positive. In case no approximation can be found, the function returns False. Note that round-off errors may cause incorrect results.

Examples:
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 , IsPositiveNumber , N .


IsNegativeReal -- test for a numerically negative value

Standard library
Calling format:
IsNegativeReal(expr)

Parameters:
expr -- expression to test

Description:
This function tries to approximate expr numerically. It returns True if this approximation is negative. In case no approximation can be found, the function returns False. Note that round-off errors may cause incorrect results.

Examples:
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:
IsPositiveReal , IsNegativeNumber , N .


IsConstant -- test for a constant

Standard library
Calling format:
IsConstant(expr)

Parameters:
expr -- some expression

Description:
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.

Examples:
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 -- test for a Gaussian integer

Standard library
Calling format:
IsGaussianInteger(z)
Parameters:
z -- a complex or real number

Description:
This function returns a boolean value depending on whether or not the argument is a Gaussian integer. 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.

Examples:
In> IsGaussianInteger(5)
Out> True;
In> IsGaussianInteger(5+6*I)
Out> True;
In> IsGaussianInteger(1+2.5*I)
Out> False;

See also:
IsGaussianPrime .


IsGaussianPrime -- test for a Gaussian prime

Standard library
Calling format:
IsGaussianPrime(z)
Parameters:
z -- a complex or real number

Description:
This function returns a boolean value depending on whether or not the argument is a Gaussian prime. Gaussian primes are Gaussian integers z=a+b*I that satisfy one of the following properties. If Re(z) and Im(z) are nonzero then, z is a Gaussian prime if and only if Re(z)^2+Im(z)^2 is an ordinary prime. If Re(z)==0, then z is a Gaussian prime if and only if Im(z) is an ordinary prime and Im(z):=Mod(3,4). If Im(z)==0, then z is a Gaussian prime if and only if Re(z) is an ordinary prime and Re(z):=Mod(3,4).

Examples:
In> IsGaussianPrime(13)
Out> False;
In> IsGaussianPrime(2+2*I)
Out> False;
In> IsGaussianPrime(2+3*I)
Out> True;
In> IsGaussianPrime(3)
Out> True;

See also:
IsGaussianInteger .


MatchLinear -- match an expression to a polynomial of degree one in a variable

Standard library
Calling format:
MatchLinear(variable,expression)

Parameters:
variable -- variable to express the univariate polynomial in

expression -- expression to match

Description:
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.

Examples:
In> MatchLinear(x,(R+1)*x+(T-1))
Out> True;
In> {a,b};
Out> {R+1,T-1};
In> MatchLinear(x,Sin(x)*x+(T-1))
Out> False;

See also:
Integrate .


HasExpr, HasExprArith, HasExprSome -- check for expression containing a subexpression

Standard library
Calling format:
HasExpr(expr, x)
HasExprArith(expr, x)
HasExprSome(expr, x, list)

Parameters:
expr -- an expression

x -- a subexpression to be found

list -- list of function atoms to be considered "transparent"

Description:
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 "+".

Examples:
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:
FuncList , VarList , HasFunc .


HasFunc, HasFuncArith, HasFuncSome -- check for expression containing a function

Standard library
Calling format:
HasFunc(expr, func)
HasFuncArith(expr, func)
HasFuncSome(expr, func, list)

Parameters:
expr -- an expression

func -- a function atom to be found

list -- list of function atoms to be considered "transparent"

Description:
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 "+".

Examples:
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:
FuncList , VarList , HasExpr .


CanProve .

Propositional logic theorem prover


CanProve -- try to prove statement

Standard library
Calling format:
CanProve(proposition)

Parameters:
proposition -- an expression with logical operations

Description:
Yacas has a small built-in 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 Not p is false. It continues to simplify Not p using the rules:

Not  ( Not x)      --> x
(eliminate double negation),
x=>y  -->  Not x  Or  y
(eliminate implication),
Not (x And y)  -->  Not x  Or  Not y
(De Morgan's law),
Not (x Or y) -->  Not x  And  Not y
(De Morgan's law),
(x And y) Or z --> (x Or z) And (y Or z)
(distribution),
x Or (y And z) --> (x Or y) And (x Or z)
(distribution), and the obvious other rules, such as,
True Or x --> True
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 Or Y)  And  ( Not p Or Z) --> (Y Or Z)
If this combination (Y Or 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.

Examples:
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;

See also:
True , False , And , Or , Not .


% , True, False , EndOfFile , Infinity , Pi , Undefined .

Constants


% -- previous result

Internal function
Calling format:
%

Description:
% 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 LazyGlobal command).

Typical examples are Simplify(%) and PrettyForm(%) to simplify and show the result in a nice form respectively.

Examples:
In> Taylor(x,0,5)Sin(x)
Out> x-x^3/6+x^5/120;
In> PrettyForm(%)

     3    5
    x    x
x - -- + ---
    6    120


See also:
LazyGlobal .


True, False -- boolean constants

Internal function
Calling format:
True
False

Description:
True and False are typically a result of boolean expressions such as 2 < 3 or True And False.

See also:
And , Or , Not .


EndOfFile -- end-of-file marker

Internal function
Calling format:
EndOfFile

Description:
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.


Infinity -- constant representing mathematical infinity

Standard library
Calling format:
Infinity

Description:
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. Thus Infinity*2 will return Infinity, and a < Infinity will evaluate to True.

Examples:
In> 2*Infinity
Out> Infinity;
In> 2<Infinity
Out> True;


Pi -- mathematical constant, pi

Standard library
Calling format:
Pi

Description:
Pi symbolically represents the exact value of pi. When the N() function is used, Pi evaluates to a numerical value according to the current precision. This is performed by the function Pi() which always returns the numerical value. It is probably better to use Pi than Pi(), because exact simplification will be possible.

Examples:
In> Sin(3*Pi/2)
Out> -1;
In> Sin(3*Pi()/2)
Out> Sin(4.7123889804);
In> Pi+1
Out> Pi+1;
In> N(Pi)
Out> 3.14159265358979323846;

See also:
Sin , Cos , Precision , N , Pi() .


Undefined -- constant signifying an undefined result

Standard library
Calling format:
Undefined

Description:
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.

Examples:
In> 2*Infinity
Out> Infinity;
In> 0*Infinity
Out> Undefined;
In> Sin(Infinity);
Out> Undefined;
In> Undefined+2*Exp(Undefined);
Out> Undefined;

See also:
Infinity .


:= , Set , Clear , ++ , -- , Object , LazyGlobal , UniqueConstant .

Variables


:= -- assign a variable or a list; define a function

Standard library
Calling format:
var := expr
{var1, var2, ...} := {expr1, expr2, ...}
var[i] := expr
fn(arg1, arg2, ...) := expr
(the := operator has precedence 1000)

Parameters:
var -- atom, variable which should be assigned

expr -- expression to assign to the variable or body of function

i -- index (can be integer or string)

fn -- atom, name of a new function to define

arg1, arg2 -- atoms, names of arguments of the new function fn

Description:
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 right-hand side and assigns it to the variable named on the left-hand side. The left-hand 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 right-hand side is assigned to the first variable mentionedon the left-hand side, the second entry on the right-hand side to the second variable on the left-hand side, etcetera. The list on the right-hand side must have at least as many entries as the list on the left-hand 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 right-hand 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 right-hand side is evaluated before the assigment and the result of the assignment is True.

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 left-hand side may take a different form if fn is defined to be a prefix, infix or bodied function. This case is special since the right-hand 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 definining the new function.

A variant of the function definition can be used to make a function accepting a variable number of arguments. The last argument

Examples:
A simple 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> x-x^3/6+x^5/120-x^7/5040+x^9/362880-
x^11/39916800+x^13/6227020800-x^15/
1307674368000+x^17/355687428096000-x^19/
121645100408832000+x^21/51090942171709440000
-x^23/25852016738884976640000+x^25
/15511210043330985984000000;
In> f(2);
Out> x-x^3/6+x^5/120-x^7/5040+x^9/362880-
x^11/39916800+x^13/6227020800-x^15
/1307674368000+x^17/355687428096000-x^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> x-x^3/6+x^5/120-x^7/5040+x^9/362880-
x^11/39916800+x^13/6227020800-x^15/
1307674368000+x^17/355687428096000-x^19/
121645100408832000+x^21/51090942171709440000
-x^23/25852016738884976640000+x^25
/15511210043330985984000000;
In> f(2);
Out> x-x^3/6+x^5/120-x^7/5040+x^9/362880-
x^11/39916800+x^13/6227020800-x^15
/1307674368000+x^17/355687428096000-x^19/
121645100408832000+x^21/51090942171709440000
-x^23/25852016738884976640000+x^25/
15511210043330985984000000;

See also:
Set , Clear , [] , Rule , Infix , Eval , Function .


Set -- assignment

Internal function
Calling format:
Set(var, exp)

Parameters:
var -- variable which should be assigned

exp -- expression to assign to the variable

Description:
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.

Examples:
In> Set(a, Sin(x)+3);
Out> True;
In> a;
Out> Sin(x)+3;

See also:
Clear , := .


Clear -- undo an assignment

Internal function
Calling format:
Clear(var, ...)

Parameters:
var -- name of variable to be cleared

Description:
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.

Examples:
In> a := 5;
Out> 5;
In> a^2;
Out> 25;

In> Clear(a);
Out> True;
In> a^2;
Out> a^2;

See also:
Set , := .
Internal function
Calling format:
Local(var, ...)

Parameters:
var -- name of variable to be declared as local

Description:
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 the Prog 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 with UnFence.

Examples:
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 of a outside the block. However, in the second block a is defined to be local and now the value outside the block stays the same, even though a is assigned the value 5 inside the block.

See also:
LocalSymbols , Prog , [] , UnFence .


++ -- increment variable

Standard library
Calling format:
var++

Parameters:
var -- variable to increment

Description:
The variable with name "var" is incremented, i.e. the number 1 is added to it. The expression x++ is equivalent to the assignment x := x + 1, except that the assignment returns the new value of x while x++ always returns true. In this respect, Yacas' ++ differs from the corresponding operator in the programming language C.

Examples:
In> x := 5;
Out> 5;
In> x++;
Out> True;
In> x;
Out> 6;

See also:
-- , := .


-- -- decrement variable

Standard library
Calling format:
var--

Parameters:
var -- variable to decrement

Description:
The variable with name "var" is decremented, i.e. the number 1 is subtracted from it. The expression x-- is equivalent to the assignment x := x - 1, except that the assignment returns the new value of x while x-- always returns true. In this respect, Yacas' -- differs from the corresponding operator in the programming language C.

Examples:
In> x := 5;
Out> 5;
In> x--;
Out> True;
In> x;
Out> 4;

See also:
++ , := .


Object -- create an incomplete type

Standard library
Calling format:
Object("pred", exp)

Parameters:
pred -- name of the predicate to apply

exp -- expression on which "pred" should be applied

Description:
This function returns "obj" as soon as "pred" returns True when applied on "obj". This is used to declare so-called incomplete types.

Examples:
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:
IsNonObject .


LazyGlobal -- global variable is to be evaluated lazily

Internal function
Calling format:
LazyGlobal(var)

Parameters:
var -- variable (held argument)

Description:
LazyGlobal enforces that a global variable will re-evaluate when used. The global variable needs to exist for this function to work. Also, this functionality doesn't survive if Clear(var) is called afterwards.

Places where this is used include the global variables % and I.

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 LazyGlobal property only holds once: after that, the result of evaluation is stored in the global variable, and it won't be reevaluated again:

In> a:=Hold(Taylor(x,0,30)Sin(x))
Out> Taylor(x,0,30)Sin(x);
In> LazyGlobal(a)

Then the first time you call a it evaluates Taylor(...) and assigns the result to a. The next time you call a it immediately returns the result. LazyGlobal is called for % each time % changes.

Examples:
In> a:=Hold(2+3)
Out> 2+3;
In> a
Out> 2+3;
In> LazyGlobal(a)
Out> True;
In> a
Out> 5;

See also:
Set , Clear , Local , % , I .


UniqueConstant -- create a unique identifier

Standard library
Calling format:
UniqueConstant()

Description:
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.

Examples:
In> UniqueConstant()
Out> C9
In>  UniqueConstant()
Out> C10

See also:
LocalSymbols .


FullForm , Echo , PrettyForm , EvalFormula , TeXForm , CForm , IsCFormable , Write , WriteString , Space , NewLine , FromFile , FromString , ToFile , ToString , Read , LispRead, ListReadListed , ReadToken , Load , Use , DefLoad , FindFile , PatchLoad , Nl , V, Verbose , Plot2D .

Input/output and plotting

This chapter contains commands to use for input and output and plotting. 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 -- print an expression in LISP-format

Internal function
Calling format:
FullForm(expr)

Parameters:
expr -- expression to be printed in LISP-format

Description:
Evaluates "expr", and prints it in LISP-format 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.

Examples:
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, 2*I is first evaluated to Complex(0,2) before the expression is printed.

See also:
LispRead , Listify , Unlist .


Echo -- high-level printing routine

Standard library
Calling format:
Echo(item)
Echo(list)
Echo(item,item,item,...)

Parameters:
item -- the item to be printed

list -- a list of items to be printed

Description:
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.

Examples:
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 , Write , WriteString , RuleBaseListed .


PrettyForm -- print an expression nicely with ASCII art

Standard library
Calling format:
PrettyForm(expr)

Parameters:
expr -- an expression

Description:
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.

Examples:
In> Taylor(x,0,9)Sin(x)
Out> x-x^3/6+x^5/120-x^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 .


EvalFormula -- print an evaluation nicely with ASCII art

Standard library
Calling format:
EvalFormula(expr)

Parameters:
expr -- an expression

Description:
Show an evaluation in a nice way, using PrettyPrinter to show 'input = output'.

Examples:
In> EvalFormula(Taylor(x,0,7)Sin(x))

                                      3    5
                                     x    x  
Taylor( x , 0 , 5 , Sin( x ) ) = x - -- + ---
                                     6    120

See also:
PrettyForm .


TeXForm -- export expressions to LaTeX

Standard library
Calling format:
TeXForm(expr)

Parameters:
expr -- an expression to be exported

Description:
TeXForm returns a string containing a LaTeX representation of the Yacas expression expr. Currently the exporter handles most expression types but not all.

Example:
In> TeXForm(Sin(a1)+2*Cos(b1))
Out> "$\sin a_{1} + 2 \cos b_{1}$";

See also:
PrettyForm , CForm , ShowPS .


CForm -- export expression to C++ code

Standard library
Calling format:
CForm(expr)

Parameters:
expr -- expression to be exported

Description:
CForm returns a string containing C++ code that attempts to implement the Yacas expression expr. Currently the exporter handles most expression types but not all.

Example:
In> CForm(Sin(a1)+2*Cos(b1));
Out> "sin(a1) + 2 * cos(b1)";

See also:
PrettyForm , TeXForm , IsCFormable .


IsCFormable -- check possibility to export expression to C++ code

Standard library
Calling format:
IsCFormable(expr)
IsCFormable(expr, funclist)

Parameters:
expr -- expression to be exported (this argument is not evaluated)

funclist -- list of "allowed" function atoms

Description:
IsCFormable returns True if the Yacas expression expr can be exported into C++ code. This is a check whether the C++ exporter CForm 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 of IsCFormable can be used to "allow" certain function names that will be available in the C++ code.

Examples:
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 function func123 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;

See also:
CForm , V .


Write -- low-level printing routine

Internal function
Calling format:
Write(expr, ...)

Parameters:
expr -- expression to be printed

Description:
The expression "expr" is evaluated and written to the current output. Note that Write accept an arbitrary number of arguments, all of which are written to the current output (see second example). Write always returns True.

Examples:
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 of Write.

See also:
Echo , WriteString .


WriteString -- low-level printing routine for strings

Internal function
Calling format:
WriteString(string)

Parameters:
string -- the string to be printed

Description:
The expression "string" is evaluated and written to the current output without quotation marks. The argument should be a string. WriteString always returns True.

Examples:
In> Write("Hello, world!");
"Hello, world!"Out> True;
In> WriteString("Hello, world!");
Hello, world!Out> True;

This example clearly shows the difference between Write and WriteString. Note that Write and WriteString do not write a newline, so the Out> prompt immediately follows the output.

See also:
Echo , Write .


Space -- print one or more spaces

Standard library
Calling format:
Space()
Space(nr)

Parameters:
nr -- the number of spaces to print

Description:
The command Space() prints one space on the current output. The second form prints nr spaces on the current output. The result is always True.

Examples:
In> Space(5);
     Out> True;

See also:
Echo , Write , NewLine .


NewLine -- print one or more newline characters

Standard library
Calling format:
NewLine()
NewLine(nr)

Parameters:
nr -- the number of newline characters to print

Description:
The command NewLine() prints one newline character on the current output. The second form prints "nr" newlines on the current output. The result is always True.

Examples:
In> NewLine();

Out> True;

See also:
Echo , Write , Space .


FromFile -- connect current input to a file

Internal function
Calling format:
FromFile(name) body

Parameters:
name - string, the name of the file to read

body - expression to be evaluated

Description:
The current input is connected to the file "name". Then the expression "body" is evaluated. If some functions in "body" try to read from current input, they will now read from the file "name". Finally, the file is closed and the result of evaluating "body" is returned.

Examples:
Suppose that the file foo contains

2 + 5;

Then we can have the following dialogue:

In> FromFile("foo") res := Read();
Out> 2+5;
In> FromFile("foo") res := ReadToken();
Out> 2;

See also:
ToFile , FromString , Read , ReadToken .


FromString -- connect current input to a string

Internal function
Calling format:
FromString(str) body;

Parameters:
str -- a string containing the text to parse

body -- expression to be evaluated

Description:
The commands in "body" are executed, but everything that is read from the current input is now read from the string "str". The result of "body" is returned.

Examples:
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:
ToString , FromFile , Read , ReadToken .


ToFile -- connect current output to a file

Internal function
Calling format:
ToFile(name) body

Parameters:
name -- string, the name of the file to write the result to

body -- expression to be evaluated

Description:
The current output is connected to the file "name". Then the expression "body" is evaluated. Everything that the commands in "body" print to the current output, ends up in the file "name". Finally, the file is closed and the result of evaluating "body" is returned.

Examples:
Here is how one can create a file with C code to evaluate an expression:

In> ToFile("expr1.c") WriteString(
  CForm(Sqrt(x-y)*Sin(x)) );
Out> True;
The file expr1.c was created in the current working directory and it contains the line
sqrt(x-y)*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 -- connect current output to a string

Internal function
Calling format:
ToString() body

Parameters:
body -- expression to be evaluated

Description:
The commands in "body" are executed. Everything that is printed on the current output, by Echo for instance, is collected in a string and this string is returned.

Examples:
In> str := ToString() [ WriteString(  \
  "The square of 8 is "); Write(8^2); ];
Out> "The square of 8 is  64";

See also:
FromFile , ToString , Echo , Write , WriteString .


Read -- read an expression from current input

Internal function
Calling format:
Read()

Description:
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.

Examples:
In> FromString("2+5;") Read();
Out> 2+5;
In> FromString("") Read();
Out> EndOfFile;

See also:
FromFile , FromString , LispRead , ReadToken , Write .


LispRead, ListReadListed -- read expressions in the LISP syntax

Internal function
Calling format:
LispRead()
LispReadListed()

Description:
The function 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 atom EndOfFile is returned.

The Yacas expression a+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.

The function 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 applying Listify to LispRead. The function LispReadListed 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).

Examples:
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;
In> FromString("(+ a b)")LispReadListed()
Out> {+,a,b};

See also:
FromFile , FromString , Read , ReadToken , FullForm .


ReadToken -- read an token from current input

Internal function
Calling format:
ReadToken()

Description:
Read a token from the current input, and return it unevaluated. 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.

Examples:
In> FromString("a := Sin(x)") While \
  ((tok := ReadToken()) != EndOfFile) \
  Echo(tok);
a
:=
Sin
(
x
)
Out> True;

See also:
FromFile , FromString , Read , LispRead .


Load -- evaluate all expressions in a file

Internal function
Calling format:
Load(name)

Parameters:
name -- string, name of the file to load

Description:
The file "name" is opened. All expressions in the file are read and evaluated. Load always returns true.

See also:
Use , DefLoad , DefaultDirectory , FindFile .


Use -- load a file, but not twice

Internal function
Calling format:
Use(name)

Parameters:
name -- string, name of the file to load

Description:
If the file "name" has been loaded before, either by an earlier call to Use or via the DefLoad mechanism, nothing happens. Otherwise all expressions in the file are read and evaluated. Use always returns true.

The purpose of this function is to make sure that the file will at least have been loaded, but is not loaded twice.

See also:
Load , DefLoad , DefaultDirectory .


DefLoad -- load a .def file

Internal function
Calling format:
DefLoad(name)

Parameters:
name -- string, name of the file (without .def suffix)

Description:
The suffix .def is appended to "name" and the file with this name is loaded. It should contain a list of functions, terminated by a closing brace \} (the end-of-list delimiter). This tells the system to load the file "name" 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.

See also:
Load , Use , DefaultDirectory .


FindFile -- find a file in the current path

Internal function
Calling format:
FindFile(name)

Parameters:
name -- string, name of the file or directory to find

Description:
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 -- execute commands between <? and ?> in file

Internal function
Calling format:
PatchLoad(name)

Parameters:
name -- string, name of the file to "patch"

Description:
PatchLoad loads in a file and outputs the contents to the current output. The file can contain blocks delimited by <? and ?> (meaning "Yacas Begin" and "Yacas End"). 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:
PatchString , Load .


Nl -- the newline character

Standard library
Calling format:
Nl()

Description:
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.

Note that the second letter in the name of this command is a lower case L (from "line").

Examples:
In> WriteString("First line" : Nl() : "Second line" : Nl());
First line
Second line
Out> True;

See also:
NewLine .


V, Verbose -- set verbose output mode

Standard library
Calling format:
V(expression)

Parameters:
expression -- expression to be evaluated in verbose mode

Description:
The function V(expression) will evaluate the expression in verbose mode. Various parts of Yacas can show extra information about the work done while doing a calculation when using V.

The function is currently implemented using a global variable Verbose which can be set to True or False.

Examples:
In> Solve({x+2==0},{x})
Out> {{-2}};
In> V(Solve({x+2==0},{x}))
Entering Solve
From  x+2==0  it follows that  x  = -2 
   x+2==0  simplifies to  True 
Leaving Solve
Out> {{-2}};

See also:
Echo , N , Solve .


Plot2D -- adaptive two-dimensional plotting

Standard library
Calling format:
Plot2D(f(x))
Plot2D(f(x), a:b)
Plot2D(f(x), a:b, option=value)
Plot2D(f(x), a:b, option=value, ...)
Plot2D(list, ...)

Parameters:
f(x) -- unevaluated expression containing one variable (function to be plotted)

list -- list of functions to plot

a, b -- numbers, plotting range

option -- atom, option name

value -- atom, number or string (value of option)

Description:
The routine Plot2D performs adaptive plotting of one or several functions of one variable in the specified range. Several functions are specified by giving a list of expressions. Various plotting options can be specified. Output can be directed to a plotting program (the default is to use gnuplot), to a data file, or to a list of values.

The function parameter f(x) must be an unevaluated expression containing a variable (not necessarily called x). 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)}.

Data files are created in a temporary directory /tmp/plot.tmp/. File names and other information is printed if the Verbose option is switched on using V().

The current algorithm uses Newton-Cotes quadratures and some heuristics for error estimation (see the essay chapter on adaptive plotting). The initial grid of points+1 points is refined between any grid points a, b where the integral Integrate(x,a,b)f(x) is not approximated within 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 (e.g. output="gnuplot"). Several option/value pairs may be specified (the function Plot2D has a variable number of arguments).

Other options may be supported in the future. Note that currently the support for gnuplot and GNU plotutils is Unix-specific.

A frequently encountered problem: the parameter f(x) must evaluate to an expression that contains a variable (or to a constant). Test your function for this! If you have defined some f(x) which accepts a number but does not accept an undefined variable, Plot2D will fail to plot it. Use NFunction to overcome this difficulty.

The current implementation can deal with a singularity at endpoints or at any grid point only if the function f(x) returns Infinity, -Infinity or Undefined. If the function f(x) generates a numerical error and fails at a singularity, Plot2D will fail too, if one of the grid points falls on the singularity. (All grid points are generated by bisection so in principle the endpoints and the points parameter could be chosen to avoid numerical singularities.)

Examples:
In> Plot2D({(2+x)/(2-x),Exp(y)},-1.8:1.5)
Out> True;
In> V(Plot2D(Sin(1/x),0:1, depth=4, \
In>   precision=0.001, output=plotutils))
Plot2D: using 65 points for function Sin(1/x)
Plot2D'datafile: created file '/tmp/plot.tmp/data1'
Out> True;

If a function takes a long time to evaluate, one can use MakeFunctionPlugin (a Unix-specific tool) to compile the function and plot it faster:

In> f(x) := Cos( (Abs(Pi/x))^1.5 )
Out> True;
In> Time( Plot2D(f(x),0:1) )
94.93 seconds taken
Out> True;
In> MakeFunctionPlugin("f1", f(x))
Function f1(x) loaded from plugins.tmp/
  libf1_plugin_cc.so
Out> True;
In> Time( Plot2D(f1(x),0:1) )
6.97 seconds taken
Out> True;

See also:
V , NFunction , MakeFunctionPlugin .


SetStringMid , StringMid , String, Atom , ConcatStrings , LocalSymbols , PatchString .

String manipulation


SetStringMid -- change a substring

Internal function
Calling format:
SetStringMid(index,substring,string)

Parameters:
index -- index of substring to get

substring -- substring to store

string -- string to store substring in.

Description:
Set (change) a part of a string. It leaves the original alone, returning a new changed copy.

Examples:
In> SetStringMid(3,"XY","abcdef")
Out> "abXYef";

See also:
StringMid , Length .


StringMid -- retrieve a substring

Internal function
Calling format:
StringMid(index,length,string)

Parameters:
index -- index of substring to get

length -- length of substring to get

string -- string to get substring from

Description:
StringMid returns a part of a string. Substrings can also be accessed using the [] operator.

Examples:
In> StringMid(3,2,"abcdef")
Out> "cd";
In> "abcdefg"[2 .. 4]
Out> "bcd";

See also:
SetStringMid , Length .


String, Atom -- convert atom to string and vice versa

Internal function
Calling format:
Atom("string")
String(atom)

Parameters:
atom -- an atom

"string" -- a string

Description:
Returns an atom with the string representation given as the evaluated argument. Example: Atom("foo"); returns foo.

String is the inverse of Atom: turns atom into "atom".

Examples:
In> String(a)
Out> "a";
In> Atom("a")
Out> a;


ConcatStrings -- concatenate strings

Internal function
Calling format:
ConcatStrings(strings)

Parameters:
strings -- one or more strings

Description:
Concatenates strings.

Examples:
In> ConcatStrings("a","b","c")
Out> "abc";

See also:
: .


LocalSymbols -- create unique local symbols with given prefix

Standard library
Calling format:
LocalSymbols(var1, var2, ...) body

Parameters:
var1, var2, ... -- atoms, symbols to be made local

body -- expression to execute

Description:
Given the symbols passed as the first arguments to LocalSymbols a set of local symbols will be created, and creates unique ones for them, typically of the form $<symbol><number>, where symbol was the symbol entered by the user, and number is a unique number. This scheme was 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 macro-like functions (For, While, etc.).

Examples:
In> LocalSymbols(a,b)a+b
Out> $a6+ $b6;

See also:
UniqueConstant .


PatchString -- execute commands between <? and ?> in strings

Internal function
Calling format:
PatchString(string)

Parameters:
string -- a string to patch

Description:
This function does the same as PatchLoad, but it works on a string in stead of on the contents of a text file. See PatchLoad for more details.

Examples:
In> PatchString("Two plus three \
  is <? Write(2+3); ?> ");
Out> "Two plus three is 5 ";

See also:
PatchLoad .


BernoulliDistribution , BinomialDistribution , tDistribution , PDF , ChiSquareTest .

Probability and Statistics

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.


Probability


BernoulliDistribution -- Bernoulli distribution

Standard library
Calling format:
BernoulliDistribution(p)

Parameters:
p -- number, probability of an event in a single trial

Description:
A random variable has a Bernoulli distribution with probability p if it can be interpreted as an indicator of an event, where p is the probability to observe the event in a single trial.

Numerical value of p must satisfy 0<p<1.

See also:
BinomialDistribution .


BinomialDistribution -- binomial distribution

Standard library
Calling format:
BinomialDistribution(p,n)

Parameters:
p -- number, probability to observe an event in single trial

n -- number of trials

Description:
Suppose we repeat a trial n times, the probability to observe an event in a single trial is p 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 is BinomialDistribution(p,n).

Numerical value of p must satisfy 0<p<1. Numerical value of n must be a positive integer.

See also:
BernoulliDistribution .


tDistribution -- Student's t distribution

Standard library
Calling format:
{tDistribution}(m)

Parameters:
m -- integer, number of degrees of freedom

Description:

Let Y and Z be independent random variables, Y have the NormalDistribution(0,1), Z have ChiSquareDistribution(m). Then Y/Sqrt(Z/m) has tDistribution(m).

Numerical value of m must be positive integer.


PDF -- probability density function

Standard library
Calling format:
PDF(dist,x)

Parameters:
dist -- a distribution type

x -- a value of random variable

Description:
If dist is a discrete distribution, then PDF returns the probability for a random variable with distribution dist to take a value of x. If dist is a continuous distribution, then PDF returns the density function at point x.

See also:
CDF .


Statistics


ChiSquareTest -- Pearson's ChiSquare test

Standard library
Calling format:
ChiSquareTest(observed,expected)
ChiSquareTest(observed,expected,params)

Parameters:
observed -- list of observed frequencies

expected -- list of expected frequencies

params -- number of estimated parameters

Description:
ChiSquareTest 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 as ChiSquareDistribution.


GetYacasPID , ShowPS , MakeFunctionPlugin , Version , Vi .

Platform-dependent packages

Certain facilities have been developed for use on the Unix platform, which is currently the main development platform for Yacas. These packages are described in this chapter.


GetYacasPID -- obtain Yacas process number

Unix-specific add-on
Calling format:
GetYacasPID()

Description:
Returns an integer containing the process number (PID) of the Yacas session.

Requires: a Unix shell.

Example:
In> GetYacasPID()
Out> 26456;

See also:
SystemCall .


ShowPS -- view equations graphically

Unix-specific add-on
Calling format:
ShowPS(expr)

Parameters:
expr -- any expression (not evaluated)

Description:
Exports a Yacas expression to LaTeX, generates a Postscript file and shows it in a viewer. The free viewer gv must be available on the Unix shell path. An alternative viewer can be specified by assigning to the global variable PSViewCommand.

Requires: a Unix shell, latex, dvips, gv or another Postscript viewer.

Example:
In> [ PSViewCommand := "ghostview"; \
  ShowPS(x+2*Sin(x)); ]
Expression exported as /tmp/yacas-tmp
file-28802.tex
Out> True;

See also:
TeXForm .


MakeFunctionPlugin -- compile numerical functions into plugins

Unix-specific add-on
Calling format:
MakeFunctionPlugin("name", body)

Parameters:
"name" -- string, name of a new function

body -- expression, function of arguments, must evaluate to a function of some variables.

Description:
Compiles an external plugin library that computes a user-defined numerical function and dynamically loads it into Yacas, enabling a new function called "name".

Requires: a Unix shell, a compiler named c++ with ELF .so support, Yacas headers in FindFile("")/include; current directory must be writable.

The body expression must be a CForm()-exportable function of the arguments and may contain numerical constants. Pi is allowed and will be converted to floating-point.

All arguments and the return value of the function are assumed to be double precision real numbers. The result of passing a non-numerical argument will be an unevaluated expression.

Example:

In> MakeFunctionPlugin("f1", {x,y}, Sin(x/y))
Function f1(x,y) loaded from
plugins.tmp/libf1_plugin_cc.so
Out> True;
In> f1(2,3)
Out> 0.618369803069736989620253;
In> f1(x,5)
Out> f1(x,5);

The function creates the following files in subdirectory plugins.tmp/ of current directory:

After creating these files, MakeFunctionPlugin() will:

If you call MakeFunctionPlugin() repeatedly to define a function with the same name, old files will be overwritten and old libraries will be unloaded with DllUnload().

See also:
DllLoad , DllUnload , DllEnumerate , CForm .


Version -- show version of Yacas

Internal function
Calling format:
Version()

Description:
The function Version() returns a string representing the version of the currently running Yacas interpreter.

Examples:
In> Version()
Out> "1.0.48rev3";
In> LessThan(Version(), "1.0.47")
Out> False;
In> GreaterThan(Version(), "1.0.47")
Out> True;

The last two calls show that the LessThan and GreaterThan functions can be used for comparing version numbers. This method is only guaranteed, however, if the version is always expressed in the form d.d.dd as above.

See also:
LessThan , GreaterThan .


Vi -- edit a file or function

Unix-specific add-on
Calling format:
Vi(filename);
Vi(functionname);

Parameters:
filename - name of a file to edit

functionname - name of a function to find for editing

Description:
Vi will try to edit a file, or if the argument passed is a function, it will try to edit the file the function is defined in. It will try to do so by invoking the editor vi.

It finds the function by scanning the *.def files that have been reported to the system. (Vi calls FindFunction for this.) If editing a function, the command will jump directly to the first occurrence of the name of the function in the file (usually the beginning of a definition of a function).

For Vi() to be really useful, you need to start Yacas from the scripts/ directory in the development tree. In that case, FindFunction() will return the filename under that directory. Otherwise, FindFunction() will return a name in the systemwide installation directory (or directory specified in the --rootdir option).

Examples:
In> Vi("yacasinit.ys")
Out> True;
In> Vi("Sum")
Out> True;

See also:
FindFunction .


GNU Free Documentation License

Version 1.1, March 2000
Copyright (C) 2000 Free Software Foundation, Inc.

59 Temple Place, Suite 330
Boston, MA, 02111-1307
USA

Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.


Preamble

The purpose of this License is to make a manual, textbook, or other written document ``free'' in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it, with or without modifying it, either commercially or noncommercially. Secondarily, this License preserves for the author and publisher a way to get credit for their work, while not being considered responsible for modifications made by others.

This License is a kind of ``copyleft'', which means that derivative works of the document must themselves be free in the same sense. It complements the GNU General Public License, which is a copyleft license designed for free software.

We have designed this License in order to use it for manuals for free software, because free software needs free documentation: a free program should come with manuals providing the same freedoms that the software does. But this License is not limited to software manuals; it can be used for any textual work, regardless of subject matter or whether it is published as a printed book. We recommend this License principally for works whose purpose is instruction or reference.


Applicability and Definitions

This License applies to any manual or other work that contains a notice placed by the copyright holder saying it can be distributed under the terms of this License. The ``Document'', below, refers to any such manual or work. Any member of the public is a licensee, and is addressed as ``you''.

A ``Modified Version'' of the Document means any work containing the Document or a portion of it, either copied verbatim, or with modifications and/or translated into another language.

A ``Secondary Section'' is a named appendix or a front-matter section of the Document that deals exclusively with the relationship of the publishers or authors of the Document to the Document's overall subject (or to related matters) and contains nothing that could fall directly within that overall subject. (For example, if the Document is in part a textbook of mathematics, a Secondary Section may not explain any mathematics.) The relationship could be a matter of historical connection with the subject or with related matters, or of legal, commercial, philosophical, ethical or political position regarding them.

The ``Invariant Sections'' are certain Secondary Sections whose titles are designated, as being those of Invariant Sections, in the notice that says that the Document is released under this License.

The ``Cover Texts'' are certain short passages of text that are listed, as Front-Cover Texts or Back-Cover Texts, in the notice that says that the Document is released under this License.

A ``Transparent'' copy of the Document means a machine-readable copy, represented in a format whose specification is available to the general public, whose contents can be viewed and edited directly and straightforwardly with generic text editors or (for images composed of pixels) generic paint programs or (for drawings) some widely available drawing editor, and that is suitable for input to text formatters or for automatic translation to a variety of formats suitable for input to text formatters. A copy made in an otherwise Transparent file format whose markup has been designed to thwart or discourage subsequent modification by readers is not Transparent. A copy that is not ``Transparent'' is called ``Opaque''.

Examples of suitable formats for Transparent copies include plain ASCII without markup, Texinfo input format, LaTeX input format, SGML or XML using a publicly available DTD, and standard-conforming simple HTML designed for human modification. Opaque formats include PostScript, PDF, proprietary formats that can be read and edited only by proprietary word processors, SGML or XML for which the DTD and/or processing tools are not generally available, and the machine-generated HTML produced by some word processors for output purposes only.

The ``Title Page'' means, for a printed book, the title page itself, plus such following pages as are needed to hold, legibly, the material this License requires to appear in the title page. For works in formats which do not have any title page as such, ``Title Page'' means the text near the most prominent appearance of the work's title, preceding the beginning of the body of the text.


Verbatim Copying

You may copy and distribute the Document in any medium, either commercially or noncommercially, provided that this License, the copyright notices, and the license notice saying this License applies to the Document are reproduced in all copies, and that you add no other conditions whatsoever to those of this License. You may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute. However, you may accept compensation in exchange for copies. If you distribute a large enough number of copies you must also follow the conditions in section 3.

You may also lend copies, under the same conditions stated above, and you may publicly display copies.


Copying in Quantity

If you publish printed copies of the Document numbering more than 100, and the Document's license notice requires Cover Texts, you must enclose the copies in covers that carry, clearly and legibly, all these Cover Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on the back cover. Both covers must also clearly and legibly identify you as the publisher of these copies. The front cover must present the full title with all words of the title equally prominent and visible. You may add other material on the covers in addition. Copying with changes limited to the covers, as long as they preserve the title of the Document and satisfy these conditions, can be treated as verbatim copying in other respects.

If the required texts for either cover are too voluminous to fit legibly, you should put the first ones listed (as many as fit reasonably) on the actual cover, and continue the rest onto adjacent pages.

If you publish or distribute Opaque copies of the Document numbering more than 100, you must either include a machine-readable Transparent copy along with each Opaque copy, or state in or with each Opaque copy a publicly-accessible computer-network location containing a complete Transparent copy of the Document, free of added material, which the general network-using public has access to download anonymously at no charge using public-standard network protocols. If you use the latter option, you must take reasonably prudent steps, when you begin distribution of Opaque copies in quantity, to ensure that this Transparent copy will remain thus accessible at the stated location until at least one year after the last time you distribute an Opaque copy (directly or through your agents or retailers) of that edition to the public.

It is requested, but not required, that you contact the authors of the Document well before redistributing any large number of copies, to give them a chance to provide you with an updated version of the Document.


Modifications

You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above, provided that you release the Modified Version under precisely this License, with the Modified Version filling the role of the Document, thus licensing distribution and modification of the Modified Version to whoever possesses a copy of it. In addition, you must do these things in the Modified Version:

If the Modified Version includes new front-matter sections or appendices that qualify as Secondary Sections and contain no material copied from the Document, you may at your option designate some or all of these sections as invariant. To do this, add their titles to the list of Invariant Sections in the Modified Version's license notice. These titles must be distinct from any other section titles.

You may add a section entitled ``Endorsements'', provided it contains nothing but endorsements of your Modified Version by various parties -- for example, statements of peer review or that the text has been approved by an organization as the authoritative definition of a standard.

You may add a passage of up to five words as a Front-Cover Text, and a passage of up to 25 words as a Back-Cover Text, to the end of the list of Cover Texts in the Modified Version. Only one passage of Front-Cover Text and one of Back-Cover Text may be added by (or through arrangements made by) any one entity. If the Document already includes a cover text for the same cover, previously added by you or by arrangement made by the same entity you are acting on behalf of, you may not add another; but you may replace the old one, on explicit permission from the previous publisher that added the old one.

The author(s) and publisher(s) of the Document do not by this License give permission to use their names for publicity for or to assert or imply endorsement of any Modified Version.


Combining Documents

You may combine the Document with other documents released under this License, under the terms defined in section 4 above for modified versions, provided that you include in the combination all of the Invariant Sections of all of the original documents, unmodified, and list them all as Invariant Sections of your combined work in its license notice.

The combined work need only contain one copy of this License, and multiple identical Invariant Sections may be replaced with a single copy. If there are multiple Invariant Sections with the same name but different contents, make the title of each such section unique by adding at the end of it, in parentheses, the name of the original author or publisher of that section if known, or else a unique number. Make the same adjustment to the section titles in the list of Invariant Sections in the license notice of the combined work.

In the combination, you must combine any sections entitled ``History'' in the various original documents, forming one section entitled ``History''; likewise combine any sections entitled ``Acknowledgements'', and any sections entitled ``Dedications''. You must delete all sections entitled ``Endorsements.''


Collections of Documents

You may make a collection consisting of the Document and other documents released under this License, and replace the individual copies of this License in the various documents with a single copy that is included in the collection, provided that you follow the rules of this License for verbatim copying of each of the documents in all other respects.

You may extract a single document from such a collection, and distribute it individually under this License, provided you insert a copy of this License into the extracted document, and follow this License in all other respects regarding verbatim copying of that document.


Aggregation With Independent Works

A compilation of the Document or its derivatives with other separate and independent documents or works, in or on a volume of a storage or distribution medium, does not as a whole count as a Modified Version of the Document, provided no compilation copyright is claimed for the compilation. Such a compilation is called an ``aggregate'', and this License does not apply to the other self-contained works thus compiled with the Document, on account of their being thus compiled, if they are not themselves derivative works of the Document.

If the Cover Text requirement of section 3 is applicable to these copies of the Document, then if the Document is less than one quarter of the entire aggregate, the Document's Cover Texts may be placed on covers that surround only the Document within the aggregate. Otherwise they must appear on covers around the whole aggregate.


Translation

Translation is considered a kind of modification, so you may distribute translations of the Document under the terms of section 4. Replacing Invariant Sections with translations requires special permission from their copyright holders, but you may include translations of some or all Invariant Sections in addition to the original versions of these Invariant Sections. You may include a translation of this License provided that you also include the original English version of this License. In case of a disagreement between the translation and the original English version of this License, the original English version will prevail.


Termination

You may not copy, modify, sublicense, or distribute the Document except as expressly provided for under this License. Any other attempt to copy, modify, sublicense or distribute the Document is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.


Future Revisions of This License

The Free Software Foundation may publish new, revised versions of the GNU Free Documentation License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. See http://www.gnu.org/copyleft/ .

Each version of the License is given a distinguishing version number. If the Document specifies that a particular numbered version of this License "or any later version" applies to it, you have the option of following the terms and conditions either of that specified version or of any later version that has been published (not as a draft) by the Free Software Foundation. If the Document does not specify a version number of this License, you may choose any version ever published (not as a draft) by the Free Software Foundation.


ADDENDUM: How to use this License for your documents

To use this License in a document you have written, include a copy of the License in the document and put the following copyright and license notices just after the title page:

Copyright (C) YEAR   YOUR NAME. Permission is
granted to copy, distribute and/or modify this
document under the terms of the GNU Free
Documentation License, Version 1.1 or any later
version published by the Free Software Foundation;
with the Invariant Sections being LIST THEIR
TITLES, with the Front-Cover Texts being LIST, and
with the Back-Cover Texts being LIST. A copy of
the license is included in the section entitled
``GNU Free Documentation License''.

If you have no Invariant Sections, write ``with no Invariant Sections'' instead of saying which ones are invariant. If you have no Front-Cover Texts, write ``no Front-Cover Texts'' instead of ``Front-Cover Texts being LIST''; likewise for Back-Cover Texts.

If your document contains nontrivial examples of program code, we recommend releasing these examples in parallel under your choice of free software license, such as the GNU General Public License, to permit their use in free software.


/*, */, // , Prog, [, ] , Bodied, Infix, Postfix, Prefix , IsBodied, IsInfix, IsPostfix, IsPrefix , OpPrecedence, OpLeftPrecedence, OpRightPrecedence , RightAssociative , LeftPrecedence, RightPrecedence , RuleBase , RuleBaseListed , Rule , HoldArg , Retract , UnFence , HoldArgNr , RuleBaseArgList , MacroSet, MacroClear, MacroLocal, MacroRuleBase, MacroRuleBaseListed, MacroRule , Backquoting , SetExtraInfo, GetExtraInfo , GarbageCollect , FindFunction , Secure .

Programming

This chapter describes functions useful for writing Yacas scripts.


/*, */, // -- comments

Internal function
Calling format:
/* comment */
// comment

Description:
Introduce a comment block in a source file, similar to C++ comments. // makes everything until the end of the line a comment, while /* and */ may delimit a multi-line comment.

Examples:
a+b; // get result
a + /* add them */ b;


Prog, [, ] -- block of statements

Internal function
Calling format:
Prog(statement1, statement2, ...)
[ statement1; statement2; ... ]

Parameters:
statement1, statement2 -- expressions

Description:
The Prog and the [ ... ] construct have the same effect: they evaluate all arguments in order and return the result of the last evaluated expression.

Prog(a,b); is the same as typing [a;b;]; and is very useful for writing out function bodies. The [ ... ] construct is a syntactically nicer version of the Prog call; it is converted into Prog(...) during the parsing stage.


Bodied, Infix, Postfix, Prefix -- define function syntax

Internal function
Calling format:
Bodied("op", precedence)
Infix("op")
Infix("op", precedence)
Postfix("op")
Postfix("op", precedence)
Prefix("op")
Prefix("op", precedence)

Parameters:
"op" -- string, the name of a function

precedence -- nonnegative integer (evaluated)

Description:
Declares a function for the parser to understand as a bodied, infix, postfix, or prefix operator. Function name can be any string but meaningful usage would require it to be either made up entirely of letters or entirely of non-letter characters (such as "+", ":" etc.). Precedence can be specified (will be 0 by default).

Examples:
In> YY x := x+1;
CommandLine(1) : Error parsing expression

In> Prefix("YY", 2)
Out> True;
In> YY x := x+1;
Out> True;
In> YY YY 2*3
Out> 12;
In> Infix("##", 5)
Out> True;
In> a ## b ## c
Out> a##b##c;

See also:
IsBodied , OpPrecedence .


IsBodied, IsInfix, IsPostfix, IsPrefix -- check for function syntax

Internal function
Calling format:
IsBodied("op")
IsInfix("op")
IsPostfix("op")
IsPrefix("op")

Parameters:
"op" -- string, the name of a function

Description:
Check whether the function with given name "op" has been declared as a "bodied", infix, postfix, or prefix operator, and return True or False.

Examples:
In> IsInfix("+");
Out> True;
In> IsBodied("While");
Out> True;
In> IsBodied("Sin");
Out> False;
In> IsPostfix("!");
Out> True;

See also:
Bodied , OpPrecedence .


OpPrecedence, OpLeftPrecedence, OpRightPrecedence -- get operator precedence

Internal function
Calling format:
OpPrecedence("op")
OpLeftPrecedence("op")
OpRightPrecedence("op")

Parameters:
"op" -- string, the name of a function

Description:
Returns the precedence of the function named "op" which should have been declared as a bodied function or an infix, postfix, or prefix operator. Generates an error message if the string str does not represent a type of function that can have precedence.

For infix operators, right precedence can differ from left precedence. Bodied functions and prefix operators cannot have left precedence, while postfix operators cannot have right precedence; for these operators, there is only one value of precedence.

Examples:
In> OpPrecedence("+")
Out> 6;
In> OpLeftPrecedence("!")
Out> 0;


RightAssociative -- declare associativity

Internal function
Calling format:
RightAssociative("op")

Parameters:
"op" -- string, the name of a function

Description:
This makes the operator right-associative. For example:
RightAssociative("*")
would make multiplication right-associative. Take care not to abuse this function, because the reverse, making an infix operator left-associative, is not implemented. (All infix operators are by default left-associative until they are declared to be right-associative.)

See also:
OpPrecedence .


LeftPrecedence, RightPrecedence -- set operator precedence

Internal function
Calling format:
LeftPrecedence("op",precedence)
RightPrecedence("op",precedence)

Parameters:
"op" -- string, the name of a function

precedence -- nonnegative integer

Description:
"op" should be an infix operator. This function call tells the infix expression printer to bracket the left or right hand side of the expression if its precedence is larger than precedence.

This functionality was required in order to display expressions like a-(b-c) correctly. Thus, a+b+c is the same as a+(b+c), but a-(b-c) is not the same as a-b-c.

Note that the left and right precedence of an infix operator does not affect the way Yacas interprets expressions typed by the user. You cannot make Yacas parse a-b-c as a-(b-c) unless you declare the operator "-" to be right-associative.

See also:
OpPrecedence , OpLeftPrecedence , OpRightPrecedence , RightAssociative .


RuleBase -- define function with a fixed number of arguments

Internal function
Calling format:
RuleBase(name,params)

Parameters:
name -- string, name of function

params -- list of arguments to function

Description:
Define a new rules table entry for a function "name", with params as the parameter list. Name can be either a string or simple atom.

In the context of the transformation rule declaration facilities this is a useful function in that it allows the stating of argument names that can he used with HoldArg.

Functions can be overloaded: the same function can be defined with different number of arguments.

See also:
MacroRuleBase , RuleBaseListed , MacroRuleBaseListed , HoldArg , Retract .


RuleBaseListed -- define function with variable number of arguments

Internal function
Calling format:
RuleBaseListed("name", params)

Parameters:
"name" -- string, name of function

params -- list of arguments to function

Description:
The command RuleBaseListed defines a new function. It essentially works the same way as RuleBase, except that it declares a new function with a variable number of arguments. The list of parameters params determines the smallest number of arguments that the new function will accept. If the number of arguments passed to the new function is larger than the number of parameters in params, then the last argument actually passed to the new function will be a list containing all the remaining arguments.

A function defined using RuleBaseListed will appear to have the arity equal to the number of parameters in the param list, and it can accept any number of arguments greater or equal than that. As a consequence, it will be impossible to define a new function with the same name and with a greater arity.

The function body will know that the function is passed more arguments than the length of the param list, because the last argument will then be a list. The rest then works like a RuleBase-defined function with a fixed number of arguments. Transformation rules can be defined for the new function as usual.

Examples:
The definitions

RuleBaseListed("f",{a,b,c})
10 # f(_a,_b,{_c,_d}) <--
  Echo({"four args",a,b,c,d});
20 # f(_a,_b,c_IsList) <--
  Echo({"more than four args",a,b,c});
30 # f(_a,_b,_c) <-- Echo({"three args",a,b,c});
give the following interaction:

In> f(A)
Out> f(A);
In> f(A,B)
Out> f(A,B);
In> f(A,B,C)
three args A B C 
Out> True;
In> f(A,B,C,D)
four args A B C D 
Out> True;
In> f(A,B,C,D,E)
more than four args A B {C,D,E} 
Out> True;
In> f(A,B,C,D,E,E)
more than four args A B {C,D,E,E} 
Out> True;

The function f now appears to occupy all arities greater than 3:

In> RuleBase("f", {x,y,z,t});
CommandLine(1) : Rule base with this arity
  already defined

See also:
RuleBase , Retract , Echo .


Rule -- define a rewrite rule

Internal function
Calling format:
Rule("operator", arity,
  precedence, predicate) body
Parameters:
"operator" -- string, name of function

arity, precedence -- integers

predicate -- function returning boolean

body -- expression, body of rule

Description:
Define a rule for the function "operator" with "arity", "precedence", "predicate" and "body". The "precedence" goes from low to high: rules with low precedence will be applied first.

The arity for a rules database equals the number of arguments. Different rules data bases can be built for functions with the same name but with a different number of arguments.

Rules with a low precedence value will be tried before rules with a high value, so a rule with precedence 0 will be tried before a rule with precedence 1.


HoldArg -- mark argument as not evaluated

Internal function
Calling format:
HoldArg("operator",parameter)

Parameters:
"operator" -- string, name of a function

parameter -- atom, symbolic name of parameter

Description:
Specify that parameter should not be evaluated before used. This will be declared for all arities of "operator", at the moment this function is called, so it is best called after all RuleBase calls for this operator. "operator" can be a string or atom specifying the function name.

The parameter must be an atom from the list of symbolic arguments used when calling RuleBase.

See also:
RuleBase , HoldArgNr , RuleBaseArgList .


Retract -- erase rules for a function

Internal function
Calling format:
Retract("function",arity)

Parameters:
"function" -- string, name of function

arity -- positive integer

Description:
Remove a rulebase for the function named "function" with the specific arity, if it exists at all. This will make Yacas forget all rules defined for a given function. Rules for functions with the same name but different arities are not affected.

Assignment := of a function does this to the function being (re)defined.

See also:
RuleBaseArgList , RuleBase , := .


UnFence -- change local variable scope for a function

Internal function
Calling format:
UnFence("operator",arity)

Parameters:
"operator" -- string, name of function

arity -- positive integers

Description:
When applied to a user function, the bodies defined for the rules for "operator" with given arity can see the local variables from the calling function. This is useful for defining macro-like procedures (looping and such).

The standard library functions For and ForEach use UnFence.


HoldArgNr -- specify argument as not evaluated

Standard library
Calling format:
HoldArgNr("function", arity, argNum)

Parameters:
"function" -- string, function name

arity, argNum -- positive integers

Description:
Declares the argument numbered argNum of the function named "function" with specified arity to be unevaluated ("held"). Useful if you don't know symbolic names of parameters, for instance, when the function was not declared using an explicit RuleBase call. Otherwise you could use HoldArg.

See also:
HoldArg , RuleBase .


RuleBaseArgList -- obtain list of arguments

Internal function
Calling format:
RuleBaseArgList("operator", arity)

Parameters:
"operator" -- string, name of function

arity -- integer

Description:
Returns a list of atoms, symbolic parameters specified in the RuleBase call for the function named "operator" with the specific arity.

See also:
RuleBase , HoldArgNr , HoldArg .


MacroSet, MacroClear, MacroLocal, MacroRuleBase, MacroRuleBaseListed, MacroRule -- define rules in functions

Internal function
Description:
These functions have the same effect as their non-macro counterparts, except that their arguments are evaluated before the required action is performed. This is useful in macro-like procedures or in functions that need to define new rules based on parameters.

Make sure that the arguments of Macro... commands evaluate to expressions that would normally be used in the non-macro versions!

See also:
Set , Clear , Local , RuleBase , Rule , Backquoting .


Backquoting -- macro expansion (LISP-style backquoting)

Internal function
Calling format:
`(expression)

Parameters:
expression -- expression containing "@var" combinations to substitute the value of variable "var"

Description:
Backquoting is a macro substitution mechanism. A backquoted expression is evaluated in two stages: first, variables prefixed by @ are evaluated inside an expression, and second, the new expression is evaluated.

To invoke this functionality, a backquote ` needs to be placed in front of an expression. Parentheses around the expression are needed because the backquote binds tighter than other operators.

The expression should contain some variables (assigned atoms) with the special prefix operator @. Variables prefixed by @ will be evaluated even if they are inside function arguments that are normally not evaluated (e.g. functions declared with HoldArg). If the @var pair is in place of a function name, e.g. "@f(x)", then at the first stage of evaluation the function name itself is replaced, not the return value of the function (see example); so at the second stage of evaluation, a new function may be called.

One way to view backquoting is to view it as a parametric expression generator. @var pairs get substituted with the value of the variable var even in contexts where nothing would be evaluated. This effect can be also achieved using UnList and Hold but the resulting code is much more difficult to read and maintain.

This operation is relatively slow since a new expression is built before it is evaluated, but nonetheless backquoting is a powerful mechanism that sometimes allows to greatly simplify code.

Examples:
This example defines a function that automatically evaluates to a number as soon as the argument is a number (a lot of functions do this only when inside a N(...) section).

In> Decl(f1,f2) := \
In>   `(@f1(x_IsNumber) <-- N(@f2(x)));
Out> True;
In> Decl(nSin,Sin)
Out> True;
In> Sin(1)
Out> Sin(1);
In> nSin(1)
Out> 0.8414709848;

This example assigns the expression func(value) to variable var. Normally the first argument of Set would be unevaluated.

In> SetF(var,func,value) := \
In>     `(Set(@var,@func(@value)));
Out> True;
In> SetF(a,Sin,x)
Out> True;
In> a
Out> Sin(x);

See also:
MacroSet , MacroLocal , MacroRuleBase , Hold , HoldArg .


SetExtraInfo, GetExtraInfo -- annotate objects with additional information

Internal function
Calling format:
SetExtraInfo(expr,tag)
GetExtraInfo(expr)

Parameters:
expr -- any expression

tag -- tag information (any other expression)

Description:
Sometimes it is useful to be able to add extra tag information to "annotate" objects or to label them as having certain "properties". The functions SetExtraInfo and GetExtraInfo enable this.

The function SetExtraInfo returns the tagged expression, leaving the original expression alone. This means there is a common pitfall: be sure to assign the returned value to a variable, or the tagged expression is lost when the temporary object is destroyed.

The original expression is left unmodified, and the tagged expression returned, in order to keep the atomic objects small. To tag an object, a new type of object is created from the old object, with one added property (the tag). The tag can be any expression whatsoever.

The function GetExtraInfo(x) retrieves this tag expression from an object x. If an object has no tag, it looks the same as if it had a tag with value False.

No part of the Yacas core uses tags in a way that is visible to the outside world, so for specific purposes a programmer can devise a format to use for tag information. Association lists (hashes) are a natural fit for this, although it is not required and a tag can be any object (except the atom False because it is indistinguishable from having no tag information). Using association lists is highly advised since it is most likely to be the format used by other parts of the library, and one needs to avoid clashes with other library code. Typically, an object will either have no tag or a tag which is an associative list (perhaps empty). A script that uses tagged objects will check whether an object has a tag and if so, will add or modify certain entries of the association list, preserving any other tag information.

Note that FlatCopy currently does not copy the tag information (see examples).

Examples:
In> a:=2*b
Out> 2*b;
In> a:=SetExtraInfo(a,{{"type","integer"}})
Out> 2*b;
In> a
Out> 2*b;
In> GetExtraInfo(a)
Out> {{"type","integer"}};
In> GetExtraInfo(a)["type"]
Out> "integer";
In> c:=a
Out> 2*b;
In> GetExtraInfo(c)
Out> {{"type","integer"}};
In> c
Out> 2*b;
In> d:=FlatCopy(a);
Out> 2*b;
In> GetExtraInfo(d)
Out> False;

See also:
Assoc , := .


GarbageCollect -- do garbage collection on unused memory

Internal function
Calling format:
GarbageCollect()

Description:
GarbageCollect garbage-collects unused memory. The Yacas system uses a reference counting system for most objects, so this call is usually not necessary.

Reference counting refers to bookkeeping where in each object a counter is held, keeping track of the number of parts in the system using that object. When this count drops to zero, the object is automatically removed. Reference counting is not the fastest way of doing garbage collection, but it can be implemented in a very clean way with very little code.

Among the most important objects that are not reference counted are the strings. GarbageCollect collects these and disposes of them when they are not used any more.

GarbageCollect is useful when doing a lot of text processing, to clean up the text buffers. It is not highly needed, but it keeps memory use low.


FindFunction -- find the library file where a function is defined

Internal function
Calling format:
FindFunction(function)

Parameters:
function -- string, the name of a function

Description:
This function is useful for quickly finding the file where a standard library function is defined. It is likely to only be useful for developers. The function FindFunction scans the .def files that were loaded at start-up. This means that functions that are not listed in .def files will not be found with FindFunction.

Examples:
In> FindFunction("Sum")
Out> "sums.rep/code.ys";
In> FindFunction("Integrate")
Out> "integrate.rep/code.ys";

See also:
Vi .


Secure -- guard the host OS

Internal function
Calling format:
Secure(body)

Parameters:
body -- expression

Description:
Secure evaluates body in a "safe" environment, where files cannot be opened and system calls are not allowed. This can help protect the system when e.g. a script is sent over the Internet to be evaluated on a remote computer, which is potentially unsafe.

See also:
SystemCall .


MultiplyNum , CachedConstant , NewtonNum , SumTaylorNum .

Arbitrary-precision numerical programming

This chapter contains functions that help programming numerical calculations with arbitrary precision.


MultiplyNum -- optimized numerical multiplication

Standard library
Calling format:
MultiplyNum(x,y)
MultiplyNum(x,y,z,...)
MultiplyNum({x,y,z,...})

Parameters:
x, y, z -- integer, rational or floating-point numbers to multiply

Description:
The function MultiplyNum is used to speed up multiplication of floating-point numbers with rational numbers. Suppose we need to compute p/q*x where p, q are integers and x is a floating-point number. At high precision, it is faster to multiply x by an integer p and divide by an integer q than to compute p/q to high precision and then multiply by x. The function MultiplyNum performs this optimization.

The function accepts any number of arguments (not less than two) or a list of numbers. The result is always a floating-point number (even if Numeric is not set).

See also:
MathMultiply .


CachedConstant -- precompute multiple-precision constants

Standard library
Calling format:
CachedConstant(cache, Cname, Cfunc)

Parameters:
cache -- atom, name of the cache

Cname -- atom, name of the constant

Cfunc -- expression that evaluates the constant

Description:
This function is used to create precomputed multiple-precision values of constants. Caching these values will save time if they are frequently used.

The call to CachedConstant defines a new function named Cname() that returns the value of the constant at given precision. If the precision is increased, the value will be recalculated as necessary, otherwise calling Cname() will take very little time.

The parameter Cfunc must be an expression that can be evaluated and returns the value of the desired constant at the current precision. (Most arbitrary-precision mathematical functions do this by default.)

The associative list cache contains elements of the form {Cname, prec, value}, as illustrated in the example. If this list does not exist, it will be created.

This mechanism is currently used by N() to precompute the values of Pi and gamma. The name of the cache for N() is CacheOfConstantsN. The code in the function N() assigns unevaluated calls to Pi() and gamma() to the atoms Pi and gamma and declares them LazyGlobal. The result is that the constants will be recalculated only when they are used in the expression under N(). In other words, the code in N() does the equivalent of
Pi := Hold(Pi());
gamma := Hold(gamma());
LazyGlobal(Pi);
LazyGlobal(gamma);
After this, evaluating an expression such as 1/2+gamma will call the function gamma() but not the function Pi().

Example:
In> CachedConstant( my'cache, Ln2, LnNum(2) )
Out> 0.6931471806;
In> Ln2
Out> Ln2;
In> Ln2()
Out> 0.6931471806;
In> [ Precision(20); V( Ln2() ); ]
CachedConstant: Info: constant Ln2 is being
  recalculated at precision 20 
Out> 0.69314718055994530942;
In> my'cache
Out> {{"Ln2",20,0.69314718055994530942}};

See also:
N , Pi() , Precision , gamma .


NewtonNum -- low-level optimized Newton's iterations

Standard library
Calling format:
NewtonNum(func, x0, prec0, order)
NewtonNum(func, x0, prec0)
NewtonNum(func, x0)

Parameters:
func -- a function specifying the iteration sequence

x0 -- initial value (must be close enough to the root)

prec0 -- initial precision (at least 4, default 5)

order -- convergence order (typically 2 or 3, default 2)

Description:
This function is an optimized interface for computing Newton's iteration sequences for numerical solution of equations in arbitrary precision.

NewtonNum will iterate the given function starting from the initial value, until the sequence converges within current precision. Initially, up to 5 iterations at the initial precision prec0 is performed (the low precision is set for speed). The initial value x0 must be close enough to the root so that the initial iterations converge. If the sequence does not produce even a single correct digit of the root after these initial iterations, an error message is printed. The default value of the initial precision is 5.

The order parameter should give the convergence order of the scheme. Normally, Newton iteration converges quadratically (so the default value is order=2) but some schemes converge faster and you can speed up this function by specifying the correct order. (Caution: if you give order=3 but the sequence is actually quadratic, the result will be silently incorrect. It is safe to use order=2.)

Example:
In> Precision(20)
Out> True;
In> NewtonNum({{x}, x+Sin(x)}, 3, 5, 3)
Out> 3.14159265358979323846;

See also:
Newton .


SumTaylorNum -- optimized numerical evaluation of Taylor series

Standard library
Calling format:
SumTaylorNum(x, NthTerm, order)
SumTaylorNum(x, NthTerm, TermFactor, order)

Parameters:
NthTerm -- a function specifying n-th coefficient of the series

x -- number, value of the expansion variable

TermFactor -- a function specifying the ratio of n-th term to the previous one

order -- power of x in the last term

Description:
SumTaylorNum computes a Taylor series Sum(k,0,n,a[k]*x^k) numerically. This function allows very efficient computations of functions given by Taylor series, although some tweaking of the parameters is required for good results.

The coefficients a[k] of the Taylor series are given as functions of one integer variable (k). It is convenient to pass them to SumTaylorNum as closures. For example, if a function a(k) is defined, then
SumTaylorNum(x, {{k}, a(k)}, n)
computes the series Sum(k,0,n,a(k)*x^k).

Often a simple relation between successive coefficients a[k-1], a[k] of the series is available; usually they are related by a rational factor. In this case, the second form of SumTaylorNum should be used because it will compute the series faster. The function TermFactor applied to an integer k>=1 must return the ratio a[k]/a[k-1]. (If possible, the function TermFactor should return a rational number and not a floating-point number.) The function NthTerm must also be given, but the current implementation only calls NthTerm(0) and obtains all other coefficients by using TermFactor.

The algorithm is described in the essays. The number of terms order+1 must be specified and a sufficiently high precision must be set in advance to achieve the desired accuracy.

Example:
To compute 20 digits of Exp(1) using the Taylor series, one needs 21 digits of working precision and 21 terms of the series:

In> Precision(21)
Out> True;
In> SumTaylorNum(1, {{k},1/k!}, {{k},1/k}, 21)
Out> 2.71828182845904523535;
In> RoundTo(N(Ln(%)),20)
Out> 1;

See also:
Taylor .


Check , Assert , DumpErrors, ClearErrors , IsError , GetError, ClearError , CurrentFile, CurrentLine .

Error reporting

This chapter contains commands useful for reporting errors to the user.


Check -- report "hard" errors

Internal function
Calling format:
Check(predicate,"error text")

Parameters:
predicate -- expression returning True or False

"error text" -- string to print on error

Description:
If predicate does not evaluate to True, the current operation will be stopped, the string "error text" will be printed, and control will be returned immediately to the command line. This facility can be used to assure that some condition is satisfied during evaluation of expressions (guarding against critical internal errors).

A "soft" error reporting facility that does not stop the execution is provided by the function Assert.

Example:
In> [Check(1=0,"bad value"); Echo(OK);]
In function "Check" : 
CommandLine(1) : "bad value"

Note that OK is not printed.

See also:
Assert .


Assert -- signal "soft" custom error

Standard library
Calling format:
Assert("str", expr) pred
Assert("str") pred
Assert() pred
(bodied function, precedence 60000)
Parameters:
pred -- predicate to check

"str" -- string to classify the error

expr -- expression, error object

Description:
Assert is a global error reporting mechanism. It can be used to check for errors and report them. An error is considered to occur when the predicate pred evaluates to anything except True. In this case, the function returns False and an error object is created and posted to the global error tableau. Otherwise the function returns True.

Unlike the "hard" error function Check, the function Assert does not stop the execution of the program.

The error object consists of the string "str" and an arbitrary expression expr. The string should be used to classify the kind of error that has occurred, for example "domain" or "format". The error object can be any expression that might be useful for handling the error later; for example, a list of erroneous values and explanations. The association list of error objects is currently the global variable ErrorTableau.

If the parameter expr is missing, Assert substitutes True. If both optional parameters "str" and expr are missing, Assert creates an error of class "generic".

Errors can be handled by a custom error handler in the portion of the code that is able to handle a certain class of errors. The functions IsError, GetError and ClearError can be used.

Normally, all errors posted to the error tableau during evaluation of an expression should be eventually printed to the screen. This is the behavior of prettyprinters DefaultPrint, Print, PrettyForm and TeXForm; they call DumpErrors after evaluating the expression.

Examples:
In> Assert("bad value", "must be zero") 1=0
Out> False;
In> Assert("bad value", "must be one") 1=1
Out> True;
In> IsError()
Out> True;
In> IsError("bad value")
Out> True;
In> IsError("bad file")
Out> False;
In> GetError("bad value");
Out> "must be zero";
In> DumpErrors()
Error: bad value: must be zero
Out> True;
No more errors left:
In> IsError()
Out> False;
In> DumpErrors()
Out> True;

See also:
IsError , DumpErrors , Check , GetError , ClearError , ClearErrors .


DumpErrors, ClearErrors -- simple error handlers

Standard library
Calling format:
DumpErrors()
ClearErrors()

Description:
DumpErrors is a simple error handler for the global error reporting mechanism. It prints all errors posted using Assert and clears the error tableau.

ClearErrors is a trivial error handler that does nothing except it clears the tableau.

See also:
Assert , IsError .


IsError -- check for custom error

Standard library
Calling format:
IsError()
IsError("str")

Parameters:
"str" -- string to classify the error

Description:
IsError() returns True if any custom errors have been reported using Assert. The second form takes a parameter "str" that designates the class of the error we are interested in. It returns True if any errors of the given class "str" have been reported.

See also:
GetError , ClearError , Assert , Check .


GetError, ClearError -- custom errors handlers

Standard library
Calling format:
GetError("str")
ClearError("str")

Parameters:
"str" -- string to classify the error

Description:
These functions can be used to create a custom error handler.

GetError returns the error object if a custom error of class "str" has been reported using Assert, or False if no errors of this class have been reported.

ClearError("str") deletes the same error object that is returned by GetError("str"). It deletes at most one error object. It returns True if an object was found and deleted, and False otherwise.

Examples:
In> x:=1
Out> 1;
In> Assert("bad value", {x,"must be zero"}) x=0
Out> False;
In> GetError("bad value")
Out> {1, "must be zero"};
In> ClearError("bad value");
Out> True;
In> IsError()
Out> False;

See also:
IsError , Assert , Check , ClearErrors .


CurrentFile, CurrentLine -- show current file and line of input

Internal function
Calling format:
CurrentFile()
CurrentLine()

Description:
The functions CurrentFile and CurrentLine return a string with the file name of the current file and the current line of input respectively.

These functions are most useful in batch file calculations, where there is a need to determine at which line an error occurred. One can define a function

tst() := Echo({CurrentFile(),CurrentLine()});
which can then be inserted into the input file at various places, to see how far the interpreter reaches before an error occurs.

See also:
Echo .


MathNot , MathAnd , MathOr , BitAnd, BitOr, BitXor , Equals , GreaterThan, LessThan , Math... , Fast... , ShiftLeft, ShiftRight , IsPromptShown , MathLibrary .

Built-in (core) functions

Yacas comes with a small core of built-in functions and a large library of user-defined functions. Some of these core functions are documented in this chapter.

It is important for a developer to know which functions are built-in and cannot be redefined or Retract-ed. Also, core functions may be somewhat faster to execute than functions defined in the script library. All core functions are listed in the file yacasapi.cpp in the src/ subdirectory of the Yacas source tree. The declarations typically look like this:

SetCommand(LispSubtract, "MathSubtract");
Here LispSubtract is the Yacas internal name for the function and MathSubtract is the name visible to the Yacas language. Built-in bodied functions and infix operators are declared in the same file.


MathNot -- built-in logical "not"

Internal function
Calling format:
MathNot(expression)

Description:
Returns "False" if "expression" evaluates to "True", and vice versa.


MathAnd -- built-in logical "and"

Calling format:
MathAnd(...)

Description:
Lazy logical And: returns True if all args evaluate to True, and does this by looking at first, and then at the second argument, until one is False. If one of the arguments is False, And immediately returns False without evaluating the rest. This is faster, but also means that none of the arguments should cause side effects when they are evaluated.


MathOr -- built-in logical "or"

Internal function
Calling format:
MathOr(...)

MathOr is the basic logical "or" function. Similarly to And, it is lazy-evaluated. And(...) and Or(...) do also exist, defined in the script library. You can redefine them as infix operators yourself, so you have the choice of precedence. In the standard scripts they are in fact declared as infix operators, so you can write expr1 And expr.


BitAnd, BitOr, BitXor -- bitwise arithmetic

Internal function
Calling format:
BitAnd(n,m)
BitOr(n,m)
BitXor(n,m)

Description:
These functions return bitwise "and", "or" and "xor" of two numbers.


Equals -- check equality

Internal function
Calling format:
Equals(a,b)

Description:
Compares evaluated a and b recursively (stepping into expressions). So "Equals(a,b)" returns "True" if the expressions would be printed exactly the same, and "False" otherwise.


GreaterThan, LessThan -- comparison predicates

Internal function
Calling format:
LessThan(a,b), GreaterThan(a,b)

Parameters:
a, b -- numbers or strings
Description:
Comparing numbers or strings (lexicographically).

Example:
In> LessThan(1,1)
Out> False;
In> LessThan("a","b")
Out> True;


Math... -- arbitrary-precision math functions

Internal function
Calling format:

MathGcd(n,m) (Greatest Common Divisor), MathAdd(x,y), MathSubtract(x,y), MathMultiply(x,y), MathDivide(x,y), MathSqrt(x) (square root), MathFloor(x), MathCeil(x), MathAbs(x), MathExp(x), MathLog(x) (natural logarithm), MathPower(x,y), MathSin(x), MathCos(x), MathTan(x), MathArcSin(x), MathArcCos(x), MathArcTan(x), MathDiv(x,y), MathMod(x,y)

Description:
Calculation of sin, cos, tan and other mathematical functions. The argument must be a number. The reason for the prefix Math is that the library needs to define equivalent non-numerical functions for symbolic computations, such as Exp, Sin and so on.


Fast... -- double-precision math functions

Internal function
Calling format:

FastExp(x), FastLog(x) (natural logarithm), FastPower(x,y), FastSin(x), FastCos(x), FastTan(x), FastArcSin(x), FastArcCos(x), FastArcTan(x)

Description:
Versions of these functions using the C++ library. These should then at least be faster than the arbitrary precision versions.


ShiftLeft, ShiftRight -- built-in bit shifts

Internal function
Calling format:
ShiftLeft(expr,bits)
ShiftRight(expr,bits)

Description:
Shift bits to the left or to the right.


IsPromptShown -- test for the Yacas prompt option

Internal function
Calling format:
IsPromptShown()
Description:
Returns False if Yacas has been started with the option to suppress the prompt, and True otherwise.


MathLibrary -- obtain current math library name

Internal function
Calling format:
MathLibrary()
Description:
Returns a string that describes the currently used arbitrary-precision arithmetic library name.

Possible names are "Internal" and "Gmp", indicating the internal math library libyacasnumbers and the GNU Multiple Precision library libgmp.

Example:
In>  MathLibrary()
Out> "Internal";


Full listing of core functions

The following Yacas functions are currently declared in yacasapi.cpp as core functions:

=
And
ApplyPure
ArrayCreate
ArrayGet
ArraySet
ArraySize
Atom
Berlekamp
BitAnd
BitOr
BitXor
Bodied
CTokenizer
Check
Clear
CommonLispTokenizer
Concat
ConcatStrings
CurrentFile
CurrentLine
DefLoad
DefLoadFunction
DefaultDirectory
DefaultTokenizer
Delete
DestructiveDelete
DestructiveInsert
DestructiveReplace
DestructiveReverse
DllEnumerate
DllLoad
DllUnload
Equals
Eval
FastArcCos
FastArcSin
FastArcTan
FastAssoc
FastCos
FastExp
FastLog
FastPower
FastSin
FastTan
FindFile
FindFunction
FlatCopy
FromBase
FromFile
FromString
FullForm
GarbageCollect
GenericTypeName
GetExtraInfo
GetPrecision
GreaterThan
Head
Hold
HoldArg
If
Infix
Insert
IsAtom
IsBodied
IsBound
IsFunction
IsGeneric
IsInfix
IsInteger
IsList
IsNumber
IsPostfix
IsPrefix
IsString
LazyGlobal
LeftPrecedence
Length
LessThan
LispRead
LispReadListed
List
Listify
Load
Local
LocalSymbols
MacroClear
MacroLocal
MacroRule
MacroRuleBase
MacroRuleBaseListed
MacroRulePattern
MacroSet
MathAbs
MathAdd
MathAnd
MathArcCos
MathArcSin
MathArcTan
MathCeil
MathCos
MathDiv
MathDivide
MathExp
MathFac
MathFloor
MathGcd
MathLibrary
MathLog
MathMod
MathMultiply
MathNot
MathNth
MathOr
MathPi
MathPower
MathSin
MathSqrt
MathSubtract
MathTan
MaxEvalDepth
Not
OpLeftPrecedence
OpPrecedence
OpRightPrecedence
Or
PatchLoad
PatchString
PatternCreate
PatternMatches
Postfix
Precision
Prefix
PrettyPrinter
Prog
Read
ReadToken
Replace
Retract
RightAssociative
RightPrecedence
Rule
RuleBase
RuleBaseArgList
RuleBaseDefined
RuleBaseListed
RulePattern
Secure
Set
SetExtraInfo
SetStringMid
ShiftLeft
ShiftRight
String
StringMid
Subst
SystemCall
Tail
ToBase
ToFile
ToString
TraceExp
TraceRule
TraceStack
Type
UnFence
UnList
Use
Version
While
Write
WriteString
XmlExplodeTag
XmlTokenizer
`

In addition, the following functions are declared with special syntax and precedence:

@ --- prefix (prec. 0).

BackQuote --- bodied (prec. KMaxPrecedence).

FromFile --- bodied (prec. KMaxPrecedence).

FromString --- bodied (prec. KMaxPrecedence).

LocalSymbols --- bodied (prec. KMaxPrecedence).

MacroRule --- bodied (prec. KMaxPrecedence).

MacroRulePattern --- bodied (prec. KMaxPrecedence).

Rule --- bodied (prec. KMaxPrecedence).

RulePattern --- bodied (prec. KMaxPrecedence).

Subst --- bodied (prec. KMaxPrecedence).

ToFile --- bodied (prec. KMaxPrecedence).

ToString --- bodied (prec. KMaxPrecedence).

TraceRule --- bodied (prec. KMaxPrecedence).

While --- bodied (prec. KMaxPrecedence).

_ --- prefix (prec. 0).

_ --- infix (prec. 0).

` --- prefix (prec. 0).


DllLoad, DllUnload, DllEnumerate , StubApiCStart , StubApiCShortIntegerConstant , StubApiCInclude , StubApiCFunction , StubApiCRemark , StubApiCSetEnv , StubApiCFile , StubApiCStruct .

The Yacas plugin structure

Yacas supports dynamically loading libraries at runtime. This chapter describes functions for working with plugins.

The plugin feature allows Yacas to interface with other libraries that support additional functionality. For example, there could be a plugin enabling the user to script a user interface from within Yacas, or a specific powerful library to do numeric calculations.

The plugin feature is currently in an experimental stage. There are some examples in the plugins/ directory. These are not built by default because they cannot be guaranteed to compile on every platform (yet). The plugins need to be compiled after Yacas itself has been compiled and installed successfully. The plugins/ directory contains a README file with more details on compilation.

In addition to the plugin structure in the Yacas engine, there is a module cstubgen (currently still under development) that allows rapid scripting of a plugin. Essentially all that is required is to write a file that looks like the header file of the original library, but written in Yacas syntax. The module cstubgen is then able to write out a C++ file that can be compiled and linked with the original library, and then loaded from within Yacas. Including a function in the plugin will typically take just one line of Yacas code. There are a few examples in the plugins/ directory (the files ending with api.stub). The file makefile.plugin is configured to automatically convert these to the required C++ files. See also an essay on plugins for a worked-out example.

In addition to the C++ stub file, cstubgen also automatically generates some documentation on the functions included in the stub. This documentation is put in a file with extension 'description'.

The plugin facility is not supported for each platform yet. Specifically, it is only supported on platforms that support the elf binary format. (Loading DLLs is platform-dependent).

This chapter assumes the reader is comfortable programming in C++.


DllLoad, DllUnload, DllEnumerate -- manipulate plugins

Internal function
Calling format:
DllLoad(file)
DllUnload(file)
DllEnumerate()

Parameters:
file -- file name of the plugin

Description:
DllLoad forces Yacas to load the dynamic link library (.so file under Linux). The full path to the DLL has to be specified, or the file needs to be in a path where dlopen can find it.

DllUnload unloads a dynamic link library previously loaded with DllLoad. Note the dll file name has to be exactly the same, or the system will not be able to determine which dll to unload. It will scan all the dll files, and delete the first one found to exactly match, and return silently if it didn't find the dll. DllUnload always returns True.

DllEnumerate returns a list with all loaded dynamic link libraries.

Example:
In> DllLoad("./libopengl.so");
Out> True;


StubApiCStart -- start of C++ plugin API

Standard library
Calling format:
StubApiCStart()

Description:
To start up generating a c stub file for linking a c library with Yacas. A stub specification file needs to start with this function call, to reset the internal state of Yacas for emitting a stub C++ file.

See also:
StubApiCShortIntegerConstant , StubApiCInclude , StubApiCFunction , StubApiCFile , StubApiCSetEnv .


StubApiCShortIntegerConstant -- declare integer constant in plugin

Standard library
Calling format:
StubApiCShortIntegerConstant(const,value)

Parameters:
const -- string representing the global variable to be bound runtime

value -- integer value the global should be bound to

Description:
define a constant 'const' to have value 'value'. The value should be short integer constant. This is useful for linking in defines and enumerated values into Yacas. If the library for instance has a define
#define FOO 10
Then
StubApiCShortIntegerConstant("FOO","FOO")
will bind the global variable FOO to the value for FOO defined in the library header file.

See also:
StubApiCStart , StubApiCInclude , StubApiCFunction , StubApiCFile , StubApiCSetEnv .


StubApiCInclude -- declare include file in plugin

Standard library
Calling format:
StubApiCInclude(file)

Parameters:
file -- file to include from the library the plugin is based on

Description:
Declare an include file (a header file for the library, for instance) The delimiters need to be specified too. So, for a standard library like the one needed for OpenGL, you need to specify
StubApiCInclude("\<GL/gl.h\>")
and for user include file:
StubApiCInclude("\"GL/gl.h\"")

See also:
StubApiCStart , StubApiCShortIntegerConstant , StubApiCFunction , StubApiCFile , StubApiCSetEnv .


StubApiCFunction -- declare C++ function in plugin

Standard library
Calling format:
StubApiCFunction(returntype,fname,args)
StubApiCFunction(returntype,fname,
  fname2,args)

Parameters:
returntype -- return type of new function

fname -- function of built-in function

fname2 -- (optional) function name to be used from within Yacas

args -- list of arguments to the function

Description:
This function declares a new library function, along with its calling sequence. cstubgen will then generate the C++ code required to call this function.

Return type, function name, and list of arguments should be literal strings (surrounded by quotes).

If fname2 is not supplied, it will be assumed to be the same as fname.

The return types currently supported are "int", "double" and "void".

The argument values that are currently supported are "int", "double", and "input_string".

Argument types can be specified simply as a string referring to their type, like "int", or they can be lists with an additional element stating the name of the variable: {"int","n"}. The variable will then show up in the automatically generated documentation as having the name "n".

Examples:
To define an OpenGL function glVertex3d that accepts three doubles and returns void:

StubApiCFunction("void","glVertex3d",
  {"double","double","double"});

See also:
StubApiCStart , StubApiCShortIntegerConstant , StubApiCInclude , StubApiCFile , StubApiCSetEnv .


StubApiCRemark -- documentation string in plugin

Standard library
Calling format:
StubApiCRemark(string)

Parameters:
string -- comment string to be added to the documentation

Description:
StubApiCRemark adds a piece of text to the stub documentation file that gets generated automatically. The documentation is put in a .description file while the input file is being processed, so adding a remark on a function just after a function declaration adds a remark on that function.

See also:
StubApiCShortIntegerConstant , StubApiCInclude , StubApiCFunction , StubApiCSetEnv , StubApiCFile .


StubApiCSetEnv -- access Yacas environment in plugin

Standard library
Calling format:
StubApiCSetEnv(func)

Parameters:
func -- name of the function to call to set the environment variable

Description:
This function forces the plugin to call the function func, with as argument LispEnvironment& aEnvironment. This lets the plugin store the environment class (which is needed for almost any thing to do with Yacas), somewhere in a global variable. aEnvironment can then be used from within a callback function in the plugin that doesn't take the extra argument by design.

There needs to ba a function in the plugin somewhere of the form

static LispEnvironment* env = NULL;
void GlutSetEnv(LispEnvironment& aEnv)
{
    env = &aEnv;
}
Then calling
StubApiCSetEnv("GlutSetEnv");
will force the plugin to call GlutSetEnv at load time. All functions in the plugin will then have access to the Yacas environment.

See also:
StubApiCStart , StubApiCShortIntegerConstant , StubApiCInclude , StubApiCFunction , StubApiCFile .


StubApiCFile -- set file name for plugin API

Standard library
Calling format:
StubApiCFile(basename)

Parameters:
basename -- name for the generation of the stub file

Description:
Generate the C++ stub file, "basename.cc", and a documentation file named "basename.description". The descriptions are automatically generated while adding functions and constants to the stub.

See also:
StubApiCStart , StubApiCShortIntegerConstant , StubApiCInclude , StubApiCFunction , StubApiCSetEnv .


StubApiCStruct -- declare C struct in plugin

Standard library
Calling format:
StubApiCStruct(name)
StubApiCStruct(name,freefunction)

Parameters:
name -- name of structure

freefunction -- function that can be called to clean up the object

Description:
StubApiCStruct declares a struct in a specific library. The name should be followed by an asterisk (clearly showing it is a pointer). After that, in the stub api definition, this type can be used as argument or return type to functions to the library.

By default the struct will be deleted from memory with a normal call to free(...). This can be overriden with a function given as second argument, freefunction. This is needed in the case where there are additional operations that need to be performed in order to delete the object from memory.

Examples:
In a library header file, define:

typedef struct SomeStruct
{
  int a;
  int b;
} SomeStruct;
Then in the stub file you can declare this struct by calling:

StubApiCStruct("SomeStruct*")

See also:
StubApiCFunction .


IsGeneric , GenericTypeName , ArrayCreate , ArraySize , ArrayGet , ArraySet , ArrayCreateFromList , ListFromArray .

Generic objects

Generic objects are objects that are implemented in C++, but can be accessed through the Yacas interpreter.


IsGeneric -- check for generic object

Internal function
Calling format:
IsGeneric(object)

Description:
Returns True if an object is of a generic object type.


GenericTypeName -- get type name

Internal function
Calling format:
GenericTypeName(object)

Description:
Returns a string representation of the name of a generic object.

EG

In> GenericTypeName(ArrayCreate(10,1))
Out> "Array";


ArrayCreate -- create array

Internal function
Calling format:
ArrayCreate(size,init)

Description:
Creates an array with size elements, all initialized to the value init.


ArraySize -- get array size

Internal function
Calling format:
ArraySize(array)

Description:
Returns the size of an array (number of elements in the array).


ArrayGet -- fetch array element

Internal function
Calling format:
ArrayGet(array,index)

Description:
Returns the element at position index in the array passed. Arrays are treated as base-one, so index set to 1 would return the first element.

Arrays can also be accessed through the [] operators. So array[index] would return the same as ArrayGet(array, index).


ArraySet -- set array element

Internal function
Calling format:
ArraySet(array,index,element)

Description:
Sets the element at position index in the array passed to the value passed in as argument to element. Arrays are treated as base-one, so index set to 1 would set first element.

Arrays can also be accessed through the [] operators. So array[index] := element would do the same as ArraySet(array, index,element).


ArrayCreateFromList -- convert list to array

Internal function
Calling format:
ArrayCreateFromList(list)

Description:
Creates an array from the contents of the list passed in.


ListFromArray -- convert array to list

Internal function
Calling format:
ListFromArray(array)

Description:
Creates a list from the contents of the array passed in.


Verify, TestYacas, LogicVerify , KnownFailure , RoundTo , VerifyArithmetic, VerifyDiv .

The Yacas test suite

This chapter describes commands used for verifying correct performance of Yacas.

Yacas comes with a test suite which can be found in the directory tests/. Typing
make test
on the command line after Yacas was built will run the test. This test can be run even before make install, as it only uses files in the local directory of the Yacas source tree. The default extension for test scripts is .yts (Yacas test script).

The verification commands described in this chapter only display the expressions that do not evaluate correctly. Errors do not terminate the execution of the Yacas script that uses these testing commands, since they are meant to be used in test scripts.


Verify, TestYacas, LogicVerify -- verifying equivalence of two expressions

Standard library
Calling format:
Verify(question,answer)
TestYacas(question,answer)
LogicVerify(question,answer)

Parameters:
question -- expression to check for

answer -- expected result after evaluation

Description:
The commands Verify, TestYacas, LogicVerify can be used to verify that an expression is equivalent to a correct answer after evaluation. All three commands return True or False.

For some calculations, the demand that two expressions are identical syntactically is too stringent. The Yacas system might change at various places in the future, but 1+x would still be equivalent, from a mathematical point of view, to x+1.

The general problem of deciding that two expressions a and b are equivalent, which is the same as saying that a-b=0 , is generally hard to decide on. The following commands solve this problem by having domain-specific comparisons.

The comparison commands do the following comparison types:

Examples:
In> Verify(1+2,3)
Out> True;
In> Verify(x*(1+x),x^2+x)
******************
x*(x+1) evaluates to x*(x+1) which differs
  from x^2+x
******************
Out> False;
In> TestYacas(x*(1+x),x^2+x)
Out> True;
In> Verify(a And c Or b And Not c,a Or b)
******************
 a And c Or b And Not c evaluates to  a And c
  Or b And Not c which differs from  a Or b
******************
Out> False;
In> LogicVerify(a And c Or b And Not c,a Or b)
Out> True;
In> LogicVerify(a And c Or b And Not c,b Or a)
Out> True;

See also:
Simplify , CanProve , KnownFailure .


KnownFailure -- Mark a test as a known failure

Standard library
Calling format:
KnownFailure(test)

Parameters:
test -- expression that should return False on failure

Description:
The command KnownFailure marks a test as known to fail by displaying a message to that effect on screen.

This might be used by developers when they have no time to fix the defect, but do not wish to alarm users who download Yacas and type make test.

Examples:
In> KnownFailure(Verify(1,2))
Known failure:
******************
 1 evaluates to  1 which differs from  2
******************
Out> False;
In> KnownFailure(Verify(1,1))
Known failure:
Failure resolved!
Out> True;

See also:
Verify , TestYacas , LogicVerify .


RoundTo -- Round a real-valued result to a set number of digits

Standard library
Calling format:
RoundTo(number,precision)

Parameters:
number -- number to round off

precision -- precision to use for round-off

Description:
The function RoundTo rounds a floating point number to a specified precision, allowing for testing for correctness using the Verify command.

Examples:
In> N(RoundTo(Exp(1),30),30)
Out> 2.71828182110230114951959786552;
In> N(RoundTo(Exp(1),20),20)
Out> 2.71828182796964237096;

See also:
Verify , VerifyArithmetic , VerifyDiv .


VerifyArithmetic, VerifyDiv -- Special purpose arithmetic verifiers

Standard library
Calling format:
VerifyArithmetic(x,n,m)
RandVerifyArithmetic(n)
VerifyDiv(u,v)

Parameters:
x, n, m, u, v -- integer arguments

Description:
The commands VerifyArithmetic and VerifyDiv test a mathematic equality which should hold, testing that the result returned by the system is mathematically correct according to a mathematically provable theorem.

VerifyArithmetic verifies for an arbitrary set of numbers x, n and m that

(x^n-1)*(x^m-1)=x^(n+m)-x^n-x^m+1.

The left and right side represent two ways to arrive at the same result, and so an arithmetic module actually doing the calculation does the calculation in two different ways. The results should be exactly equal.

RandVerifyArithmetic(n) calls VerifyArithmetic with random values, n times.

VerifyDiv(u,v) checks that

u=v*Div(u,v)+Mod(u,v).

Examples:
In> VerifyArithmetic(100,50,60)
Out> True;
In> RandVerifyArithmetic(4)
Out> True;
In> VerifyDiv(x^2+2*x+3,x+1)
Out> True;
In> VerifyDiv(3,2)
Out> True;

See also:
Verify .


GNU Free Documentation License

Version 1.1, March 2000
Copyright (C) 2000 Free Software Foundation, Inc.

59 Temple Place, Suite 330
Boston, MA, 02111-1307
USA

Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.


Preamble

The purpose of this License is to make a manual, textbook, or other written document ``free'' in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it, with or without modifying it, either commercially or noncommercially. Secondarily, this License preserves for the author and publisher a way to get credit for their work, while not being considered responsible for modifications made by others.

This License is a kind of ``copyleft'', which means that derivative works of the document must themselves be free in the same sense. It complements the GNU General Public License, which is a copyleft license designed for free software.

We have designed this License in order to use it for manuals for free software, because free software needs free documentation: a free program should come with manuals providing the same freedoms that the software does. But this License is not limited to software manuals; it can be used for any textual work, regardless of subject matter or whether it is published as a printed book. We recommend this License principally for works whose purpose is instruction or reference.


Applicability and Definitions

This License applies to any manual or other work that contains a notice placed by the copyright holder saying it can be distributed under the terms of this License. The ``Document'', below, refers to any such manual or work. Any member of the public is a licensee, and is addressed as ``you''.

A ``Modified Version'' of the Document means any work containing the Document or a portion of it, either copied verbatim, or with modifications and/or translated into another language.

A ``Secondary Section'' is a named appendix or a front-matter section of the Document that deals exclusively with the relationship of the publishers or authors of the Document to the Document's overall subject (or to related matters) and contains nothing that could fall directly within that overall subject. (For example, if the Document is in part a textbook of mathematics, a Secondary Section may not explain any mathematics.) The relationship could be a matter of historical connection with the subject or with related matters, or of legal, commercial, philosophical, ethical or political position regarding them.

The ``Invariant Sections'' are certain Secondary Sections whose titles are designated, as being those of Invariant Sections, in the notice that says that the Document is released under this License.

The ``Cover Texts'' are certain short passages of text that are listed, as Front-Cover Texts or Back-Cover Texts, in the notice that says that the Document is released under this License.

A ``Transparent'' copy of the Document means a machine-readable copy, represented in a format whose specification is available to the general public, whose contents can be viewed and edited directly and straightforwardly with generic text editors or (for images composed of pixels) generic paint programs or (for drawings) some widely available drawing editor, and that is suitable for input to text formatters or for automatic translation to a variety of formats suitable for input to text formatters. A copy made in an otherwise Transparent file format whose markup has been designed to thwart or discourage subsequent modification by readers is not Transparent. A copy that is not ``Transparent'' is called ``Opaque''.

Examples of suitable formats for Transparent copies include plain ASCII without markup, Texinfo input format, LaTeX input format, SGML or XML using a publicly available DTD, and standard-conforming simple HTML designed for human modification. Opaque formats include PostScript, PDF, proprietary formats that can be read and edited only by proprietary word processors, SGML or XML for which the DTD and/or processing tools are not generally available, and the machine-generated HTML produced by some word processors for output purposes only.

The ``Title Page'' means, for a printed book, the title page itself, plus such following pages as are needed to hold, legibly, the material this License requires to appear in the title page. For works in formats which do not have any title page as such, ``Title Page'' means the text near the most prominent appearance of the work's title, preceding the beginning of the body of the text.


Verbatim Copying

You may copy and distribute the Document in any medium, either commercially or noncommercially, provided that this License, the copyright notices, and the license notice saying this License applies to the Document are reproduced in all copies, and that you add no other conditions whatsoever to those of this License. You may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute. However, you may accept compensation in exchange for copies. If you distribute a large enough number of copies you must also follow the conditions in section 3.

You may also lend copies, under the same conditions stated above, and you may publicly display copies.


Copying in Quantity

If you publish printed copies of the Document numbering more than 100, and the Document's license notice requires Cover Texts, you must enclose the copies in covers that carry, clearly and legibly, all these Cover Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on the back cover. Both covers must also clearly and legibly identify you as the publisher of these copies. The front cover must present the full title with all words of the title equally prominent and visible. You may add other material on the covers in addition. Copying with changes limited to the covers, as long as they preserve the title of the Document and satisfy these conditions, can be treated as verbatim copying in other respects.

If the required texts for either cover are too voluminous to fit legibly, you should put the first ones listed (as many as fit reasonably) on the actual cover, and continue the rest onto adjacent pages.

If you publish or distribute Opaque copies of the Document numbering more than 100, you must either include a machine-readable Transparent copy along with each Opaque copy, or state in or with each Opaque copy a publicly-accessible computer-network location containing a complete Transparent copy of the Document, free of added material, which the general network-using public has access to download anonymously at no charge using public-standard network protocols. If you use the latter option, you must take reasonably prudent steps, when you begin distribution of Opaque copies in quantity, to ensure that this Transparent copy will remain thus accessible at the stated location until at least one year after the last time you distribute an Opaque copy (directly or through your agents or retailers) of that edition to the public.

It is requested, but not required, that you contact the authors of the Document well before redistributing any large number of copies, to give them a chance to provide you with an updated version of the Document.


Modifications

You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above, provided that you release the Modified Version under precisely this License, with the Modified Version filling the role of the Document, thus licensing distribution and modification of the Modified Version to whoever possesses a copy of it. In addition, you must do these things in the Modified Version:

If the Modified Version includes new front-matter sections or appendices that qualify as Secondary Sections and contain no material copied from the Document, you may at your option designate some or all of these sections as invariant. To do this, add their titles to the list of Invariant Sections in the Modified Version's license notice. These titles must be distinct from any other section titles.

You may add a section entitled ``Endorsements'', provided it contains nothing but endorsements of your Modified Version by various parties -- for example, statements of peer review or that the text has been approved by an organization as the authoritative definition of a standard.

You may add a passage of up to five words as a Front-Cover Text, and a passage of up to 25 words as a Back-Cover Text, to the end of the list of Cover Texts in the Modified Version. Only one passage of Front-Cover Text and one of Back-Cover Text may be added by (or through arrangements made by) any one entity. If the Document already includes a cover text for the same cover, previously added by you or by arrangement made by the same entity you are acting on behalf of, you may not add another; but you may replace the old one, on explicit permission from the previous publisher that added the old one.

The author(s) and publisher(s) of the Document do not by this License give permission to use their names for publicity for or to assert or imply endorsement of any Modified Version.


Combining Documents

You may combine the Document with other documents released under this License, under the terms defined in section 4 above for modified versions, provided that you include in the combination all of the Invariant Sections of all of the original documents, unmodified, and list them all as Invariant Sections of your combined work in its license notice.

The combined work need only contain one copy of this License, and multiple identical Invariant Sections may be replaced with a single copy. If there are multiple Invariant Sections with the same name but different contents, make the title of each such section unique by adding at the end of it, in parentheses, the name of the original author or publisher of that section if known, or else a unique number. Make the same adjustment to the section titles in the list of Invariant Sections in the license notice of the combined work.

In the combination, you must combine any sections entitled ``History'' in the various original documents, forming one section entitled ``History''; likewise combine any sections entitled ``Acknowledgements'', and any sections entitled ``Dedications''. You must delete all sections entitled ``Endorsements.''


Collections of Documents

You may make a collection consisting of the Document and other documents released under this License, and replace the individual copies of this License in the various documents with a single copy that is included in the collection, provided that you follow the rules of this License for verbatim copying of each of the documents in all other respects.

You may extract a single document from such a collection, and distribute it individually under this License, provided you insert a copy of this License into the extracted document, and follow this License in all other respects regarding verbatim copying of that document.


Aggregation With Independent Works

A compilation of the Document or its derivatives with other separate and independent documents or works, in or on a volume of a storage or distribution medium, does not as a whole count as a Modified Version of the Document, provided no compilation copyright is claimed for the compilation. Such a compilation is called an ``aggregate'', and this License does not apply to the other self-contained works thus compiled with the Document, on account of their being thus compiled, if they are not themselves derivative works of the Document.

If the Cover Text requirement of section 3 is applicable to these copies of the Document, then if the Document is less than one quarter of the entire aggregate, the Document's Cover Texts may be placed on covers that surround only the Document within the aggregate. Otherwise they must appear on covers around the whole aggregate.


Translation

Translation is considered a kind of modification, so you may distribute translations of the Document under the terms of section 4. Replacing Invariant Sections with translations requires special permission from their copyright holders, but you may include translations of some or all Invariant Sections in addition to the original versions of these Invariant Sections. You may include a translation of this License provided that you also include the original English version of this License. In case of a disagreement between the translation and the original English version of this License, the original English version will prevail.


Termination

You may not copy, modify, sublicense, or distribute the Document except as expressly provided for under this License. Any other attempt to copy, modify, sublicense or distribute the Document is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.


Future Revisions of This License

The Free Software Foundation may publish new, revised versions of the GNU Free Documentation License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. See http://www.gnu.org/copyleft/ .

Each version of the License is given a distinguishing version number. If the Document specifies that a particular numbered version of this License "or any later version" applies to it, you have the option of following the terms and conditions either of that specified version or of any later version that has been published (not as a draft) by the Free Software Foundation. If the Document does not specify a version number of this License, you may choose any version ever published (not as a draft) by the Free Software Foundation.


ADDENDUM: How to use this License for your documents

To use this License in a document you have written, include a copy of the License in the document and put the following copyright and license notices just after the title page:

Copyright (C) YEAR   YOUR NAME. Permission is
granted to copy, distribute and/or modify this
document under the terms of the GNU Free
Documentation License, Version 1.1 or any later
version published by the Free Software Foundation;
with the Invariant Sections being LIST THEIR
TITLES, with the Front-Cover Texts being LIST, and
with the Back-Cover Texts being LIST. A copy of
the license is included in the section entitled
``GNU Free Documentation License''.

If you have no Invariant Sections, write ``with no Invariant Sections'' instead of saying which ones are invariant. If you have no Front-Cover Texts, write ``no Front-Cover Texts'' instead of ``Front-Cover Texts being LIST''; likewise for Back-Cover Texts.

If your document contains nontrivial examples of program code, we recommend releasing these examples in parallel under your choice of free software license, such as the GNU General Public License, to permit their use in free software.