CodeCodeCode

ENGR132: HW05 - square_root

May 1st, 2012
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 1.39 KB | None | 0 0
  1. function [sqr_rt] = square_root(num, num_error)
  2.  
  3. % FUNCTION: Calculates the square root of a number to a user defined
  4. % level of accuracy.
  5. %
  6. % INPUTS:
  7. % 1) num: The number the user inputs.
  8. % 2) num_error: The percent error the answer can be within. (%)
  9. %
  10. % OUTPUTS:
  11. % 1) sqr_rt: The calculted square root of the number.
  12.  
  13. %Checks if input is less than zero; displays warning and calculates absolute
  14. %values of given inputs.
  15. if num < 0 || num_error < 0
  16.     warning('Cannot use negative value(s); taking absolute value.');
  17.     num = abs(num);
  18.     num_error = abs(num_error);
  19. end
  20.  
  21. %Sets the primary guess as the user's input number.
  22. guess = num;
  23. %Sets counter to 0.
  24. counter = 0;
  25.    
  26. %While loop to loop until answer is found; escapes with counter = 1.
  27. while counter == 0
  28.     %Calculates quotient.
  29.     quo = num / guess;
  30.        
  31.     %If calculated error is less than or equal to user-set error,
  32.     %escape loop.
  33.     if (abs(quo^2 - guess^2) / num) <= (num_error / 100)
  34.         counter = 1;
  35.     %If calculated error is more than user-set error, perform below
  36.     %calculations and continue with loop.
  37.     else
  38.         %Calculate average of the current guess and quotient.
  39.         av = (guess + quo) / 2;
  40.         %New guess is the average above.
  41.         guess = av;
  42.     end %If (error check) end
  43. end %While end
  44.    
  45. %Sets final guess to output value "sqr_rt".
  46. sqr_rt = guess;
Advertisement
Add Comment
Please, Sign In to add comment