Numerical Solutions to Ordinary Differential Equations in Scilab

58

description

Techniques and methods for obtaining solutions to different kind of Ordinary Differential Equations is investigated in Scilab. The approach is based on solving different kind of Ordinary Differential Equations with different method some which are user defined for example Euler's method and other which are ready made in Scilab for example Runge-Kutta, Fehlberg's runge-Kutta, Adams-Bashforth and Stiff (belonging to stiff category problems). Emphasis is placed on mathematical justifiation of the approach. Time required to complete a task and step size for desired accuracy of solution are the main concern and basis of comparison between methods. On the basis of this approach problem and difficulties in Scilab are observed and suggestions are made for their remedies.

Transcript of Numerical Solutions to Ordinary Differential Equations in Scilab

Page 1: Numerical Solutions to Ordinary Differential Equations in Scilab

Kishor Vaigyanik Protsahan Yojana

(Department of Science and Technology, Government of India)

June 11, 2009

Summer Camp Report on

Numerical Solution to Ordinary Di�erentialEquations in Scilab

by

Rahul Kumar Soni

([email protected])

Department of Fuel and Mineral Engineering

Indian School of Mines University Dhanbad

under the mentorship of

Professor Kannan M. Moudgalya

([email protected])

Department of Chemical Engineering

Indian Institute of Technology Bombay, India

1

Page 2: Numerical Solutions to Ordinary Differential Equations in Scilab

Certi�cate

This is to certify that Mr. Rahul Kumar Soni, a stu-

dent of Department of Fuel and Mineral Engineering from

Indian School of Mines University Dhanbad has done his

Kishor Vaigyanik Protsahan Yojana summer camp project

at Department of Chemical Engineering of Indian Insti-

tute of Technology Bombay from May 11, 2009 to June

10, 2009 under my guidance.

The project work entitled �Numerical Solution to Ordi-

nary Di�erential Equations in Scilab� embodies the origi-

nal work done by Mr. Rahul Kumar Soni during his sum-

mer camp.

Signature

Professor Kannan M. Moudgalya

Department of Chemical Engineering

Indian Institute of Technology Bombay

2

Page 3: Numerical Solutions to Ordinary Differential Equations in Scilab

Acknowledgement

My sincere thanks to Prof. Kannan Moudgalya for having givenme this opportunity to work on such a lucrative project. I wish tothank the KVPY cell for having provided a great work environment.This project would not have been complete without the guidance andtimely inputs from Prof. G K Srinivasan ( Professor, Departmentof Mathematics, IIT Bombay), Prof. V K Gupta (Tata Steel ChairProfessor at Department of Fuel and Mineral Engineering, ISMU),Dr. Nikkam Suresh(Asso. Prof. and HOD, Department of Fuel andMineral Engineering, ISMU), Dr. Biswajit Paul (Department of En-vironment Science and Engineering, ISMU), Dr. S Bhattacharya(Asso. Prof., Department of Fuel and Mineral Engineering, ISMU),Dr. N K Singh(Asso. Prof. and HOW, Department of Mechani-cal Egineering, ISMU), Ms. Inderpreet Arora (M.Tech Student, IITBombay), Ms. Sandhya Sourirajan (B.E. student, Coimbtore Insti-tute of Technology), all teachers and my friends.

I am thankful to the entire work force at ERTS lab, CDEEP andChemical Department of IIT Bombay for the part they played inmaking the period of work a joyful experience.

Last but not the least, I thank to Indian Institute of ScienceBanglore (the Organizing Institute) and Department of Science andTechnology, Government of India (the sponsoring agency) for theirsupport and encouragement.

3

Page 4: Numerical Solutions to Ordinary Differential Equations in Scilab

Abbreviations and meaning of symbols

ODE: ordinary di�erential equationIVP: initial value problemBVP: boundary value problemrk: Runge-Kutta 4thorder methodrkf: Fehlberg's Runge-Kutta order 4 and 5 method (RKF45)LT: Laplace TransformILT: Inverse Laplace Transforms//**S: Shows the start of the part of program executed online in Scilab

window.//**E: Shows the end of the part of program executed online in Scilab win-

dow.//##S: Shows start of the writer's contribution to the program or in the

matter taken from references orcomplete work of writer.//##E: Shows end of the writer's contribution to the program or in the

matter taken from references orcomplete work of writer.

Machine con�gurations

Simulation has done in two machines of following con�gurations

1. Notepad

Microsoft Windows Vista Home Premium, Intel(R) Core(TM)2 DuoCPU 1.67GHz 32 bit operating system, 2GB RAM, 160GB HDD.

2. Lab PC

Microsoft Windows XP Professional version 2002 SP2, Intel(R) Pen-tium(R) D CPU 3.40GHz, 1GB RAM, 160GB HDD.

Disclaimer

1. All the programs written in the report are tested in Scilab andproduced �gure are attached in the report, so in any case not properworking of program is might be due to printing mistake.

2. For purpose of contracting space in the report; position of someplots/�gures have changed, however they are correct.

3. In some places in programs '...' this notation has used at last ofthe lines. Notation is for continuation purpose, in running programthis may replace by continuing next line.

4

Page 5: Numerical Solutions to Ordinary Differential Equations in Scilab

Contents

1 Scilab 8

1.1 SCILAB HISTORY . . . . . . . . . . . . . . . . . . . 8

1.2 HOW TO OBTAIN ? . . . . . . . . . . . . . . . . . 8

1.3 INSTALLATION & REQUIREMENTS . . . . . . . 8

2 Method involve in solution to ODE 9

2.1 Analytical Solutions of Ordinary Di�erential Equa-tions (ODEs) . . . . . . . . . . . . . . . . . . . . . . 9

2.1.1 Introduction to Di�erent kind of ODEs andtheir analytical Solution . . . . . . . . . . . . 9

2.2 Numerical methods for solution of ODEs available inScilab . . . . . . . . . . . . . . . . . . . . . . . . . . 12

2.2.1 Euler's method (Non-Sti�): Solution of ODEs

of non-sti� type by the basic de�nition of di�er-

entiation and by fourier transform expansion. . . 12

2.2.2 Scilab ODE Solvers . . . . . . . . . . . . . . 12

3 Some Useful Commands regarding to ODE solutions: 13

4 Stability of a solution and Sti�/Non-sti� problems 13

4.1 Stability . . . . . . . . . . . . . . . . . . . . . . . . . 13

4.2 Sti� and Non-sti� problems . . . . . . . . . . . . . . 14

5 Scilab Programs for solving ODEs and their exam-ples 16

5.1 Solution to Simple ODE explicit in terms of indepen-dent variable . . . . . . . . . . . . . . . . . . . . . . 16

5.2 Solution by Euler method . . . . . . . . . . . . . . . 18

5.3 A simple ODE of type dy/dt = f(t,y) . . . . . . . . . 20

5.4 Sti� type problem and its solution by other methodscomparing with sti� method . . . . . . . . . . . . . . 21

5.5 Solution to Linear �rst order linear system of ODEs 25

5.6 Solution to the system of Linear ODEs with help ofLaplace Transform . . . . . . . . . . . . . . . . . . . 26

5.7 Solution to a Second Order ODE with constant coef-�cients . . . . . . . . . . . . . . . . . . . . . . . . . . 28

5.8 Solution to Higher order non-homogeneous ODEs withconstant coe�cients . . . . . . . . . . . . . . . . . . 33

5

Page 6: Numerical Solutions to Ordinary Differential Equations in Scilab

6 Miscellaneous Problems 36

6.1 Predator-Prey model . . . . . . . . . . . . . . . . . . 36

6.1.1 Predator-Prey problem solution by Euler's method 38

6.1.2 Predator-Prey problem solution by Scilab ODESolver . . . . . . . . . . . . . . . . . . . . . . 42

6.2 Lorenz �ow and Lorenz equation . . . . . . . . . . . 44

6.3 Curve �tting with Scilab for Data analysis purpose . 46

6.4 Solution to ODE where analytical is solution is di�cult 51

6.4.1 Solution of Example 11 by Scialb ode solver . 51

6.5 Modeling and Simulation of a Pressure wave generator 52

7 Demerits and di�culties in Scilab and suggestion forimprovement 55

6

Page 7: Numerical Solutions to Ordinary Differential Equations in Scilab

Abstract

Techniques and methods for obtaining solutions to di�erent kindof Ordinary Di�erential Equations is investigated in Scilab. Theapproach is based on solving di�erent kind of Ordinary Di�eren-tial Equations with di�erent method some which are user de�nedfor example Euler's method and other which are ready made inScilab for example Runge-Kutta, Fehlberg's runge-Kutta, Adams-Bashforth and Sti� (belonging to sti� category problems). Empha-sis is placed on mathematical justi�cation of the approach. Timerequired to complete a task and step size for desired accuracy of so-lution are the main concern and basis of comparison between meth-ods. On the basis of this approach problem and di�culties in Scilabare observed and suggestions are made for their remedies.

Preamble

In mathematics, an ordinary di�erential equation (or ODE) isa relation that contains functions of only one independent variable,and one or more of its derivatives with respect to that variable. SirIsaac Newton has �rst developed the concept of ordinary Di�erentialEquations for a series solution in the �eld of Astronomy and fromthat time ODE has wide applications in Industry, scienti�c work,Economics, Ecology, Geology and many other �elds including bio-logical sciences. ODE always gives the relation among independentvariables, dependent variable and their derivatives which are di�-cult to analyze. A better analysis of these equations requires theirsolution in terms of independent and dependent variables. Varioustechniques are available for the solution of these ODEs in di�erentsoftware packages like Mathematica, Maple, Matlab, Scilab etc. Thisreport mainly deals with the solution of ODEs in Scilab by di�erentmethods like Adams-Bashforth, Runge-kutta , Fehlberg's Runge-Kutta , Discrete time simulation and �nally Sti� type of equationsalong with examples, comparison of their solutions (error involved,smoothness of curve).

7

Page 8: Numerical Solutions to Ordinary Differential Equations in Scilab

Aim

Aim of this paper is to examine the apparent trend in

Simulation of Ordinary Di�erential Equation using Scilab

by various methods, their applicability and �nally ana-

lyzing the method with optimize solution for a various

category of problems.

1 Scilab

1.1 SCILAB HISTORY

It is an open source software package developed at INRIA (France), for systemcontrol and signal processing applications. It also features a wide variety oftools for various Engineering and Mathematical applications. It was introducedas an Open source alternative to MATLAB. It is also a vector and matrix basedprogram. Scilab introduced Scicos equivalent to Simulink. It has constantlyundergone vital changes ever since its inception in 1994.

1.2 HOW TO OBTAIN ?

It can be freely downloaded at the home page(http://www.scilab.org/). The siteo�ers the latest version for all the prominent Operating systems. The Windowsversion is a 83.6 MB zip �le ( Scilab 5.1.1). The user is free to modify the sourcewhich is also readily available at the same link. The package also includes asimulator called SCICOS which is an open source alternative to SIMULINK ofMatLab. The minimal package does not include subject speci�c toolboxes andare to be downloaded separately.

1.3 INSTALLATION & REQUIREMENTS

The Scilab installation �le has to be unzipped into a folder from which it canbe easily installed into the desired location by double clicking the installation�le. In case of Linux, the setup �le in binary version is a 15.6 MB .tar �le whichhas to be extracted into a directory. Open the Linux terminal and then moveto the directory into which the SCILAB .tar �le has been extracted. Typingthe �make� command from the SCILAB directory produces an executable �le,which can be invoked by typing �scilab� .The standard package occupies only130 MB of disk space upon installation.

8

Page 9: Numerical Solutions to Ordinary Differential Equations in Scilab

2 Method involve in solution to ODE

2.1 Analytical Solutions of Ordinary Di�erential Equa-tions (ODEs)

(Preparation done by attending Continuing Education Program-CEP02 on Ordinary Di�erential Equations at Indian Institute ofTechnology Bombay held from May 11,09 to May 22,09.)

2.1.1 Introduction to Di�erent kind of ODEs and their analyticalSolution

1. Simple linear ordinary di�erential equation

dy

dt= ax+ bxy

dx

dt= cy + dxy

2. Clairut's ODE

y = xdy

dx+ f(

dy

dx)

3. Singular and General solution, General solution as Envelope of Singularsolution.

4. Curl, Divergence, Laplacian of a vector, Convex and Concave domain.

5. Exact or Total Di�erential Equation

Mdx+Ndy = 0

6. Necessary and Su�cient condition for Exact or Total Di�erential Equa-tion.

∂M

∂y=∂N

∂x

M =∂f(x, y)∂x

N =∂f(x, y)∂y

7. Along with vector �eld Mi+Nj must be conservative in nature.

8. Linear �rst order ODE and its solution by operation with Integratingfactor.

dy

dx+ P (x)y = Q(x)

9

Page 10: Numerical Solutions to Ordinary Differential Equations in Scilab

9. Bernoulli's Equation and its solution.

dy

dx+ P (x)y = Q(x)yn

10. Orthogonal Trajectories.

11. Solution of second order Non-homogeneous di�erential Equation by methodof variation of parameters.

12. Higher order di�erential Equation with variable coe�cients.

Dny +n−1∑j=0

aj(x)Djy = 0

Calculation of Wronskian.

13. Homogeneous Linear Di�erential Equation with constant coe�cients

Dny +n−1∑j=0

ajDjy = 0

In cases of Real distinct, Real repeative and complex roots.

14. Non-homogeneous Linear Di�erential Equation with constant coe�cients

Dny +n−1∑j=0

ajDjy = R(x)

Solution of such problems require Annihilators, which are

Table1

R(x) Annihilatorxkeax (D − a)k+1

xkeaxsinbx {(D − a)2 + b2}k+1

xkeaxcosbx {(D − a)2 + b2}k+1

15. Improper Integrals (1st and 2nd kind).

16. Riemann Integrals and its properties, theorems, tests.

17. Functional function.f(x+ 1) = x(x)

andf(1) = 1

10

Page 11: Numerical Solutions to Ordinary Differential Equations in Scilab

18. Gamma function and its properties.

Γ(a) =∫ ∞

0

exp(−t)ta−1dt

19. Beta function and its properties.

β(a, b) =∫ 1

0

xa−1(1− x)b−1dx

20. Euler's formulaΓ(a)Γ(a− 1) =

π

sin(πa)

21. Exponential type function, Necessary and Su�cient condition for LaplaceTransform.

22. Laplace Transform and its properties.

F (s) = L{f(t)} =∫ ∞

0

exp(−st)f(t)dt

23. Shift theorem, Uniqueness Theorem for Laplace Transform.

24. Inverse Laplace Transform , properties, theorems.

L−1{F (s)} = f(t)

25. Solution of ODE, system of linear di�erential equation by Laplace Trans-form method.

26. Application of Laplace Transform in calculating Integrals.

27. Convolution theorem.H(s) = F (s) ∗G(s)

then

h(t) = (f ∗ g)(t) =∫ 1

0

f(τ)g(τ − t)dτ

28. Homogeneous Linear Di�erential Equation with constant coe�cients andtheir di�erent combinations as:

3 Legendre Equation

3 Tchebychev Equation

3 Airy Equation

3 Hermits Equation

3 Laguerre Equation

3 Bessel's Equation

3 Hypergeometric Equation

3 Jacobi's Equation.

11

Page 12: Numerical Solutions to Ordinary Differential Equations in Scilab

2.2 Numerical methods for solution of ODEs available inScilab

2.2.1 Euler's method (Non-Sti�): Solution of ODEs of non-sti� type

by the basic de�nition of di�erentiation and by fourier transform

expansion.

2.2.2 Scilab ODE Solvers

Although there are other ode solvers like ode, dassl, dassrt, odedc are availablein Scilab but we will consider only 'ode' solver here.

General call syntax of Scilab ODE solver 'ode'

y = ode(′type′, y0, t0, t, f(t, y))

where

y is a function of t and dy/dt = f(t,y)

y0 and t0are initial condition as y(to) = y0

t is the range for the solution of ODE

type is a character string given in a single quote and direct machine for anyspeci�c type of numerical solution method. This methods and correspondingstring are as follows;

3 '(empty input)': Default Lsoda method uses non-sti� procedure initially and

then uses Sti� backward di�erentiation method , if required.

3 'adams': Solves Non-sti� problems by Adams-Bashforth method.

3 'rk': Uses Runge-Kutta 4th order method to solve non-sti� problem.

3 'rkf': For non-sti� and mildly sti� problems, uses Fehlberg's Runge-Kutta pair

of order 4 and 5 (RKF45) method, should not use when high accuracy is

desired.

3 '�x': Similar to Fehlberg's Runge Kutta method, with easier user interface (for

non-sti� problems).

3 'root': Use default lsoda method and gives roots of the solution (for non-sti�

problems).

3 'discrete': For Discrete time simulation, can solve ODE at discrete points (for

non-sti� problems).

3 'sti�': Only method which can deal with to deal with sti� problems.

Note: However, sti� ode solver is particularly for sti� problems but other canalso solve them under depression of intervals for the whole range of t or for thesegment where solution is unstable, same is explained in an example later also.

12

Page 13: Numerical Solutions to Ordinary Differential Equations in Scilab

3 Some Useful Commands regarding to ODE so-lutions:

3 ODE solvers: ode, dassl, dassrt, odedc

3 Polynomials: poly, roots, coe�, horner, clean, freq

3 Linear systems: syslin

3 Programming: function, de�, argn, for, if, end, while, select,warning, er-ror, break, return

3 Comparison symbols: ==, >=, >, =, & (and),| (or)

3 Execution of a �le: exec

3 Character strings: string, part, evstr, execstr

3 Graphics: plot, xset, driver, plot2d, xgrid, locate, plot3d, Graphics

3 Interconnected dynamic systems: scicos

Furthermore, Scilab provides several facilities for nonlinear calculations. Numer-ical simulation of systems of di�erential equations is made by the ode primitive.Many solvers are available, mostly from odepack, for solving sti� or non-sti�systems. Implicit systems can be solved by dassl. There is a number of optionalarguments available for solving ode's (tolerance parameters, jacobian, order ofapproximation, time steps etc). For ode solvers, these parameters are set by theglobal variable %ODEOPTIONS. Minimizing non linear functions is done theoptim function. Several algorithms (including non di�erentiable optimization)are available. Codes are from INRIA's modulopt library. Enter help optim formore a more detailed description.

(Reference: http://www.scilab.org/doc/intro/node51.html)

4 Stability of a solution and Sti�/Non-sti� prob-lems

4.1 Stability

Let us take dy/dt = ky, kεC solution of this is in the form of y = exp(kt) , thisapproaches y→ 0 as t→ ∞ when Re(k)<0. If numerical solution exhibit thisnature then called A-stable solution and don't have stability problems.

While solving above equation by Runge-Kutta method we get yn = ϕ(h, k)ynor yn = {ϕ(h, k)}n y0, for a stable solution |ϕ(h, k)| must be <1.

13

Page 14: Numerical Solutions to Ordinary Differential Equations in Scilab

4.2 Sti� and Non-sti� problems

What's a sti� equation? No, precise de�nition exist. Operationally

dY

dx= f(x, y)

Y (x0) = Y0

is 'Sti�' if its solution by some methods requires (perhaps in a portion of aninterval) a signi�cant depression of the step size in order to avoid instabilities.

Take an example ofdy

dt= −15y

solution of this by Euler's method shows followoing plots for di�erent values ofsteps of t (i.e. h). As h goes smaller solution tends to stable condition.

Although a sti� problem can be solve by general methods of numericalsolution of ODE with a precision of step increment.

Problems other than sti� therefore those not show instability while solve bygeneral methods of Solution of ODE are Non-sti� problems, also these don'trequires more precision on step increment.

Another example of sti� equation is following linear combination of di�erentialequations as:

14

Page 15: Numerical Solutions to Ordinary Differential Equations in Scilab

and the ODE isdY

dt= AY

solution of this ODE for two values of h; h1 = 2.702703× 10−2andh2 = 2.73972× 10−2is

(References: http://en.wikipedia.org/wiki/stiff_equation,http://

www.physics.arizona.edu/~restrepo/475B/Notes/source/node16.html)

15

Page 16: Numerical Solutions to Ordinary Differential Equations in Scilab

5 Scilab Programs for solving ODEs and theirexamples

5.1 Solution to Simple ODE explicit in terms of indepen-dent variable

dy

dx= f(x)

Above can be easily solve by basic integration method like Summation ofelemental rectangular area, Trapezoidal rule, Simpon's 1/3 rd etc.

Here an examples present to show integration by Summation of elemental

rectangular area. Here area between xiand xi+1can be calculated in three ways

a. h*f(xi)

b. h*( f(xi)+f(xi+1)2 )

c. h*f(xi+1)

Above three are called Lower sum, Middle sum and Upper sum respectively.

Program 1:

//##Sfunction [I]=integration(stype,a,b,n,f)//stype is the way of integration may be 'U','M' & 'L' for upper, middle &

lower sum//a,b is the range of x for integration, n=no. of intervals, f be the function

de�ned onlineh=(b-a)/n;xset('window',1)if (stype<>'L')&(stype<>'M')&(stype<>'U') thenerror('stype must be L,M,U as string ');abort;endif stype=='L' then x=a & j=1elseif stype=='M' then x=a+(h/2) & j=2else x=a+h & j=3endA=zeros(1,n)X=zeros(1,n)Y=zeros(1,n)for i=1:nX(1,i)=xy=feval(x,f)Y(1,i)=y

16

Page 17: Numerical Solutions to Ordinary Differential Equations in Scilab

A(1,i)=h*yx=x+hendsubplot(2,2,1)plot(X,Y)title('x,y function plot')I=sum(A)B=zeros(1,n);for i=1:nB(1,i)=sum(A(1,1:i))endsubplot(2,2,2)plot(X,B) title('Integrated curve for '+stype)endfunction//##E

The function name above is given as integration and calling syntax isintegration(stype,a,b,n,f), here stype is the type of integration (Lower, Middleor Upper sum), a and b are limit of integration, n is the no. of intervals foracccuracy of result.

Example 1:

Letdy

dx= x2 + x+ 3

//**S//##Sde�('[z]=f(x)','z=x^2+x+3');getf('integration.sci');integration('L',0,5,10,f)ans =68.41875integration('M',0,5,10,f)ans =69.165625integration('M',0,5,10,f)ans =69.91875//**E//##E

Three answer shown above are for Lower, Middle and Upper sum respetively,let them call L-ans, M-ans and U-ans.

Note:

17

Page 18: Numerical Solutions to Ordinary Differential Equations in Scilab

L− ans < M − ans < U − ans

and from the exact solution we have answer as 69.166667, which is closest tothe M-ans. Why? This can be explained by �gure.

Fig 1.4 shows the plot of integrated curve of given problem, there are threecurves for each sum and so make the curve line thick.

Fig 1

Note: However, above program is correct to get answer and individual plotsbut given Fig 1 is not produce by above program. Some more programming isrequired for the same.

5.2 Solution by Euler method

as we know of the ODE isdy

dt= g(t, y)

theng(y + h) = g(y) + hg(t, y)

18

Page 19: Numerical Solutions to Ordinary Differential Equations in Scilab

oryn+1 = yn + hg(tn, yn)

Following above program for solution by Euler's method can be written as:

Program 2:

function [t,y]=Euler(t0,y0,tn,h,g)//Euler 1st order method for solving ODE//dy/dx=g(t,y)//t0 and tn are the range of t and h is the interval betymaxallowed=1e+100; //Actually it is abs(ymaxallowed)t=t0:h:tn; y=zeros(t); n=length(y); y(1)=y0;for j=1:n-1y(j+1)=y(j)+h*g(t(j),y(j));if abs(y(j+1))>ymaxallowed thendisp('Euler-warning: under�ow or over�ow')n=j; t=t(1,1:n); y=y(1,1:n);break;end;end;endfunction;

(Reference: numerical and statistical methods with SCILAB

for science and engineering, vol. 1, gilberto e. urroz)

Example 2:

//Let the function is dydt = f(t, y) = 1

2(1+y) with initial condition y(0)=-1

,from t:2 to 10//**S//##St0=1; y0=0;de�('[z]=g(t,y)','z=1./(2*(1+y))');getf('Euler.sci') //calling earlier de�ned Euler programEuler(t0,y0,tn,h,g);plot(t,y)xtitle('Fig 2-Solution plot to Example 1 by Euler method','t','y')//##E//##S

19

Page 20: Numerical Solutions to Ordinary Differential Equations in Scilab

Fig 2

5.3 A simple ODE of type dy/dt = f(t,y)

Example 3: Let us solve the problem of Example 2 again

//**S//##S�>t0=1; y0=0; //initial condition�>de�('[z]=f(t,y)','z=1./(2*(1+y))')//de�ning function�>t=1:1:10;�>y=ode(y0,t0,t,f);�>plot(t,y)�>xtitle('Fig 1-Solution plot to Example 1','t','y')//**E//##SIt can be observe that the output plots between dependent and independent

variable are similar for both the method therefore by Euler's method and ScilabODE solver.

It is di�cult to distinguish them with such simple problems. Their perfor-mance may be distinguish in case of complicated problems or in system of ODEswith large no. of iterations.

20

Page 21: Numerical Solutions to Ordinary Differential Equations in Scilab

Fig 3

5.4 Sti� type problem and its solution by other methodscomparing with sti� method

What is Sti� type of problem?

Example 4:

Let us take an example dy/dx=-1000(y-x)+2001 (whose exact solution isy1(x)=-exp(-1000x) and y2(x)=x+2 )

We will plot a particular solution y=y1(x)+y2(x)=-exp(-1000x)+x+2 of givenODE

Note: In particular solution �rst part goes zero rapidly while second partproduces a straight line

Program 4:

//##Sde�('[y]=f(x)','y=-exp(-1000.*x)+x+2')//PHASE 1: Plotting exact solution for small values of xx1=linspace(0,0.01,100);y1=feval(x1,f);xset('window',0)clfsubplot(4,1,1)plot(x1,y1)

21

Page 22: Numerical Solutions to Ordinary Differential Equations in Scilab

xtitle('Fig 4.1:Plot for exact solution for small values of x','x','y')//PHASE 2:Plotting exact solution for small values of xx2=linspace(0,1,100);y2=feval(x2,f);subplot(4,1,2)plot(x2,y2)xtitle('Fig 4.2:Plot for exact solution for comparatively large values of x','x','y')//PHASE 3:Now we will see what happen when we plot the curves fordi�erent numerical solutionsde�('[Dy]=g(x,y)','Dy=-1000.*(y-x)+2001')//Call 'Euler' program for Numerical solution by Euler methodgetf('Euler.sci')//Plot the curve for di�erent increment as 0.0005,0.0010,0.0020,0.0025//For initial condition y(0)=1y0=1; x0=0;h1=0.0005; h2=0.0010; h3=0.0020; h4=0.0025;[x1,y1]=Euler(x0,y0,0.01,h1,g);[x2,y2]=Euler(x0,y0,0.01,h2,g);[x3,y3]=Euler(x0,y0,0.01,h3,g);[x4,y4]=Euler(x0,y0,0.01,h4,g);ymin=min([y1 y2 y3 y4]);ymax=max([y1 y2 y3 y4]);disp(ymin)disp(ymax)//Let us de�ne the axis propertiesrect=[0 -4 0.01 6];subplot(4,1,3)//plots to give discrete curve with di�erent signsplot2d(x1,y1,-1,'011',�,rect)plot2d(x2,y2,-2,'011',�,rect)plot2d(x3,y3,-3,'011',�,rect)plot2d(x4,y4,-4,'011',�,rect)//plots to give continuous curvesplot2d(x1,y1,1,'011','h=0.0005',rect)plot2d(x2,y2,5,'011','h=0.0010',rect)plot2d(x3,y3,3,'011','h=0.0020',rect)plot2d(x4,y4,2,'011','h=0.0025',rect)title('Fig 4.3:Plots by Euler method for di�erent value of h (increment)')//Here corresponding curves for di�erent colors are as follows//h=0.0005, color=Black//h=0.0010, color=Red//h=0.0020, color=Pale Green//h=0.0025, color=Blue//PHASE 4:Now Let us see what happen when we plot the above curveswith sti� ODE solver of Scilabsubplot(4,1,4)

22

Page 23: Numerical Solutions to Ordinary Differential Equations in Scilab

rect=[0 1 0.01 2.2]x1=x0:h1:0.01;x2=x0:h2:0.01;x3=x0:h3:0.01;x4=x0:h4:0.01;y1=ode(y0,x0,x1,g);y2=ode(y0,x0,x2,g);y3=ode(y0,x0,x3,g);y4=ode(y0,x0,x4,g);plot2d(x1,y1,1,'011','h=0.0005',rect)plot2d(x2,y2,5,'011','h=0.0010',rect)plot2d(x3,y3,3,'011','h=0.0020',rect)plot2d(x4,y4,2,'011','h=0.0025',rect)title('Fig 4.4:Plot for di�erent h (x-increment) by sti� solver of Scilab')//From the plot it is obvious that sti� ODE solver of Scilab stabilizes solutionfor x-increment=0.0005,0.0010,0.0020,0.0025//##E

Answer: - 3.0525, 5.3825

Explanation: However, program itself explains everything but still detailedexplanation is as follows:

Fig 4.1 is the plot of exact solution {y(x) = −exp(−1000x)andy(x) = x+ 2}for the smaller values of x.

Fig 4.2 gives the same solution plot for comparatively larger values of x. It isobvious from the plots that solution faces sudden changes between 0.0 and0.01.

Fig 4.3 gives the solution of ODE by Euler's Method at di�erent values ofx-increment (h), for those curves are shown with di�erent colors. Answer givenafter execution of program is the minimum and maximum value of yrespectively, comes in the solution of ODE by Euler's method (just to checkdegree of instability).

Color and their corresponding (h) curves are as follows:

Table 2

Value of regular x-increment Color of curve

h=0.0005 Blackh=0.0010 Redh=0.0020 Pale Greenh=0.0025 Blue

Apparently as value of interval increases (h) instability of curve increases.

23

Page 24: Numerical Solutions to Ordinary Differential Equations in Scilab

Fig 4.4 comes after solution of given ODE by SCILAB Sti� ODE solver at allpreviously de�ned values of h (colors of curve are corresponds to values of h assimilar to Fig 4.3).

It is apparent from the plots that sti� solver stabilize the solution but inbetter way for higher value of h.

Fig 4

(Reference: numerical and statistical method with SCILAB

for science and engineering, Volume 1, gilaberto e. urroz)

24

Page 25: Numerical Solutions to Ordinary Differential Equations in Scilab

5.5 Solution to Linear �rst order linear system of ODEs

This is example gives the idea behind how to solve system of ODE with a singleode solver

Example 5:

Let us take system of ODEs as

dy1dx

= y2 + x

anddy2dx

= −y1 + y2

with initial condition as

y1(0) = 1;y2(0) = 2;between 0 to 2 with regular increment of 0.1

Program 5:

//**Sde�('[w]=f(x,y)',['f1=y(2)+x';'f2=-y(1)+y(2)';'w=[f1;f2]'])x0=0; Dx=0.1; xn=2;y0=[1;2];x=[x0:Dx:xn];y = ode(y0,x0,x,f);plot2d([x',x'],[y(1,:)',y(2,:)'],[1,-1],'111','y1@y2',[0 -3 2 4])xtitle('ode solution to a system of ODEs in example 3','x','f(x)')pause//**EIn the Fig 5 continuous plot gives the solution y1 and the plot which is shown

in discrete pattern shows solution y2.

25

Page 26: Numerical Solutions to Ordinary Differential Equations in Scilab

Fig 5

(Reference: Youngstown state University,http://www.eng.ysu.

edu/~jalam/engr6924s07/sessions/session27/session27.pdf)

5.6 Solution to the system of Linear ODEs with help ofLaplace Transform

Let a system is asdY

dt= A ∗ Y + g(t)

where A is a n×n matrix if n no. of ODEs are there.

Taking Laplace Transform at both side

L{dYdt} = A ∗ L{Y }+ L{g(t)}

sL{Y } − Y0 = A ∗ L{Y }+ L{g(t)}

(sI −A)L{Y } = Y0 + L{g(t)}

L{Y } = (sI −A)−1Y0 + (sI −A)−1L{g(t)}

26

Page 27: Numerical Solutions to Ordinary Differential Equations in Scilab

Taking Inverse Laplace Transform at both side

Y = L−1{(sI −A)−1}Y0 + L−1{(sI −A)−1L{g(t)}}

Program 6: Following program has been made in MatLab.

//##Sfunction [Y]=LT(A,x0)[m,n]=size(A);if m>nerror('matrix must of square type')elseif m<nerror('matrix must of square type')endsyms s;S=s*eye(2,2)-A;Si=inv(S);IL=ilaplace(Si);syms t;syms C1 C2;ParticularSolutions=IL*x0'GeneralSolutions=IL*[C1; C2]//##E

Example 6: Let us consider the following problem

dy1dt

= 4y1 + 2y2

dy2dt

= −2y2

for initial conditions as y1(0) = 0 and y2(0) = 1 and 0<t<20This problem can be re-written as

dY

dt= A ∗ Y

where

A =4 20 −2

//**S//##SA=[4 2;0 -2];x0=[0 1];LT(A,x0)//##E//**E

27

Page 28: Numerical Solutions to Ordinary Differential Equations in Scilab

Answers:ParticularSolutions =y1=2/3*exp(t)*sinh(3*t)y2=exp(-2*t)GeneralSolutions =y1=exp(4*t)*C1+2/3*exp(t)*sinh(3*t)*C2y2=exp(-2*t)*C2

5.7 Solution to a Second Order ODE with constant coef-�cients

This type of ODE is discussed here, because it comes frequently in di�erentdisciplines of Engineering especially in Electrical, Mechanical and CivilEngineering.

Let us take an example of spring-mass system as shown

Let m be the mass, k be the spring constant and b be the damping constantwhich appear due to frictional losses (may be heat losses in case of ElectricalLCR circuits).

And forces corresponding to above are

F = −kx

F = −bv

28

Page 29: Numerical Solutions to Ordinary Differential Equations in Scilab

where x and v are instant position and velocity of mass respectively.

From Newton's 2ndlaw

−kx− bv = md2x

dt2

−kx− bdxdt

= md2x

dt2

d2x

dt2+k

mx+

b

m

dx

dt= 0

D2 +b

mD +

k

m= 0

which is a quadratic equation whose roots may be real distinct, real repeatedand complex roots. A particular type of roots gives the relation among m, band k or inequalities among them which is important because a particular typeof root decides the characteristic of system and its functioning, this can beseen as follows:

Program to solve above ODE

Program 7:

//##Sfunction []=dampedoscillation(m,B,k,t0,x0,v0,t1,t2)//m=mass, b=damping constant, k=spring constant, t0=initial time...//at which xo,vo are given,//t=time range for plot,//F1=-kx, F2=-bv//Di�. Equation: (D^2+(b/m)D+(k/m))x=0t=linspace(t1,t2,1000);D=poly([(k/m) (B/m) 1],'D','coe�')R=roots(D)disp('roots')disp(R)a=R(1,1)b=R(2,1)//PHASE 1: For distinct real rootsif imag(a)==0 & a<>b thenM=[exp(a*t0) exp(b*t0);a*exp(a*t0) b*exp(b*t0)]\[x0 v0]'//A & B are coe�cients in the solution x=Aexp(R1*t)+Bexp(R2*t)A=M(1,1)

29

Page 30: Numerical Solutions to Ordinary Differential Equations in Scilab

B=M(2,1)x=(A*exp(a*t))+(B*exp(b*t))v=(a*A*exp(a*t))+(b*B*exp(b*t))a=(a*a*A*exp(a*t))+(b*b*B*exp(b*t))clfsubplot(2,2,1)plot(t,x)title('x-t curve')subplot(2,2,2)plot(t,v)title('v-t curve')subplot(2,2,3)plot(t,a)title('a-t curve')subplot(2,2,4)plot(t,x,t,v,t,a)title('x-t, v-t & a-t curve at one place')//PHASE 2: For repeated real rootselseif a==b thenM=(exp(a*t0))*[1 t0;a (a*t0)+1]\[x0 v0]' //A & B are coe�cients ...//in the solution x=Aexp(R1*t)+Bexp(R2*t)A=M(1,1)B=M(2,1)x=(A*exp(a*t))+(B*t.*exp(a*t))v=(a*A*exp(a*t))+(B*(a*t+1).*exp(b*t)) a=(a*a*A*exp(a*t))+...(a*B*(a*t+2).*exp(b*t))clfsubplot(2,2,1)plot(t,x)title('x-t curve')subplot(2,2,2)plot(t,v)title('v-t curve')subplot(2,2,3)plot(t,a)title('a-t curve')subplot(2,2,4)plot(t,x,t,v,t,a)title('x-t, v-t & a-t curve at one place')//PHASE 3: For complex rootselseb=imag(a)b=abs(b)a=real(a)c=(a*cos(b*t0))-(b*sin(b*t0))d=(a*sin(b*t0))+(b*cos(b*t0))

30

Page 31: Numerical Solutions to Ordinary Differential Equations in Scilab

M=(((exp(a*t0)))*[cos(b*t0) sin(b*t0);c d])\[x0; v0]//A & B are coe�cients in the solutionx=Aexp(R1*t)+Bexp(R2*t)A=M(1,1)B=M(2,1)x=((A*cos(b*t))+(B*sin(b*t))).*exp(a*t)v=(exp(a*t)).*(((a*A+b*B)*cos(b*t))+((a*B-b*A)*sin(b*t)))a=(exp(a*t)).*((((a*a*A+b*a*B)*cos(b*t))+((a*a*B-b*a*A)*sin(b*a*t)))+......(((-b*a*A-b*b*B)*sin(b*t))+((a*b*B-b*b*A)*cos(b*a*t))))// Note that in all above three equation 'a' i.e. the real part of the rootshas the role for damping similarly 'b' i.e. the imaginary part of roots...//has the role for frequency or say angular frequency=bclfsubplot(2,2,1)plot(t,x)title('x-t curve')subplot(2,2,2)plot(t,v)title('v-t curve')subplot(2,2,3)plot(t,a)title('a-t curve')subplot(2,2,4)plot(t,x,t,v,t,a)title('x-t, v-t & a-t curve at one place')endxset('window',5)clf subplot(3,1,1)plot(x,v)title('v(vertical axis)-x(horizontal axis)')subplot(3,1,2)plot(v,a)title('a(vertical axis)-v(horizontal axis)')subplot(3,1,3) plot(x,a)title('a(vertical axis)-x(horizontal axis)')endfunction;//##E

Now we will see characteristics of system by their response plotsfor three cases

3 Real distinct roots

3 Real repeated roots

3 Complex roots

31

Page 32: Numerical Solutions to Ordinary Differential Equations in Scilab

Fig 6

Explanation: To plot above �gures following of m, b and k have been taken

Table 3

Root type m b k Roots

Real distinct 2 4 1 -0.2928,-1.7071Real repeated 2 4 2 -1,-1Complex 2 4 50 -1±4.8989795 i

32

Page 33: Numerical Solutions to Ordinary Differential Equations in Scilab

Assume Fig 6 a matrix of 4×3 then the �rst row plots the position vs time(x-t), velocity vs time (v-t) and acceleration vs time (a-t). Second, third andforth rows gives velocity vs position (v-x), acceleration vs velocity (a-v) andacceleration vs position (a-x) plots respectively.

Conclusions from the plot:

3 If damping constant is not zero then all motion decays.

3 In case of both real root cases motion is only decaying not oscillatory.

3 To make motion oscillatory roots must be complex which concludes

b2 < 4mk

this gives an inequlity between damping constant, mass and springconstant.

3 In the complex root case when damping constant b 6= 0, oscillatory motiongoes on reducing which is obvious from all last plots of �rst, second andthird rows.

3 In case of oscillatory motion acceleration is always proportionate to posi-tion of massive body.

5.8 Solution to Higher order non-homogeneous ODEs withconstant coe�cients

Dny +n−1∑j=0

ajDjy = R(x)

or

Dny = −n−1∑j=0

ajDjy +R(x)

Example 7: Let the problem is

d4y

dx4+ 3

d3y

dx3− 2

d2y

dx2+ 5

dy

dx+ y =

x2

2or

d4y

dx4= −3

d3y

dx3+ 2

d2y

dx2− 5

dy

dx− y +

x2

2

for initial conditions at x=0

D3y = −1, D2y = 0, Dy = −1,y = 1

33

Page 34: Numerical Solutions to Ordinary Differential Equations in Scilab

This problem can be re-written as

d

dx

u3(x)u2(x)u1(x)y(x)

=

−3 2 −5 −11 0 0 00 1 0 00 0 1 0

∗u3(x)u2(x)u1(x)y(x)

+

0.5x2

000

where ui(x)are intermediate function of x.

for this initial condition matrix can be written as

u(0) =

−10−11

Now above problem can be easily solve by Scilab ode solver for 0<x<10.

Let us also check here is sti� ode solver is required for a non-sti� problem oralready stabilize problem.

Program 8:

// D^4(y)+3D^3(y)-2D^2(y)+5D(y)+y=(x^2)/2, 0<t<10clft0=0;v0=[-1 0 -1 1]';A=[-3 2 -5 -1;1 0 0 0;0 1 0 0;0 0 1 0];t=t0:0.5:10;de�('[Dv]=f(x,v)','Dv=A*[v(1);v(2);v(3);v(4)]+[(x^2)/2;0;0;0]')v=ode(v0,t0,t,f);subplot(5,1,1)plot(t,v(4,:))xgrid(5)xtitle('solution to the 4th order non-homogeneous ODE ...(constant coe�cient), Abscissa-time',�,'y')subplot(5,1,2)plot(t,v(3,:))xgrid(5)xtitle('solution to the 4th order non-homogeneous ODE...(constant coe�cient), Abscissa-time',�,'Dy')subplot(5,1,3)plot(t,v(2,:))xgrid(5)xtitle('solution to the 4th order non-homogeneous ODE...(constant coe�cient), Abscissa-time',�,'(D^2)y')subplot(5,1,4)plot(t,v(1,:))

34

Page 35: Numerical Solutions to Ordinary Differential Equations in Scilab

xgrid(5)xtitle('solution to the 4th order non-homogeneous ODE...(constant coe�cient), Abscissa-time',�,'(D^3)y')yprim4=-3*v(1,:)+2*v(2,:)-5*v(3,:)-v(4,:)+(t.^2)/2;subplot(5,1,5)plot(t,yprim4)xgrid(5)xtitle('solution to the 4th order non-homogeneous ODE...(constant coe�cient), Abscissa-time',�,'(D^4)y')pause

0 1 2 3 4 5 6 7 8 9 10−20

020406080

100120

solution to the 4th order non−homogeneous ODE (constant coefficient), Abscissa−time

y

0 1 2 3 4 5 6 7 8 9 10−20

020406080

100solution to the 4th order non−homogeneous ODE (constant coefficient), Abscissa−time

Dy

0 1 2 3 4 5 6 7 8 9 10−80−60−40−20

0204060

solution to the 4th order non−homogeneous ODE (constant coefficient), Abscissa−time

(D^2

)y

0 1 2 3 4 5 6 7 8 9 10−160−140−120−100

−80−60−40−20

02040

solution to the 4th order non−homogeneous ODE (constant coefficient), Abscissa−time

(D^3

)y

0 1 2 3 4 5 6 7 8 9 10−120−100

−80−60−40−20

02040

solution to the 4th order non−homogeneous ODE (constant coefficient), Abscissa−time

(D^4

)y

Fig 7

(Reference: numerical and statistical method with SCILAB

for science and engineering, Volume 1, gilaberto e. urroz)

35

Page 36: Numerical Solutions to Ordinary Differential Equations in Scilab

6 Miscellaneous Problems

6.1 Predator-Prey model

Model describes the interaction of two species in an eco-system when they areisolated from others. Here we will discuss growth rate of Fish and Shark whenthey don't interact with other species (assumed). In this situation ratechanges will follow relations given below

Growth rate of �sh=Rate at which �sh born-Rate at which �sh are eaten bysharks

Growth rate of shark=Rate at which �sh turned into sharks-Rate at whichshark die without �sh

Now

Rate at which �sh born∝F

Rate at which �sh are eaten by sharks∝FS

Rate at which �sh turned into sharks∝FS

Rate at which shark die without �sh∝S

where F and S are instant population of Fish and Shark respectively. So, wehave

dF

dt= αF − βFS (1)

dS

dt= εβFS − γS (2)

with the initial conditionsF (0) = F0

S(0) = S0

where

F0 and S0 are initial population at time t=0 (relatively).

α :growth rate of �sh in absence of shark (1/years)

γ :death rate of sharks in the absence of their prey i.e. �sh (1/years)

β :death rate per encounter of �sh with sharks (1/sharks/years)

36

Page 37: Numerical Solutions to Ordinary Differential Equations in Scilab

ε :e�ciency of turning predated �sh into shark (shark/�sh)

From above equations, it is apparent that

1. In absence of sharkdF

dt= αF

F = F0eαt (3)

Thus population of �sh increases exponentially.

2. In absence of �shdS

dt= −γS

S = S0e−γt (4)

Thus population of �sh decreases exponentially.

Non-dimensionalization:

Non-dimensionalization of equations is a process to make all termsdimensionless. Bene�ts of this are described later

If we nondimensionalize according to

F ∗ =F

F0

S∗ =S

S0

t∗ = αt

putting this in equations 1 and 2, we get

dF ∗

dt∗= F ∗ − βS0

αF ∗S∗

dS∗

dt∗=εβF0

αF ∗S∗ − γ

αS∗

if we write

a =βS0

α

b =εβF0

α

37

Page 38: Numerical Solutions to Ordinary Differential Equations in Scilab

c =γ

α

Then equations can be re-writtem as

dF ∗

dt∗= F ∗ − aF ∗S∗ (5)

dS∗

dt∗= bF ∗S∗ − cS∗ (6)

with initial conditions

F ∗(0) = 1

S∗(0) = 1

So, bene�ts of non-dimensionalization

Equation becomes easy by reducing no. of undetermined constants.

Initial condition are not undetermined for solution of this ODE.

6.1.1 Predator-Prey problem solution by Euler's method

Program 9: Program for the Solution of the above problem.//##Sfunction []=PP(Alpha,Beta,Gamma,Epsilon,t,Dt,F0,S0)//Note: t must be in years (absolute, not by transformation) and...//Dt must be in terms of monthsa=Beta*S0/Alpha;b=Epsilon*Beta*F0/Alpha;c=Gamma/Alpha;t=t*Alpha;Dt=(1/52)*Dt;//Since Dt is given in terms of weeks, so converting it to yearsDt=Alpha*Dt;t=0:Dt:t; //t here is the vector from 0 to t multiplied by Alpha//We have {dF^{*}}/{dt^{*}}=F^{*}-aF^{*}S^{*} and...//{dS^{*}}/{dt^{*}}=bF^{*}S^{*}-cS^{*} as transformed equations//Above equations can be re-written as dy1/dt=y1-a*y1*y2 and...//dy2/dt=b*y1*y2-c*y2//Now the RHS of both above equations are assumed as f1 and f2d=size(t); e=d(1,2);f1=zeros(1,e);

38

Page 39: Numerical Solutions to Ordinary Differential Equations in Scilab

f2=zeros(1,e);y1=zeros(1,e+1);y2=zeros(1,e+1);y1(1,1)=1;y2(1,1)=1;f1(1,1)=y1(1,1)-a*y1(1,1)*y2(1,1);f2(1,1)=b*y1(1,1)*y2(1,1)-c*y2(1,1);for i=1:ef1(1,i+1)=y1(1,i)-a*y1(1,i)*y2(1,i);f2(1,i+1)=b*y1(1,i)*y2(1,i)-c*y2(1,i);y1(1,i+1)=y1(1,i)+Dt*f1(1,i);y2(1,i+1)=y2(1,i)+Dt*f2(1,i);endy1max=max(y1);y2max=max(y2);y1min=min(y1);y2min=min(y2);Fmax=y1max*F0Smax=y2max*S0Fmin=y1min*F0Smin=y2min*S0disp(Fmin, Fmax, Smin, Smax)disp(Fmin)disp(Fmax)disp(Smin)disp(Smax)if y1min < y2min thenp=-y1minelsep=-y2minendif y1max > y2max thenq=y1max+0.1*y1maxelseq=y2max+0.1*y2maxendr=(max(t))/Alpha;rect=[0 p r q];t=t/Alpha;subplot(2,1,1)plot2d(t,y2(1,1:e),5,'111',�,rect)plot2d(t,y1(1,1:e),11,'111',�,rect)xtitle('Fish and Shark population Vs time','time',...'Shark(S/S0-Red),Fish(F/F0-Blue)')subplot(2,1,2)plot(y1(1,1:e),y2(1,1:e))

39

Page 40: Numerical Solutions to Ordinary Differential Equations in Scilab

xtitle('Shark Vs Fish relative population plot',...'Fish(F/F0)','Shark(S/S0)')endfunction//##E

Example 8: Following are the results come from the solution by Euler'smethod for given values of

α = 0.7, β = 0.007, γ = 0.5, ε = 0.3, t = 50, F0 = 200, S0 = 50

Table 4

Time step(weeks) Fmin Fmin Smin Smax

1.00e+00 58 654 30 2265.00e-01 79 543 40 2062.50e-01 90 501 45 1911.25e-01 95 483 47 1846.25e-02 98 474 48 1813.13e-02 99 470 45 1801.56e-02 100 468 49 1797.81e-03 100 467 49 178

Conclusion:

1. As steps goes smaller, answers tends to stabilized values.

2. It is aapprent from the plots that as time steps goes smaller solution tendsto cyclic solution with invariable cycle amplitudes.

Here, Fish and Shark relative population plot with time and their phaseportrait for three values of time steps 1.00e+00, 6.25e-02 and 7.81e-03 aregiven.

40

Page 41: Numerical Solutions to Ordinary Differential Equations in Scilab

Fig 8

However by Euler' method solution of Predator-Prey problems are possiblebut for accurate result (i.e. cyclic curve Population Vs time, should be ofconstant amplitudes or Predator Vs Prey population plot should be thin innature) time step should be su�ciently less and while doing such simulation, ittakes a longer time than usual and sometimes due to limited stack size notgives the desired result.

(Reference: Stanford University, http://fluid.stanford.edu/

~finger/teaching/numerical_methods_02/tutorials/tutorial2.pdf)

41

Page 42: Numerical Solutions to Ordinary Differential Equations in Scilab

6.1.2 Predator-Prey problem solution by Scilab ODE Solver

Program 10://##Sfunction []=PPS(stype,Alpha,Beta,Gamma,Epsilon,t,Dt,F0,S0) //Here stype

is the method by which...//solution is going to be taken and it may be 'adams', 'rk', 'rkf', 'sti�' etc.a=Beta*S0/Alpha;b=Epsilon*Beta*F0/Alpha;c=Gamma/Alpha;t=t*Alpha;Dt=(Dt/52)*Alpha;t=0:Dt:t; y0=[1;1];t0=0;de�('[w]=f(x,y)',['f1=y(1)-a*y(1).*y(2)';'f2=b*y(1).*y(2)-c*y(2)';'w=[f1;f2]'])y=ode('stype',y0,t0,t,f);t=t/Alpha;subplot(2,1,1)plot2d([t',t'],[y(1,:)',y(2,:)'],[11,5],'111','Fish@Shark',[0 -0.5 50 5])title('Fish and Shark population Vs time')subplot(2,1,2)plot(y(1,:),y(2,:))xtitle('Shark Vs Fish relative population plot','Fish(F/F0)','Shark(S/S0)')endfunction//##E

Above Predator-Prey problem has been also solved by adams, rk, rkf , sti�method and conclusions after them are as follows:

1. All these methods are able to give �ne results even for a time step of 1 week.

2. Problem is not of sti� type because for a same time step solution bymethod other than sti� method and solution by sti� method are similar.Solution is already stabilize in nature so there is no need for sti� solution.

3. It has been observed that for larger time steps (for eg: 1 year) plots are nonsmooth and similar for all method, one of this i.e. by rk method is given in Fig10.

4. Plots in Fig 9 are given for adams, rk, rkf and sti� method with time stepof 1 week.

42

Page 43: Numerical Solutions to Ordinary Differential Equations in Scilab

Fig 9.1

Fig 9.2

43

Page 44: Numerical Solutions to Ordinary Differential Equations in Scilab

Fig 10

6.2 Lorenz �ow and Lorenz equation

The Lorenz equation was published in 1963 by a meteorologist andmathematician from MIT called Edward N. Lorenz.This is a model for some ofthe unpredictable behavior which we normally associate with the weather.

The Lorenz equation is commonly de�ned as three coupled ordinarydi�erential equation like

dx

dt= σ(y − x)

dy

dt= x(τ − z)− y

dz

dt= xy − βz

where

44

Page 45: Numerical Solutions to Ordinary Differential Equations in Scilab

where the three parameter σ, τ , β are positive and are called the Prandtlnumber, the Rayleigh number, and a physical proportion, respectively. It isimportant to note that the x, y, z are not spacial coordinate. The �x isproportional to the intensity of the convective motion, while y is proportionalto the temperature di�erence between the ascending and descending currents,similar signs of x and y denoting that warm �uid is rising and cold �uid isdescending. The variable z is proportional to the distortion of verticaltemperature pro�le from linearity, a positive value indicating that thestrongest gradients occur near the boundaries.�

Program 11:

//##Sfunction []=Lorenz(stype,Sigma,Tou,Beta,x0,y0,z0)//Let for convenience xset('window',4)clfa=Sigma;b=Tou;c=Beta;de�('[w]=f(t,u)','w=[a*(u(2)-u(1)); u(1).*(b-u(3))-u(2); u(1).*u(2)-c*u(3)]');t0=0;t=0:0.01:50;u0=[x0 y0 z0]';u=ode(stype,u0,t0,t,f);subplot(3,1,1)plot(t,u(1,:),�,'t','x')subplot(3,1,2)plot(t,u(2,:),�,'t','y')subplot(3,1,3)plot(t,u(3,:),�,'t','z')xset('window',2)clfplot3d3(u(1,:),u(2,:),u(3,:))title('Phase portrait of x,y,z')endfunction//##E

Example 9: Lorenz Equation is famous for its drastic dependency on initialconditions and parameters σ, τ, β.

We will take here three examples by changing parameters to see their e�ect.

1. σ = 10, τ = 28 and β = 8/3 (which is the classical example).The initialcondition of the system is (x0, y0, z0)= (3,15,1).

2. σ = 5, τ = 28 and β = 8/3 (which is the classical example).The initialcondition of the system is (x0, y0, z0)= (3,15,1).

45

Page 46: Numerical Solutions to Ordinary Differential Equations in Scilab

3. σ = 10, τ = 100 and β = 8/3 (which is the classical example).The initialcondition of the system is (x0, y0, z0)= (3,0,1).

Conclusions:

1. For all rk, rkf, adams solution are similar.

2. Fig 11 shows how solution changes drastically with variation in parameterand initial conditions.

Fig 11

(Reference: http://planetmath.org/encyclopedia/lorenzEquation.html)

6.3 Curve �tting with Scilab for Data analysis purpose

Curve �tting is �nding a curve which has the best �t to a series of data pointsand possibly other constraints. This section is an introduction to both inter-polation (where an exact �t to constraints is expected) and regression analysis.Both are sometimes used for extrapolation. Regression analysis allows for anapproximate �t by minimizing the di�erence between the data points and thecurve. Technique to �t set of data in a curve (or polynomial) is based on min-imizing their sum of square of di�erence between experimental data and dataprovided by considered polynomial.

46

Page 47: Numerical Solutions to Ordinary Differential Equations in Scilab

Here a program has been made without using Scilab readymade curve �ttingfunctions. Program can �t up to �ve curve at a time and shoes their plot atone place for analysis purpose. Function curve�tting given below requiresthree input these are vector of independent variable, vector of experimentaldata and a vector which may have size up to �ve and contains degree ofpolynomials on which curve has to be �tted.

As the result of executing program it gives the coe�cient of individual termsof a polynomial. Program also gives the error plot for each �tted curve andvalue of sum of squares of di�erence between experimental and value providedby plot.

y = a0 + a1x+ ax22 + a3x

3 + a4x4........

Program 12:

//##S//let k be the degree of the polynomial//Fundamental equation A*a=Bfunction []=curve�tting(x,y,D)xset('window',1);clf//let us �rst de�ne how many elements are there in Dp=size(D);q=p(1,2);//##PHASE1: Getting Asubplot(6,2,1);plot(x,y)xgrid(#)title('DATA CURVE')m=size(x);//n actually gives the no. of elements in the vector x or y n=m(1,2);for l=1:q // starting of this for loopk=D(1,l)A=zeros(k+1,k+1);for j=1:k+1for i=1:k+1A(i,j)=sum(x.^(i+j-2))endend//##PHSAE2:Getting BB=zeros((k+1),1);for i=1:k+1;B(i,1)=sum(y.*(x.^(i-1)))end//##PHASE3:Getting 'a' the coe�cient matrix

47

Page 48: Numerical Solutions to Ordinary Differential Equations in Scilab

//'a' is the desired coe�cient matrix shows a0,a1,a2...// in the �tting polynomiala=(A\B)';disp(a)//##PHASE4:Ploting curve by di�erent solutions//c & d be the �rst & last value of vector xc=x(1,1);d=x(1,n);x1=linspace(c,d,50);//getting the smooth value of xx2=x1';//getting transpose of x1//we have made x1 because to get a smooth curve of resultant polynomialx3=zeros(50,k+1);// an assumed matrix for further operation//we going to make x3 a matrix having �rst row as...//1,x2.^2,x2.^3.... for �rst value of x2, similarly second row...//will be for second value of x2, so in the above manner we...//will get a matrix having its row as 1,x2.^2,x2.^3....//now if any of the row of this matrix multiply with 'a'...//& suppose then give a vector then sum of that vector...//element will be the corresponding y2(or say y3 here) for x2x3(:,1)=1;x3(:,2)=x1';for i=1:k+1;x3(:,i)=x2.^(i-1)endy3=zeros(50,1);for i=1:50y3(i,1)=sum(a.*x3(i,:))end//de�ning y4 as calculated from result polynomial according to 'a' matrixsubplot(6,2,(2*(l-1)+3))plot(x2,y3)xgrid(3)title('CURVE FOR DEGREE='+string(k));//PHASE5:To get the value of y corresponding to given x for resultant poly-

nomialx4=zeros(n,k+1);for i=1:k+1;x4(:,i)=x'.^(i-1)endy4=zeros(n,1);for i=1:ny4(i,1)=sum(a.*x4(i,:))end

48

Page 49: Numerical Solutions to Ordinary Differential Equations in Scilab

//PHASE6:To get the error curve for corresponding plot,...//i.e. plot between (ye-yr) & x. where ye is the experimental... //value and yr is the real valuez=y'-y4;z1=z'.^2;z2=sum(z1);z3=sqrt(z1);b=[k,z2];subplot(6,2,2*(l+1))plot(x,z3)xgrid(3)title('SUMOF SQUAREOF DEVIATIONS FOR THIS ERROR CURVE='+string(z2));ylabel('DEGREE OF CURVE='+string(k));end // end of �rst for loopendfunction;//##E

Example 10.1: Let us try to �t the known data for a circle of radius 5 centeredat origin.

Producing data//**S�>de�('[y]=f(x)','y=sqrt(25-x.^2)')�>x=-5:0.1:5;�>y=feval(x,f);//**ENow �tting the generated data for polynomial of degrees 1,2,3,4, and 5 by

using the program 12.It is apparent from the plots second and third degree curves are more or less

representing the circle.The answer came from program are as follows:

Degree Coe�cients Sum of square of deviations

1 3.9,-1.6D-17 142.872332 5.2,1.0D-16,-0.2 7.03249853 5.2,-2.5D-17,-0.2,8.5D-18 7.03249854 5.0,2.0D-16,-0.1,-3.0D-18,-0.01 1.84513985 5.0,-6.0,-0.1,1.1D-15,-0.01,-4.0D-17 1.8451398

49

Page 50: Numerical Solutions to Ordinary Differential Equations in Scilab

Fig 12.1

From the above plot conclusion can be made that while approaching tohigher degree plots although sum of square of deviation (sum of least squares)reduces but along with this smoothness of the curve is also reduces, which areopposite to each other for a desired result in industry. So one should go withthe optimize result.

Example 10.2:

Similar thing has been done a Gaussian curve for σ = 0.9 ,xmean = 5andthus the Fig 12.2 came out concludes that no �tted curve able to represent theGaussian curve.

50

Page 51: Numerical Solutions to Ordinary Differential Equations in Scilab

−10 −5 0 5 10 15 200.000.050.100.150.200.250.300.350.400.45 DATA CURVE

−10 −5 0 5 10 15 20−1.0−0.8−0.6−0.4−0.20.00.20.40.60.81.0 CURVE FOR DEGREE=1

−10 −5 0 5 10 15 200.000.050.100.150.200.250.300.350.400.45SUM OF SQUARE OF DEVIATIONS FOR THIS ERROR CURVE=2.8021607

DE

GR

EE

OF

CU

RV

E=1

−10 −5 0 5 10 15 20−0.06−0.04−0.020.000.020.040.060.08 CURVE FOR DEGREE=2

−10 −5 0 5 10 15 200.000.050.100.150.200.250.300.350.40SUM OF SQUARE OF DEVIATIONS FOR THIS ERROR CURVE=2.3957277

DE

GR

EE

OF

CU

RV

E=2

−10 −5 0 5 10 15 20−0.06−0.04−0.020.000.020.040.060.08 CURVE FOR DEGREE=3

−10 −5 0 5 10 15 200.000.050.100.150.200.250.300.350.40SUM OF SQUARE OF DEVIATIONS FOR THIS ERROR CURVE=2.3957277

DE

GR

EE

OF

CU

RV

E=3

−10 −5 0 5 10 15 20−0.05−0.04−0.03−0.02−0.010.000.010.020.03 CURVE FOR DEGREE=4

−10 −5 0 5 10 15 200.000.050.100.150.200.250.300.350.400.45SUM OF SQUARE OF DEVIATIONS FOR THIS ERROR CURVE=3.0490262

DE

GR

EE

OF

CU

RV

E=4

−10 −5 0 5 10 15 20−0.020−0.015−0.010−0.0050.0000.0050.0100.015 CURVE FOR DEGREE=5

−10 −5 0 5 10 15 200.000.050.100.150.200.250.300.350.400.45SUM OF SQUARE OF DEVIATIONS FOR THIS ERROR CURVE=3.1182013

DE

GR

EE

OF

CU

RV

E=5

Fig 12.2

6.4 Solution to ODE where analytical is solution is di�-cult

Example 11:Consider a problem

dy

dt=

2 + 18t+ 68t2 + 180t3 + 250t4 + 250t5

y2

for initial condition y(t=1)=0, and 0<t<24.Here we will solve this by Scilab ODE solver.

6.4.1 Solution of Example 11 by Scialb ode solver

//**S

//##S

de�('[z]=g(t,y)','z=(2+18*t+68*t^2+180*t^3+250*t^4+250*t^4)/(y^2)')

t0=0; y0=1; tn=24; h=0.1; t=0:0.1:24;

y=ode(y0,t0,t,g); //We have already de�ne f(t,y) in previous solu-tion.

plot(t,y)

xtitle('Solution plot to Example 11','t','y')

51

Page 52: Numerical Solutions to Ordinary Differential Equations in Scilab

//##E

//**E

0 5 10 15 20 250

200

400

600

800

1000

1200

1400

Solution plot to Example 11

t

y

Fig 13

6.5 Modeling and Simulation of a Pressure wave generator

(One of the KVPY mentorship holder work on the same project in the Refrig-eration Lab at Department of Mechanical Engineering of IIT Bombay duringKVPY summer camp 2009. We have model the system and simulate for opti-mize result).

since there are spring attached (not shown) in the system for restoring pur-pose and it has found that cylinders also behave like spring, so if we have havecombined spring constant as k, then natural frequency of the system

w0 =√k/m

where m is the mass of the moving part of the system.In this derivation damping forces due to friction and others are assumed to

be zero.Since a current carrying coil is suspended in the magnetic �eld, so a Lorentz

force appear as

52

Page 53: Numerical Solutions to Ordinary Differential Equations in Scilab

Fl =2πrnBi0

m(L− x)sin(wt)

wherer =radius of coiln =no. of turns per unit length of coilB =Magnetic �eld produce by Magnetic corei0=Amplitude of supplied AC current to coilL =Length of the coil inside magnetic core at steady or mean statex =Position of the moving part (or piston) at any timew =Angular frequency of the AC current

while balancing these force we have the di�erential equation as

d2x

dt2+ w2

0x =Bi0m

(L− x)sin(wt)

ord2x

dt2+ {w2

0 +2πrnBi0

msin(wt)}x =

2πrnBi0m

Lsin(wt)

Leta = w2

0

b =2πrnBi0

m

So we have equations as

d2x

dt2+ {a+ bsin(wt)}x = bLsin(wt)

Above things are for ideal conditions, in practical we have one more term inthe equation as

d2x

dt2+ {a+ bsin(wt)}x =

b

2(2L+ hg)sin(wt)

where hgis the height of air gap between coil and magnetic core.To solve this di�erential equations in Scilab we can re-write them as

dx1

dt= x2

anddx2

dt= −{a+ bsin(wt)}x1 +

b

2(2L+ hg)sin(wt)

Following program have been made to solve above di�erential equations

53

Page 54: Numerical Solutions to Ordinary Differential Equations in Scilab

Program 13:

//##Sfunction []=mech1(n,r,B,w,i0,m,v0,t0,tn,Dt,hg,k,w0,L)if length(hu)<>length(w0) thenerror('length of w0 and lv must be same')abort;endt=t0:Dt:tn;p=length(w0);a=(w0)^2; b=B*(i0)*n*2*%pi*r/m;de�('[z]=f(t,x)','z=[x(2);-(a+b*sin(w*t))*x(1)+(b/2)*(hg+2*L)*sin(w*t)]')t0=[0; 0];x=ode([0 v0]',0,t,f);xset('window',k)clfsubplot(2,1,1)plot(t,x(1,:))xtitle('Position Vs time plot','time','Position(x)')subplot(2,1,2)plot2d(x(1,:)',x(2,:)')xtitle('Phase plot between velocity and position','Position','Velocity')endfunction##EIn the program v0 is the initial condition for the velocity, t0 and tn are start

and end time for solution, Dt is the time increment for time range, k is the�gure window no. on which we want the current solution plot.

For ideal conditions of manufacturing the solution plot should have sinusoidalpattern, which depends upon all input parameteres.

Simulation for the above has been done for following parameters (all valuesare given in their corresponding SI units) to approach ideal conditions and thecorresponding solutions are plotted in Fig 13:

(a)n=12000m−1,r=0.02m,B=0.5T,w=314rad/sec,

i0 = 2amp,m=0.03kg,v0=0.25m/sec,t0=0sec,tn=25sec,

Dt==0.05sec,hg=0.01m,k=0,w0=250rad/sec,L=0.1m.

(b)n=12000m−1,r=0.02m,B=0.5T,w=314rad/sec,

i0 = 2amp,m=0.03kg,v0=0.25m/sec,t0=0sec,tn=25sec

,Dt==0.05sec,hg=0.01m,k=1,w0=350rad/sec,L=0.1m.

(c)n=12000m−1,r=0.02m,B=0.5T,w=314rad/sec,

i0 = 2amp,m=0.03kg,v0=0.25m/sec,t0=0sec,tn=100sec

,Dt==0.05sec,hg=0.01m,k=2,w0=330rad/sec,L=0.15m.

54

Page 55: Numerical Solutions to Ordinary Differential Equations in Scilab

Fig 14

Fig 13 clearly explains how changes in parameters can change the solution.

7 Demerits and di�culties in Scilab and sugges-tion for improvement

(Scilab has been compared with MatLab for same problems and tasks. How-ever, it is found that Scilab has some feature better than Matlab but here onlydemerits and di�culties found are shown for its development).

1. It is limited to the developer community and open source users. It needsadvertisement and implementation in various disciplines of Engineeringand Science for better feedback and development.

2. The implementation of some �eld especially studied ODE is quite simpleand readymade functions are available. The program crashes after 4-5function implementations or when no. of iterations are large. This hasbeen especially seen during implementation of a Chemical EngineeringODE of sti� type.

3. Scilab has a very poor help browser as compared to its competitive soft-ware packages. While searching by some string, mostly Scilab only looksfor matching strings in the topic title only and not inside the topic also.The help contains neither a categorical listing of functions nor an exten-sive search. It does not feature tutorials or a Getting Started tool. Theonline help available is also limited and not many tutorials are available.

55

Page 56: Numerical Solutions to Ordinary Differential Equations in Scilab

4. Scilab has week GUI in command, Editor and other windows while com-paring with Matlab. While error for something wrong in Editor window,Scilab only shows at which line it is and not shows the column position,for complicated functions sometimes it becomes di�cult to �x it. Simi-lar case is with brackets in the Editor window, at any moment it doesn'tshows desired animation for paired brackets.

5. Limited no. of toolboxes availability (if available then di�cult to access)lacks Scilab. For example a basic toolbox for computation of Laplace andInverse Laplace Transform which comes frequently in Electrical, Mechani-cal, Chemical Engineering disciplines. The spectrum of topics dealt with,even in the contributors page is not large.

6. Many times it crash or hang or shows 'stack size exceeded' for large no.of iterations.

7. A good timer function is not available for comparative studies. Example:comparison of Runge-Kutta, Fehlberg's Runge-Kutta, Adams-Bashforthand Sti� methods for the solution of ODEs.

8. Scilab don't have symbolic solution environment that means readymadefunctions like sin, log, sinh etc. which reduces its capacity to solve sym-bolic equations. Di�cult to de�ne functions with symbolic terms, in themanner we de�ne polynomial by 'poly' command. Example

−− > y = poly([2, 43, 4], x,′ coeff ′)

−− > derivat(y)

−− > ans = 43 + 8x

Now how to derivate this

y = cosx+ eaxlnx

similar thing is for integration.

9. Frequently while loading �les it hangs and request for unnecessary time.

10. While looking for help regarding plot or scicos related commands, helpbrowser doesn't show visual graphic example like plots and scicos model.

56

Page 57: Numerical Solutions to Ordinary Differential Equations in Scilab

Summary and Conclusion

The purpose of the present investigation was to study an optimizeapproach for solution of a particular category of ordinary di�erentialequation. However, almost all type of ordinary di�erential equationcan solve by all given methods but our concern is on two points �rstis the simulation time for numerical solution and the second is thetime step required for a desired accuracy of solution. In general fora particular method time taken for computation increases as timestep (or may be independent variable step in some cases) reduces.Comparative study has done by keeping one of this constant andother as variable. It is found that although Euler's method cansolve problems but simulation time required by it is usually more orsay time step should be less in this case, especially in case of sti�category problem it takes large time as compared to other methods.On, other hands in this study methods other than Euler's methodall methods are found to more or less similar (Note: Higher Engi-neering problems are not taken in this study they may distinguishthese methods) until unless problem is not of sti� type. In the sti�category problem it is possible to solve them other methods but sim-ulation time are very high for a desired accuracy which is found tobe highest in case of Euler's method, Sti� solver stands best herein terms of simulation time, time step and performance of machine.Meanwhile time of above work some other task related to main workdone for example curve �tting, solution of ode by Laplace TransformTechnique which concludes that Scilab generates interactive plots atone place for a better analysis but it should be equipped with someessential toolboxes. The main conclusion of the approach is thatScilab is capable to lead everyone but needs a sincere and successivedevelopment for this achievement. Also Scilab is capable to solve dif-ferent kind of ordinary di�erential equations and their system whichregularly comes in industry. The important consequence is beingthe Scilab free of cost and open source so that can be use easily andsometimes it is faster than other software packages.

57

Page 58: Numerical Solutions to Ordinary Differential Equations in Scilab

References

1. http://www.physics.arizona.edu/~restrepo/475B/Notes/source/node16.html,http://en.wikipedia.org/wiki/sti�_equation2. numerical and statistical methods with SCILAB for science and

engineering, vol. 1, gilberto e. urroz3. Youngstown state University, http://www.eng.ysu.edu/~jalam/engr6924s07/sessions/session27/session27.pdf4. Stanford University, http://�uid.stanford.edu/~�nger/teaching/numerical_methods_02/tutorials/tutorial2.pdf

5. http://planetmath.org/encyclopedia/lorenzEquation.html

58