An Xcas Tutorial

Contents

Xcas is a free (as in Free Software) computer algebra system. Although there are other computer algebra systems, both free and commercial, few if any are as versatile as Xcas, which is capable of, among other things:

This tutorial will briefly introduce you to calculating, programming and graphing with Xcas. The first section, “Getting started”, will be just enough information to get you started. The second section will be a brief overview of the graphic interface and the rest will be more in-depth tutorial.

For more information, you can refer to the manual or any of the other sources of information under the Help menu.

1  Getting started

1.1  Starting Xcas

Xcas is available from http://www-fourier.ujf-grenoble.fr/~parisse/giac_fr.html. This page also has information on installation. Once installed, the way to start the program depends on the operating system.

For this tutorial, you will mostly be working with the command line, which will be a white rectangle next to the number 1. There you can enter a command, after which there will be a window with the result, followed by another command line with the number 2.

1.2  XCas as a calculator

Once you have started Xcas, you can immediately use it as a calculator. Simply type in the expression that you wish to use using the standard arithmetic operators; namely + for addition, - for subtraction, * for multiplication, / for division and ^ for exponentiation. If you enter

34+45*12

you will get

574

If you enter

2/3 + 98/7

you will get

44
3

The operators have a standard order of operations, and parentheses can be used for grouping. (Brackets have a different meaning, see section 3.5, “Lists, sequences and sets”.)

Notice that if you enter integers or other exact values, Xcas will give you the exact result. If you enter an approximate value, such as a number with a decimal point (computers regard numbers with decimal points as approximate values), then Xcas will give you an approximate result. For example, if you enter

2/3 + 3/2

you will get

13
6

but if you enter

2/3 + 1.5

you will get

2.16666666667

You can also get a decimal approximation using the evalf function. If you enter

evalf(2/3 + 3/2)

you will get

2.16666666667

By default, Xcas will give you 12 decimal places of accuracy in its approximations, but this is configurable (see section 2.3, “Configuration”).

Xcas also has the standard functions, such as sin, cos, asin (for the arcsin), log (for the natural logarithm). It also has common constants such as pi, e and i.

The trigonometric functions assume that angles are measured in radians. (This can be configured, see section 2.3, “Configuration”.) If you enter

sin(pi/4)

you will get

2
2

1.3  Functions and variables

Xcas can work with expressions and variables as well as numbers. A variable in Xcas needs to begin with a letter and can include numbers and underscores. If you enter

x^2 + x + 2*x + 2

you will get

x2 + 3*x + 2

You can give a variable a value with the assignment operator, :=. To assign the variable myvar the value 5, for example, you can enter

myvar := 5

If you later use myvar in an expression, it will be replaced by 5; entering

myvar*x + myvar^2

will result in

5*x + 25

The assignment operator can also be used to define functions. To define the squaring function, for example, you can enter

sqr(x) := x^2

Afterwards, whenever you enter sqr(expression) you will get the expression squared. For example, entering

sqr(7)

will return

49

and entering

sqr(x+1)

will result in

(x+1)2

1.4  Simplifying expressions

When you enter an expression into Xcas, some simplifications will be done automatically. For example, if you enter

a := 3
b := 4

and

a*b*x + 4*b^2

you will get

12*x + 64

Xcas has several transformations in case you want an expression to be simplified beyond the automatic simplifications, or perhaps transformed in another way. Some examples are:

expand
This will expand integer powers, and more generally distribute multiplication across addition. For example, if you enter
expand((x+1)^3)
you will get
x3 + 3*x2 + 3*x + 1
factor
This will factor polynomials. For example, if you enter
factor(x^2 + 3*x + 2)
you will get
(x + 1)*(x + 2)

1.5  Graphs

Xcas has several functions for plotting graphs; perhaps the simplest is the plot function. The plot function requires two arguments, an expression to be graphed and a variable. For example, if you enter

plot(sin(x),x)

you will get the graph

To the right of the graph will be a panel you can use to control various aspects. By default, the graph will cover values of the variable from −10 to 10; this is of course configurable (see section 2.3, “Configuration”). To plot over a different interval you can also use a second argument of var=min..max instead of simply var. For example, if you enter

plot(sin(x),x=-pi..pi)

you will get the graph

1.6  The Help Index

You can get a list of all Xcas commands and variables using the HelpIndex menu item. This will bring up the following window:

Under Index will be a scrollable list of all the commands and variables. If you begin typing to the right of the question mark, you will be taken to the part of the list beginning with the characters you typed; for example, if you type evalf, you will get the following:

In the upper right-hand pane under Related is a list of commands related to the chosen command, below that is a list of synonyms; you can see that the approx command is the same as the evalf command. Below the line where you typed the command name is a description of the command; here you can see that evalf takes an optional second argument (brackets in the description indicate that an argument is optional) which can specify the number of digits in the approximation; for example,

evalf(pi)

will return

3.14159265359

but

evalf(pi,20)

will return

3.1415926535897932385

Below the description is a line where you can enter the arguments for the command; if you enter values in these boxes then the command with the chosen arguments will be placed on the Xcas command line. At the bottom of the help window is a list of examples of the command being used; if you click on one of these examples it will appear on the Xcas command line.

As well as using the menu, you can get to the help index by using the tab key while at the Xcas command line. If you have typed the beginning of a command before using the tab key, then that beginning will be presented to you in the help index.

2  The interface

2.1  Overview

When you start Xcas, you will be presented with a window which looks like the following:

From top to bottom, there is

2.2  The menu bar

The menu items have submenus, and sometimes sub-submenus. When indicating a submenu item, it will be separated from the menu item with ▸; for example, you can save a session with FileSave, which is the Save item in the File menu.

The menu bar contains the usual menus for graphic programs. It also contains all of the Xcas commands grouped by themes. For some commands, if you choose it from a menu then the command will be put on the command line. If the message window is open (which you can open with the CfgShowmsg menu item), a brief description of the command will appear in that window. For other commands, for example the Graphic commands, you will get a dialog box which lets you specify the arguments; afterwards, the command with the arguments will be placed on the command line.

The Help menu has links to the Help index, various manuals, as well as the online forum.

2.3  Configuration

The Cfg menu has various items that allow you to configure various aspects of Xcas. This tutorial will refer to the CfgCas configuration and CfgGraph configuration menu items. The CfgCas configuration menu item will bring up the same configuration page as clicking on the status bar. These items will bring up windows with various entry fields and check boxes; after you make any changes, you can click the Apply button to apply them and the Save button to save them for future sessions.

The CfgCas configuration menu item will bring up a window with options that determine how Xcas computes. This includes some things mentioned in this tutorial, such as:

The CfgGraph configuration menu item will bring up a window with options that determine how Xcas draws graphs. This includes the default ranges for the axes; the x-axis will go from X- to X+, the y-axis will go from Y- to Y+ and the z-axis will go from Z- to Z+.

2.4  The command line

You can run a command by typing it into the command line and pressing Enter. If you want to enter more than one command on a line, you can separate them with semicolons. If you want to suppress the output of a command, you can end it with a colon-semicolon (:;).

If you have enough commands, there will be a scroll bar on the right which you can use to scroll through different command line levels. The Edit menu will allow you to merge levels, group levels and add comments.

All commands are kept in memory. You can scroll through previous commands with Ctrl+ arrow keys, and modify them if you want.

3  Computational objects

3.1  Numbers

Operations
+addition
-subtraction
*multiplication
/division
^power

Conversions
evalfapproximate a number
exactfind an exact number close to the given number
epsilondetermine how close a fraction has to be to a floating point number to be returned by exact

Constants
piπ≃ 3.14159265359
ee ≃ 2.71828182846
ii=√−1
infinity or inf
+infinity or +inf+∞
-infinity or -inf−∞

There are two types of numbers in Xcas, approximate and exact.

Computer programs like Xcas regard floating point numbers, which are numbers displayed with decimal points, as approximations. Other numbers will be regarded as exact. For example, the number 2 is exactly 2, while 2.0 represents a number that equals 2 to within the current precision, which by default is about 12 significant digits (see section 2.3, “Configuration”). Approximate numbers can be entered by typing in a number with a decimal point or in scientific notation (which is a decimal number followed by e and then an integer, where the integer represents the power of 10). So 2000.0, 2e3 and 2.0e3 all represent the same approximate number.

Exact numbers are integers, symbolic constants (like e and π), and numeric expressions which only involve exact numbers. For example, sin(1) will be exact, and so won’t be given a decimal approximation; if you enter

sin(1)

you will get

sin(1)

However, sin(1.0) involves the approximate number 1.0, and so will be regarded as approximate itself. If you enter

sin(1.0)

you will get

0.841470984808

As with many computer languages, if you enter an integer beginning with the digit 0, the Xcas will regard it as an integer base 8; if you enter

011

you will get

9

since 11 is the base 8 representation of the decimal number 9. Similarly, if you write 0x at the beginning of an integer, Xcas will regard it as a hexadecimal (base 16) integer. If you enter

0x11

you will get

17

since 11 is the base 16 representation of the decimal number 17.

The symbolic constants that are built in to Xcas are pi, e, i, infinity, +infinity and -infinity. Note that Xcas distinguishes between +infinity, -infinity and infinity, which is unsigned infinity. The distinction can be noted in the following calculations:

1/0

will result in infinity,

while

(1/0)^2

will result in +infinity,

+∞

and

-(1/0)^2

will result in -infinity,

−∞

These variables cannot be reassigned; in particular, the variable i can’t be used as a loop index.

Xcas can handle integers of arbitrary length; if, for example, you enter

500!

you will be given all 1135 digits of the factorial of 500.

When Xcas combines two numbers, the result will be exact unless one of the numbers is approximate, in which case the result will be approximate. For example, entering

3/2 + 1

will return the exact value

5
2

while entering

1.5 + 1

will return

2.5

The evalf function will transform a number to an approximate value. While entering

sqrt(2)

will return

2

entering

evalf(sqrt(2))

will return

1.41421356237

which is the square root of two to the default precision, in this case 12 digits. The evalf function can also take a second argument which you can use to specify how many digits of precision that you want; for example if you want to know the square root of two to 50 digits, you can enter

evalf(sqrt(2),50)

and get

1.4142135623730950488016887242096980785696718753770

The exact function will turn an approximate value into a nearby exact value. Specifically, given an approximate value x, exact(x) will be a rational number r with |xr| < є, where є is the value of the variable epsilon, which has a default value of 10−12. This value is configurable (see section 2.3, “Configuration”).

3.2  Variables

Variables
:=assignment
substgive a variable a value for a single instance
assumeput assumptions on variables
andcombine assumptions
orcombine assumptions
purgeremove values and assumptions attached to variables

A variable in Xcas begins with a letter and can contain letters, numbers and underscores.

A variable can be given a value with the assignment operator :=. If you enter

a := 3

then a will be replaced by 3 in all later calculations. If you later enter

4*a^2

you will get

36

The purge command will unassign a variable; if you enter

purge(a)

and then

4*a^2

you will get

4· a2

The assignment operator := is one of three types of equalities used in Xcas. They are

If you want to replace a variable by a value for a single expression, you can use the subst command. This command takes an expression and an equation var = value as a second argument. If a is an unassigned variable, for example, then entering

subst(a^2 + 2, a=3)

will result in

11

Afterwards, a will still be unassigned.

Even without giving a variable a value, you can still tell Xcas some of its properties with the assume command. For example, for a real number a, the expression √a2 simplifies to |a|, since a could be positive or negative. If you enter

sqrt(a^2)

you will get

|a|

If you enter

assume(a<0)

beforehand, then Xcas will work under the assumption that a is negative, and so entering

sqrt(a^2)

will result in

a

As well as assuming that a variable satifies an equation or inequality, you can use the keywords and and or to assume that a variable satisifies more than one inequality. Some assumptions on a variable require a second argument; for example, to assume that a is an integer you can enter

assume(a,integer)

Afterwards

sin(a*pi)

will result in

0

The purge command will remove any assumptions about a variable as well as any assigned values.

3.3  Expressions

Conversions
expandexpand powers and distribute multiplication
normalreduce to lowest terms
ratnormalreduce to lowest terms
factorfactor
simplifyreduce an expression to simpler form
tsimplifyreduce and expression to simpler form
convertconvert an expression to a different type

An expression is a combination of numbers and variables combined by arithmetic operators. For example, x^2 + 2*x + c is an expression.

When you enter an expression, Xcas will perform some automatic simplifications, such as

Other simplifications are not done automatically, since it isn’t always clear what sort of simplifications the user might want, and besides non-trivial simplifications are time-consuming. The most used commands for simplifying and transforming commands are:

expand
This will expand integer powers and more generally distribute multiplication across addition. For example, if you enter
expand((x+1)^3)
you will get
x3 + 3*x2 + 3*x + 1
normal and ratnormal
These commands will reduce a rational function to lowest terms. For example, if you enter
normal((x^3-1)/(x^2-1))
then Xcas will cancel a common factor of x−1 from the top and bottom and return
x2+x+1
x+1
ratnormal will have the same behavior on this expression. The difference between the two commands is that ratnormal does not take into account reductions with algebraic numbers, while normal does. If you enter
ratnormal((x^2-2)/(x-sqrt(2)))
you will get
x2−2
x
2
but if you enter
normal((x^2-2)/(x-sqrt(2)))
you will get
x+
2

Neither of these commands will take into account relationships between transcendental functions such as sin and cos.

factor
This will factor polynomials and reduce rational expressions. This is a little slower than normal and ratnormal and different in that it will give the result in factored form. For example, if you enter
factor(x^2 + 3*x + 2)
you will get
(x + 1)*(x + 2)
simplify
This command will try to reduce an expression to algebraically independent variables, then it will apply normal. Simplifications requiring algebraic extensions (such as roots) may require two calls to simplify and possibly adding some assumptions with assume.
tsimplify
Like simplify, this will try to reduce an expression to algebraically independent variables, but will not apply normal afterwards.

The convert command will rewrite expressions to different formats; the first argument will be the expression and the second argument will indicate the format to convert the expression to. For example, you can convert ei θ to sines and cosines with

convert(exp(i*theta),sincos)

the result will be

cos(θ) + i*sin(θ)

You can use convert to find the partial fraction decomposition of a rational expression with a second argument of partfrac; for example, if you enter

convert((x-1)/(x^2 - x -2), partfrac)

you will get

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

3.4  Functions

Common functions
absabsolute value
signsign (-1,0,+1)
maxmaximum
minminimum
roundround to the nearest integer
floorgreatest integer less than or equal to
fracfractional part
ceilleast integer greater than or equal to
rereal part
imimaginary part
absabsolute value
argargument
conjconjugate
coordinatesthe coordinates of a point
factorialfactorial
!factorial
sqrtsquare root
expexponential
lognatural logarithm
lnnatural logarithm
log10logarithm base 10
sinsine
coscosine
tantangent
cotcotangent
asinarcsine
acosarccosine
atanarctangent
sinhhyperbolic sine
coshhyperbolic cosine
tanhhyperbolic tangent
asinhinverse hyperbolic sine
acoshinverse hyperbolic cosine
atanhinverse hyperbolic tangent

Create functions
:=assign an expression to a function
->define a function
unapplyturn an expression into a function

Xcas has many built in functions; you can get a complete list with the help index. You can also define your own functions with the assignment (:=) operator. To define a function f given by f(x) = x*exp(x), for example, you can enter

f(x) := x*exp(x)

Note that in this case the name of the function is f; f(x) is the value of the function evaluated at x. The function is a rule which takes an input x and returns x*exp(x). This rule can be written without giving it a name as x -> x*exp(x). In fact, another way you can define the function f as above is

f := x ->x*exp(x)

In either case, if you enter

f(2)

you will get

2*exp(2)

You can similarly define functions of more than one variable. For example, to convert polar coordinates to rectangular coordinates, you could define

p(r,theta) := (r*cos(theta), r*sin(theta))

or equivalently

p := (r, theta) -> (r*cos(theta),r*sin(theta))

The unapply command will transform an expression into a function. It takes as arguments an expression and a variable, it will return the function defined by the expression. If you enter

unapply(x*exp(x),x)

you will get

x −>x*exp(x)

The unapply command will return the function written in terms of built in functions; for example, for the function f defined above, if you enter

unapply(f(x),x)

you will also get

x −>x*exp(x)

You can define a function in terms of a function that you previously defined, but it’s probably better to define any new functions in terms of built-in functions. For example, if you define

f(x) := exp(x)*sin(x)

you can define a new function

g(x) := x*f(x)

but it might be better to write

g(x) := x*exp(x)*sin(x)

Perhaps a better alternative is to use unapply; you can define g by g := unapply(x*f(x),x)

In some cases, it will be necessary to use unapply to define a function. For example (see section 4.1, “Derivatives”), the diff command will find the derivative of an expression; if you enter

diff(x*sin(x),x)

you will get

sin(x) + x * cos(x)

However, you cannot simply define a function g(x) := diff(x*sin(x),x) if you tried to do this, then evaluating g(0) for example would give you diff(0*sin(0),0), which is not what you want. Instead, you could define g by

g := unapply(diff(x*sin(x),x)

Another case where you need to use unapply to define a function is when you have a function of two variables and you want to use it to define a function of one variable, where the other variable is a parameter. For example, consider the polar coordinate function

p(r,theta) := (r*cos(theta), r*sin(theta))

If you want to use this to define C(r) as a function of θ for any value of r, you cannot simply define it as

C(r) := p(r,theta)

Doing this will define C(r) as an expression involving θ, not a function of θ. Entering

C(1)(pi/4)

would be the same as

(cos(theta),sin(theta))(pi/4)

which is not what you want. To define C(r), you would have to use unapply:

C(r) := unapply(p(r,theta),theta)

The necessity of using unapply in these cases is because when you define a function, the right hand side of the assignment is not evaluated. For example, if you try to define the squaring function by

sq := x^2
f(x) := sq

it will not work; if you enter f(5), for example, it will get the value sq, which will then be replaced by its value. You will end up getting x^2 and not 5^2. You should either define the function f by

f(x) := x^2

or perhaps

f := unapply(sq,x)

Functions (not just expressions) can be added and multiplied. To define a function which is the sine function times the exponential, instead of defining f(x) as the expression sin(x)*exp(x), you could simply enter

f := sin*exp

Functions can also be composed with the @ symbol. For example, if you define functions f and g by

f(x) := x^2 + 1
g(x) := sin(x)

then

f @ g

will result in

x −>(sin(x))2 + 1

You can use the @ operator to compose a function with itself; f@f(x) is the same as f(f(x)), but if you want to compose a function with itself several times, you can use the @@ operator. Entering f @@ n for a positive integer n will give you the composition of f with itself n times; for example, if you enter

sin @@ 3

you will get

x −> sin(sin(sin(x)))

3.5  Lists, sequences and sets

Sequences and lists
(  )sequence delimiters
[  ]list delimiters
%{  %}set delimiters
NULLempty sequence
E$(k=n..m)create a sequence
seq(E,k=n..m)create a sequence
[E$(k=n..m)]create a list
makelist(f,k,n,m,p)create a list
appendappend an element to a list
op(li)convert a list to a sequence
nop(se)convert a sequence to a list
nops(li)the number of elements
size(li)the number of elements
mid(li)extract a subsequence
sumthe sum of the elements
productthe product of the elements
cumSumthe cumulative sums
apply(f,li)apply a function to the list elements
map(li,f)apply a function to the list elements
map(li,f,matrix)apply a function to the elements of a matrix
poly2symbconvert a polynomial expression to a polynomial list
symb2polyconvert a polynomial list to a polynomial expression

Xcas can combine objects in several different ways.

sequences
A sequence is simply several items between parentheses, separated by commas. For example, (1,2,x,4) is a sequence. (The parentheses can be omitted, but it’s a good idea to use them.) Sequences are flat, meaning an element in a sequence cannot be another sequence. The empty sequence is denoted NULL.
lists
A list consists of several items between square brackets, separated by commas. For example, [1,2,x,4] is a list. A list can contain other lists as elements. Matrices, which will be discussed later, are lists of lists. The empty list is denoted [].
sets
A set consists of several items between %{ and %}, separated by commas. For example, %{1,2,3%} is a set. In a set, order doesn’t matter and each item only counts once. The sets %{1,2,3%} %{3,2,1%} and %{1,2,2,3%} are all the same set.
tables
Tables are described later.

A sequence can be turned into a list or a set by putting it between the appropriate delimiters. For example, if you define a sequence

se := (1,2,4,2)

then if you enter

[se]

you will get the list

[1,2,4,2]

You can turn a set or list into a sequence with the op command; if you define a set

st := %{1,2,3%}

and then enter

op(st)

you will get the sequence

(1,2,3)

You can find the number of elements in a sequence, list or set with the size command; with st as above,

size(st)

will return

3

Sequences can be built using one of the iteration commands seq or $. The seq command takes an expression as the first argument, the second argument will be a variable followed by a range in the form variable=beginning value..ending value. The resulting sequence will be the values of the expression with the variable replaced by the sequence of values. For example,

seq(k^2,k=-2..2)

will result in the sequence

(4,1,0,1,4)

The $ operator is an infix version of seq. If you enter

k^2$k=-2..2

you will get, as above,

(4,1,0,1,4)

A list can be built by putting a sequence in brackets; if you enter

[k^3,k=1..3]

you will get the list

[1,8,27]

You can also create a list with the makelist command. It takes three arguments; a function (not an expression), an initial value for the variable and an ending value for the variable. If you enter

makelist(x -> x^2,-2,2)

you will get the list

[4,1,0,1,4]

There is an optional fourth argument, which will be the step size.

You can add an element to the end of a list with the append command. If you enter

append([1,5],3)

you will get

[1,5,3]

The elements of sequences and lists are indexed, beginning with the index 0. You can get an element by following the sequence or list with the index number in square brackets; if you enter

ls := [A,B,C,D,E,F]

then

ls[1]

will return

B

You can get a subsequence (or sublist) by putting an interval (a beginning value and an ending values separated by two dots) in brackets. If you enter

ls[2..4]

you will get

[C,D,E]

The mid command is another way to get a subsequence or sublist. Given a sequence or list, a beginning index and a length, then mid will return the subsequence of the sequence beginning at the given index of the given length. With ls as above, if you enter

mid(ls,2,3)

you will get

[C,D,E]

If the length is left off, then the subsequence will go to the end of the given sequence; if you enter

mid(ls,2)

you will get

[C,D,E,F]

You can change the element in a particular position with the := operator; for example, to change the second element in ls, you can enter

ls[1] := 7

The value of ls will then be

[A,7,C,D,E,F]

If a variable var is not a list or sequence and you assign a value to var[n], then var becomes a table. A table is like a list, but the indices don’t have to be integers. If you define

newls := []

and then set

newls[2] := 5

then since newls was previous a list, it will now be equal to the list

[0,0,5]

If nols is an undefined variable and you set

nols[2] := 5

then nols will be a table,

table(2=5)

When changing an element of a list (or sequence or table) using :=, the entire list is copied. This can be inefficient. To save copy time and modify the list element in place, you can use =<. If you have

ls := [a,b,c]

and then enter

ls[2] =< 3

then ls will be equal to

[a,b,3]

Polynomials are typically given by expressions, but they can also be given by a list of the coefficients in decreasing order, delimited with poly1[ and ]. The symb2poly will transform a polynomial written as an expression to the list form of the polynomial. If you enter

symb2poly(2*x^3 - 4*x + 1)

you will get

poly1[2,0,−4,1]

The poly2symb will transform in the other direction; if you enter

poly2symb(poly1[2,0,-4,1])

you will get

2*x3 − 4*x + 1

There is also a way to represent a multivariable polynomial with lists; see the manual for more information.

3.6  Characters and strings

String commands
ascconvert a string to a list of ASCII codes
charconvert a list of ASCII codes to a string
sizethe number of characters
concat or +concatenation
midsubstring
headfirst character
tailthe string without the first character
stringconvert a number or expression to a string
exprconvert a string to a number or expression

A string is simply text enclosed within quotation marks. You can find out how many characters are in a string with the size command; if you enter

size("this string")

you will get

11

A character is simply a string with length 1. The char command will take an ASCII code (or a list of ASCII codes) and return the character or string determined by the codes. For example, the letter “a” has ASCII code 65, so

char(65)

will return

A

The asc command will turn a string into the list of ASCII codes; if you enter

asc("A")

you will get

[65]

The characters in a string are indexed starting with 0. To get the first character, for example, you can enter a string, or the name of a string, followed by [0]. If you enter

str := "abcde"
str[0]

you will get

a

You can choose a substring from a string by putting the beginning and ending indices in the brackets, separated by two periods ... If you enter

str[1..3]

you will get

bcd

An alternate way of getting the first character from a string is with the head command. With str as above,

head(str)

will return

a

The tail command will produce the remaining characters;

tail(str)

will return

bcde

Strings can be combined with the concat command or the infix + operator. Both

concat("abc","def")

and

"abc" + "def"

will return

abcdef

If a string represents a number, then the expr command will convert the string to the number. For example,

expr("123")

will return the number 123. More generally, expr will convert a string representing an expression or command into the corresponding expression or command. The string command works in the opposite direction; it will take an expression and convert it to a string.

3.7  Calculation time and memory space

One major issue with symbolic calculations is the complexity of the intermediate calculations. This complexity takes the form of the amount of time required for the calculations and the amount of computer memory needed. The algorithms used by Xcas are efficient, but not necessarily optimal. The time command will tell you how long a calculation takes. For very quick calculations, Xcas will execute it several times and return the average for a more accurate result. The amount of memory used by Xcas is shown in the status line of the Unix version of Xcas.

If a command that you are timing takes more than a few seconds, you could have made an input error and you may have to interrupt the command (with the red STOP button on the status line, for example). It is a good idea to make a backup of your session beforehand.

4  Analysis with Xcas

4.1  Derivatives

Derivatives
diff(ex,t)the derivative of an expression with respect to t
function_diff(f)the derivative of a function
diff(ex,x$n,y$m)partial derivatives
gradgradient
divergencedivergence
curlcurl
laplacianlaplacian
hessianhessian matrix

The diff function will find the derivative of an expression and returns the derivative as an expression. If you have a function f, you can find the derivative by entering

diff(f(x),x)

Note that the result will itself be an expression; do not define the deritivave function by fprime(x) := diff(f(x),x). If you want to define the derivative as a function, you can use unapply:

fprime := unapply(diff(f(x),x),x)

Alternatively, you can use function_diff, which takes a function (not an expression) as input and returns the derivative function;

fprime := function_diff(f)

The diff function can take a sequence of variables as the second argument, and so can calculate successive partial derivatives. Given

E := sin(x*y)

then

diff(E,x)

will return

y*cos(x*y)
diff(E,y)

will return

x*cos(x*y)
diff(E,x,y)

will return

x*y*sin(x*y) + cos(x*y)

and

diff(E,x $ 2)

will return

y2*sin(x*y)

If the second argument to diff is a list, then a list of derivatives is returned. For example, to find the gradient of E, you can enter

diff(E,[x,y])

and get

[y*cos(x*y),x*cos(x*y)]

There is also a special grad command for this, as well as commands for other types of special derivatives.

4.2  Limits and series

Limits and series
limitthe limit of an expression
taylorTaylor series
seriesTaylor series
order_sizeused in the remainder term of a series expansion

The limit function will take an expression, a variable and a point and return the limit at the point. If you enter

limit(sin(x)/x,x,0)

you will get

1

Xcas can also find limits at plus and minus infinity;

limit(sin(x)/x,x,+infinity)

will return

0

as well as limits of infinity;

limit(1/x,x,0)

will return

which recall is unsigned infinity. An optional fourth argument can be used to find one-sided limits; if the fourth argument is 1 it will be a right-handed limit and if the argument is -1 it will be a left-handed limit. Entering

limit(1/x,x,0,-1)

will result in

−∞

Given an expression and a variable, the taylor function will find the Taylor series of the expression. If you enter

taylor(sin(x)/x,x)

you will get

1−
x2
6
 + 
x4
120
 + x6*order_size(x)

The series function works the same as the taylor function.

By default, taylor will find the terms up to the fifth degree. The order_size(x) represents a factor for which for all a>0, the term xaorder_size(x) will approach 0 as x approaches 0.

The series returned by taylor will also be centered about 0 by default; if you want to center it around the number a, you can replace x by x=a;

taylor(exp(x),x=1)

will result in

exp(1)+exp(1)*(x−1)+exp(1)*(x−1)2/2+ exp(1)*(x−1)3/6+
exp(1)*(x−1)4/24+exp(1)*(x−1)5/120+(x−1)6*order_size(x−1)

You can also give the center of the series with a third argument. To find the terms to a different you can add an extra argument giving the order;

taylor(sin(x)/x,x=0,3)

will return

1−
x2
6
 + x4*order_size(x)

Note that in this case you must explicitly give the center of the series, even if it is 0.

To find the Taylor polynomial, you can add an extra argument of polynom;

taylor(sin(x)/x,x,polynom)

will return

1−
x2
6
 + 
x4
120

4.3  Antiderivatives and integrals

Integrals
intantiderivatives and exact integrals
rombergapproximation of integrals

The int function will find an antiderivative of an expression. By default, it will assume that the variable is x, to use another variable you can give it as an argument.

int(x*sin(x))

will result in

sin(x) − x*cos(x)

and

int(t*sin(t),t)

will result in

sin(t) − t*cos(t)

To compute a definite integral, you can give the limits of integration as arguments after the variable; to integrate x*sin(x) from x=0 to x=π, you can enter

int(x*sin(x),x,0,pi)

and get

π

The limits of integration are allowed to be expressions; this can be useful when computing a multiple integral over a non-rectangular region. For example, you can integrate x y over the triangle 0 ≤ x ≤ 1, 0 ≤ yx with

int(int(x*y,y,0,x),x,0,1)

resulting in

1
8

The romberg function will approximate the value of a definite integral, for cases when the exact value can’t be computed or you don’t want to compute it. For example,

romberg(exp(-x^2),x,0,10)

will return

0.886226925452

4.4  Solving equations

Solving equations
solve(eq,x)exact solutions of an equation
solve([eq1,eq2],[x,y])exact solutions of a system of equations
fsolve(eq,x)approximate solution of an equation
fsolve([eq1,eq2],[x,y])approximate solution of a system of equations
linsolvesolve a linear system
prootapproximate roots of a polynomial

Solving equations is important, but it is often impossible to find exact solutions. Xcas has the ability to find exact solutions in some cases and to approximate solutions.

The solve function will attempt to find the exact solution of an equation that you give it. If you enter an expression that isn’t an equation, it will try to solve for the expression equal to zero. By default, the variable will be x, but you can give a different variable as a second argument. If you enter

solve(x^3 -2*x^2 + 1=0, x)

you will get




−(
5
)+1
2
,1,
5
+1
2



By default, solve will only try to find real solutions; if you enter

solve(x^3+1=0,x)

you will get

[−1]

You can configure Xcas to find complex solutions (see section 2.3, “Configuration”). If you do that, then entering

solve(x^3+1=0,x)

will result in




−1,
3
*i+1
2
,
3
*i+1
2



For linear and quadratic functions, solve will always return the exact solution. For higher degree polynomials, solve will try some approaches, but may return intermediate results or approximate solutions. (It doesn’t use the Cardan and Ferrari formulas for polynomials of degrees 3 and 4, since the solutions would then not be easily managable.)

For trigonometric equations, the primary solutions are returned. For example,

solve(cos(x) + sin(x) = 0, x)

will result in




π
4
,
3*π
4



You can configure Xcas to find all solutions (see section 2.3, “Configuration”). If you do that, then

solve(cos(x) + sin(x) = 0, x)

will result in




4*n0*π−π
4



where n0 represents an arbitrary integer.

The solve function can also handle systems of equations. For this, use a list of equations for the first argument and a list of variables for the second. If you enter

solve([x^2 + y - 2, x + y^2 - 2],[x,y])

you will get all four solutions as a matrix; each row represents one solution.

















1,1
−2,−2
5
+1
2
,



5
+1
2



2



 
 + 2
−(
5
)+1
2
,



−(
5
)+1
2



2



 
 + 2
















To approximate a solution to an equation or system of equations, Xcas provides the fsolve command. If you enter

fsolve(x^3 -3*x + 1,x)

you will get

[−1.87938524157,0.347296355334,1.53208888624]

Algorithms for approximating solutions of equations typically involve starting with a given point and finding a sequence which converges to a solution. The fsolve command can take a starting point, if you enter

fsolve(x^3 -3*x + 1,x,1)

you will get

0.347296355334

4.5  Differential equations

Commands for differential equations
desolveexact solution
odesolveapproximate solution
plotodegraph of solution
plotfieldvector field
interactive_plotodeclickable interface

The desolve command is used to try to find exact solutions of differential equations. The first argument is the differential equation itself, the second argument is the function. The derivative of an unknown function y is denoted diff(y), which can be abbreviated y’. The second derivative will be diff(diff(y)) or y’’, etc. If you enter

desolve(x^2*y’ = y,y)

you will get

c0 * exp(−
1
x
)

where c0 is an arbitrary constant. By default the variable is x, if you want to use a different variable, put it in the function in the second argument;

desolve(t^2*y’ = y,y(t))

will return

c0 * exp(−
1
t
)

If you want to solve a differential equation with initial conditions, the first argument should be a list with the differential equation and the conditions. If you enter

desolve([y’’ + 2*y’ + y = 0, y(0) = 1, y’(0) = 2],y)

you will get

exp(−x)*(3*x+1)

To solve a differential equation numerically, you can use the odesolve command. This will allow you to solve the equation y′=f(x,y) where the graph passes through a point (x0,y0). The command

odesolve(f(x,y),[x,y],[x_0,y_0],a)

will find y(a) in this case. For example, to calculate y(2) where y(x) is the solution of y′(x) =sin(xy) with y(0)=1, you can enter

odesolve(sin(x*y),[x,y],[0,1],2)

The result will be

[1.82241255674]

The plotode command will plot the graph of the solution; if you enter

plotode(sin(x*y),[x,y],[0,1])

you will get

The plotfield command will plot the entire vector field;

plotfield(sin(x*y),[x,y])

will result in

If you use the interactive_odeplot command, you will get the vector field and you will be able to click on a point to find the graph of the solution passing through the point.

5  Algebra with Xcas

5.1  Integer arithmetic

Integers
iremremainder
iquoquotient
iquoremquotient and remainder
ifactorprime factorization
ifactorslist of prime factors
idivislist of divisors
gcdgreatest common divisor
lcmleast common multiple
iegcdBezout’s identity
isprimeprimality test
nextprimenext prime number
previousprimeprevious prime number
a%pa modulo p
powmod(a,n,p)an modulo p

Xcas has the usual number theoretic functions. The iquo command will find the integer quotient of two integers and irem will find the remainder. The iquorem command will return a list of both the quotient and remainder; if you enter

iquorem(30,7)

you will get

[4,2]

since 30 divided by 7 is 4 with a remainder of 2.

The gcd and lcm commands will find the greatest common divisor and least common multiple of two integers. If you enter

gcd(72,120)

you will get

24

The greatest common divisor d of two integers a and b can always be written in the form a*u + b*v = d for integers u and v. (This is known as Bézout’s Identity.) The iegcd will return the coefficients u and v as well as the greatest commond divisor. If you enter

iegcd(72,120)

you will get

[2,−1,24]

since

72· 2 + 120·(−1) = 24

The ifactor command will give the prime factorization of an integer; if you enter

ifactor(250)

you will get

2*53

You can use ifactors to get a list of the prime factors of an integer, where in the list each factor is followed by its multiplicity. If you enter

ifactors(250)

you will get

[2,1,5,3]

since 250 has a prime factor of 2 (it has 1 factor of 2) and a prime factor of 5 (it has 3 factors of 5). The idivis command will return a complete list of factors;

idivis(250)

will return

[1,2,5,10,25,50,125,250]

The subject of primes is a difficult one, and you should see the manual for a discussion of how Xcas checks for primes. But the command isprime will return true or false depending on whether or not you enter a prime. If you enter

isprime(37)

you will get

true

since 37 is a prime number. The commands nextprime and previousprime will find the first prime after (or before) the number that you give it; if you enter

nextprime(37)

you will get

41

since the first prime after 37 is 41.

Integers modulo p are defined by putting % p after them. Once an integer modulo p is defined, then any calculations done with it are done in ℤ/pℤ. For example, if you define

a := 3 % 5

then

a*2

will return

1 % 5

(since 6 mod 5 is reduced to 1 mod 5);

1/a

will return

2 % 5

etc. The powermod or powmod functions can be used to efficiently calculate powers modulo a number.

5.2  Polynomials and rational functions

Polynomials
normalnormal form (expanded and reduced)
expandexpanded form
ptaylTaylor form
peval or hornerevaluation using Horner’s method
canonical_formcanonical form for a trinomial
coefflist of coefficients
poly2symbtransform an algebraic polynomial to list form
symb2polytransform the list form of a polynomial to algebraic form
pcoeffreturn the polynomial (list form) given a list of zeroes
degreedegree
lcoeffthe coefficient of the leading term
valuationthe lowest degree of the terms
tcoeffthe coefficient of the term with the lowest degree
factorprime factorization
factorslist of prime factors
divislist of divisors
frootroots with multiplicities
prootapproximate values of the roots
sturmabthe number of roots in an interval
getNumthe numerator of a rational function
getDenomthe denominator of a rational function
propfracwrites a rational expression as a whole part and a proper rational part
partfracpartial fraction decomposition
quoquotient
remremainder
gcdgreatest common divisor
lcmleast common multiple
egcdBezout’s identity
divpcTaylor polynomial for a rational expression
randpolyrandom polynomial
cyclotomiccyclotomic polynomial
lagrangeLagrange polynomials
hermiteHermite polynomials
laguerreLaguerre polynomials
tchebyshev1Tchebyshev polynomials
tchebyshev2Tchebyshev polynomials

Various polynomial operations are available in the Polynomials submenu of the Cmds menu.

The expand and normal operators will distribute multiplication across addition, and so expand a polynomial completely out. If you enter

expand((x+1)*(x+2)^2)

you will get

x3+5*x2+8*x+4

Additionally, normal will reduce a rational expression to lowest terms; if you enter

normal((x-1)^2/(x^2-1))

you will get

x−1
x+1

The factor operator will factor a polynomial. If you enter

factor(x^3+6*x^2+3*x-10

you will get

(x−1)*(x+2)*(x+5)

The result often depends on the number field being used. For example, over the rational numbers the polynomial x4 − 1 factors as (x−1)(x+1)(x2 + 1), while over the complex numbers it factors as (x−1)(x+1)(xi)(x+i). If the coefficients of a polynomial are exact fractions, then the factoring will be over the rationals. To factor over the complex numbers, you can configure Xcas to do complex factorization (see section 2.3, “Configuration”) or use the cfactor command. If the coefficients are in ℤ/pℤ then the polynomial will be factored over ℤ/pℤ.

5.3  Trigonometry

Trigonométrie
tlinlinearize
tcollectlinearize and regroup
texpandexpand
trig2exptrigonometric to exponential
exp2trigexponential to trigonometric
hyp2exphyperbolic to exponential

Xcas has the usual trigonometic functions, both circular and hyperbolic, as well as their inverses. It also has commands for manipulating trigonometric expressions; these are in the Trigo submenus of the Expression menu.

One example is the tlin command will write products and powers of sines and cosines as linear combinations of sin(n x)s and cos(n x)s. If you enter

tlin(2*sin(x)^2*cos(3*x))

you will get

cos(x)
2
 + cos(3*x) − 
cos(5*x)
2

The texpand command will take expressions involving sin(n x) and cos(n x) and write them in terms of powers if sin(x) and cos(x). If you enter

texpand(sin(2*x)^2*cos(3*x))

you will get

16*cos(x)5*sin(x)2−12*cos(x)3*sin(x)2

5.4  Vectors and matrices

Vectors and matrices
v*wscalar product
cross(v,w)cross product
A*Bmatrix product
A.*Bterm by term product
1/Ainverse
trantranspose
rankrank
detdeterminant
kerbasis for the kernel
imagebase for the image
idnidentity matrix
ranmmatrix with random coefficients
makematrixmake a matrix from a function
matrixmake a matrix from a function
blockmatrixcombine matrices

A vector is a list of numbers, such as [2,3,5], and a matrix is a list of vectors all of the same length, such as [[1,2,3],[4,5,6]].

The usual matrix operations (addition, scalar multiplication, matrix multiplication) are done with the usual operators + and *. If you define

A := [[1,2,3],[4,5,6],[7,8,9]]
B := [[1,1,1],[2,2,2]]

then

3*A

will give you




369
121518
212427



and

B*A

will give you



121518
243036


A vector can be regarded as a matrix with one row, except that if a matrix is multiplied on the right by a vector, the vector will be regarded as a column. In particular, if v and w are vectors of the same length, then v*w will return the scalar product.

The idn command will create an identity matrix;

idn(2)

will return



10
01


You can also use makemat or matrix commands to build a matrix. They both require a real-valued function of two variables, the number of rows and the number of columns. The indices start at 0, and with the makemat the function comes first, with matrix the function comes last. Both

makemat((j,k)->j+k,3,2)

and

matrix(3,2,(j,k)->j+k)

produce




01
12
23



Several matrices can be combined into a larger matrix with the blockmatrix command. To arrange m * n matrices into m rows and n columns, you give blockmatrix the values m, n and a list of the matrices. If you enter

A := [[1,2,3],[4,5,6]]
B := [[1,2],[2,3]]

then

blockmatrix(2,2,[A,B,B,A])

will give you





12312
45623
12123
23455




You can get the elements from a matrix by following the matrix with the indices in brackets, separated by commas. For A as above,

A[1,2]

will return

6

You can extract a submatrix by using intervals of indices (the beginning and end index separated by two periods);

A[0..1,1..2]

returns



23
56


Note that if you change one value of a matrix in Xcas, the entire matrix will be copied. If a program modifies parts of a large matrix one element at a time, this time can add up.

5.5  Linear systems

Linear systems
linsolvesolution of a linear system
simultsolutions of many linear systems
rrefGauss-Jordan reduction

The linsolve command will solve a system of linear equations; its syntax is the same as that of solve (see section 4.4, “Solving equations”). If you enter

linsolve([2*x + 3*y = 4, 5*x + 4*y = 3],[x,y])

you will get

[−1,2]

The simult command can also solve a system of linear equations; more generally, it can solve several systems with the same coefficient matrix. To solve the systems

Ax = b1,…,Ax=bk

you can enter

simult(A,B)

where

B = 
b1 ⋯ bk

The result will be a matrix whose jth column is the solution of Ax=bj. For example, if you want to solve the systems





 x+yz=1
 xy+z=
 −x+y+z=−2 




 x+yz=−2
 xy+z=
 −x+y+z=

which both have the same matrix of coefficients




  11−1
  1−11
  −111



you can create the matrix which has one column for each system




  1−2
  11
  −21



If you enter

simult([[1,1,-1],[1,-1,1],[-1,1,1]],[[1,-2],[1,1],[-2,1]])

you will get




1−1/2
−1/2−1/2
−1/21



The solution to the first system is the first column, x=1,y=−1/2,z=−1/2, and the solution to the second system is the second column, x=−1/2,y=−1/2,z=1.

When there are no solutions, linsolve will return the empty list while simult will return an error. When there are infinitely many solutions, linsolve will return formulas for all solutions while simult will return one solution.

5.6  Matrix reduction

Matrix reduction
jordandiagonalization or Jordan reduction
pcarcharacteristic polynomial (list form)
pminminimal polynomial (list form)
eigenvalseigenvalues
eigenvectseigenvectors

The jordan command will take a matrix A and returns a transition matrix P and a matrix J in Jordan canonical form, so that P−1 A P = J. In particular, if A is diagonalizable, then J will be diagonal with the eigenvalues of A on the diagonal and the columns of P will be the corresponding eigenvectors. If you enter

jordan([[4,1],[-8,-5]])

you will get





11
−1−8 


,


30
0−4 




This means that 3 and −4 (the diagonal elements of the second matrix) are the eigenvalues of (

41
−8−5

) and the corresponding eigenvectors are (

1
−1

) and (

1
−8

) (the columns of the first matrix). For diagonalizable matrices you can also get this information with the eigenvals and eigenvects commands;

eigenvals([[4,1],[-8,-5]])

will return

(3,−4)

and

eigenvects([[4,1],[-8,-5]])

will return



11
−1−8 


For matrices with exact and symbolic values, the only eigenvalues used are those computable with solve; for matrices with floating point numbers, a numerical algorithm is used to find the eigenvalues. This algorithm may fail in some cases where there are very close eigenvalues or eigenvalues with multiplicity greater than one.

If a function is defined by a polynomial, you can evaluate it with an argument of a square matrix. If a function is given by a series, the Jordan form of the matrix can be used to define the value of the function at a matrix. For example, you can find the exponential of a square matrix;

exp([[0,-1],[1,2]])

will result in



0−exp(1)
exp(1)2*exp(1)


6  Graphs

Plotting graphs
plotgraph an expression of one variable
plotfuncgraph an expression of one or two variables
tangenttangent to a curve
plotparamparametric curve
plotpolarpolar plotting
plotimplicitimplicit curve

The Graphic menu has entries for several graphing commands; if you choose one you will be given a template you can fill out to produce a graphic. The appropriate command will be placed on the command line. If you want several graphs in the same window, you can put the commands on the same command line separated by semicolons.

Once you have created a graphic window, there will be a panel to the right with buttons allowing you to control the image. The default parameters for graphs, such as the size of the graphs, are configurable (see section 2.3, “Configuration”).

As well as being displayed in the Xcas window, the two dimensional graphics also appear in the DispG (Display Graphics) window. You can bring that window up with the CfgShowDispG menu item. This window will contain all two dimensional graphs; they can be cleared with the ClrGraph command.

6.1  Curves

The simplest way to draw graphs is with the templates from the Graphic menu, but there are command line equivalents.

The command line instruction for graphing a function is the plot command. It takes an expression (or list of expressions) followed by the variable. To use a domain different than the default, you can indicate the range of the variable by setting it equal to an interval. If you are plotting several curves, you can distinguish them by giving them different colors; you can do this with a third argument color= followed by a list of colors. If you plot

plot([x^2,x^3],x=-1..1,color=[red,blue])

you will get

You can draw parameterized curves with the plotparam command. The coordinates of the curve must be given as a single complex expression; the x coordinate will be the real part of the expression and the y coordinate will be the imaginary part. For example, if you enter

plotparam(sin(t) + i*cos(t),t)

you will get the circle

(Since the x- and y-axes are scaled differently, the circle looks elliptical.)

You can draw a curve using polar coordinates with the plotpolar command. This takes the form plotpolar(f(theta),theta,theta-min,theta-max).

You can draw an implicitly defined curve with the plotimplicit command; the command plotimplicit(f(x,y),x,y) will draw the curve f(x,y)=0. For example, the command

plotimplicit(x^2 + y^2 = 1,x,y)

will draw a circle.

The tangent command will draw the tangent line to a curve, if you tell it the curve and the point. To draw the tangent line to the graph y=x2 at x=1, for example, you can enter

tangent(plotfunc(x^2,x),1)

You will get

6.2  Plane geometry

2D graphical objects
legendplace text starting from a given point
pointdetermine a point given a complex number or two coordinates
segmentsegment determined by 2 points
circlecircle determined by a point and radius
interfind the intersection of curves
equationreturn the cartesian equation of a curve
parameqreturn the parametric equation of a curve
polygonplotdraw a polygonal line
scatterplotdraw a cloud of dots
polygondraw a closed polygon
open_polygondraw an open polygon

Among its other capabilities, Xcas works with plane geometry. The GeoNew figure 2D menu item or the Alt+g key will bring up the screen for plane geometry.

A point on the geometry screen can be specified with the point command, which can take either an ordered pair or real numbers or a complex number as argument. The Geo menu contains many commands for drawing geometric objects, such as circle (which takes a point and a radius as arguments) and polygon (which takes a sequence of points as arguments).

Some functions, such as polygonplot and scatterplot, take lists of x-coordinates and y-coordinates as arguments. For example,

polygonplot([0,2,0],[0,0,2])

and

open_polygon(point(0,0),point(2,0),point(0,2))

will both draw the same segments.

The legend can be used to place text on the screen; one simple way of using it is to give it a point and text as arguments.

6.3  3D graphical objects

3D graphical objects
plotfuncgraph of a function
plotparamparametric surface
pointpoint
planeplane
spheresphere with a center and radius
conecone with a center, axis and opening angle
interintersection
polygonpolygon
open_polygonopen polygon

Xcas can also handle three-dimensions graphically, either by drawing curves and graphs in three-dimensions or by drawing three-dimensional geometric objects. A three-dimensional screen can be brought up with the GeoNew figure 3D menu item or the Alt+h key. There will controls for the view window to the right of the screen. You can rotate the visualization cube by using the mouse outside of the cube or by clicking in the cube and using the x, y and z keys to rotate and the + and - keys for zooming.

You can draw a graph z = f(x,y) with the plotfunc command, which takes an expression and a list of two variables. Like graphs of functions of one variable, you can use a domain different than the default by giving the variables their own intervals. The command

plotfunc(y^2 - x^2,[x=-1..1,y=-1..1])

will give you the graph

The plotparam command can be used to draw a parameterized curves and surfaces in three-dimensions. If the first argument is a list of three expressions involving two variables and the next two arguments are the variables (with optional intervals), then plotparam will plot the surface. If you enter

plotparam([u,u+v,v],u,v)

you will get

If the first argument is a list of three expressions involving one variable and the next argument is the variable, then plotparam will plot the curve. If you enter

plotparam([cos(t),sin(t),t],t)

you will get

A point in three-dimensions is given with the point command with three arguments. Commands like polygon and open_polygon work in three-dimensions as well as two, as well as additional commands such as sphere. A plane can be drawn with the plane command, which can be given either three points, a line and two points, or an equation of the form a*x + b*y + c*z = d.

7  Programming

7.1  The language

Instructions for Xcas
a:=2;assignment
input("a=",a);input expression
textinput("a=",a);string input
print("a=",a);output
return(a);return value
break;break out of loop
continue;go to the next iteration
if (<condition>) <inst>;if…then
if (<condition>) <inst1> else <inst2>; if…then …else
for (j:= a;j<=b;j++) <inst>;for loop
for (j:= a;j<=b;j:=j+p) <inst>;for loop
repeat <inst> until <condition>;repeat loop
while (<condition>) <inst>;while loop
do <inst1> if (<condition>) break;<inst2> od;do loop

Boolean operators
==test for equality
!=test for inequality
<test for strictly less than
>test for strictly greater than
<=tes for less than or equal
>=test for greater than or equal to
&&, andinfixed “and”
||, orinfixed “or”
trueboolean true (same as 1)
falseboolean false (same as 0)
not, !“not”

You can extend Xcas by adding desired functions with its built-in programming language. The main features of the language are:

A function declaration looks like

   function_name (var1, var2, ...) := {
   local var_loc1, var_loc2, ... ;
     statement1;
     statement2;
     ...
   }

The syntax is similar to C++, although many variants are recognized, particularly in compatibility mode. Recall that i is √−1 and cannot be used for a loop variable. The conditional tests are Booleans, which are the results of the usual Boolean operators.

A program can capture runtime errors with a trycatch construction, which takes the form

   try 
     {
      block to catch errors
     }
   catch (variable)
     {
      block to execute when an error is caught
     }

For example, the following will catch an error caused by incorrect matrix multiplication:

   try 
     { A := idn(2) * idn(3) }
   catch (error)
     { print("The error is " + error) }

7.2  Some examples

To write a program, it is a good idea to use the program editor that comes with Xcas, which provides a template and commands helpful for writing programs. You can open this editor with the New Program item in the Prg menu or the Alt+p key.

Consider the following program, which takes two integers and returns the quotient and remainder of the Euclidean division algorithm (like the iquorem function).

   idiv2(a,b) := {
     local q,r;
     if (b != 0) {
       q := iquo(a,b);
       r := irem(a,b);
       }
     else {
       q := 0;
       r := a;
       }
     return [q,r];
   }

If you enter this into the editor, you can test it with the OK button. You can then use the function in the command line; if you enter

idiv2(25,15)

you will get

[1,10]

You can save it in a file; the name idiv2.cxx would be a good name. You can then use it in later session with the command

read("idiv2.cxx")

or by opening it in the program editor and validating it with the OK button.

Here are some more programs that you can play with. This first one computes the GCD of two integers iteratively.

   pgcdi(a,b) := {
     local r;
     while (b != 0) {
       r := irem(a,b);
       a := b;
       b := r;
       }
     return a;
   }:;

The second one computes the GCD recursively.

   pgcdr(a,b) := {
     if (b == 0) return a;
     return pgcdr(b, irem(a,b));
   }:;

If a program doesn’t work the way you expect, you can run it in step-by-step mode with the debug command. For more details, consult the Interface item of the Help menu. For example, you can start the debugging by typing

debug(idiv2(25,15))

The debugger will automatically display the values of the parameters a and b and local variables q and r when executing the program line by line with the sst button.

7.3  Programming style

The Xcas programming language is interpreted, not compiled. The run time of an Xcas program is affected by the number of instructions rather than the number of lines.

The speed of a program does not always match up with the clarity of the program; compromises are often necessary. For the most part, the calculation time isn’t an issue; interpreted languages are often used to test algorithms and create models. Full scale applications are written in a compiled language like C++. A C++ can use giac for the formal calculations.

When you are trying to write a fast program, you may want to take into account the number of instructions and the speed of the instructions. For example, it is in general faster to create lists and sequences than it is to program loops. Recall than in Xcas you can find out how long it takes to run a command by entering

time(command)

8  Exercises

There are usually several ways to get the same result in Xcas. We will try to use the simplest approaches.

Exercise 1  Verify the following identities.
  1. (21/3+41/3)3−6(21/3+41/3)=6
  2. π /4 = 4arctan(1/5)−arctan(1/239)
  3. sin(5x) = 5sin(x)−20sin3(x)+16sin5(x)
  4. (tan(x)+tan(y))cos(x)cos(y) = sin(x+y)
  5. cos6(x)+sin6(x) = 1−3sin2(x)cos2(x)
  6. ln(tan(x/2+π/4)) = argsinh(tan(x))
Exercise 2  Transform the rational expression
x4+x3−4x2−4x
x4+x3x2x
into the following:
(x+2)(x+1)(x−2)
x3+x2x−1
 ,  
x4+x3−4x2−4x
x(x−1)(x+1)2
 ,  
(x+2)(x−2)
(x−1)(x+1)
 ,
x2
(x−1)(x+1)
4
(x−1)(x+1)
 .
Exercise 3  Transform the rational expression
2
x3yx2yx+y2
x3yx2x+y
into the following
2
x2y
x2−1
 ,   2
x2y
(x−1)(x+1)
 ,
2−
y−1
x−1
+
y−1
x+1
 ,   2−2
y−1
x2−1
 .
Exercise 4  For each of the following definitions of a function f
f(x) = 
ex−1
 ,   f(x) = 
1
x
1+x2
 ,
f(x) = 
1
1+sin(x)+cos(x)
 ,   f(x) = 
ln(x)
x(x2+1)2
 .
  1. Find an antiderivative F.
  2. Find F′(x) and show that F′(x) can be simplified to f(x).
Exercise 5  For each of the following integrals
−1


−2
1
x
 dx , 
1


0
 xarctan(xdx ,
π/2


0
 
cos(x)
 dx , 
π/2


0
 x4sin(x)cos(xdx .
  1. Find the exact value, and find an approximation.
  2. For n=100 and n=1000, do the following. For each j=0,…,n, let xj=a+j(ba)/n and yj=f(xj). Find an approximate value for the integral by using the left endpoint rule:
    n−1
    j=0
     f(xj)(xj+1xj) .
  3. Do the same as the previous part, except use the trapezoid method:
    n−1
    j=0
     
    1
    2
    (f(xj)+f(xj+1))(xj+1xj) .
Exercise 6  Define the function f by f(x,y)=cos(xy).
  1. Let x0=y0=π/4. Define the function that maps (u,v,t) to
    f(x0+ut,y0+vt) .
  2. Define the function g which is the partial derivative of the preceding function with respect to t (so this will be a directional derivative of f).
  3. Find the gradient of f at (x0,y0), then find the scalar product of this gradient with the vector (u,v). Write this result in terms of g.
Exercise 7  Consider x3−(a−1)x2+a2xa3=0 as an equation in x.
  1. Graph the solution x as a function of a using plotimplicit.
  2. Find the three solutions of the equation. You can use rootof to find the first solution, then use quo to factor out the first solution. You can then find the last two solutions by solving the resulting second degree equation. (You can use coeff to find the discriminant of the equation.)
  3. For the values of a which give three real roots, graph each of the roots in different colors on the same graph. (You can use resultant to find the values of a for which the equation has a multiple root; these values are the possible bounds of intervals for a where each of the roots is real.)
  4. Find the solutions for a=0,1,2.
Exercise 8  For each of the limits
 
lim
x→ 0
 
sin(x)
x
 , 
 
lim
x→ 0+
 (sin(x))1/x  , 
 
lim
x→ +∞
 (1+1/x)x  , 
 
lim
x→ +∞
 (2x+3x)1/x
  1. Find the exact value.
  2. Find a value of x such that the distance from f(x) to the limit is less than 10−3.
Exercise 9  For each function f, find ranges for the x coordinates and the y coordinates that give the most informative graph.
  1. f(x)=1/x.
  2. f(x)=ex.
  3. f(x)=1/sin(x).
  4. f(x)=x/sin(x).
  5. f(x)=sin(x)/x.
Exercise 10  Let f(x)=3x2+1+1/π4ln((π−x)2).
  1. Verify that this function takes negative values on ℝ+. Graph the function over the interval [0,5].
  2. Find є >0 such that Xcas gives the correct graph of the function over the interval [π−є,π+є].
Exercise 11   
  1. Graph the function exp(x) over the interval [−1,1]. On the same graph, plot the Taylor polynomials (of orders 1,2,3 and 4) for this function centered at x=0.
  2. Same question for the interval [1,2].
  3. Graph the function sin(x) on the interval [−π,π]. On the same graph, plot the Taylor polynomials (of orders 1,3 and 5) for this function centered at x=0.
Exercise 12  Plot the following graphs on the same window, with x and y coordinates from 0 to 1.
  1. The line y=x.
  2. The graph of the function f :  x↦ 1/6+x/3+x2/2.
  3. The tangent line to the graph of f at x=1.
  4. The vertical line segment from the x-axis to the point where the graph of f intersects the line y=x, and a horizontal line segment from the y-axis to that point of intersection.
  5. The labels “fixed point” and “tangent”, at the appropriate positions.
Exercise 13  The goal of this exercise is to graph a family of functions on the same screen. You will need to choose the number of curves, the interval to graph over to obtain the most informative graphic.
  1. Functions fa(x) = xaex for a from −1 to 1.
  2. Functions fa(x)=1/(xa)2 for a from −1 to 1.
  3. Functions fa(x)=sin(ax), for a from 0 to 2.
Exercise 14  Graph each of the following curves. You will need to choose a range of values for the parameter to make sure you have the complete graph.


  1. x(t)=sin(t)
    y(t)=cos3(t)


  2. x(t)=sin(4 t)
    y(t)=cos3(6 t)


  3. x(t)=sin(132 t)
    y(t)=cos3(126 t)
Exercise 15  The goal of this exercise is to visualize in different ways the surface of the graph z=f(x,y)=x y2. You will need to have a 3-d geometry window open.
  1. Use plotfunc to draw an informative graph, choosing an appropriate domain and number of steps.
  2. Create an editable parameter a with assume. Draw the curve z=f(a,y) and vary the parameter with the mouse.
  3. Create an editable parameter b with assume. Draw the curve z=f(x,b) and vary the parameter with the mouse.
Exercise 16  The goal of this exercise is to visualize a cone in different ways.
  1. Draw the surface given by z=1−√x2+y2.
  2. Sketch the parameterized surface defined by




    x(u,v)=u cos(v)
    y(u,v)=u sin(v)
    z(u,v)=1−u .
  3. For a sufficiently large value of a, draw the curve parameterized by




    x(t)=t cos(a t)
    y(t)=t sin(a t)
    z(t)=1−t .
  4. Draw the family of curves parameterized by




    x(t)=a cos(t)
    y(t)=a sin(t)
    z(t)=1−a .
  5. Draw the cone using the cone function.
Exercise 17   
  1. Generate a list ℓ of 100 integers randomly generated between 1 and 9.
  2. Verify that all values in ℓ are in {1,…,9}.
  3. Extract from the list ℓ all values greater than or equal to 5.
  4. For each k=1,…,9, find the number of values in ℓ which are equal to k.
Exercise 18  For a real number x, the continued fraction for x of order n is a list of integers [a0,…,an] created in the following way: The list [a0,…,an] is associated with the fraction
un = a0+
1
a1+
1
a2+
1
⋱+
1
an
For x∈{π,√2, e} and n∈ {5,10} :
  1. Find [a0,…,an].
  2. Compare your result with the value given by Xcas’s dfc function.
  3. Find un and the numeric value of xun.
Exercise 19  Write (without using a loop) the following sequences:
  1. The numbers from 1 to 3 in steps of 0.1.
  2. The numbers from 3 to 1 in steps of −0.1.
  3. The squares of the first 10 integers.
  4. Numbers of the form (−1)n n2 for n=1,…,10.
  5. 10 “0”s followed by 10 “1”s.
  6. 3 “0”s followed by 3 “1”s, followed by 3 “2”,…, followed by 3 “9”s.
  7. “1” followed by 1 “0”, followed by a “2” followed by 2 “0”s, …, followed by “8” followed by 8 “0”s, followed by “9”.
  8. 1 “1” followed by 2 “2”s, followed by 3 “3”s,…, followed by 9 “9”s.
Exercise 20   
  1. Define the following polynomials of degree 6.
    1. A polynomial whose roots are the integers from 1 to 6.
    2. A polynomial whose roots are 0 (triple root), 1 (double root) and 2 (simple root).
    3. The polynomial (x2−1)3.
    4. The polynomial x6−1.
  2. Write (without using the companion function) the companion matrix A for each of the polynomials in (1). Recall the the companion matrix for the polynomial
    P=xd+ad−1xd−1+⋯+a1x+a0 ,
    is
    A = 






    010 0
     
          
      0
    0 01
    a0a1  ad−1







     .     (1)
  3. Find the eigenvalues of the matrix A.
  4. Find the characteristic polynomial of A.
Exercise 21   
  1. For variables a and b, write the square matrix A of order 4 with aj,k=a if j=k and aj,k=b if jk.
  2. Find and factor the characteristic polynomial of A.
  3. Find an orthogonal matrix P such that PT A P is a diagonal matrix.
  4. Use your answer to the previous question to define the function that maps an integer n to the matrix An.
  5. Find Ak for k=1,…,6 by finding the matrix products. Check that the function given in the previous part gives the same results.
Exercise 22   
  1. Find the square matrix N of order 6 given by nj,k=1 if k=j+1 and nj,k=0 if kj+1.
  2. Find Np for p=1,…,6.
  3. Write the matrix A = xI+N, where x is a variable.
  4. Find Ap for p=1,…,6.
  5. Find exp(At) as a function of x and t :
    exp(At) = I+
    p=1
    tp
    p!
     Ap .
Exercise 23  Define the following functions without using a loop.
  1. The function f which takes as input an integer n and two real numbers a and b and returns the n× n matrix A whose diagonal terms are all equal to a and whose non-diagonal entries are equal to b.
  2. The function g which takes as input an integer n and three real numbers a,b and cm and returns the matrix A=(aj,k)j,k=1,…,n whose diagonal elements are equal to a, whose terms aj,j+1 are equal to b and whose terms aj+1,j are equal to c, and whose remaining terms are 0.
  3. The function H which takes as input an integer n and returns Hilbert’s Matrix; the matrix A=(aj,k)j,k=1,…,n where aj,k = 1/(j+k+1). Compare the execution time of your function with that of the hilbert function.
  4. The function V which takes as input a vector x=[x1,…,xn] and returns Vandermonde’s Matrix; the matrix A=(aj,k)j,k=1,…,n where aj,k = xkj−1. Compare the execution time of your function with that of the vandermonde function.
  5. The function T which takes as input a vector x=[x1,…,xn] and returns the Toeplitz Matrix; the matrix A=(aj,k)j,k=1,…,n where aj,k = x|jk|+1 .
Exercise 24  Write the following functions, which take as input a function f:ℝ → ℝ and three real numbers xmin, x0 and xmax with xminx0xmax.
  1. derive : This function calculates and graphs the derivative of f over the interval [xmin,xmax] and returns f′(x0).
  2. tangent : This function graphs the function f on the interval [xmin,xmax] and in the same window draws the tangent to the graph at x0. It returns the equation for the tangent line as a first degree polynomial.
  3. araignee : This function graphs the function f on the [xmin,xmax], as well as the line y=x. It calculates and returns the first 10 iterates of f starting at x0 (so x1 = f(x0), x2 = f(x1),…). It also draws the sequence of segments, alternately vertical and horizontal, allowing you to visualize the iterations: segments joining (x0,0), (x0,x1), (x1,x1), (x1,x2), (x2,x2), …(compare this to the function plotseq)
  4. newton_graph : This function graphs the function f over the interval [xmin,xmax]. It also calculates and returns the first ten iterates of the sequence starting at x0 given by Newton’s Method: x1=x0f(x0)/f′(x0), x2=x1f(x1)/f′(x1) …  (The values of the derivative should be approximated.) This function also graphs in the same window the segments displaying the iterations: segments joining (x0,0), (x0,f(x0)), (x1,0), (x1,f(x1)), (x2,0), (x2,f(x2)),…(compare with the function newton)
Exercise 25  Let D be the unit square D=(0,1)2. Let Φ be the function defined on D by
Φ(x,y) = (z(x,y),t(x,y))=


x
1+y
 , 
y
1+x



 .
  1. Find the inverse of Φ.
  2. Find and graph the image under Φ of the domain D: Δ=Φ(D).
  3. Let A(x,y) be the Jacobian matrix of Φ at a point (x,y) in D, and B(z,t) the Jacobian matrix of Φ−1 at a point (x,y) in Δ. Calculate these two matrices, and verify that B(Φ(x,y)) and A(x,y) are inverses of each other.
  4. Let J(z,t) be the determinant of the matrix B. Calculate and simplify J(z,t).
  5. Evaluate
    I1=
     


    D
     


    1+x+y
    (1+x)(1+y)
     


    3



     
      dxdy .
  6. Evaluate
    I2=
     


    Δ
     (1+z)(1+tdzdt ,
    and verify that I1=I2.

Index


This document was translated from LATEX by HEVEA.