Appendix and Index
Appendix and Index
Solution of Linear
Systems by
Matrix Methods
-__--- -
OVERVIEW OF MATRICES
A matrix is a rectangular array of elements arranged in rows and col-
umns. If the matrix contains in rows and n columns, the matrix is said
1.0 be of size in x a. The element in the ith row and jtii column of the
matrix A is denoted by 07. For example,
is a 4 x 3 matrix.
Types of Matrices
Matrices may belong to one of the many types discussed here.
1.Square Matrix A matrix in which rows in is equal o columns a.
2. identity Matrix A square matrix in which all the diagonal elements
are one and other elements are zero. That is
a1 for i=j
a ,, = 0 for ij
Numerical Methods
[1 2
A=13 "
[5 6
then,
AT 11 3 5
2 4 6
It is clear that AT is obtained by interchanging the rows and the columns
of A.
6. Zero Matrix A matrix in which every element is zero.
7. Equal Matrix A matrix is said to be equal to another matrix if and
only if they have the same order and the corresponding elements are
equal. That is,
matrix A = matrix B
if = b i, for all i audi,
Matrix Algebra
We can perform only three operations, namely, addition, subtraction and
multiplication on the matrices. The division, although not defined, is
replaced by the concept of inversion discussed later.
Two matrices A and B can be added together (or subtracted from each
other) if they are of the same order. Then
sum C = A + B
can be obtained by adding the corresponding elements. That is,
c 1— a0 +b v for all i and
Similarly,
difference E A - B
can be obtained by subtracting the corresponding elements. That is,
= a0 - b v for all i and
Solution at Linear Systems by Matrix Methods
a ll a 12 a13
Al a 31 a 22 1(23
=
1 a 32 a33
and so on. That is, the minor of a particular element is the determinant
that remains after the row and the column that contain the element
have been deleted.
The cofactor of an element is its minor with a sign attached. The
cofactor d, of an element a0 is given by
d0 = ( _ 1)t "
The value of the determinant of a matrix can be obtained by expanding
the determinant by cofactors. This is done by choosing any column or
row and determining the sum of the product of eac i element in the
chosen row or column and its cofactor.
Solutn of Urear Systems b y Matrix Methods 509
Ad joint Matrix
If d, is the cofactor of the element o, of the square matrix A, then, by
definition, the adjoint matrix of A is given by
ac(A)
Where
H l 22
[d d2
Inverse of a Matrix
If 3 and C are two n x n square matrices such that
BC CB = I (Identity matrix
then, B is called the inverse of C and C the inverse of A. The common
notation for inverses is B ' and C 1 . That is.
B B =I
C -1 C = I
The concept of matrix inversion is useful iii solving linear s ystems of
equations.
Similarly,
af - cd
cxc - bd
IQ NumercoI Methods
c a c
fe
XL = and x2=
czb a
Id e Id e
12
10 -i] -12-30 423
X' - 3 -2-12 14
4
12 -1
2 121
4 101 20-48 28
X2 -==2
2 3I -14 14
4
U a12
a 21 a22
A
a, 1 0n2
Solution of Unear Systems by Matrix Methods 5.11
5,
X= x :2 B=
XrJ
0 0 0 ... ii
Therefore,
A-'AX=IXX
is the solution of the system of equations and is obtained from
= GB
If we know the inverse of the matrix A, we can obtain the solution vector
X by past-multiplying it by B.
The inverse A' 1 of a square matrix A exists, if and only if, A is
nonsingular (i.e. det A 0). A' 1 is the matrix obtained from A by replac-
ing each element a j, by its cofactor d and then transposing the resulting
matrix and dividing it by the determinant of A.
adj(A)
C-A
det A
where adj(A) is the adjoint of matrix A and is given by the transpose of
the cofactor matrix of A.
Then
adj(A) = DT
where
d1, d, 2 ... di,,
d2, d 22 ... d2
d, 42 ... d
J.2 Numerical Methods
21 1
Given, A 1 -1 1 and B=O
[7j
42 -3 4
M
" -- I- 1 d11 = 1
-3
M12=1 _13j=_7
=7
j3 = -1^M =6 =6
M2 = =-5 d21 = 5
M = .H_io = -10
21
Mn4 2 0
I19
M31= =2
2J4
1 ifl1 32
(/33 -3
17 6
D 5 -10 0
2 -1 -3
15 2
AdjA_DT = 7 -10 -1
6 0 -3
1 5 2
15 15 15
A'=C=--
15 15 15
6
15 15
[7
B0
[4
We know that X = CB and therefore
1 =-L + o + _ 1
15 15
X2
15 15
+ 0 -- =2
15 15
a 11 (112 11n 1 1 0 0
0 22 a2fl 0 1 0
a, 0 0 1
If we carry out Gauss-Jordan elimination using the first row as a pivot
o-' we get
L° 0n2
an,, a n, n I
When we repeat the process using the second row as the pivot row, the
result is
This elimination process, if continued for all the it rows, yields the final
result as follows:
Fi 0 0 ... 0
o 1 0 .. 0 8 I a2,l
o o 1 - oa
a,,. 1 n?i41 .fl+rL
O 0 0 ...
Find the inverse of the coefficient matrix of the system given in Example
A2 using Gauss-,Jordan elimination technique.
21 1100
Augmented A = 1 -1 1 0 1 0
4 2 -3 0 0 1
Pivot row-1
Pivot row2
= 1cjb1 tr],...,n
i-I
Note that ci, = of augmented A in the final step.
Key Terms
Adjoint matrix Inverse matrix
Coefficient matrix Minor
Co factor Nonsingular matrix
Column vector Row vector
Cramer's rule Square matrix
Determinant Trace of a matrix
Equal matrix Transpose matrix
Identity matrix Zero matrix
APKNOIX
Solution of
Polynomials by
Graeffe's Root
Squaring Method
-
x1 =
x2 =
Xj =
Now, let us repeat the procedure for finding the roots of p 1 y ). Consider
a third polynomial
P2(z) -p i (y) p1(-y)
= (5 - 1)i.z 16Xz - 81) (B.3)
The roots of Eq. (8.3) are
1 (= y1) -• = x) x1
= 16 (= V)2
Y2 x) --------
z=8l(=y) - - =x) ---. y3(
Iteration 2 Iteration I
That is, after the second iteration, we can estimate the roots of original
equation p 3 x) from the relation
Z1 = (X) 2 =x, i=1,2,3
1-
Suppose we have done the squaring process k times and the roots of the
final equation are r 1 , then
r -x =-(x)' (8.4)
Remember that we never have p 0 (x) in factored form as given in
Eq. (8.1), but the result is the same.
Now, let us consider a third degree polynomial in standard form as
P OW = ax3 + a2x 2 + a 1 x + a 0 (B.5)
Then,
p1(y) = -p 0(-x) p(x)
= ((7 3x 3 + u2x 2 + a 1 x + o,) (a 3 x - a 2 x2 + a 1 x - a0)
= a32
X - (a - 2a 1a3)x4 + (a - 2a0a 2)x - a02
Numerical Methods
where
Y x2
and
b3=+a
b2 .- - 2a 1 (1 3 )
= + (a 2 2aa) (B.7)
L bo TL_____
We can thus show that for a general polynomial of degree n,
p 0 (xj = ax + a, - n 1 + + a0
after first squaring process,
r
b,z - -( a 2a /7,, -
ja,:i±2a,,u,,_4
This process can be repeated replacing 'a' values by 'b' values in Eq.
(13.9) each time. Let, us suppose that our final equation after k iterations
(i.e. squaring k times) is
+ B 0 = (J
4 B- (B. 10)
Assuming that the roots of Eq. (BIll) are now more widely separated,
we have
1y11>>Iy2I>>Iy3 ... >>yfl
Then,
Yi
B.
B,, 2
Y2
1fl-I
B0
Y,
That is.
B1
yi ----.--,i=1,2,...,n
i+1
(R.11)
Solution of Polynomials by Graeffes Root Squaring Method
Thus,
E
x = 2 k th root of y = 2t)1_ (B.12)
vi B
The m -'vantage of Graeffe's root squaring method over other meth-
ods is th it does not require any initial guessing about roots. The
method is also capable of giving all the roots but the limitation is that
the polynomial should have only real coefficients.
Difference Operators
and Central Difference
Interpolation
Formulae
—--— --------
INTRODUCTION
In Chapter 9 we have already discussed briefly the application of finite
differences for interpolating the function values. Here we consider again
the finite differences of functions and discuss in detail various operators
used on them. We also discuss here some of the central difference formulae
used for interpolation.
-- MM_FINITE DIFFERENCES
Suppose we have a function, f(x), whose values are known (or tabulated
at a set of points x 0, i i , x9,.., x. Let us denote the function values f(x0),
fx,) by 10.11...../. The difference between any two consecutive
function values is called the finite difference. The difference in function
values
fix1 - fL = + ( Cl)
is k.nown as the first forward difference at x = x. We may denote this
first diflrence at .v = x1 as
Li1
where A is an operator called the forward thffererwe operator.
Difference Operators and Central Dffefence Interpolation Formulae 5M
= [14 a- 3f 2 + /+ -- t
F vf=_1j
where V is an operator called the backward diffrenee operator.
The kth backward difference of fix) at x = x is defined by
V fV ( Vf)VfV h f I (C,6)
Forward and backward differences introduce asymmetry. Sometimes we
may need formulae which are symmetrical about the points of interest.
Such formulae are based on central differences.
The difference in function values
(C.7)
is known as the first central difference of at x x1 . This is denoted by
(C.8)
where a is called the central dtffere;we operator.
The kth central difference at x x is defined as
Note that if the function values are only known at x 1 , x2....., x,, then
f(x 112) is indeterminate and therefore 5f(xi ) is not computable. However,
we can evaluate 5 2f(x) as follows:
S L_ O ,in — T1 •1P2
Numerical Methods
= + - - + t;. 1
(CdO)
2
In general, we can compute 3 kf, for all positive integers h,
DIFFERENCE OPERATORS
We have seen three difference operators, namely, forward operator A,
backward operator V, and central operator 6. We consider here some
more operators that are often used in the manipulation of interpolation
formulae.
Shift Operator
We have an operator known as ,slu/i or thsphicernent or translation
operator denoted by E. The displacement or shift operator is defined as
LE t 1 (CII)
E kf=/ C.12)
If the values of x1 are equally spaced such that
* - X = h
then
=Xi +h
Eq. (C.12) may he written as
1? fl x ) =Pxi+ kh) C.13)
Inverse Operator
An operator opposite of E is known as inverse operator and is defined as
E'f(x) = g(x) (C.14)
Note that
Eg(x) = EE-'f(x) = f(x)
Eg(x) = g(x + It)
Then
g(x -f h) = f(x)
Therefore,
g(x) f(x - It)
That is,
(C. 15)
Similarly.
Ef(x)=J(x —kIt) (C. 16)
Difference Operators and Central Difference interpofation Formulae
Averaging Operator
The averaging operator p is defined as
(C.17)
That is,
/if(x)=[f(x +.k)+f(x
)]
RELATIONS BETWEEN THE OPERATORS
The difference operators are related to one another in a number of ways.
We consider here a few of them.
Therefore
Lii] (C.20)
Similarly, we can show that
E 1 =V
.( /'
ö f( x = / X + - f X -
=Ef(x)
Therefore,
5= E" E E 112 A E 1 ' 2 V (C.21
Similarly, we can show that
(C.22)
E- E*
\Ve know
. + V (E U
Th en,
+V
Example C.2.
- V =E- 1) -(1-E1)
R 2 +
Av=(E-1)(1-E:l
= E--2 + E
Therefore
-
Example C.3
Show that S2 = E2 -- 2E + I
= (E - 1) (E --1)
- 2E + 1
Difference Operators and Central Difference Interpolation Formulae
Prove 82 V
- E1°12
82 = EE 1 '
= E + E' 2
- V r'(E-1)--(1—E1)
Hence,
1. p2 =1+_ or
2.
VA
3.
FORMULAE
We can now form a difference table with the values f(x) on either side of
as shown in Table C.!.
Table C.l Central difference table
x f First Second Third Fourth
L (Jiffer( . m ilif/i.'ren.re diff'renn diffiir.nce
2/? 12
of-312
- h / AL2 = h
I Al I = f2 Af26 f- Il)
A1, 2
To - = Sf
I A = f=
2
Af 1 =
L*2h 12
The entries in the table are related using the relation between A and ö
Operators. We know that
S
and therefore we can show that
= (
i;2 = 2
Ef =
Similarl y , we can prove for all the entries.
We present here the following central diflrence interpolation formulae
which use differences close to the centre of the table.
1. Gauss forward formula
2. Gauss backward formula
3. Stirling formula
4. Bessel formula
5. Lap]ace- Everett formula
f(x)=f0 +i12f +
3!f0 +... (C.23)
where
a=x0+ph or
= Ef 1 (1 + z)f = Alf- +
= i 1f 1 + ' f-.1 and so on.
Substituting for Afo, if0........e above equivalents in Eq. (C.23) and
after simplification, we obtain
f(X)=fL .
+ (P) 2 11+ ( ) 3f +( P " ) A4f +...
(C.24)
where
m(m—l)(m-2) ... (rn—n+1)
Stirling Formula
Stirling formula is obtained by taking the average of the two Gauss
formulae. Therefore, adding Eqs (C.24) and (C.25) and dividing by 2, we
obtain
0 f-i L2
f(x)=fo + P
1) 2 —_14
f-i f-2
1-2 +--- (C.26)
+
M Numerical Methods
Equation (C.26) is known as Stirling formula, Note that Eq. C.26 in-
volves the means of the odd' differences just above and just below the
central line and even' differences on the line. To use this formula, p
must satisfy the condition
2 <p 2
Bessel Formula
Bessel formula is a modified form of Gauss forward formula, which is
given below.
We know
O
Af = f1 - f0 and, therefore, f) f1 (C.28'
= 'ff0 - then, = - (C.2)
Similarly,
= - E5f_2 (C.30)
Now, we rewrite Eq. (C27) as
p(p—l)21
+Al + (C.31)
= fo f + p( j — 1) (A2 f0 + 2 f )
p — A) P (p - 1)
(A3f1)+... (C.32)
3!
Equation (C.32) is called Beacl formula. Note that the Bosse] formula
involves odd differences below the centre line and averages of the even
differences on and below the central line.
Difference Operators and Central Difference Interpolation Formulae ¶
Observe that when p = - 1all odd order differences vanish and we get
1 fO' Mf.2+A4f_1
2 f(x) k(fo+f1)_ iI
8 ) 128 2
5 LVf_3+AJf_2
14 2 C.33)
Laplace-Everett Formula
Again consider the Gauss forward forrnua
p(p- 1) (p L1)p(p_1)
f(x) - fçj + + A"! + , - A 3 f-i '... ( C.34)
W: elifluhlaLe die add diiThreticei rou Eq. (C34) tue result vill give
us the Laplace-Everett form i1a. Vve inow
= f1 -
= Au0 - Af
A 5f A4f1 --
and so on.
Substitutin g these in Eq. (C.34) and rearranging the terms, we get
1tIiiii4
P or 1-p=q
and simplifying, Eq. (C.35) becomes
Key Terms
Averaging operator Forward difference operator
Backward difference Gauss backward formula
Backward difference operator Gauss forward formula
Bessel formula Inverse operator
Central difference Laplace-Fverett formula
Central difference operator Shift operator
Displacement operator Stirling formula
Forward difference Translation operator
M0 7 APPE"Ix.
C Programs
—T.
INTRODUCTION
; programs are basically made of functions. As we know, a function is a
unit of a program that performs a particular task. A C function is similar
to a subroutine in FORTRAN. A function begins running when its name
is used in the program.
All C programs need a main function which is named as
niainU
Therefore, the programs in this appendix begin with the main function.
Since the main function does not use any arguments, its name is followed
by a set of empty parentheses.
Ever ything inside a C function is enclosed between two curly brackets.
like C..). The left curly bracket signals the beginning of the function and
the right one signals the end of the function.
Some features of C that are dist-inctIy dif1irent from FOPTR.\N aie
A Cee-form language and tlt-isfiur vc nay follow any torn
of statements that may please us.
• A comment or remark can he inserted anywhere that a space can
appear in a C program provided it is preceded by /@ and followed by
• C language does not have STOP and END statements. While the
closing bracket } represents the "END" of a function, STOP may be
replaced by invoking the exit() function available in C.
• Unlike FORTRAN. all variables and functions that return values
must explicitly be declared for their types.
jut ,,d,l); /* deciarinq integer variables .
tijrt X, y, JO1 / *declori ng r:ai varabs.. /
• C supports what are known as preprocessor directives #include
and #define. The #include directive is used to include in the
program library functions and other files. We may use the #deflne
directive to define constants and functions that are used in the
program.
• C does not support any operator for exponentiation. Instead, it uses
a function pow(x,y) to compute x.
• C uses square brackets to represent arrays variables, like, a[ij.
b[i]j], etc.
• Unlike FORTRAN, C array elements are numbered from ZERO,
not ONE. That is, the array u{3] will be represenled in the memory
as alOI, al 1], and el2].
• C uses an operator & known as address operator to read the values
from the keyboard. We may use this operator to obtain the address
of a variable in the memory. For example, & x gives the address of
the location of x.
• C defines as the modules operator. This operator divides the first
operand by the second and gives the remainder, (not the quotient)
as the result.
• C defines another operator known as "star operator to define a
pointer. The statements
:I. S
FORTRAN TO C CONVERSION
rJ FORTRAN programs in the text have been translated almost line
by line using C equivalents given in Table D.l
Table D.1 C equivalents
FORTRAN Statements C Equuaients
INTEGER int
REAL float, double
I >ARAME'I'ERS (iVI 100 /tdefine M 100
I NTRINS1C inclod(, cmath,h>
IIEAD( ') statement scanf{ j statement
WRITE ( ,) statemei1 printfl) statement
lu iiction subprograms Preprocessor macro definition
Statement number Label name
(IOTO <number> goto <label>
COTO inside a loop break or continue
STOP inside a program exit( function
IF( ... )THEN...
IF...) TI LEN ... ELSE, if (...) ... else
1)0 CONTINUE
.. for (i
EN I)
C Programs
Table 132'Contd.)
Pruiare \Nu rrie
TRAPE1 This program integral-es a given function using
the rapeodal rule,
22 SIMS1 Tins prugruol iritegraLes a given function using
the Sin- ore 'H rule.
1; .:rut Rb inthgration by
bisecting the imervals N times.
24 TRAPE2 This plugram 0: ''r'tc: t. ubu) aeud function us-
ing the trapez :1
23 8MS2 C rf3iis program integrate tabiiiated function u-
ing the Simuons 1/3 rule. If the number of seg-
mcnls is odi, the trapezoidal ruic is used for the
lest siieflt.
23 EVILERThis program estimates the solution of the first
order differep ti.ut equation y ftx, y) at ihe
given pOifl usa- Eulort; method.
1TEUN )rograaiThis solveS LbO first Q!ier differential
equation /L vi .15110 the Hiuns method.
PtLYCL- This oeu5rum eoe.'es 1 ii' ;hfI'ereiia! cquatoa of
type v = fix. ') hy pnlon method.
11JNGF4 This program computes the ohithri of ' first order
difThrential equation of t ype y' - fix, y) using
the / th order RunyeKi'tta method.
'30 MILSIM ThHs program ( ,Ives the first order diftereni i1
equation y fix, yi using the Milne-Smmpac;n
met hod.
ot'Jr;-U:S in C :Itd Lirc no! avriaIea in F'O'.
v!uts fthe. -
tiir "t i1ua'.r:Y tr y tod.:vr lop It t'iieA\ i'
Program 1 POLY
- '--.- -------------------. *
* Main p: ocioam
Pc:graTo HOLY eval.laLe:e e ç:C tnoni1 of degree n
* .it any po.rit X -. r q Ice ia: :5 LUiC
-- -------- *
* ----- - ------ ---
* SuLrouL1::3 cuec
* horrier *
* -- - - - - - - - - - - - - - - - -- - - - -------- - - ---
*
* Variables used *
* r - qceC jt
a - 2\ecny o or ,'ii-.----. :o-: t _ceCnLS
* x - P: ut of ova iat inn
p - Vale of p(lyIiOrnCc.5 a x*
*
* Constants used *
* NIL
--- ---- ---- .* /
AM Numerical Methods
main(
t; 7* Local variables */
float p;
p - aln];
for(i=n-l;i>=o;j-
p = px + a[iJ;
return(p);
Program 2 BISECT
---------- .--*
Main program
* A
This program finds a root of a nonlinear
equation using the bisection method -
*
Functions invoked
Macro F(x) a
* ---------------------------------- ------------------ *
*
* SuhroutneS used
* - ------------------ ------------------------------------ *
*
* variables used
* *
a - Left endpoint of interval
*
b - Right endpoint of interval
* *
S - Status
* *
root - Final Solution
*
Lourit -- Murnber of :teaions done
* -------------------------------------*
*
* Constants used
*
* EPS - Error bound
-*
-------------
#include <math.h>
#define BPS 0.000001
#defioe F(x) (x)*(X)4(X)_2
main(
j Ot s, count;
float a.broOt;
printf("\n")
printf('SOLUTION BY BISECTION METHOD \n");
printf(\n*)
prntf('Input starLing values \n";
scanf("%f %f" ,&a,&b)
/*Ca ll i r g the subroutine bin() !
if (s0
printf('\fl")
printH"StartirLg points do not bracket any root \n);
prinf(" (Check whether they bracket EVEN roots \oA);
printf('\n)
Numerical Methods
else
1* ------------------- ----------------------
(J;
return; /* Progiam terminated *7
else
Bisect the interval and locate the root iteratively
count = 0;
= 1;
'root = xO;
ret-u un;
j f(i*fO < 0)
C Programs
x2 = xO;
else
xl xO;
fl
*root = (xl+x2)/2.0;
return; /* Iteration ends *1
else
*count = A co t ut 1:
goto begin;
Program 3 FALSE
*
A
* Main progiam
* This program find-, a root of a nonlinear equation *
* by false position method *
* -- ----- ----- -------------------------------- - -------*
* Funcl:ions. invoked *
* Macro F(x)*
* --------------------------- --- ----------. ------------*
* Subroutines used *
* fal() *
* --- ------ --------------------------------- ----------- *
* Variables used *
* a - Left endpoint of inteai *
b - Right endpoint of intervoL *
* - Status *
* root - Final solution *
* count - Number of iterations completed *
* - --------------------------- ------------ -- -------*
* Constants used *
* EPS - Error bound *
* - - - - - - - - - - - - - - - - - - - - - - - - - ------------ - A /
4Q Numerical Methods
#include <math.h>
#define EPS 0.000001
#define F(X)
main(
mt S, count;
float a,b,root;
printf ("\n)
prinrf('SDLTTTON flY FALSE POSTTTON 1 7T1[OD \r"J; ,1
printf ('\n'
t
printf("Input s arting values \n°)
ccanf('%f %f, &a, &b);
P Calling the function fal() */
fal(&a,&b,&s,&root,&count);
if (s==0)
printf("\n)
print f('Starring points do not bracket
any root \n)
printf ("\n)
else
prnLfY'\n')
pr.intf("Root = %f \n', root);
printt('F(root) = %f ri', F(root));
printf('\n NO. OF ITERATTONS = %d \n, count-.);
if(fl*f2 > 0)
= 0;
return; /I Program terminated
else
*count = 1;
begin: /4 Iteration begins */
xO = xlflk(x2xl)/(f2fI)
f = F(xO);
if(ff2 < 0)
x2 = xO;
= fO;
else
xl = xO;
fl = fO;
= 1;
*root = (xl+x2)*0.5;
return; / Iteration ends *1
else
*CCUflt = * count 1;
goto begin;
Program 4 NEWTON
/ ---- ---------------------------------------------**
* Main program
* This program finds a root of a nonlinear equation *
*
* by Newton-Raphson method
Numerical Methods
* ---
- - - - - - - - *
* Functions invoked *
* Micros F(x), FD(x), Library function fibs() *
* --------------------------------------------------*
*Subroutines used *
* NTL
* --------------------------------------------- *
*Variablec. used
• xO - Initial vale of x *
• xn - New value of x *
• lx - Function value at x *
• fEdx - Value of function derivative at x
• count - Number of iterations done *
* ---- --------------- --------------------------------------- *
* Constants used *
* EPS - Error bound
* MAXIT - Maxiurn nufterof iterations permitt.ei
* ---------------------------------------------- - - ---*
include <rnath.h
#defino EPS 0.000001
#define MAXIT 20
#define F(x) (x)*(x)+().2
#define P0(x) 211 (x)+l
main(
lilt count;
fiot xO, xn, rx, tdx;
prm:t ("\n")
printf("Input initial value of x \n")
suariLV%f, &xO)
prntf ('S \*)
printf (" SOLUTION BY NEWTON RAPHSON METHOD \n");
printf(''n");
count 1;
begin: /* Iteration begins */
Lx = F(xO);
fdx = FD(xO);
xn = xO fx/fdx;
if(tahs((xn-xO)/xn) < EPS) 1* Iteration ends */
else
xO = Xr1;
count = count + 1;
if (count < MAXIT)
goto begin;
else
-------------------------------
Program 5 SECANT
1* -------------
*
* Main program *
* This program finds a root of a nonlinear *
* equation by secant method *
* -- - -- - - - - - - - - -- -- - - - - - *
* Functions invoked *
* Macro F(x) *
^
*
* Subroutines used *
* sec() *
A ------------------------
------------------------
------------
*
*Variables used *
* a - Left endpoint of interval A
* b- Right endpoint of interval *
* xi - New lett point A
* x2 - New right point *
• root - Final solution *
• count - Number of iterations
- completed *
--------------------------------------------
*------ A
* Constants used *
* EPS - Error bound
* MAXIT - Maximum number of iterations permitted
/
* --------------------------A
#include <math.h>
*define EPS 0.000001
44 Numerical Methods
*define MAX1T 50
define F(x)
rintf(\")
PLilitf (" DIVISION BY ZERO \fl);
prifltf("\flLast xl. = %t \n", xl);
prntf('\nLast x2 - %f \n", x2);
prfltt("\nNQ OF ITERATIONS = %d \n", count);
printf('\ii)
eisa if(status == 2)
prrntt ("\n')
prirtf("NO CONVERGENCE IN %d ITERATIONS \n", MAXIT);
prntt ("\n")
else
printf("\n")
printf("Ro - %f \n', root);
ntf value at roar = %f \n, F(root));
printf ("\n);
printf("NQ. OF ITERATIONS %d \n", count-);
printf (\n")
I
End of main() program */
* /
/' Defining subroutine sec(
status - 1;
return; / * Prograrr. trninauiod */
*tatus S 2
return; '* Program terminated */
*xl x2;
= x3;
fI = f2;
F(x3);
*count *count 4 1;
gc)to begin; /* Compute next approximation
else
*root x3;
*staLus - 3;
etufl1; /* Iteration ends /
Numerical Methods
I
/* End of subroutine sec()
1*
Program 6 FIXEDP
1* ----------------- -------------*
* Main program*
This program finds a root of a function using **
* the fixedp point iteration method
* - ------------ ------ *
* FunCtiOnS invoked *
* Library function fabs() and macro G(x)
* ---------------------**
* Subroutines used
* NIL--.----- *
* -------------------------------------------- *
* variables used *
* xO - Initial guess *
* x - Estimated root
* error - Relative error *
* -- - - - - - - - - - - - - - - - - A
-constants used *
* EPS - Error bound
* MAXTT - Maximum iterations allowed
* -------------------- ------
# include math.h>
* define EPS 0.000001
* define G(x) 2.0_(x)*(X)
main(
mt MAXIT, i;
float xO, x, error;
SOLUTION BY FIXED-POINT METHOD \n");
printf("\fl
printf("\fl)
printf(iflPUt initial estimate of a root \n);
scanf(%f, &xO);
printf('MaXimUIfl iterations allowed \n*);
scanf ("%d', &MAXIT);
i1-'-, 7hT.TTR OF X
--
ERROR \n);
priOttV\fl
/*IteratiUfl process begifls*/
for(ii;i<=MAXIT 4 I
x = G(xO);
C Programs MZ
void main)
.LnL n, status, i, j;
Numeca1 Methods
printf("\n")
printf('\n EVALUATION OF MULTIPLE ROOTS \n);
prir1tf(\n*)
printf(*Input degree of polynomial, n.
scanf('%d, &n);
newton(n,a,xO&status,&xr);
if (status == 2)
root[i] = xx;
printf ("\n')
end:
printf ('ENIY);
7* --------------------------------------------------*
mt 1, count;
float ix; / Value of polynomial at xO */
float fdx; 7* Value of oulynornial derivative at xO
Count = 1;
/* Compute the value of function at xO
begin:
fx =
for (i=n; i>=l ; 1--)
ix = fx * xO L1;
J Coruptc the value of derivative at xO *7
fdx = [n+1] *
for(inri>2;i- -)
dx - fdx * xO + n[iJ * (i-l)•
/ I Compute a root xr
= xO-fx/fdx;
4 sLamm_s = I;
returr:;
xO *Xr;
count = count + 1;
goto begin;
else
Q Numeiical Methods
*status -- 2;
return;
/ nd of subroutine newton() */
1* ----------------- -------- * /
/* Defining the subrou t ine dtlat() */
float h[1]J;
mt
A
Evaluate the coefficients of the reduced polyriunilal
b1n]] C);
for(i=n;i>l;i- -)
biJ = ali+lj + xr, * h[i+1 ]
/* Chdrge coefficients from b array to a array */
fox (i-l;i<-i+i;i++)
au]
/* Ind of subroutine dflat()
* /
Program 8 COMPR
* --- ----------------------- - ---------------------- *
* Main program
* This program locatc,.s all the roots, both real *
* and complex, using thf, Birstow method *
* ----------------------------------------------------*
* Functions invoked *
* NIL *
* --- - . --- - --------------- --------------------------- *
* Subroutines used
* input, bstow,q-uad,output *
* ---------------------------------------------------------*
* Variables useu *
* fl - Degree of polynomial
* *
a - Array of coefficients of polynomial
* *
uO,vO - TniLial values of coefficients of the
* quadratic factor *
C Programs
* u,v - Computed( values of coefficients of the *
* quadratic factor *
* b - Coefficients of the reduced polynomial *
* xl,x2 - Roots of the quadratic factor
* type - Type of roots (real,imaginary or equal) *
* ---- ---- ---- ---- ---------------------------- ----.------- *
* Constants used *
* EPS - Error bound
* ----------------------------------------------------* /
#include cmath.h>
lfdefine EPS O.00)OQl
#define image 1
*detine equal 2
#det Inc unequal 3
main
mt fl, ±;
float a[llJ, b(ll), uO, vU, u, v, xl, x2, dO, dl,
d2, root, type, status;
printf ("\n')
printf" EVALUATION OF COMPLEX ROOTS \n">;
prinrf ("\n")
begin:
if(ri > 2)
bstcw(n,a[1l] ,b[ll],uO,vO&u,&v,&status);
if (status 1)
d2 = 1;
dl = - U;
dO = -v;
else
52 Numerical Methods
quadlo3aL2,aI1J,&xl,&x2,&LYPe);
output ( ri type , x 1. , x2)
i
else / last root of an odd order polynomiai
rmot = -a[.j/e12];
printf("\n")
ptiriLf("Firial root = %f \n", root);
pririLf("\r");
end:
printt ("End");
(
float. d,deiu,de1vc111j;
mt count,
count S
begin:
b[n1] - a[n+l];
bin) - afn] - u0h(nl]
Lor(ln-i;j>-1;i)
b[i] - [ i] 4 uO * h[il + vU * bi.-2J;
c[ni1] = 0;
c E n ] - b[n+l1;
for(i=n-1;j>1;j_ -)
C[i] b1i-1] + u 0 * c[i-lJ t vU *
cl = c2] * c[2] - c[1 * c[3;
delu -(b121 * c[2] - b[l] *
deiv = -. (oti) * c 1 2J b[2] * c"] ) /d;
uC -i- deLi;
vU do2v;
*sta t us =
ret U 0;
UI)
vU =
couo count + 1;
got() beqin;
- else
2;
recuLL;
float 0;
= -
< raws w er
x2 =
x1
*2 - xi;
ce2. -,
&I 1 f U:iLft'i
k/
/ roul
xl = - :it (:) /
- q ) S
roc\irT;
- %f--%fj \n" l, x2
print0nooW = -j \n' xl. x2)
el/r2 iH t T o FCl11/il)
fl
printf("Root.1 =%f \n, xi);
printf("Root2 = %t \n, x2);
return;
Program 9 MULLER
/* --------------------------------------------------*
* Main program *
This program evaluates root of a polyncial using *
Muller's method *
* ----------------------------------------------------*
* Functions invoked *
* NIL *
*-------------------------- --- ------- --------------------------- *
* Subroutines used
* F(x) *
* ------------------------------------------------ - ------ *
* Variables used *
* xi,x.2,x3 - initial values *
fl,f2,f3 -- function values at xi,x2.x3 *
* aO,al,a2 - coefficients of quadratic polynomial *
hi - xi-x3
* di function difference fi-f3 *
* --------------------------------------------------- *
* Constants used *
* EPS - Error bound *
#incl.ude <math.h>
Ildefine BPS 0.000001
msin(
f = F(xl);
f2 F(x2);
f3 = Fx3):
begin:
hi = xi-x3;
Numerical Methods
h2 x2-x3;
di = f1-t3;
d2 = f2-L3;
/ Compute pa urtetors aOal,a2
aU f3;
al = (d2*hl*hldi*h2*h2) / (hl*h2* )hl-h2));
a2 (dith2d2h1)/(hk}12*h1_h2));
I Compute h */
f(ol>0 .0)
h=(-2 .C*aO)/ (al+sqrt (al*al4*a2aO)
else
h=(.2.0*aO)/(a1_Scrt(al*a4*a2*aO))
J* Compute x4 and f4
X4 = x3-1h;
fi F(x4)
else
= x2;
- f2:
t?
/4;
gote hegic;
float f;
f - x*XAx+2*x*X10X_20:
return (f);
/* End of subroutine ,)
------------------------------------------------* /
0
C Programs 537
Program 10 LEG
-- *
* Main program *
This program solves a system of linear equations *
* using simple Gaussian elimination method *
* Functions invoked *
NIL *
* ---------------------------------------------------*
* Subroutines used *
* GAUSS1 *
* ------------------------- -.------ ----. *
* Variables used *
* n - Number of equations in the system *
* - Matr:x of coefficients *
* b - Right side vector *
* x - Solution vector
------------------ ----- ----- ----- - -
* status - Solution status *
main(
mt statusn.i,j;
float a[lO] [10], bib, x[10]
printf('\n SOLUTION SY STMPLE GAUSS METHOD \n");
gaussl(rLa,b,x,&statug);
if(status 1= 0)
fCL (i1;ifl;j++)
printf("%106f", xLiJ)
Pr" ntf ('S
e se
inti k;
float- p vo, Eactt, 50111;
As:atus 0;
rocurn;
*SOatu S -
• - r;
sum = 0.0;
for(j=k+l;j<n;j+i)
Sum suxr. + a[kJ [j] * x[jJ
x[k] (b[k 1 - sum) / aCk]
return;
/* End of subroutine gussl () /
/ * ---------------------------------------------------- * /
Program 11 I..EG2
/ * ---------------------------------------------------*
* Main program
* This program solves a system of linear equations *
* using CuSsisn Elimination with part:ai. pivoting *
- - -------------- ------- -
--------------------------- -----------
* ----------------------------
*
Functions invoked
* NIL *
* --------------------------------------------------- *
* Subroutines used *
^ Gauss2 *
* --------------- --------------------------------------- *
Variables used
* - Number of equations *
* a Coefficients matrix *
* b - Right side vector
* x - Solution vector *
* ---------------------------------------- -- -------
* Constar:s used *
* *
NIL
* -------.--- I
main(
int i,j,n.
floar a 1] [10) hl0] x[l0J
scarif(%f, &b[i));
gauss2 (n,a.bx);
7' Wi -1.Lminat ci
f1ot fac:or;
for)k : l;k<=nl:Ji: )
pivot(n,a,b,k)
[or (i=k+1 i<=n; j++)
bEt] b[j_fctor*hIkj;
return;
!* End o' elimo rouLinc*7
7* - ---------------------------------------- - - - - - - - - -*
/* L)efntng subrotine pivoto)
i!L p,i,j;
float large, temp;
7* Find pivot. p */
P=
lerge = fhs(a[k] [k]
for (ik+l; i=-=ri; i++)
iI(fahs(a{i 1 [kl)>targe)
large fabsi[iJ[k!
p = 1;
temp = a[ p ] Ml
afp?[j] a[kl[j];
a[k)[jJ. temp;
temp = bip);
b[p
b[k) = temp;
return;
mt i,j,k;
float sum;
x[n] - b[n j / a[n]tnl;
for(k=n-1;k>-l;k-- )
5fl = 0.0;
tor( j =.k+l;j<rl; j++)
sum = sum - a[k][j] *
x[ k J = (b[k] -sum) / a(k}[k];
return;
Program 12 DOLIT
/ * -------------------------------------------------- *
Main program
* This program solves a system of linear equaLiorLs *
using L)olittlC LU decomposition
* --------------------------------- -- -- *
*
* Functions invoked
* *
NIL
* --------------------------------------------------*
*
* Subroutines used
* *
bUD, SOLVE
* ---------- ---- ------------- - ---------------*
* Variables used *
* *
n - System size
a - Coefficient matrix of the system *
* b - Right side vector *
* 1 - Lower triangular matrix *
* u - Upper triangular matrix
* fact - Factorization status *
* ---------------------------------------------------*
*
* Constants used
* *
YESNO
* ----------------------------------------------------* /
C Programs
* define YES 1
* define NO 0
main(
mt n, fact, ij;
1110) 110) bIb], x[lO];
float a,1 1011101, u[10] t1OJ
SOLTJTTON BY DOL1'IPLE NETHOL) \n\n");
printf("\n
/* Reed input data *1
print.f("\nWhet is size of A? \n');
scnf("%d", &n):
prmnt.fV'TyPe coefficients a(i, j ), row by row
foL (i=i; i< = n; i++)
for ( =1; j<-n; j ++)
scanf("%f", &a[iJ11);
priritf("\nTYPe vector U on one line \n);
for( =1; i<=i'l; i+)
scenf('%f", &b[i))
/ LU factoriZetiOfl *1
bud(ne,u,l,&fact)
,* p rint LU matrices
if (tact == YES)
/* Print. 13 matrix J
pr j il t f("\rINA TRTX U \n");
for(i1; j<fl;++)
for(j1; j<zrn;j++)
pntf("%15.6f u[iI
printf("\n")
/ Print L matrix
print f("\BMATRIX L \n");
for(i1; i<=rr; i+)
for(j1;j<fl;i)
printf("%15.6f 1[i)[j)) -
printf ( \n)
54 Numerical Methods
/* Solve for x /
soivo(ru,l.b,x);
print f("\nSOLUTIOW VECTOR X \n\n);
for(il; i<-n;j++)
printf (%l5.6f \n, x[i)
prinrt (" \n)
else
mt ijk;
float sum;
/* Initialize U and L motrices
for ( ini; i<=n; j ++)
ulil H] = 0.0;
1[i](jJ = 0.0;
for(i2;i<j;il.i
if (u [j I Ii] <i
*
reLuLfl;
for(i;ri4)
sum =
[or (k k= 1-1; k
sum - t [1.] lkJ u[kI ci)
[II [11 = sun' / u]j] {j
*tart S
coLumn;
/ Enu of nubLouLLfle d]
/
/* I3efnflg the subroutine solve(
] [10], tiodL
solve(int n, float u [ 10 1 110), float 11 10
b]l0], floaL x[iU1)
Lh€sOiut.Ofl vector x using the
/* Th 4 5 subroutine obt,itris
coefficients of L and 0 uaLriues
mt i,J;
Citoat simu, z 10]
/* Forward substitutiOn */
z]11 = bill;
for]i_2;i<sfl11
sum =
for (jl;j-i
sum '- sum Uii * z[]
zft] = b]i]
sum = 0.0;
for(j=i*l;J<=fl;J
*
sum - su1 ui[j
Numerical Methods
return;
Program 13JACIT
/* ------------------------------------
* Main program *
*
* This program uses the subprogram JACOBI to solve
a system of equations by Jacobi iteration meLhoJ
* -------------------------------------------------**
* F unctions invoked
*
* NIL
* -------------.- ---. - -
---------*
* Subroutines used *
JACOBI *
* --------------------------------------------------*
* Variables used *
*
a - Coefficient matirx *
*
b - Right side vector *
n - System size *
*
x - Solution vector *
*
count - Number of iterations completed *
*
status - Convergence status *
*
Constants used *
* EPS - Error bound *
MAXIT - Maxjnun iterations p ermiLted *
* --------------------------------------------------
#include zmathh>
#def j ne EPS 0.000001
#define MAXIT 100
main)
mt i,jflcOUfltStatus;
float a(lO) [10] bflOJ x{l0]
printf("\n SOLUTION BY JACOBI
ITERATION \n");
prjntf(\nat is the size n of the system? \n);
scanf('%d" &n);
prin Lf(\nInput coefficients a(i,j, row by row \n");
for(jrl; 1<=fl i++)
for (j=l;j<rn;j+4)
C Pogroms 56Z
scant("' &a[i)tiH
prir("\flIflPUt vector
foriii<+)
scanI(""'
&C000t, &statUS)
it atUS'""2)
iterations", MAXIT);
prirti("\° convergence in %d
printf ("\n\fl)
else
SOTJTION VECTOR X
printfV\°
for(11 i<n;)
printf(i5.6f" xifl d", co't);
rintf(1\nhta ofl5 = %
k/
J. End of main() program
* /
/* Defining the routine jacnhi()
n, float 5101103, Eloat blO), tlOat xllO].
jacobi(iflt
*cOUflL,
mt *status)
atiOflS us
S y"tern of a lineal
ÜS
subroutine solves a
the 3aCabi iteration method
mt j,j,key;
float sum, xOlO);
1* Initial values of
for{i- = l ; j<=n; 1+ F)
xO[fl = b[i]
7* jacobi iteration begins *7
*COUflt = 1;
begin:
key 0;
b[i1;
for(j=l j<n;j+)
Nurnecicat Methods
f ( L=j)
COflLjflue;
= stLm -- aIijijj * xOTj];
CiSC
*StdhS
tCr-_1jerj.j+)
*c(1Jrft = *CoUrlt 1;
q 0^-(D begin-
C Urn;
/ * End ur SuL:ejt no
jrCObt ( /
1* --- - ----
- -
/
Program 14 GAS IT
1*
-. ----.-.----
* Main --------- ------ +
proqrd:II
* *
flas
Program uses the subprogr GASE:iD to sov d
'st
of cj-
* by Guss-g ci iteral orz meubod
-------------------------- --- *
* *
FUnct;or1 invQkcj
* NIL *
*. *
---- .---
----------- *
I
c Programs 1
A
* Subroutines used *
* ;ASETD - -.------ *
* - - --------
* Variables used
a - Coefficient matrix *
h - Right side ve:LOr *
n Systen size *
* x - Solution vector
count - Number of iteratioflS completed *
* * status Convergence
--------.--
- status *
A
consLanLs used *
* EPS - Error bound *
MAXIT - MaximUm iteratiollS peflittCd
* ------------* /
# define MXIT 50
defic- FPS O.Q000
main)
if (statUs2)
printf("11N0 convergence in %d iterations; \n MAXIT)
printt(\fl\fl*)
else
SOLUTION VECTOR X
printf("\fl
for(il; i<=n;i++)
printf("%15.6 x[ifl;
print f\fl\tatbons = %d', count)
7Q Nu rn eocci l Methods
*
End of main() program.
- - - -
k
/
/*
Defining the routine gaseid */
gaseid(int n, float lOj Fbi, flct. hlnj, float x[bDh mt
ounL, mt *status)
/ This SUbXOLttjne solves a
of inear Lja jQr using
the c-auss-sejdel itorajcr, alquriLbjfl
mt key;
fboaL sum, x0[1OJ;
/* Ini ti a l values of x
for (il; i=n;i+ +)
xO[i) b[i] / [] [jj
/* Gaseid i teration begins */
*count 1;
begin:
key - 0;
/*
ComPutin q values of x'
fonHf I<=fl;i^)
Saui -:
fo! ( j l;j<n j^.)
if (i==j)
Continue;
sum = sum - * XOIji;
a(ij [jI
X[I] sum / a[i}[i];
if (key0)
/* Testing
for nccurç-v */
if (fabs ( x (ii -xO 11 /x[.j ) >Pi)
key 1;
J.f(*Count=._MAX1.,r)
C Programs
*ct-at1S = 2;
/* Program terminated */
return;
else
for(i=l;1ru j+)
xOi]
k cOUflt = *COUILt+?;
gate begin;
return;
Program 15 LAGRAN *
1* -------------------------- -----.
*
--mair, program 0 *
This progrdm cotpUtes the interlx)latiOl1 valor' at
specified points qiven a set of data x,intS, using **
* the Lagraflgc interpolation representation
* --------------------- *
* Functions invoked *
* NIL
* ------ .-- **
* Subroutines used *
* NIL
* --------------------------**
* Variables used *
* n - Number of data sets *
* x(i) - Data points
* f(i) - Function values at data points
*- Point at which interpolat ion is taquired **
* fp Interpolated value at XP *
* - Lagraflgiafl factor
* ----------------------- ------------ -- **
* Constants used
MX - Maximum rlumbur of data points permitted *
* ---------------------*
*define MAX 10
main(
Z2 Numerical Methods
irit n, i,j;
fio.3t X[MAXJ,f[F1AX)fp,lfsumxp;
-
Pr- ntf("\nlnput number of data points, n \n);
scanfl"%d, &n);
sum 0.0;
If 1.0;
f.or(j=l;j<r.;ji-)
j =j)
If
suir. = sum + if A
flu;
fp
printf ('\ :AGRANGIAN I NTERPOLATION \n\r)
• print 'IrLeLuuIaLed function valuc \n")
p rintf('at x=%f is %f \n", P, fp);
X
1* End of main() program
------------------------- --------------------------------
Program 16 NEWINT
/ **
* Main program *
*
This program constructs the Newton interpolation *
* I yriini ai for a given set of data points and then *
computes interpolation val ue at a specified value *
*
A
Functions invoked *
* NIL *
* Su
broutines used *
* NIL *
* ---------------------------------------
C Programs
*
* Variables used *
* Number of data points *
x - Array of independent data points A
* f - Array of funct i on values
*
xp - Desired point for interpolation
*
fp - Interpolation value at XP
*f Difference table
* coefficients of interpolation *
a - Array of *
* polynomial
* -----------------------**
* Constants used A
* NIL
* ------. .--- * /
main(
irLt j, r.;
i, xL li) ] mo] aFlOL d[1O1 [10]
float xp EP, sum
printfi (' \nlriput number of data points \ri*)
scant ( ,, %d", &n)
x and € (x). \n");
print t( II \r.lnpUt values of
printt("Dfle set on each line \n*);
for(l;1<fl
scanfV% f %f &x[i] &tiiI); (
7* Con struCt difference table *7
for(i1;1<=fli)
d'i] [l = E[l]; -
for (j2;j<-n)
for(irl; i<n-j+l; i++)
d[i]N] = (d[i+ll li-li -d[i] [j-1)) / (x[i+-l)
p1 = 1.0;
for(j=l;i<il;)
Pi = p1 (XP-x[)1);
sum = sum + atil * pi;
74 Numerical Methods
f = sum;
I' Write results */
printf('\n)
printf(' NEWTON I NTERPOLATION \n);
printf("\n)
print f('Interpo1ated value \n);
printf(t x = %f is %f \n, xp, fp);
Program 17 SPLINE
/* ------------- --------- -----------------------------
*
* Main program *
*
This program coniputes the interpolation value at
*
a specified value, given a set of table points, *
*
usixig the natural cubic spline interpolation *
Functions invoked *
* NIL *
--------------------------------------------------*
* Subroutines used *
* GAUSS
* ----------------------------------- ---------- -.---
* Vxiables used
* n Number of data points. *
*
x -- N by 1 array of data points. *
*
f - N by 1. array of function values
*
xp - Point at which interpolation is reiiirod *
*
fp - Interpolation value at xp
*
a - Array of second derivatives (N-2 by 1) *
*
d - Array representing (N-2 by 1)
C - Matrix (N-2 by N-2) representing the *
*
coefficients of second derivatives *
h - Array of distances between data points *
*
( h(i) = x(i) - x(i-l) ) *
*
df - Array of differences of functions *
* ---------------------*
* Constants used *
*
MAX - Maximum number of table points permitted *
*
- -.----- -------* /
#define 5 10
main(
C Programs 575
mt i.j,n,m;
float xfS1,f[S],a[S],dCS,C[S)[S],h1S,df[S],U[S),
xp, fp, qi ,q2, q3;
h[i] x(i)
=
df[ i ] = fCi] -
7* Initialize C matrix
tor(i2; i<n-l; i++)
tor(j=2; j<=n-l; j++)
ciii [JJ = 0.0;
in = n-2;
for(irl; j<=m; i++)
Numerical Methods
d[i] d[i+l);
for(j-l; j<=m;j++)
c(i)1
j
] = C[i+l) {j+1]
guss(m,c,d,a);
/k Compute the coefficients of natura' cubic spline
for(i=n-l;i>2;i- -)
a[i] au-11;
a[lJ = 0.0;
a[n] = 0.0;
ml ijk;
float pivot, factor, sum;
1* - Elimination begins ------------
for(k=l;k<=n-l;k+ I-)
C Programs fZl
sum 0.0;
for(j=k+l;j<=n; j±)
sum sum + aik] 1i] * xh]
x[k] = (h[k]-sumU/a1k McI;
ret urn;
Program 18 LINREG
1 *
* Main prugiam
* This program firs a line Y A + BX to a given *
* sot of data points b y the method least squares *
*___ ----------------------------------------
* FucL.ions invoked *
* Library function fabsM *
* ----------------------------------------------- ---------*
* Subroutincis used *
* NIL *
* *
Variables used *
* xy - Data arrays *
* n - Number of data sets *
* sumx - Sum of x values *
* sumy - Sum of y values *
* sumxx -- Sum of squares of x values
* su1ny - Sum of products of x and y *
* xmean - Mean of x values
* yniean - Mean of y values *
* *
a - y intnrcept of Lhe line
b - Slope of the line *
* --------------------------------------------------*
Numericni Methods
Constants used
*
* MAX -- Limit for number of daLe points
*
EPS - Error limit
* - - ------ *
#inclucle <rnath.h>
define MAX 10
ttdefine EPS 0.000001
ma in
tot in;
float x[101, yllO);
float sumx, surny, sunux, sumxy, xmean, vmeorl,
denom, a, b;
silrnx = sumx t
suiny = suniy + yti);
SUTflXX SUThXX + x[iI *
suraxy = sumxy - x[i]
enean = sumX/n;
ymean = surey/n;
cienom = n*sumxx - surex * sumx;
if(fabs(denom) > FPS)
else
----------------------------------------------------*1
Program 19 POLREG
/ * ----------------------- ------ - -------..------------*
Main program *
*
This program fits a polynomial curve to a given *
set of data points by the method of
* least squares *
* ---------------------------------------------------*
* Functions invoked *
* NIL *
----------------------------------------------------
* Subroutines used *
* normal, gauss *
* ----------------------------------------------------*
* Variables used *
* x,y - Arrays of data values *
* n - Number of data points *
ir - Order of the polynomial under construction *
* in -. Number of polynomial coefficients *
* *
c - Coefficient matrix of normal equations
* b - Right side vector of normal equations *
* *
a - Array of coefficients of the polynomial
* ------------------------------------------------------*
* Constants used *
* MAX Mamimumn number of data points *
* ---------------------------------------------------
/
#include <maLh.h
#define MAX 10
main(
mt fl,ITlp,m,i;
float
printf("\n POLYNOMIAL REGRESSION \n\n");
5M Numerical Methods
7* Reading values *7
pxintf("Input number of data points n
scanf("%d,&fl);
printf("Input order of polyn(Amial, mp L eqLiired \n);
scant ('%d" . &mp)
printf( , lnpUt data values, x and y \ri");
printf("orie set on each line \r.);
for(i=l; i 'z=n; j++)
scanf("%f %f &x[iJ.
lot l,j,k,ll,12;
for(j=lj<=m;i++)
for(k=l;k<'Th;k-+)
CPrograrns k.1
b[j] 0.0;
12 = i-i;
tor(i=1;i<n;j++)
[
b j l - bj1 iy[i] * pow(X[i]12);
return;
nd of subroutine norma] () *1
---------------------------..--.. -------------- *1
/* Defining giuss() subroutine */
gauss(inc n, float- aLM?X j [MAXL float b[MAX], float x[MAX]
tnt
t.Ioat rivot, factor, Suit;
/ Elimination begifis */
for (k'l ; k .n=n-l; k+ )
pivct ak [k
for i - k * 1; <=ri; j +,)
sum - 0.0;
for (jki ; j <=fl; J4 f)
2 Numerical Methods
sun + a[ k ] [ j] *
xk] (b[k]_sum)/a[k] [kh
return;
program 20 NUDIF
/ * -------------------
Main program
* This program cciTpUteS the derivative of a tal3ilated
* function at a specified value using the Newton**
* interpolation approach
* ------------------------- -------**
* Functions invoked *
* NIL
* ------------------------------ *
* Subroutines used *
* NIL
* -----------------**
* Variabl es used A
* n - Number of function values given *
* x - Array of values *
* f - Array of function values *
* a - ray of coefficients of Newton polynomial *
* d - Difference table *
* xp - Desired point of differentiation *
* dii - Derivative of the function at XP
* ------------------ *
* COflStantB used *
* NIL
• -------------------------------------------A /
main(
mt
float x[lo),flOI,a[10),d[b0]t101,xthm;
sum = 0.0;
tor(i1; i<=k-l; i++)
p = 1.0;
for(14 ; j<k_l; j+±)
if(i. == j)
continue;
P = p * (>cp -
sum = sum + p;
/* Write results
print f("\niJNFRlcAr DTFFTJENTTATTON USING
printf('rq w'roN POLYNOMIAL \n\n);
p rintf("DERIVATIVE at x %f is %f \n., xp,dit);
Program 21 TRAPE1
/ * ----------------------------------------------------*
* Main program k
* This program in tegrates a given function
* using the trap ezoidal rule *
**
A Numerical Methods
*
* Functions invoked *
NIL - *
* *
* Subroutines used *
* F
* ----------------**
Variables used *
* a - Lower limit of integration *
* b - Upper limit of integration *
* h - Segment width *
* n - Number of segments *
Ict - Value of integral
----- -------. A
* - ---- - --------
* Constants used
* NTT,*
* -------------------- --------
#include <math.h)
rtain( I
nt n,;
float a,b,h,SUXtt,1ct
float F(float x):
printf("\flGive initial value of x
scanf('%f&a);
printf('\flGiVC final value of x
scant ("%t", &b);
printf ("\nWhat is the segment width? \n")
scanf("%f", &h);
n (b-a)/h;
ict suxr *
printt ("\n")
tegtm0n between %f and %f \n, ab);
print f(I fl
printf(,Whefl h = %t is %f \n, h, itt);
prirtf ("\n)
float f;
f =
return (t);
Program 22SIMS1
/ **
* Main program *
This program integrates a given function *
*
using the Simpsons 1/3 rule *
**
* FU11CLions invoked
*
* Macro F(x) *
--------------------------------- ---------------------- *
* Subroutines used *
* NIL A
*
*
* Variables used
* a - Lower unit of integration *
*
b - Upper limit of integration *
*
h - Segment width *
n - Number of segments *
* ics - Value at the integral *
*
*
* Constants used *
NIL *
** /
#nc]ude <nathh
#defnp P(x) 1 - exp(-(x)/20)
main(
mt n,m,j;
float a,b,h,smjcsx fi, f2, f3;
NumedCal Methods
(b-a)/rt;
M -- r2
sun =
= a
fi -
for(i'L; j<rn;1--)
f2 = F(x+h);
- F(x+2')
.S um= sum + f + 4t2 +
ti f3;
= x 4- 2h;
rogram 23 ROMBRG
p
/ * ---------**
* Mai program *
This program perfo5 Romberg flLegrat1Orl *
g the intervals N times
----------------------
----------*
- byectifl
*---- ----------------------- *
*Functions invoked *
Library function tabs( *
* Macro F(X))
* ------------ *
Subroutines used *
* NIL
* ------------**
* Variables used
* a - Starting point of the interval *
b - End point of the inteal *
*
* h - Width of the interval
*
* n - Number of times bisection is done
*
* m - Number of trapezoids
r - Matrix of Romberg Integral values
* -------------*
* Constants used *
* EPS - Error bound
* -------------* /
C Programs MZ
#include <math.h> I
mt i,j,k,tTI,n;
float a,b,h,sunix,rrlQ] [10;
x a + (2*k_l)*h;
sum +
t
prin
%15.6f', r[i] [jJ );
f ( 1
prir.tf('\n)
/* Test for accuracy *1
if(fabs(r[j-1] [i-i) - r(i]{i)) < EPS)
/ Stop further refinement *,
NumehCal Methods
eI Se
continue;
stop:
printf ("End")
i nd of !flulfl() prograit
Program 24 TRAPE2
*
Ma).n program *
This progrnff, integrates a tabulate d function *
* using the trapezoidal rule
---------------
*
* Functions invoked *
* Library function fabs()
* -------- ------ *
* Subroutines used *
* NIL
* -----------------------------**
* Variables used *
* n Number of table point *
x - Array of independent daLa points
*
* y - Array of function values
*
- Lower lirniL of integration
* b - Upper limit of integration *
* h- Distance between points *
* nl - Position of A in the table *
* n2 position of 0 in the table *
* let - Value of integral
-----------*
*
Constants used
N11.*
* ------------------------ * /
C Programs
#include <math.h>
define MAX 15
main(
mt n, nl, n2, i;
float ab,h,suIn,ict,xiMAXJy[NAxJ;
Program 25 SIMS2
1* - ----------------------------------------.------- -- *
* Main program *
* This program integrates a tabulated function
using the Simpson's 1/3 rule.If the number of
* segments is odd, the trapezoidal rule is used *
for the last segment. *
* *
Functions invoked *
* Library function fabs() *
* ---------------------------------------------------*
Numerical Methods
*
* Subroutines used *
NIL
A
* Variables used *
* - Number of table points
*
* x - Array of independent values
*
* y- Array of function values
*
* a - Lower limit of integration
*
* h - Upper limit of integration
*
h - Distance between independent values
*
* ni - Position of A in the table
*
* n2 - Position of B in the table
*
* .l - Area computed using Simpson's rule
* 12 - Area of the last segrrcrit (by trapezoidal rule) *
*
ics - Value of integral
-------------------------------------------*
*
* Constants used *
Nib
* -- - ---- --------------------------- * /
tiinclude <math.h>
main(
mt i,n.nl,n2,'n,l;
float x[l51,yE15],a,b,h,5Ufl,iCS,1,i2
/* Reading table values *7
printf("Input number of data points \n);
scanf("\%d", &n);
printf("\nlflPut table values, set by set \n");
for(i=l; i<n;i++)
scant(%f %f, &x[iJ,&y[i]);
1* Reading the limits of integration
printf('Input initial value of x \n);
scanf("%f, &a);
printf("Input final value of x \n);
scanf("%f", &b);
printf(What is segment width? \n);
scenf(*%f, &h);
7* Computing the position of initial and final values
ni (int)(Labs(a-xtlJ}/h+l-.S);
n2 = (int)(fabs(b-x[lfl/h+l.5).
7* Testing for even intervals */
m = n2 - ml;
if (m%2 == 0) / m is even *1
C Programs 521
i2 = 0.0;
1 = n2 - 2;
else / in is odd */
7* Use trapezoidal rule for the last strip *1
i2 = (y[n2_]1+y(n2))*h/2.0;
1 = n2 - 3;
Program 26 EULER
----------------------------------------
* Main program *
* This program estimates the solution of the first *
* order differential oguation y' f (x, y) at a given *
* *
point using Ruler's method
*
*
*
* FuncLions invoked *
NIL
* *
*
* Subroutines used
* *
func()
* --------------------------------------------*
*
* Variables used
*
* x - Initial value of independent variable
* *
Y- Initial value of dependent variable
* *
xp - Point of solution
* h- Incrementa' step-size
* n - Number of computational steps required *
* *
dy -Incremental I in each step
-----------------------------*
5fl Numerical Methods
Constants used
* *
NIL
* ------------------------------------------------- --.-- * /
main(
mt 1,0;
float x,y,xp,h,dy;
float £unc(float, float);
for(il,-i.=n;i+l-)
dy = h * func(x,y);
X = X 4 h;
y y + dy;
printf("%5d %I0.6f %10.6f \n", a,x,y);
float f;
f 2.0 y/x;
return(f);
Program 27 HELJN
/ * -- - -- - - - - - - - - - -- - - -- ---- -- - - --- - - - --- - - - - - - - - - - - - - - - - - - - - - *
ma-in pxDgram
* This program solves the first order differential *
* equation y' = f(x,y) using the Heun's method *
* -----------------------------------------------------*
* _its invoked *
* NIL *
* ------ ---------------------------------------------------*
* Subroutines used *
* func() *
- -------------- - --------------------------- *
* Variables used *
* x - Initial value of independent variable *
* y - Initial value of dependent variable *
X I ) - Point of solution *
* h - Step-size *
* r Number of stops *
* - ---------------------------------------*
Constants used *
* NIL *
--------------------------.------------------------- * /
main(
mt 1,0;
float x,v,xp, h,ml,m2;
float func(float, float);
ml = func(x,y);
m2 = func(x+h,y+mlh);
X = X + Ii;
y y + 0.5*h*(xol+rn2)
594 Numerical Methods
printf('%5d %1-0. 6f 10 .6f \rV, i,x,y)
float f;
f - 2,0
*
return f
unct.IOr'S njoked *
NIL
*
S.ibrouLe5 used *
* t]C(
ft----------- ------,-- *
*
* Variables used
x - Initial value nf the independent variable
*
y - initial value of the dependent variable *
* - Point of solution
* h - incremental nep-size
* stops required
a -- Number of computational
A- -----_ ------------- *
*
* constariLs:sed *
* NIL
* - --------- ---------- -------
main(
mt j,n;
float xyxp,h,rfll, m2
C Pogrorns
ni = furic (x, v)
.3' h,y0.*hrnfl;
x = x -
y = y ' m2 -h;
p rintt':"%5d %l0.0 %10.6t \ri", i,x,);
float f;
f = 2.0 * y/x;
return(f)
Program 29 RUNGE4
/ * ------------------------------------------------------*
* Main program *
*
+ This program computes the solution of first order
* f(x,y) using *
differential equation of type y'
* *
the 4th order Runge-Kutta method
* -----------------------------------------------------*
Numerical Metfloas
* Functions invoked *
*
* Nil
* - *
*
* Subroutines used
func()
*---------------------------------------------------
*
* Variables used
*
x - Initial value of independent variable
y - Initial value of dependent variable *
* *
xp - Point of solution
*
h - Step-size
* *
n - Number of steps
* Constants used *
* *
NIL
* - ------------------------------------- -- ----------------* /
rnain(
nt i,fl;
float xy,xp,h,rni ,rn2,rn3m4;
float fiLnc(f Loa I:, float);
ml = func(x,y)
m2= func(xO . 5*h , y+O5*rnl*h);
m3= func(x+O.Yh, y+O.5*m2*h);
m4 = func(x- y+rn3*h)
CPograms 591
x x1-h;
y - y *- (ml+20 m n2 4 2 . 0 k m3 + .4) * h/6.0;
printfY'%5d %15.6f f15.6f \n", ixy);
printf( --------------------------------------\n4
/k WriLe the final value of y /
printf("\nValue of y at x %f is %f \n", x,y);
float f;
f 2.0 * y/x;
ret urrf)
Program 30 MILSIM
------*
/ k -- ------------------- --
k
k main program
* This program SOIVOS the first order differential *
* equation y ' = f(x,y) using Mime-Simpson method *
* - ---------------------------------------------------- ---
* Functions invoked *
* NIL
*
* Subroutines used
* *
func()
* --------- ------. .- -.- ---*
*
* Variables used
* x(l) - Initial value of independent variable *
* *
y(l) - Initial value of dependent variabTe
* *
xp - Point of solution
*
n- Number of steps
* h- Step size
* x- Array of independent variable
*
y - Array of dependent variable
-----------------------------------------------*
* Constants used
*
NIL
* --------------------------------------------------*
Numerical Methods
main(
mt i,fl;
float h,x[l5Jy[l5]xp,ml,m2,m3,m4,f2f3,f4,f5;
float funcfloet, float);
1* Reading initial values */
printf("Input initial values of x and y \n");
scanf("%t %f, &x[U,&y[l]);
printf("Iriput value of x at which y is required \n);
s can f("%f", &xp);
printf("Input step-size, h \n");
scanf("%f", &h);
ml = func(x[i].y[i));
m2 - tunc(x[i]--0.3'h, yci+O.5*ml*i1);
m3 = func(x[i]+O.5*h, y{i]+0.5*m2*h);
m4 = func(x[i]+h, yIiJ+m3*h);
x[i-.-l] xi +
yi-1-11 y[i] i (ml+.2.0*m2 2.0m3 f. m4)*h/6.0;
printf("\n%Sd %iOJf %l06f", i x{i+l]y[i-t-l]);
f2 = f i inc(x[i-2J, y[i-2]);
f3 = fun c(x[ i - lJ, y[i-lfl;
f4 func(x)ij, yli]);
C Programs 599
float
= 2.0 * y/x;
* return (f)
!.NUMERICAL COMPUTING
1 . Antia, 11 2v1, Auinei-c'cil Methods br Scicu(cs t.s and fr;igineers, Tata
McGraw-Hill Publishing Company, New Delhi, .1991.
2. Atkinson, L \', P J Harley and J D Hudson, Numerical Mrt!,ods
with PORTRAi\7 77. Addisori-Wc1cv Publishin g Comnaicv. 1989.
3. Buchanan, J L and P H Turner, Numerical Methods atul..4n.rztvscs,
McGraw-Hill Book Company, 1992.
4. Chapra. S C and It P Canale, Numerical. Methods tar Enguwers,
2nd Edition, McGraw-Hill Book Company. 1989.
5. Coristantinides, A, Applied Numerical Methods ad/i Personal
Computers, McGraw-Hill Book Company. 1987.
6. Conte, S I) and Carl do Boor. K/muon fur y Numerical Anal ysis, 3rd
Edition, McGraw-THU Book Company, 1981.
7. Gerald, C F and P 0 Wheativ. Applied Numerical Analysis. 5th
Edition. Addison-Wesley Publishing Company, 1991.
8. Griffith ,, D V and I M Smith, Numerical Methods /r Engineers.
OxThrd University Press. 1991.
9. Ledevrnann, W (Chief Editor), .Handbook of Applied Mathematics
(Volume lii) John Wiley &. Sons, 1981.
10. Mathews, J II, Numerical Methods /ir Mathc'mu/ics. &ienc'c and
Engineering, 2nd Edition, Prentice-Hall at India, 1994.
11. Scheid, F, Numerical Anal ysis i Schauin Series), McGraw-hill
Publishing Company, 1990.
12. Yakowit.z, S and F Szidrirovszkv, An. hrItroiuJinri. to Numerical
Computation, 2nd Edit ion, Macmidan I 'abashing Company, 1090.
Bibliography 6U1
PROGRAMMING