Scilab Intro

21
1 A brief introduction to Scilab Fotios Kasolis, 2010 [email protected] ABSTRACT. Scilab is an interactive scientific environment for numerics that integrates computation, visualization, and programming. It includes a large number of functionalities related to Linear Algebra, Polynomials, Ordinary Differential Equations, Optimization, etc. The matrix oriented language and the high level interpreted character of Scilab make it easy to learn and use. Scilab is available for Linux, MacOSX, and Windows and is freely redistributable under the CeCILL license (GPL compatible). To download Scilab and learn more about it visit http://www.scilab.org . 1.1 Introduction TABL LE 1.1 + - * / ^ %pi %i %inf %eps format sin cos tan asin acos atan asinh acosh exp log log10 log2 abs sqrt sign round ceil floor fix max min help The simplest way to use Scilab is to do arithmetic as we would with a common calculator. Addition, subtraction, multiplication, division, and exponentiation are represented in Scilab by the operators +, -, *, /, ^ (or **) respectively. For instance, type at the prompt (-->) the following instruction: -->(3+2^(-1))/0.5 ans = 7. Scilab displays the answer on the command window and assigns the resulting value to the variable ans. To change the way in which numbers are displayed we use the format function. format(#) sets the maximum number of displayed digits to the number # (the default is 10). A BRIEF INTRODUCTION TO SCILAB FOTIOS KASOLIS 1

Transcript of Scilab Intro

Page 1: Scilab Intro

1 A brief introduction to ScilabFotios Kasolis, 2010

[email protected]

ABSTRACT. Scilab is an interactive scientific environment for numerics that integrates computation, visualization, and programming. It includes a large number of functionalities related to Linear Algebra, Polynomials, Ordinary Differential Equations, Optimization, etc. The matrix oriented language and the high level interpreted character of Scilab make it easy to learn and use. Scilab is available for Linux, MacOSX, and Windows and is freely redistributable under the CeCILL license (GPL compatible). To download Scilab and learn more about it visit http://www.scilab.org .

1.1 Introduction

TABLE 1.1TABLE 1.1TABLE 1.1TABLE 1.1TABLE 1.1TABLE 1.1TABLE 1.1TABLE 1.1

+ - * / ^ %pi %i %inf

%eps format sin cos tan asin acos atan

asinh acosh exp log log10 log2 abs sqrt

sign round ceil floor fix max min help

The simplest way to use Scilab is to do arithmetic as we would with a common calculator. Addition, subtraction, multiplication, division, and exponentiation are represented in Scilab by the operators +, -, *, /, ^ (or **) respectively. For instance, type at the prompt (-->) the following instruction:

-->(3+2^(-1))/0.5 ans = 7.

