sol_hw2 - CE 335 Solutions to Homework 2 13 function[x err...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: CE 335 Solutions to Homework 2 13) function [x, err] = sqrt_apprx(a, err_desired) %[x, err] = sqrt_apprx(a, err_desired) %approximate the square root of a real number a %with fractional precision err_desired %using the divide-and-average method. %returns the approximate square root a %and the approximate fractional error err %take care of cases where a is zero or negative if a == 0 x = 0; err = 0; return elseif a < 0 a = -a; mult = i; %will multiply the result for -a by i else mult = 1; end %set initial value for the square root x = a; err = err_desired + 1; %ensure that iteration runs at least once %because the condition for the while loop %will start out as true %do iteration while err > err_desired x_old = x; x = 0.5 * (x + a/x); err = abs((x - x_old)/x); end %multiply result by i if input was negative x = mult * x; testing: > [x, err] = sqrt_apprx(0, 1E-4)...
View Full Document

This note was uploaded on 08/30/2011 for the course CGN 3350 taught by Professor Lybas during the Spring '11 term at University of Florida.

Page1 / 4

sol_hw2 - CE 335 Solutions to Homework 2 13 function[x err...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online