Sie sind auf Seite 1von 9

Introduction to SCILAB

August 15, 2010

1 Scilab Assignment
1. Read and test the code described at the end of this manual. (It is available as the
sample lyx file given for scilab programming)
2. Create a “tan inverse” function from its integral definition, i.e., compute the func-
tion Z x
dt
I(x) = 2
0 1+t
from 0 to x, accurate to 5 digits. To do this,
(a) Define f (t) = 1/(1 + t 2 ) as a function in Scilab. (See example code for
how to define functions)
(b) Define a vector x that covers the region 0 ≤ x ≤ 5 in steps of 0.1. (See
linspace)
(c) Look up intg in Scilab help (i.e., type help intg).. Use intg to obtain
I(x). Note that you can specify accuracy in intg.
(d) Tabulate atan(x) and I(x) for these values of x.
(e) Plot the error of the integral method (assuming that the built in function is
correct).
3. Now we develop an algorithm to compute the integral ourselves. The approach
is to compute the Trapezoidal algorithm for a running integral.
According to the Trapezoidal Rule, if a function is known at points a, a + h, . . . ,
b, its integral is given by

0 x=a
I=
0.5 ( f (a) + f (xi )) + ∑i−1
j=2 f (x j ) , x = a + ih
This can be rewritten as
!
i
1
Ii = h ∑ f (x j ) − 2 ( f (x1 ) + f (xi ))
j=1

The advantage of this is that previous work can be reused to compute successive
integrals. Code this in Scilab, and then figure out how to estimate error and
determine the “h” to use.

1
(a) Use vector operations and compute the running integral I given a vector
of values. Hint: Look at the cumsum function. Your basic implementation
should be a single line of code!
(b) Compute the running integral over a vector of function values sampled at
half the spacing, i.e., h → h/2
(c) The error is defined as the largest error for common points. For instance
if the first integral was for x = 0, 0.5, 1 and the second time the integral
was for x = 0, 0.25, 0.5, 0.75, 1, clearly we can compare the integral values
at x = 0, 0.5, 1. Keep halving h till error falls below the desired tolerance.
Apply this to the integral in Q 1 and compare to the atan function to see
if the error is correctly calculated. Plot both the error according to this part
and the actual error vs x.
4. Once you have the scilab working, make it part of a LYX report. The plots and
table should be part of the report. And ofcourse the code should be in the “scrap”
environment so that the scilab file can be extracted and run.

Submit the lyx file to the Moodle site. Please note that the plots will only be linked to
the LYX file and will not be a part of the file as is the case in a Word document. So you
will have to submit the plot files as well. To do this, create the files in a subdirectory,
zip the files and submit the zip file to Moodle.

2 Introduction to Scilab
Scilab is a scientific/engineering tool. It makes many tasks extremely easy to carry out.
The main features of such mathematics tools are:
1. It can handle complex numbers and complex functions.
2. It supports vectors and matrices as native data structures. Single line instruc-
tions can implement matrix addition, multiplication, inversion and the solution
of simultaneous equations.
3. It supports polynomials and rational functions as data types. This means that
some kinds of Laplace Transform problems can be done symbolically.
4. It has a large number of functions to plot various kinds of graphs.
5. It has a large number of functions for performing user input/output.
6. It supports "lists" which are generalised arrays whose elements can be of differ-
ent types.
7. It has a large number of utility functions to make most engineering calculations
straightforward to implement.
8. It can call Fortran and C routines and use their results. Thus, one of Scilab’s
common uses is as a "front end" for numerical codes.

2
9. It has extensive control system analysis capabilities.
10. It has a complete spectral analysis toolkit, which is useful in digital signal pro-
cessing tasks. Additionally, it has tools to design analog filters as well.
11. It has various statistical tools to analyse distributions.

12. It can deal with graphs and nets.


13. It has a simulation toolbox to simulate complex systems.
14. It can read, analyse and play sound files.

2.1 Using Scilab


Scilab can be programmed in two ways:
• Start Scilab using

scilab