Scilab displays the answer on the command window and assigns the resulting value to the variable ans. To change the way in which numbers are displayed we use the format function. format(#) sets the maximum number of displayed digits to the number # (the default is 10).

A BRIEF INTRODUCTION TO SCILAB FOTIOS KASOLIS

1

Page 2: Scilab Intro

-->%pi %pi = 3.1415927 -->format(25)-->%pi %pi = 3.1415926535897931159980

where the symbol %pi represents the constant π=3.14... Scilab knows all of the standard mathematical functions. A function is invoked with its name followed by the arguments in round brackets.

-->sin(2.7)^2+cos(2.7)^2 ans = 1.-->log(exp(2)) ans = 2.

where we note that the trigonometric functions work with radians, and the natural logarithm is log (and not ln). A complex number is one that can be written in the form z=x+yi where i=(-1)1/2 is the imaginary unit, x is the real part of z, and y the imaginary part of z. In Scilab, the imaginary unit is represented by the symbol %i. The complex number 1+2.3i is entered in Scilab as:

-->1+2.3*%i ans = 1. + 2.3i

To get detailed information about a function func we type help('func'). If no help file is available help invokes the function apropos. apropos('key') looks for the keyword key in the sort description section of the help files. Scilab provides two shortcuts for autocompletion. The TAB key tries to autocomplete an instruction based on Scilab’s knowledge, whereas the UP-ARROW key tries to autocomplete based on history.

A BRIEF INTRODUCTION TO SCILAB FOTIOS KASOLIS

2

Page 3: Scilab Intro

1.2 Assignments and variables

TABLE 1.2TABLE 1.2TABLE 1.2TABLE 1.2TABLE 1.2TABLE 1.2TABLE 1.2

= , ; .. // who_user clear

Variables are symbolic names associated with values. The name of a variable must be a sequence of letters, digits, and underscores, but it must not begin with a digit. Scilab does enforce a limit on the length of variable names (24 characters). Case is significant in variable names. The symbols x and X can be used as distinct variable names. In Scilab, the assignment operator is the equal sign (=). Some valid assignments are:

-->x=1 x = 1.-->distance=sqrt(4^2+3^2) distance = 5.-->a_long_variable_name=23 a_long_variable_name = 23.

New variables can be defined by using existing ones.

-->x=3; y=4;-->d=sqrt(x^2+y^2) d = 5.

where semicolons (;) are used to separate multiple instructions and suppress the output. To get a list showing the user defined variables we type who_user, whereas we can check a variable’s value by typing its name. Scilab does not forget assignments unless instructed to do so. To clear a previous assignment we use the clear command.

A BRIEF INTRODUCTION TO SCILAB FOTIOS KASOLIS

3

Page 4: Scilab Intro

-->clear x y-->x !--error 4 Undefined variable: x -->y !--error 4 Undefined variable: y

1.3 Vectors, ranges, and matrices

TABLE 1.3TABLE 1.3TABLE 1.3TABLE 1.3TABLE 1.3TABLE 1.3TABLE 1.3

zeros ones eye diag rand full spzeros

spones speye sparse toeplitz norm det trace

inv lu qr spec svd cond expm

A vector is an ordered set of numbers. To enter a row vector type a set of numbers separated by commas (,) or white spaces inside square brackets.

-->v=[7,3,9,0,2,4,1] v = 7. 3. 9. 0. 2. 4. 1.

We can enter a column vector by typing a set of numbers separated by semicolons (;) inside square brackets.

-->w=[7;3;9] w = 7. 3. 9.

A range is a row vector with evenly spaced elements. Ranges are created by instructions of the form <first>:<step>:<last>, where the <step> can be omitted (the default is 1).

A BRIEF INTRODUCTION TO SCILAB FOTIOS KASOLIS

4

Page 5: Scilab Intro

-->a=0:5 a = 0. 1. 2. 3. 4. 5. -->b=0:0.2:0.6 b = 0. 0.2 0.4 0.6

To change v from row to column vector we ask from Scilab for its transpose by typing v.', while for the conjugate transpose we omit the period v'. Another way to to get a column vector is by typing v(:). We can perform several operations on vectors. For instance, to square the elements of the vector v we type:

-->v.^2 ans = 49. 9. 81. 0. 4. 16. 1.

The period in the above instruction says that the numbers in v should be squared individually. Typing v^2 would tell Scilab to use matrix multiplication to multiply v by itself and would have produce an error. Similarly, we must use .* and ./ for element-wise multiplication and division respectively. Most Scilab functions are, by default, performed element by element. For example, we type exp(v) to get the exponential of each number in v. The ith element of a vector can be specified through Scilab’s indexing rules, that is by typing the vector variable followed by the position index inside round brackets. If v=[7,3,9,0,2,4,1] we have v(1)=7, v(2)=3, v(3)=9, v(4)=0, v(5)=2, v(6)=4, and v(7)=v($)=7. To extract a vector containing the first, the third, and the seventh element of v we type:

-->v([1,2,3]) ans = 7. 3. 9.

Elements of vectors can be extracted with ranges. For instance, v(4:length(v)) is the same as v(4:$) and as v([4,5,6,7]). The length function returns the number of elements in v.

A BRIEF INTRODUCTION TO SCILAB FOTIOS KASOLIS

5

Page 6: Scilab Intro

Entering matrices in Scilab is as easy. For example, the matrix

A = 1 12 2

⎝⎜⎜⎜⎜

⎠⎟⎟⎟⎟ is entered in Scilab by typing:

-->A=[1,1;2,2] A = 1. 1. 2. 2.

For that specific example we could compose the matrix A by two column vectors [1;2].

-->v=[1;2] v = 1. 2. -->A=[v,v] A = 1. 1. 2. 2.

The individual elements are extracted by typing A(row,column), we have A(1,1)=A(1,2)=1, A(2,1)=A(2,2)=2, whereas an entire row or column is denoted by a colon (:).

-->A(:,1) ans = 1. 2. -->A(:,2) ans = 1. 2. -->A(1,:) ans = 1. 1. -->A(2,:) ans = 2. 2.

A BRIEF INTRODUCTION TO SCILAB FOTIOS KASOLIS

6

Page 7: Scilab Intro

1.4 Graphs

TABLE 1.4TABLE 1.4TABLE 1.4TABLE 1.4TABLE 1.4

plot contour polarplot champ grayplot

surf grayplot subplot bar xs2pdf

The basic plotting function is plot. To plot the graph of the function f : X→Y we define a discrete version of the domain X as follows.

-->X=0:.01:2*%pi;

Moreover, we calculate the function values at X, for instance if f(x)=sin x we have:

-->Y=sin(X);

The last step is to invoke the plot function.

-->plot(X,Y);

To save the produced graph we call the function xs2pdf.

A BRIEF INTRODUCTION TO SCILAB FOTIOS KASOLIS

7

- 1.0

- 0.8

- 0.6

- 0.4

- 0.2

0.0

0.2

0.4

0.6

0.8

1.0

0 1 2 3 4 5 6 7

Page 8: Scilab Intro

-->xs2pdf(0,'~/graph1.pdf')

We can modify a plot in a number of ways. To add axes’ labels and title we use the functions xlabel, ylabel, and title.

-->xlabel('x')-->ylabel('y')-->title('f(x)=sin(x)')

We would also like to change the font size, the font style, and the axes’ limits to fit exactly the plotted function.

-->h=gca();-->h.font_size=3;-->h.font_style=2;-->h.tight_limits='on';-->h.x_label.font_style=2;-->h.x_label.font_size=4;-->h.y_label.font_style=2; -->h.y_label.font_size=4;-->h.title.font_style=2;-->h.title.font_size=4;

A BRIEF INTRODUCTION TO SCILAB FOTIOS KASOLIS

8

-0.8

-0.6

-0.4

-0.2

0.0

0.2

0.4

0.6

0.8

0 1 2 3 4 5 6

f(x)=sin(x)

x

y

Page 9: Scilab Intro

Often we want to overlay two (or more) plots on the same set of axes. The way to do it is shown below.

-->x=0:0.01:2*%pi;-->plot(x,sin(x),'g',x,cos(x),'m')

This example also shows how to control the line color. To change the color replace g and m in the above instruction with k, b, y, r. Apart from color we can use different markers instead of a continuous line.

A BRIEF INTRODUCTION TO SCILAB FOTIOS KASOLIS

9

- 1.0

- 0.8

- 0.6

- 0.4

- 0.2

0.0

0.2

0.4

0.6

0.8

1.0

0 1 2 3 4 5 6 7

- 1.0

- 0.8

- 0.6

- 0.4

- 0.2

0.0

0.2

0.4

0.6

0.8

1.0

0 1 2 3 4 5 6 7

Page 10: Scilab Intro

-->x=0:0.1:2*%pi;-->plot(x,sin(x),'xg',x,cos(x),'om')

Below we give a complete example in which several different properties of a plot are changed in order to achieve a publication quality result.

-->x=0:0.1:40;-->f=besselj(0,x);-->d=f + rand(1,length(x))-0.5;-->u=f + 0.5;-->l=f - 0.5;-->plot(x,f,'k',x,d,'b.',x,u,'--m',x,l,'--g')-->xlabel('x')-->ylabel("J0(x)")-->title('Inaccurate measurement of ..-->Bessel function (1st kind)')-->h=gca();-->h.tight_limits='on';-->h.thickness=2;-->h.font_size = 3;-->h.font_style = 2;-->h.x_label.font_style = 2;-->h.x_label.font_size = 4;-->h.y_label.font_style = 2;-->h.y_label.font_size = 4;-->h.title.font_style = 2;-->h.title.font_size = 4;-->h.children.children(1).thickness=2;-->h.children.children(2).thickness=2;-->h.children.children(3).mark_size=4;-->h.children.children(4).thickness=4;-->legend('Bessel function','Measured data',..-->'Upper bound','Lower bound',5);

The gca function returns the handle of the current axes for the current figure. The axes entity is the second level of the graphics entities hierarchy. This entity defines the parameters allowing the change of coordinates and the axes drawing as well as the parameters’ default values for the children creation.1

For more information type help axes_properties ans/or visit the webpage http://wiki.scilab.org/The_Graphic_Hierarchy.

A BRIEF INTRODUCTION TO SCILAB FOTIOS KASOLIS

10

1 From Scilab’s documentation.

Page 11: Scilab Intro

1.5 Loops and conditionals

TABLE 1.5TABLE 1.5TABLE 1.5TABLE 1.5TABLE 1.5TABLE 1.5TABLE 1.5

& | ~ == ~= or <> < >

<= >= if elseif else for while

end break pause return resume abort disp

In Scilab, control flow statements operate like those in most computer languages. Indenting the instructions of a loop or conditional statement is optional, but helps readability.

-->v=rand(1);-->if v < 0.25--> x = -1;--> y = 0;-->elseif v < 0.5--> x = +1;--> y = 0;-->elseif v < 0.75--> x = 0;--> y = -1;-->else--> x = 0;--> y = +1;-->end

A BRIEF INTRODUCTION TO SCILAB FOTIOS KASOLIS

11

Bessel functionMeasured dataUpper boundLower bound

-0.5

0.0

0.5

1.0

1.5

0 5 10 15 20 25 30 35 40

Inaccurate measurement of Bessel function (1st kind)

x

J0(x

)

Page 12: Scilab Intro

The if statement evaluates a logical expression and executes a group of instructions when the expression is true (%t). Alternative instructions can be executed by using the optional keywords elseif and else. In the example above a random number is generated using the function rand and a conditional decides the direction of a step. Scilab includes for and while loops. To make the above example more interesting we modify it as follows.

-->N = 10000;-->x = zeros(1,N);-->y = zeros(1,N);-->for i = 1:N-1--> v = rand(1);--> if v < 0.25--> x(i+1) = x(i) - 1;--> y(i+1) = y(i);--> elseif v < 0.5--> x(i+1) = x(i) + 1;--> y(i+1) = y(i); --> elseif v < 0.75--> x(i+1) = x(i);--> y(i+1) = y(i) - 1;--> else--> x(i+1) = x(i)--> y(i+1) = y(i) + 1;--> end-->end-->plot(x,y)

A BRIEF INTRODUCTION TO SCILAB FOTIOS KASOLIS

12

0

10

20

30

40

50

60

70

80

90

-100 -80 -60 -40 -20 0

Random walk

x

y

Page 13: Scilab Intro

1.6 Scripts and functions

TABLE 1.6TABLE 1.6TABLE 1.6TABLE 1.6TABLE 1.6

function endfunction deff argn varargin

feval add_profile profile showprofile plotprofile

We can execute a sequence of regular Scilab instructions stored in simple text files called scripts. Apart from regular statements we can create new function files specific to the problem we want to solve. Conventionally, script files have the extension .sce, while function files the extension .sci. To write our first script we open our favorite (simple) text editor (if we do not like the one that ships with Scilab) and we type the instructions shown below.

// example 1: xmpl_1.sce A=[1 2; 2 2];b=[3; 2];x=A\b

We save the file as xmpl_1.sce. To execute the created script we type in Scilab’s prompt:

-->exec('~/xmpl_1.sce')

A function file has the general form:

function [<out>] = <function name>(<in>) <instructions>endfunction

To invoke a function we must load the function file using exec as we did previously with the script file. Preferably the <function name> and the name of the sci file that defines the function are the same. Below we give an example of a function which uses central difference approximation to calculate the derivative of a function f at a point x0:

A BRIEF INTRODUCTION TO SCILAB FOTIOS KASOLIS

13

Page 14: Scilab Intro

f '(x0)≈f(x

0+ h)− f(x

0+ h)

