Advertisement
hiddenGem

Square Root of a Number

Jun 29th, 2020
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 1.04 KB | None | 0 0
  1. %% Square Root of a Number
  2. % This code allows users to calculate the square root of a given number
  3. %   when given an initial guess
  4. clc, clear
  5.  
  6. a = input( 'Enter a positive number "a" to be square-rooted' );
  7.  
  8. while a <= 0
  9.        a = input( 'Enter number that is greater than 0 \n' );  
  10. end         %while
  11.  
  12. fprintf ( 'The value of a is recorded as: %i \n', a )
  13.  
  14. x = input( 'Enter a positive number to be the initial guess of the square root' );
  15.  
  16. while x <= 0
  17.         x = input( 'Enter a number that is greater than 0 \n');
  18. end         %while
  19.  
  20. abs_tol  = 10^-5;
  21. xOld = x;
  22. while  1
  23.    xNew = ( xOld + ( a/xOld ) )/2;
  24.         if ( abs( xNew - xOld ) < abs_tol )
  25.           break;
  26.         end         %if statement
  27.     xOld = xNew;
  28.     fprintf ( 'The current guess for the square root is %i \n', xNew);
  29. end             %while
  30. fprintf( 'The actual square root of %i is %i',a,xNew)
  31.  
  32. %{
  33. This code will print the estimate for the square root until it is in range
  34.      of the absolute tolerance
  35. The absolute tolerance can be edited in line 20
  36. %}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement