6:03 AM

Solving square root using Octave.

The GNU octave is a high level language for performing numerical computations.
It provides command line interface for solving linear and non linear problems represented using matrices.The language has all set of operations that can be performed on matrices.

The octave makes data manipulation much easier with matrices.In octave variables need not be declared and can be used directly by simply assigning the values.A matrix can be initialized as
a=[elements]
where the elements in each column are separated using a semicolon.
a=[1,2;3,4]
The size of a matrix can be found using the in built function size(matrix).
Traversing of the matrix is easy by using indexes as a(i,j).The octave enables slicing of the matrices in any way the programmer needs.
a(:,1) displays all the elements in the first row and so on.....



Square root of a number


Square root of a number can found using any of the following methods.

The simplest method is guess a number , square it and check whether it equals the provided number until you find one .A simple octave code for this is

guess=0;
while x-guess^2<0
     guess=guess+1
endwhile

the final value of the guess will be the required root.
This algorithm can be used only for perfect squares.It can be further improved by updating the guess for a small value say .001 and checking the difference as the same.


Bisection method
The number of steps involved in the above method can reduced using a bisection method.In bisection method  repeatedly bisects an interval and then selects a subinterval in which a root must lie for further processing.The octave code for performing bisection is

low=0;
high=x;
mid=(low+high)/2;
while abs(x-mid^2)>.001
        if mid^2<x
             low=mid;
        endif
        if mid^2>x
             high=mid;
        endif
        mid=(low+high)/2;
endwhile

the final value of mid will be the root.


Newton Raphson method
The number of steps involved can be further reduced by the using the Newton Raphson method.In this method one stars with an initial guess close to the root,then the function is approximated to the tangent line and the x intercept of the tangent line is computed which is a better guess for the root and can be approximated as the root.This process is iterate to find the root.The eqaution for the next guess is given by

x_{1} = x_0 - \frac{f(x_0)}{f'(x_0)} \,.











The octave code for the same can be written as.
guess=x;
diff=guess^2-x
while abs(diff)>.001
     guess=guess-(diff/2*x);
     diff=guess^2-x;

the final value of guess corresponds to the root
..................................................................................................................











0 comments: