Wednesday, February 8, 2012

2.7

The "divide and average" method, an old-time method for approximating the square root of any positive number a can be formulated as x=(x+a/x)/2.
For this problem, we wrote a function

function [ sqrroot ] = fp27( a )


tol = 1.0E-5;
if (a>0)
    
     x = a/2; 
    while(1==1)
      y = (x+a/x)/2;
      e = abs((y-x)/y);
      x=y;
      if (e<tol) break;
    end
    end
    
    sqrroot = x;
else
    sqrroot = 0;
end

end

which can be implemented for verification as follows

EDU>> fp27(4)

ans =

     2

EDU>> fp27(9)

ans =

    3.0000

EDU>> fp27(16)

ans =

    4.0000

No comments:

Post a Comment