2h

function [dfdx]=Derivative(f, x0, h) dfdx = (feval(x0+h,f) - feval(x0-h,f))/(2*h);endfunction

where feval stands for function evaluation. To call this function we have to define the mathematical function f which we want derivate. To do so we can create another function file, but for simple cases we can use deff to define on-line functions, for instance if f(x)=sin x we type:

-->deff('y=f(x)','y=sin(x)');

and we invoke the Derivative function as in the following example.

-->exec('~/Derivative.sci');-->Derivative(f,%pi,0.001) ans = - 0.9999998 -->cos(%pi) ans = - 1.

When writing a function we can easily define default values for input arguments.

function [dfdx]=Derivative(f, x0, h) [lhs,rhs] = argn(0); if rhs < 3 h = 0.001; end dfdx = (feval(x0+h,f) - feval(x0-h,f))/(2*h);endfunction

This function could be called with only two arguments. Variables in a function file are local, meaning that unlike the variables defined in script files, these variables are completely unrelated to any of the variables

A BRIEF INTRODUCTION TO SCILAB FOTIOS KASOLIS

14

Page 15: Scilab Intro

with the same names that are defined in the command line, and Scilab does not remember their values after executing the function. Time can be measured by the tic - toc macros (tic starts the timer and toc prints the elapsed time since tic was used).