at the command line. This brings up a GUI in which you can enter commands.
One of the menu buttons brings up an programming editor which allows you to
write your code and to execute them in the Scilab window. To execute the entire
buffer in scilab, press Ctrl-L. To execute a selected portion of text, select the text
and press CTRL-Y.
• Create a “file format” called scilab anddefine a converter from noweb to scilab.
The file format should have

– extension: sci
– viewer: scilab -e ’scipad(“$$i”)’

This calls up Scilab and puts you in the scipad editor where you can further edit
the code or run the program as mentioned above.
Note that some versions give trouble with this. While there is a work around, the
simplest is to simply use
– viewer: scilab -e ’scipad()’
and open the file from within the editor.
The convertor should have the command

nountangle -c++ $$i > $$o

Note that if you don’t want the comments distracting you, use notangle instead
of nountangle.

3
2.2 Example Scilab Program
As an example, let us code the trapezoidal integral in Scilab. We first define the function
that carries out trapezoidal integration. Note the typeless nature of variables. We do
not have to declare the types of functions or their arguments. Scilab knows from the
context.
4a h* 4ai≡
function I=trapzd(a,b,f,n,Iold)
if n==0
I=(f(a)+f(b))*0.5*(b-a);
else
N=2^n;
Create 2n + 1 values uniformly spaced between a and b.
4b h* 4ai+≡
x=linspace(a,b,N+1);
We evaluate the function only at new points, and use the old integral for the old
values. "sum" sums up a vector, and x(2:2:N) selects the even indices of “x”, i.e., the
new values. f(x(2:2:N)) returns a vector of function values at all the new points. The
formula is
N
1
In = In−1 + hn ∑ f (a + khn )
2
k odd
4c h* 4ai+≡
I=Iold*0.5+sum(f(x(2:2:N)))*(x(2)-x(1))
end
endfunction
We define the function.
1 − e−x
f (x) = ecos x
1 + x2
Note that this function takes a vector “x” and computes f (x) for each value. Also note
that the number of calls counter is incremented by the number of elements of “x” since
this is a vector function.
The number of calls is a “global” variable, in that changes to it in functions changes
the variable in the calling program as well. We have to declare variables to be global,
and this must be done both in the function and in the calling program.
4d h* 4ai+≡
function y=f(x)
global count;count=count+length(x);
y=exp(cos(x)).*(1-exp(-x))./(1+x.*x);
endfunction

4
Now we write the main function. We obtain the values from the user, via a dialog
box. x_mdialog takes a title string, a column vector of labels and a column vector of
strings as initial values. It returns a column of strings as the user’s choice of values.
5a h* 4ai+≡
vals=["0";"1";"1e-10";"1e-4";"15"];
labels=["a";"b";"epsmin";"epsmax";"Neps"];
vals=x_mdialog("Enter the values for the run:",labels,vals);
We want numbers, not strings. But Scilab, like all interpreters, can evaluate any
string as if it is a bit of code and return the answer. Evaluating a string representing
a number, returns the numeric value. So the first line below converts vals from a
column vector of strings to a column vector of numbers. These are then assigned to the
appropriate variables.
5b h* 4ai+≡
vals=evstr(vals);
a=vals(1);
b=vals(2);
epsmin=vals(3);
epsmax=vals(4);
Neps=vals(5);
We define the range of accuracy values as a logarithmically uniform set of values.
5c h* 4ai+≡
eps=logspace(log10(epsmin),log10(epsmax),Neps)';
Allocate space for the Integral, the error and the actual error. “zeros(eps)” generates
a vector of the same shape as “eps” and sets the elements to zero.
5d h* 4ai+≡
Ivals=zeros(eps);
errvals=zeros(eps);
trueErr=zeros(eps);
calls=zeros(eps);
Use the built in integrator to integrate the function exactly. Note that this is correct
to 8 digits or 10−14 whichever is less stringent. We also declare count to be global and
initialize its value.
5e h* 4ai+≡
global count;
count=0;
Iexact=intg(a,b,f);
countExact=count;

