Calqit tutorial

5. Tutorial

To get started, just start typing in expressions such as (5+2/3)^3, or pi/4, etc. (Don't forget to finish with the "enter" or "return" key). calqit will evaluate the expression and display the value. There are quite a few pre-defined symbols, type "const" and "who" or "list" to list them. "func all" will list the built-in functions.

Make use of the help feature. For example, if you want to plot something, first enter ?plot and then double-click on one of the examples. You will soon get the idea.

Use the up-arrow key to get back the last instruction you entered. You can then edit it as you like, and enter it again using the "enter" key.

To define your own symbols, use "=" or ":=". The single = means evaluate the expression now, and store the answer. The 'becomes' sign := means store the formula and evaluate it on demand later. Here is an illustration of the two cases (to test these ideas you can type them in, or cut and paste text from here into calqit if you like). Each line begins with a the calqit prompt ">" followed by an instruction; the following line shows the response from calqit. The '#' symbol signifies the start of a comment; this part is ignored by Calqit.

> a=2; b=3; x=a b; y:=a b    # x is a number, y is an expression
ok
> y                          # evaluate y
6
> ??y                        # ask about y
This user-defined function was defined at the command prompt
y:= a b
> x                          # ask for the value of x
6
> a=3
3
> x,y                        # x is still 6, y now evaluates to 9
6 9

Terminate commands with ; to prevent display. If you want to enter several expressions but still want display, then use ;; or disp().

For example

> x=[1,4,9,16]; sqrt(x)       # the semicolon suppressed display of x
1 2 3 4
> x, sqrt(x)                  # the comma means form a list. The 8-element list is displayed.
1 4 9 16 1 2 3 4 
> x=[1,4,9,16];; sqrt(x)      # use of ;; to request display of the first result
1 4 9 16
1 2 3 4 
> x=[1:4]^2; disp(x); sqrt(x) # use of disp()
1 4 9 16

1 2 3 4

In these examples x is called an "array" or "vector" (generalizing the idea of the three-element vector you meet at school). To take a look at individual elements in a vector, use a dot, as in the following

> x                           # show all the elements
1 4 9 16
> x.2                         # request the 2nd element
4
> x.2 = 0                     # change it (and display the resulting value of x)
1 0 9 16
> x[4]                        # another way to pick an element is to use a bracket like this
16
For arrays and matrices, see under Index verses multiplication

For long vectors, by default calqit displays just a few values (to avoid spewing out long streams of output, which is time consuming and often not wanted). Use the disp() function, or a double-query as in
??x
to display in full.

Use ? or help to get further information. For example, ?y asks for information about y, where y can be a function or a symbol.

The # symbol is used for comments: anything after this on a given line is ignored. Consider adding a comment whenever you define a formula or a function. If you do this in a script then the comment will be reported 'help' command. For example:

> area(r) := pi r^2   # area(r) returns the area of a circle of radius r
ok
> area(2)
12.5664
>?area
area(r) := pi r^2   # area(r) returns the area of a circle of radius r
This user-defined function was defined at the command prompt
In the case of a user function defined inside a script file, put the comment on its own line immediately after the line defining the function. Alternatively, you may put a longer comment before the function definition, but then you must begin it with a double-# to allow the help feature to locate it correctly (see the demo files for examples).

You can easily work with lists and vectors. Use commas to separate items in a list, and use the colon : to create sequences. The syntax is "start:step:finish" or "start:finish" if the step is 1. For example:

> n=1:7; n^2         # define a sequence, square it
1 4 9 16 25 36 49
> m=2:2:14           # a sequence with step 2
2 4 6 8 10 12 14
> m/n                # divide one vector by another. All operations are element by element
2 2 2 2 2 2 2
> seq(0,pi,10)       # a sequence of 10 equally spaced points between 0 and pi
0 0.349066 0.698132 1.0472 1.39626 ...3.14159
You can do arithmetic operations between vectors and between scalars and vectors, just use your common sense. You can create matrices using functions such as zero, diag, eye, rand, or by using commas and semicolons. For example

> m=[1, 2; 3, 4]     # a simple 2x2 matrix
1 2
3 4
> m=[1 2; 3 4]       # if the brackets are square [...], you can omit the commas
1 2
3 4
> m = 1:100; m.reshape([10,10])     # try it!

Create user-defined functions by the syntax
name(x,y) := expr
where you invent the name, and x,y are variables used in the expression. For example you could use sinc(x) := sin(x)/x to define the sinc function (actually it is better to use Calqit's own version of that function in order to guarantee that the point x=0 is handled correctly). When a function has more than one statement, use braces {}. For example:

> solveit(a,b,c):={ s=sqrt(b^2-4 a c); return (-b+[1,-1]*s)//2a; }
This function implements the formula for the solution of a quadratic equation "a x^2 + b x + c = 0". First s stores an intermediate result (the square root of b^2 - 4 a c), then the function calculates the roots. The [1,-1] part in the formula gives "plus or minus" so as to obtain both roots. To use the function, next one might enter for example
> solveit(1,-2,0)
2 0
Calqit returns the evaluation. In this case the solutions of (x^2 - 2x) are 2 and 0.

Note that in this example the "return" statement was put in for ease of seeing what the function returns. It can be omitted, and then the function returns the result of the last statement evaluated. So the same function could be written

> solveit(a,b,c):={ s=sqrt(b^2-4 a c);  (-b+[1,-1]s)//2a; }
or simply
> solveit(a,b,c):= -b + [1,-1]sqrt(b^2-4a c) % 2a
The last version illustrates how Calqit offers a succinct notation. Here the % operator means 'divide the entire expression to the left by the entire expression to the right'.

This is a good moment to introduce another ideas: the 'such that' operator /. (slash-dot). This operator can be placed after some expression you wish to evaluate, and whatever comes after the /. is evaluated first. For example

> (1+n/2) /. n = 6
means 'evaluate (1+n/2) such that n=6'. The answer is 4. Here is another example:
> plot(a x^2+b x+c; x,0,4) /. [a,b,c]=[1,-3,1]
This means 'plot the quadratic curve (a x^2 + b x + c) such that a=1, b=-3, c=1'.

While we are thinking about quadratic formulae, let's also introduce complex numbers. To declare a complex number you use an expression such as

> z = complex(1,2)
or
> z = 1 + 2*1i
If you wish your solveit function to handle complex roots, you have to tell Calqit you are anticipating that complex numbers may be involved. One way to do this is to use the complex number 0i which is simply zero.

Here is another example of a user-defined function:

gcd(a, b):= {while b: {t=b; b=a mod b; a=t;} t;}
This is a famous algorithm discovered by Euclid. It returns the greatest common divisor of a and b. The return value is the result of the last statement, which in this example is just the statement "t", so it reports the value of t when the while loop finishes. Try gcd(12,8) for example: you should get 4.

When you develop programs using a text editor, you will want to write longer functions. An alternative syntax is provided, which makes your program easier to read. This is the combination "function" ... "end", as for example

function dostuff(a,b)
   disp(a, ' is ', a);
   if a.size ~= b.size: {  disp('a and b have different sizes'); return a;  }
   else return a / b;
end
In this example the return value is given by the return statement. More generally, you can use the syntax
function [v] = dostuff(a,b)
   disp(a, ' is ', a);
   if a.size ~= b.size
       disp('a and b have different sizes'); v = [a.size,b.size]
   else v = a / b;
end
Here the symbol v provides the output and you don't need a 'return' statement. Notice that in the function declaration the output variable(s) has to be in square brackets.

5.1 Demo

This may be a good moment to examiner the demonstration scripts which are provided with Calqit. They can be found in

 [Calqit-folder]/clq/demo 

The scripts have the filename extension '.clq' and are written in plain text. Load them into any text editor (better still, one with programming language features such as colouring) to see simple examples of Calqit programming.

For further information (and some fun), take Calqit to the folder

 [Calqit-folder]/clq/games 
and run one of the games there using the Calqit command 'use [filename]'.

5.2 Functionals

A function such as sin(x) associates one number to another number. A functional takes a function as argument and returns a number (think of integration for example). The following are examples of built-in functions having this type of behaviour:

plot, qinteg, fzero, min, qmin, fmin, fminbrac, sum, differ, cheby

For example, to find the integral of the sin function between 0 and pi you can enter

qinteg(sin, 0, pi)

Often you want to know the integral of a function of your own choosing, rather than a built-in function. For example, to find the integral of sin(x^2) you could use

f(x) := sin(x^2);
qinteg(f, [0, pi])

Since this is a common situation, calqit offers a shorthand:

qinteg(sin(x^2); x, [0, pi])

Note the presence of the semi-colon here: it signals that a function is being specified, and it indicates that the variable is x. This is needed because the expression may include other symbols, such as in

qinteg(sin(k x - w t); t, [0, pi])

In this example t is the variable being integrated over, and k,x and w would have to be already defined.

For many situations where a function is to be supplied, it makes sense to supply a vector or array of values instead. For example plot(v) for a vector v means plot the elements of v, while plot(f, x1, x2) for a function f means plot f(x) between x1 and x2.

Sometimes you want to integrate a function that is only available through a set of previously calculated values, obtained for example by numerical solution of a differential equation. In this case you can pass the vector of values to the function binteg. This does a good job of estimating the area (using a 5-point rule, i.e. like Simpon's rule but more accurate):

binteg(y) dx

Here the values have to be equispaced in x, and you multiply the output of binteg by the spacing as in the example above.

Note that qinteg always returns a single number (a "scalar" as opposed to a "vector"). It can't handle multiple integrals all in one go. If you need a set of integrals, you can use a for-loop such as

a=zeros(1,10); for k=1:10; a.k = qinteg(sin(k x)f(x); x, [0,2]);
A neater method is to do this using the Calqit function 'table', as in
a = table( qinteg(sin(k x)f(x); x, [0,2]); k,1:10 )
(The syntax here is quite like the one you might use in Mathematica). The example given calculates a Fourier sine series. The function f(x) is to be supplied by you. For example
f(x) := x^2

The case of a sum is slightly different from integration, because usually you want to sum over a known discrete set of values. This leaves room for calqit to be more flexible: you can sum vector functions as well as scalar functions. e.g.

y = sum(cos(k x)/k; k,1:10)

where x is allowed to be a vector of values.

The plot function allows several types of syntax:

plot(f, x1, x2)      # plots function f between x1 and x2.
plot(f(x); x,x1,x2)  # does the same
plot(f(x); x, xvals) # plots at xvals
plot(x,y)            # for vector x,y, plots y verses x.
plot(x1,y1,x2,y2)    # plots y1 vs x1 and y2 vs x2. etc.
The plot function also allows a further argument to indicate the line or point style, see ?plot for more information.

Use the individual function help (?qinteg, ?plot, etc.) for more information. Other functionals include fzero, fmin, differ.

5.3 Physical data

Physical data such as atomic masses, densities, etc. are accessed via the function "property". The syntax is property(substance_name, property_name). For example
property('density','copper')
or
property density copper
There is also a shorthand:
<< density copper
This function uses a file-based database and so is slow. In normal use, you would obtain the properties of interest to you just once, and store them in your own variables for subsequent fast access, using a statement such as
rho << density copper
or
[rho,info] = property('density', 'copper')
These two version both provide the same value in rho, but the second version puts the accompanying information into info instead of displaying it.

5.4 Array indexing

See under Index verses multiplication

5.5 Writing programs

Once you are familiar with calqit as a calculator, you will probably want to start writing programs. If you are unfamiliar with programming, this is a great way to learn. You will need a "text editor", that is, another program which enables you to write, edit and save text files. Windows has one of these, but calqit recommends you obtain one with a bit more functionality. A good programmer's text editor, available for free, is Notepad++ at
"Notepad++"

There are many text editors 'out there', and many have nice features such as code colouring which you can take advantage of. If your editor does not recognize your file as one to be coloured, then telling it to adopt Python-style colouring will give reasonable results.

A program is essentially a list of instructions, just like those illustrated above, but it usually contains plenty of user-defined functions and things like loops ("for j=..." and "while ...") and "if" statements. You write your program in a text file, then save the file with the ".clq" filename extension. That is, if you want to call your program "gogo" then specify the file name to be "gogo.clq" when you save it. Make sure you save it in a convenient directory (also called "folder") on your computer. For example you might want to create a new folder. Then use "cd" in calqit to go to the folder containing your program, and run it using "use gogo". If calqit reports that it can't find the program, then you may be in the wrong folder or the file name is wrong. Try "dir gogo.*" to see.

The text file containing a program is sometimes called a "script".

Example programs are provided with calqit in the demo folder. You can learn a lot by examining these and experimenting.

[top] . [home]