-->tic; d=Derivative(f,0:0.0001:2*%pi); toc ans = 2.942

Moreover, Scilab includes a profiler. To add profiling instructions to a function we use add_profiling.

-->add_profiling('Derivative');-->Derivative(f,0:0.0001:2*%pi);-->showprofile(Derivative)function dfdx=fun(f, x0, h) |1|0 |0 | |1|0 |0 | [lhs,rhs] = argn(0); |1|0 |3 | |1|0 |0 | if rhs < 3 then |1|0 |0 | h = 0.001; |1|0 |2 | end, |1|0 |0 | |1|0 |0 | dfdx = (feval(x0 + h, f) - feval(x0 - h, f))/(2 * h);|1|2.46|16|endfunction |1|0 |0 |

The first column shows how many times each line is executed, the second column shows how much cpu time is spend, and the third column gives a measure of the effort. A graphical (and more interactive) result is obtained through the plotprofile function.

A BRIEF INTRODUCTION TO SCILAB FOTIOS KASOLIS

15

0.00.10.20.30.40.50.60.70.80.91.0

1 2 3 4 5 6 7 8 9 10

# of calls per code line

0.0

0.5

1.0

1.5

2.0

2.5

1 2 3 4 5 6 7 8 9 10

CPU t ime per code line

02468