5
Iterate over the different accuracies desired.
6a h* 4ai+≡
for k=1:length(eps);
count=0;
Iold=trapzd(a,b,f,0,0);
I=trapzd(a,b,f,1,Iold);
n=1;
for n=2:20
We limit the trapzoidal routine to 220 + 1 evaluations. The error in I is given by
2
err < I − Iold
3
(For details of error calculations, look up the chapter on integration in Numerical
Recipes in C)
6b h* 4ai+≡
err=(2/3)*abs(I-Iold);
Iold=I;
I=trapzd(a,b,f,n,Iold);
if err<eps(k), break, end;
end
Ivals(k)=I;
errvals(k)=err;
trueErr(k)=abs(I-Iexact);
calls(k)=count;
end
We fit the number of calls to a regression fit of the form Ncalls ≈ Aε B (This will be
discussed in the next Scilab assignment in more detail)
6c h* 4ai+≡
M=[ones(eps) log(eps)];
soln=M\log(calls-1);
A=exp(soln(1));B=soln(2);
We plot the errors, using a log-log plot. The xset commands control the plot
window. The first one opens plot window zero. The second command fixes the size of
the window in pixels. The third fixes the location of the window on the screen.
6d h* 4ai+≡
xset("window",0);
xset("wdim",400,300);
xset("wpos",0,0);
I use below the plot since it is closer to the Matlab syntax. When (if) you learn
Matlab you will be less confused.
6e h* 4ai+≡
plot(eps,errvals,'rx',eps,trueErr,'k');

6
To modify attributes of the plot, we must get the “handle” of (i.e., pointer to) its
axes. This is done via the gca() command. using it, we turn on grids, set the plot to
log-log and add labels and title.
7a h* 4ai+≡
a=gca(); // get the handle of the axis object
a.grid=[1 1]; // draw grids
a.log_flags="lln"; // x and y axes should be logarithmic.
legends(["estimated error";"actual error"],[-2 1],1);
a.title.text="Scaling of error";
a.x_label.text="desired accuracy";
a.y_label.text="error";
We also plot the number of calls, along with the regression fit. Put in some extra
information such as the number of calls needed by the built in integrator and the best fit
obtained by the regression analysis. Needless to say the built in integrator demonstrates
trapezoidal integration to be an extremely poor algorithm.
7b h* 4ai+≡
xset("window",1);
xset("wdim",400,300);
xset("wpos",0,350);
plot(eps,calls,'rx',eps,A*eps.^B,'k');
a=gca();
a.log_flags="lln";
s=sprintf("%.3f eps^%.2f",A,B);
legends(["Num calls";s],[-2 1],1);
a.title.text=["Scaling of No. of calls with eps";s];
a.x_label.text="desired accuracy (eps)";
a.y_label.text="Ncalls";

7
On executing the program, we get plots like so

Scaling of error

−3
10
estimated error
actual error

−6
10
error

−9
10

−12
10 −10 −8 −6 −4 −2
10 10 10 10 10

desired accuracy

8
Scaling of No. of calls with eps
Scilab built in integrator took 21 calls

6
10
Num calls

1.932 eps^−0.51

5
10
Ncalls

4
10

3
10

2
10 −10 −8 −6 −4 −2
10 10 10 10 10

desired accuracy (eps)

As can be seen in the second plot, the regression fit shows that the number of calls
scales as ε −0.5 . We have,

b−a 2
 
2 2
err < c1 h2 = c1
3 3 N

Hence we expect N + 1, the number of calls to the function to scale as the inverse
square root of error as confirmed in the plot.
The advantage of Scilab that should be obvious from this example is that the things
that are tedious in C are very simple in Scilab. If our work is mainly with vectors and
arrays, and our algorithms are expressible as array operations, Scilab or Matlab can be
very effective tools for us. However, there are algorithms that are more suited to C than
to Scilab. A good engineer uses each where it is best suited.

3 References
intro.pdf: The manual introducing Scilab, available here

Das könnte Ihnen auch gefallen