daily pastebin goal
48%
SHARE
TWEET

Untitled

a guest Mar 22nd, 2019 53 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function [output, absError] = square_root(x, x1)
  2.     %square_root Calculates an approximation of sqrt(x).
  3.     %   Approximates the sqrt(x) using iterative methods with x1 being the
  4.     %   initial starting value to iterate upon.
  5.  
  6.     % Set first iteration result to x and absError to -1.
  7.     x_iterations(1) = x1;
  8.     absError = -1;
  9.  
  10.     % If x or x1 are not positive integers...
  11.     if x < 0 || x1 < 0
  12.  
  13.         % Return output = 0 and absError = -1.
  14.         output = 0;
  15.         return;
  16.     end
  17.  
  18.     % While the absoulte error is still to large.
  19.     while absError < -0.000001
  20.  
  21.         % Get the last item in the iterations list (the most recent
  22.         % calculation).
  23.         xn = x_iterations(end);
  24.  
  25.         % Calculate the next iteration.
  26.         xNext = 0.5 * ( xn + (x / xn));
  27.  
  28.         % Add new calculation to the end of the iterations list.
  29.         x_iterations(end+1) = xNext;
  30.  
  31.         % Calculate the new absoulte error.
  32.         absError = xNext - xn;
  33.  
  34.         % Set the output to the most recent calculation (will not be
  35.         % returned until the while loop has ended).
  36.         output = xNext;
  37.     end
  38. end
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top