10121416

1 2 3 4 5 6 7 8 9 10

Measure of efort per code line

Page 16: Scilab Intro

1.7 Application: Root finding

TABLE 1.7TABLE 1.7TABLE 1.7TABLE 1.7

poly roots horner fsolve

Polynomials are represented in Scilab by their coefficients in ascending order of powers. For instance, the polynomial:

p(x)=124x4 −

12x2 +1

is entered in Scilab by typing:

-->p=poly([1,0,-1/2,0,1/24],'x','coeff') p = 2 3 1 - 0.5x + 0.0416667x

Its roots can be found using the function roots.

-->r=roots(p) r = 1.5924504 - 1.5924504 3.076378 - 3.076378

To check the correctness of this result we evaluate the polynomial values at the roots:

-->f=horner(p,r) f = 1.0D-15 * - 0.2220446 - 0.2220446 0.2220446 - 0.4440892

A BRIEF INTRODUCTION TO SCILAB FOTIOS KASOLIS

16

Page 17: Scilab Intro

and we check it graphically:

-->x=-4:0.01:4;-->plot(x,x.^4/24-x.^2/2+1,'k',r,f,'om')

The more general problem of finding the zeros of a transcendental function is solved in Scilab by the function fsolve. Suppose we are interested in finding a zero of the function:

f(x)= cos x− x2

To do so we type in Scilab’s prompt:

-->deff('y=f(x)','y=cos(x)-x^2');-->fsolve(0.5,f) ans = 0.8241323

where the first argument in the fsolve function is a starting point. In 1D problems a good starting point (a point relatively close to the root) can be found by plotting the function. Scilab’s function fsolve can be also used to solve systems of non-linear equations. Consider the following set of three equations in three unknowns (x, y, z):

A BRIEF INTRODUCTION TO SCILAB FOTIOS KASOLIS

17

0.0

0.5

1.0

1.5

2.0

2.5

3.0

3.5

-4 -3 -2 -1 0 1 2 3 4x

p(x)

Page 18: Scilab Intro

sin(xy)+ exp(−xz)− 0.95908 = 0

z x2 + y2 − 6.7082= 0

tan(y / x)+ cos z+ 3.17503= 0

To solve this system we first define the following function:

function [J]=SystemOfEq(x) J = zeros(3,1); J(1) = sin(x(1)*x(2))+exp(-x(1)*x(3))-0.95908; J(2) = x(3)*sqrt(x(1)^2+x(2)^2)-6.7082; J(3) = tan(x(2)/x(1))+cos(x(3))+3.17503;endfunction

and we load it to Scilab:

-->exec('~/Desktop/SystemOfEq.sci')

The final step is to invoke fsolve with a proper initial condition.

-->fsolve([0.1 1.8 2.2],SystemOfEq) ans = 0.1251917 2.2169497 3.0210562

Problem set

Introduction01.Make sure you understand how (and when) to use the functions shown in the TABLE 1.1 (use the function help).

02.Calculate the value of the expression 2/(e2+2/3) and its square without retyping the expression.

03.What is the expected value of the expression 1-sin2(π/2)-cos2(π/2). Change the format of the displayed output to 25 digits and calculate its value using Scilab. Are the computed and expected values the same?

A BRIEF INTRODUCTION TO SCILAB FOTIOS KASOLIS

18

Page 19: Scilab Intro

Assignments and variables04.Find the distance between the points A(1.1,2.7) and B(7.9,2.2) and assign the result to the symbol d. Use the function norm to calculate the same distance.

05.(a) Set the symbol x equal to 1 and suppress the output. (b) Set the symbol y equal to 7 using the line continuation operator after the assignment operator. (c) Set the symbol z equal to 3.1 and in the same line set the symbol w equal to true.

Vectors, ranges, and matrices

06.Let x=[9 8 3 1 0 2 3] and (a) add 2 to the odd index elements, (b) compute the square root of each element, (c) divide each element of x with its position index squared.

07.Write the inner product of two vectors v and w using matrix multiplication. Choose v=[1;0;2] and w=[8;1;1] to check your answer.

08.Create a vector e with elements given by 1n/n!, where n=0,1,2,...,N is the position index, and n!=1 ∙ 2 ∙ 3 ∙ ... ∙ n is the factorial of n (given in Scilab by the function factorial). Choose N=10, N=100, and N=1000 and sum up the elements of the vector e. Interpret the result. You must not use a for loop.

09.Given the matrix A=[2 7 9 7; 3 1 5 6; 8 1 2 5], explain the results of the following instructions. (a) A', (b) A(:,[1 4]), (c) A(:), (d) matrix(A,2,6), and size(A,'*').

Graphs

10.Make a good plot of the tan function over the domain [0,4π].

11.Make sure you understand how to use the functions shown in the TABLE 1.4 (use the function help and execute all the examples).

Loops and conditionals

12.Given v=[1 5 5 6 7] and w=[2 5 6 6 9], execute and explain the following instructions. (a) v>w, (b) v|w, (c)(v==5)&(w<>6).

A BRIEF INTRODUCTION TO SCILAB FOTIOS KASOLIS

19

Page 20: Scilab Intro

13.Evaluate n and m in the following Scilab code fragments and use Scilab to check your answers.

(a) n=1; m=1; if n>3 m=n+1; else m=m-1; end.(b) n=4; m=2; if n>3 m=n+1; else m=m-1; end.(c) n=3; m=1; if n*m>3 m=m^2; else m=m-1; end.(d) n=1; m=4; if n<>4 m=n-1; n=n-1; end.

14.Evaluate the vector x in the following Scilab code fragments and use Scilab to check your answers.

(a) (b) (c)

n=1; m=2;for i=1:10 if n==m x(i)=n^2+m^2; n=m+1; else x(i)=n/m; n=m-1; endend

n=1; m=2;for i=1:10 if n==m x(i)=n^2+m^2; n=m+1; else x(i)=n/m; n=m; endend

n=1; m=2;for i=1:10 if n==m x(i)=n^2+m^2; n=m+1; else x(i)=n/m; n=n*m; endend

Scripts and functions15.Study the following scripts. In all cases the resulting vector is the same column vector. What is the problem with the cases (a) and (b)?

(a) (b) (c)

clear xticx=[];for i = 1:10^5 x=[x; sin(i)];endtoc

clear xticfor i = 1:10^5 x(i)=sin(i);endtoc

clear xticx=zeros(10^5,1);for i = 1:10^5 x(i) = sin(i);endtoc

16.Write a function that returns a vector with the Fibonacci numbers which are given by:

xn= x

n−1+ x

n−2

with initial conditions x0=0 and x1=1, and n=0,1,2,...N. Use the number N as user input. Execute your function for N=100 and plot the resulting

A BRIEF INTRODUCTION TO SCILAB FOTIOS KASOLIS

20

Page 21: Scilab Intro

values (vs position index). For the first 50 Fibonacci numbers, compute the ratio xn/xn-1.

17.Write two function that return the roots of the quadratic equation ax2+bx+c=0 given a, b, and c. In the first function use the formulas:

x−=−b− b2 − 4ac

2a, x

+=−b+ b2 − 4ac

2aand in the second use the equivalent alternatives:

x−=

2c

−b+ b2 − 4ac, x

+=

2c

−b− b2 − 4ac

Invoke both functions for a=10-5, b=1/10-5, and c=-10-5 and compare the solutions with respect to accuracy.

A BRIEF INTRODUCTION TO SCILAB FOTIOS KASOLIS

21