Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function [output, absError] = square_root(x, x1)
- %square_root Calculates an approximation of sqrt(x).
- % Approximates the sqrt(x) using iterative methods with x1 being the
- % initial starting value to iterate upon.
- % Set first iteration result to x and absError to -1.
- x_iterations(1) = x1;
- absError = -1;
- % If x or x1 are not positive integers...
- if x < 0 || x1 < 0
- % Return output = 0 and absError = -1.
- output = 0;
- return;
- end
- % While the absoulte error is still to large.
- while absError < -0.000001
- % Get the last item in the iterations list (the most recent
- % calculation).
- xn = x_iterations(end);
- % Calculate the next iteration.
- xNext = 0.5 * ( xn + (x / xn));
- % Add new calculation to the end of the iterations list.
- x_iterations(end+1) = xNext;
- % Calculate the new absoulte error.
- absError = xNext - xn;
- % Set the output to the most recent calculation (will not be
- % returned until the while loop has ended).
- output = xNext;
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement