function y = my_sqrt(x) %Use Newton's method to compute the square root of x % -The essential point to understand is that Newton's Method can % solve for r, such that f(r)=0. % % -Hence, if r is the square root of x, then f(r) = r^2-x = 0, % which gives us a function to solve for. % % First, check that x>0 if(x<0) error('my_sqrt: the argument needs to be positive'); end % Since we can't define a function in advance because we don't know % x, we need to define it inside the function, this is called an % 'inline function'. Here, we want 'x' to be just a parameter, and % the function to be a function of the variable 'r'. % % We define it as follow: function_body = ['x.^2 - ' num2str(x)]; f = inline(function_body); %For the precision of the result, we'll accept 'single-precision' %results, i.e we want the relative error between our solution %and the real solution to be less than 2^(-32), i.e we should %choose a tolerance smaller than 2^(-32) times x (not too small %if not we won't be able to converge tol = max(x * 2^(-40), 2^(-64)); %Maybe we could do better than that but an easy first guess for the %square root of x is to use x itself. y=simpleNewtonSolver(f,x,tol);