create a program to use the heron´s method to compute square roots in matlab

To create a program to use the Heron's method to compute square roots in MATLAB, you can follow these steps:

main.m
function result = heron_square_root(n, p)
% Inputs:
% - n: number for which we want to compute the square root
% - p: number of iterations for the approximation (larger p gives a more accurate result)
% Output:
% - result: approximate square root of n

% Initial guess for the square root
x = n/2;

% Iterate p times to improve the approximation
for i = 1:p
    x = (x + n/x) / 2;
end

result = x;

end
403 chars
19 lines

Here's a breakdown of the code:

  • The function heron_square_root takes two inputs: n (the number for which we want to compute the square root) and p (the number of iterations for the approximation).
  • We initialize an initial guess for the square root (x) as n/2.
  • We then iterate p times, updating the value of x using the Heron's method formula: x = (x + n/x) / 2.
  • Finally, we return x as the approximate square root of n.

To use this function, you can call it with your desired inputs:

main.m
n = 25; % Example number for computing the square root
p = 10; % Example number of iterations

result = heron_square_root(n, p); % Call the function

disp(result); % Display the result
185 chars
7 lines

This will compute the square root of 25 using 10 iterations and display the result. You can change the values of n and p as per your requirements.

gistlibby LogSnag