NAME PERSON LAB SECTION 3 12 pts Converting a Script to a F

NAME: PERSON #: LAB SECTION: 3. (12 pts) Converting a Script to a Function The script square root.m was presented itn lecture-it is also attached to this assignment and shown below. For this problem, you must convert this script m-file to a function m-file. Your new square_root.m function must have one input argument and one output argument. Of course, it must not prompt the user and it must not produce output to the command window. You must include a proper comment header block and you must use good programming practices. % This script computes the square root of a number % using the \"successive approximation method.\" % Geometrically speaking, the number can be considered to be % the area of a rectangle. This rectangle is successively made % into a square by increasing the length and decreasing the % width until they are the same (within a tolerance, of course) % The length (or width) is then the square root of the area A = input ( \'Enter a positive number to estimate its square root: \'); while A

Solution

% matlab code to determine square roo of a number


% This function computes the square root of a number
% using the \"successive approximation method.\"
function squareRoot = square_root(A)
   old_length = A; %initial length = A
   new_length = 1; %initial width = 1
   k = 0; % loop counter
   loop_tolerance = 0.00001;

   while abs(new_length - old_length) > loop_tolerance
       old_length = new_length;
       new_length = (old_length + A/old_length)/2;
       k = k + 1; % loop counter
   end
   squareRoot = new_length;
end

% main code, the function will be called from this main body
A = input(\'Enter a positive number to estimate its square root: \');
while A <= 0
   disp(\'Invalid entry. The number cannot be zero or negative!\')
   A = input(\'Enter a positive number to estimate its square root: \');
end
loop_tolerance = 0.00001;
% function call
squareRoot = square_root(A);
fprintf(\'The square root of %0.2f is approximately %0.6f (to a tolerance of %0.5f).\ \', A, squareRoot, loop_tolerance);

%{
output:

Enter a positive number to estimate its square root: 25
The square root of 25.00 is approximately 5.000000 (to a tolerance of 0.00001).     

Enter a positive number to estimate its square root: 46                             
The square root of 46.00 is approximately 6.782330 (to a tolerance of 0.00001).

%}

 NAME: PERSON #: LAB SECTION: 3. (12 pts) Converting a Script to a Function The script square root.m was presented itn lecture-it is also attached to this assig

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site