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.
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.
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
|
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
|
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
|
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 |
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((x+1)^3)you will get
x3 + 3*x2 + 3*x + 1 |
factor(x^2 + 3*x + 2)you will get
(x + 1)*(x + 2) |
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
You can get a list of all Xcas commands and variables using the Help▸Index 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.
When you start Xcas, you will be presented with a window which looks like the following:
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 File▸Save, 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 Cfg▸Show▸msg 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.
The Cfg menu has various items that allow you to configure various aspects of Xcas. This tutorial will refer to the Cfg▸Cas configuration and Cfg▸Graph configuration menu items. The Cfg▸Cas 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 Cfg▸Cas 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 Cfg▸Graph 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+.
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.
Operations | |
+ | addition |
- | subtraction |
* | multiplication |
/ | division |
^ | power |
Conversions | |
evalf | approximate a number |
exact | find an exact number close to the given number |
epsilon | determine how close a fraction has to be to a floating point number to be returned by exact |
Constants | |
pi | π≃ 3.14159265359 |
e | e ≃ 2.71828182846 |
i | i=√−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
|
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
√ |
|
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 |x − r| < є, 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”).
Variables | |
:= | assignment |
subst | give a variable a value for a single instance |
assume | put assumptions on variables |
and | combine assumptions |
or | combine assumptions |
purge | remove 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)
sin(a*pi)
will result in
0 |
The purge command will remove any assumptions about a variable as well as any assigned values.
Conversions | |
expand | expand powers and distribute multiplication |
normal | reduce to lowest terms |
ratnormal | reduce to lowest terms |
factor | factor |
simplify | reduce an expression to simpler form |
tsimplify | reduce and expression to simpler form |
convert | convert 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((x+1)^3)you will get
x3 + 3*x2 + 3*x + 1 |
normal((x^3-1)/(x^2-1))then Xcas will cancel a common factor of x−1 from the top and bottom and return
|
ratnormal((x^2-2)/(x-sqrt(2)))you will get
|
normal((x^2-2)/(x-sqrt(2)))you will get
x+ | √ |
|
Neither of these commands will take into account relationships between transcendental functions such as sin and cos.
factor(x^2 + 3*x + 2)you will get
(x + 1)*(x + 2) |
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
| + |
|
Common functions | |
abs | absolute value |
sign | sign (-1,0,+1) |
max | maximum |
min | minimum |
round | round to the nearest integer |
floor | greatest integer less than or equal to |
frac | fractional part |
ceil | least integer greater than or equal to |
re | real part |
im | imaginary part |
abs | absolute value |
arg | argument |
conj | conjugate |
coordinates | the coordinates of a point |
factorial | factorial |
! | factorial |
sqrt | square root |
exp | exponential |
log | natural logarithm |
ln | natural logarithm |
log10 | logarithm base 10 |
sin | sine |
cos | cosine |
tan | tangent |
cot | cotangent |
asin | arcsine |
acos | arccosine |
atan | arctangent |
sinh | hyperbolic sine |
cosh | hyperbolic cosine |
tanh | hyperbolic tangent |
asinh | inverse hyperbolic sine |
acosh | inverse hyperbolic cosine |
atanh | inverse hyperbolic tangent |
Create functions | |
:= | assign an expression to a function |
-> | define a function |
unapply | turn 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))) |
Sequences and lists | |
( ) | sequence delimiters |
[ ] | list delimiters |
%{ %} | set delimiters |
NULL | empty 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 |
append | append 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 |
sum | the sum of the elements |
product | the product of the elements |
cumSum | the 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 |
poly2symb | convert a polynomial expression to a polynomial list |
symb2poly | convert a polynomial list to a polynomial expression |
Xcas can combine objects in several different ways.
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
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.
String commands | |
asc | convert a string to a list of ASCII codes |
char | convert a list of ASCII codes to a string |
size | the number of characters |
concat or + | concatenation |
mid | substring |
head | first character |
tail | the string without the first character |
string | convert a number or expression to a string |
expr | convert 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.
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.
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 |
grad | gradient |
divergence | divergence |
curl | curl |
laplacian | laplacian |
hessian | hessian 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.
Limits and series | |
limit | the limit of an expression |
taylor | Taylor series |
series | Taylor series |
order_size | used 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− |
| + |
| + 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− |
| + 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− |
| + |
|
Integrals | |
int | antiderivatives and exact integrals |
romberg | approximation 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 ≤ y ≤ x with
int(int(x*y,y,0,x),x,0,1)
resulting in
|
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 |
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 |
linsolve | solve a linear system |
proot | approximate 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
⎡ ⎢ ⎢ ⎣ |
| ,1, |
| ⎤ ⎥ ⎥ ⎦ |
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, |
| , |
| ⎤ ⎥ ⎥ ⎦ |
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
⎡ ⎢ ⎢ ⎣ | − |
| , |
| ⎤ ⎥ ⎥ ⎦ |
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
⎡ ⎢ ⎢ ⎣ |
| ⎤ ⎥ ⎥ ⎦ |
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.
⎡ ⎢ ⎢ ⎢ ⎢ ⎢ ⎢ ⎢ ⎢ ⎢ ⎢ ⎢ ⎢ ⎢ ⎢ ⎢ ⎣ |
| ⎤ ⎥ ⎥ ⎥ ⎥ ⎥ ⎥ ⎥ ⎥ ⎥ ⎥ ⎥ ⎥ ⎥ ⎥ ⎥ ⎦ |
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 |
Commands for differential equations | |
desolve | exact solution |
odesolve | approximate solution |
plotode | graph of solution |
plotfield | vector field |
interactive_plotode | clickable 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(− |
| ) |
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(− |
| ) |
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.
Integers | |
irem | remainder |
iquo | quotient |
iquorem | quotient and remainder |
ifactor | prime factorization |
ifactors | list of prime factors |
idivis | list of divisors |
gcd | greatest common divisor |
lcm | least common multiple |
iegcd | Bezout’s identity |
isprime | primality test |
nextprime | next prime number |
previousprime | previous prime number |
a%p | a 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.
Polynomials | |
normal | normal form (expanded and reduced) |
expand | expanded form |
ptayl | Taylor form |
peval or horner | evaluation using Horner’s method |
canonical_form | canonical form for a trinomial |
coeff | list of coefficients |
poly2symb | transform an algebraic polynomial to list form |
symb2poly | transform the list form of a polynomial to algebraic form |
pcoeff | return the polynomial (list form) given a list of zeroes |
degree | degree |
lcoeff | the coefficient of the leading term |
valuation | the lowest degree of the terms |
tcoeff | the coefficient of the term with the lowest degree |
factor | prime factorization |
factors | list of prime factors |
divis | list of divisors |
froot | roots with multiplicities |
proot | approximate values of the roots |
sturmab | the number of roots in an interval |
getNum | the numerator of a rational function |
getDenom | the denominator of a rational function |
propfrac | writes a rational expression as a whole part and a proper rational part |
partfrac | partial fraction decomposition |
quo | quotient |
rem | remainder |
gcd | greatest common divisor |
lcm | least common multiple |
egcd | Bezout’s identity |
divpc | Taylor polynomial for a rational expression |
randpoly | random polynomial |
cyclotomic | cyclotomic polynomial |
lagrange | Lagrange polynomials |
hermite | Hermite polynomials |
laguerre | Laguerre polynomials |
tchebyshev1 | Tchebyshev polynomials |
tchebyshev2 | Tchebyshev 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
|
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)(x−i)(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ℤ.
Trigonométrie | |
tlin | linearize |
tcollect | linearize and regroup |
texpand | expand |
trig2exp | trigonometric to exponential |
exp2trig | exponential to trigonometric |
hyp2exp | hyperbolic 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(3*x) − |
|
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 |
Vectors and matrices | |
v*w | scalar product |
cross(v,w) | cross product |
A*B | matrix product |
A.*B | term by term product |
1/A | inverse |
tran | transpose |
rank | rank |
det | determinant |
ker | basis for the kernel |
image | base for the image |
idn | identity matrix |
ranm | matrix with random coefficients |
makematrix | make a matrix from a function |
matrix | make a matrix from a function |
blockmatrix | combine 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
|
and
B*A
will give you
|
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
|
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
|
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
|
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
|
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.
Linear systems | |
linsolve | solution of a linear system |
simult | solutions of many linear systems |
rref | Gauss-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
⎧ ⎪ ⎨ ⎪ ⎩ |
|
⎧ ⎪ ⎨ ⎪ ⎩ |
|
which both have the same matrix of coefficients
|
you can create the matrix which has one column for each system
|
If you enter
simult([[1,1,-1],[1,-1,1],[-1,1,1]],[[1,-2],[1,1],[-2,1]])
you will get
|
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.
Matrix reduction | |
jordan | diagonalization or Jordan reduction |
pcar | characteristic polynomial (list form) |
pmin | minimal polynomial (list form) |
eigenvals | eigenvalues |
eigenvects | eigenvectors |
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
⎛ ⎜ ⎝ |
| , |
| ⎞ ⎟ ⎠ |
This means that 3 and −4 (the diagonal elements of the second matrix) are the eigenvalues of (
4 | 1 |
−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
|
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
|
Plotting graphs | |
plot | graph an expression of one variable |
plotfunc | graph an expression of one or two variables |
tangent | tangent to a curve |
plotparam | parametric curve |
plotpolar | polar plotting |
plotimplicit | implicit 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 Cfg▸Show▸DispG menu item. This window will contain all two dimensional graphs; they can be cleared with the ClrGraph command.
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
2D graphical objects | |
legend | place text starting from a given point |
point | determine a point given a complex number or two coordinates |
segment | segment determined by 2 points |
circle | circle determined by a point and radius |
inter | find the intersection of curves |
equation | return the cartesian equation of a curve |
parameq | return the parametric equation of a curve |
polygonplot | draw a polygonal line |
scatterplot | draw a cloud of dots |
polygon | draw a closed polygon |
open_polygon | draw an open polygon |
Among its other capabilities, Xcas works with plane geometry. The Geo▸New 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.
3D graphical objects | |
plotfunc | graph of a function |
plotparam | parametric surface |
point | point |
plane | plane |
sphere | sphere with a center and radius |
cone | cone with a center, axis and opening angle |
inter | intersection |
polygon | polygon |
open_polygon | open 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 Geo▸New 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.
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 |
&&, and | infixed “and” |
||, or | infixed “or” |
true | boolean true (same as 1) |
false | boolean 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 try–catch 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) }
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.
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)
There are usually several ways to get the same result in Xcas. We will try to use the simplest approaches.
|
| , |
| , |
| , |
| − |
| . |
2 |
|
2 |
| , 2 |
| , |
2− |
| + |
| , 2−2 |
| . |
f(x) = | √ |
| , f(x) = |
| , |
f(x) = |
| , f(x) = |
| . |
∫ |
|
| dx , | ∫ |
| xarctan(x) dx , |
∫ |
| √ |
| dx , | ∫ |
| x4sin(x)cos(x) dx . |
| f(xj)(xj+1−xj) . |
|
| (f(xj)+f(xj+1))(xj+1−xj) . |
f(x0+ut,y0+vt) . |
|
| , |
| (sin(x))1/x , |
| (1+1/x)x , |
| (2x+3x)1/x |
⎧ ⎨ ⎩ |
|
⎧ ⎨ ⎩ |
|
⎧ ⎨ ⎩ |
|
⎧ ⎪ ⎨ ⎪ ⎩ |
|
⎧ ⎪ ⎨ ⎪ ⎩ |
|
⎧ ⎪ ⎨ ⎪ ⎩ |
|
un = a0+ |
|
P=xd+ad−1xd−1+⋯+a1x+a0 , |
A = | ⎛ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎝ |
| ⎞ ⎟ ⎟ ⎟ ⎟ ⎟ ⎟ ⎠ | . (1) |
exp(At) = I+ |
|
| Ap . |
Φ(x,y) = (z(x,y),t(x,y))= | ⎛ ⎜ ⎜ ⎝ |
| , |
| ⎞ ⎟ ⎟ ⎠ | . |
I1= | ∬ |
| ⎛ ⎜ ⎜ ⎝ |
| ⎞ ⎟ ⎟ ⎠ |
| dxdy . |
I2= | ∬ |
| (1+z)(1+t) dzdt , |
|
|
This document was translated from LATEX by HEVEA.