Iterative Scheme-Programming Matlab

80 Views Asked by At

I don't know if this is going to seem like a dumb question, I am new to this and to matlab, but I'm trying to construct an iterative scheme in MATLAB to compute $\sqrt(b)$ for a given b>0, and program it to make tests to see if it works. The book is very vague and doesn't really say how to construct or program the scheme. But this is what I have so far:

I've set $x=1/\sqrt(b)$. Therefore $b=x^2$, $b-x^2=0$ and I set f(x)=$x^2-b$.

Therefore,

$f(x)=x^2$, $f'(x)=2x$.

I use the formula $f(x_0)+(x_1-x_0)f'(x_0)=0$, $x_1=x_0-f(x_0)/f'(x_0)$

Plugging in the values I get $x_0-(x^2-b)/2x$=$(x(2x)-(x^2-b))/2x$=$(2x^2-x^2+b)/2x$.

I am stuck here as to where to go with my scheme or how to use this? Then once I have my scheme how do I program it?

1

There are 1 best solutions below

5
On BEST ANSWER

$\sqrt{b}$ is one of the numbers that solves $f(x) \stackrel{\tiny\text{def}}{=} x^2-b=0$.

So what you need to do is iterate values of $x$ to arrive at a solution. One such method is Newton's method, which is what you're ostensibly trying to use.

Simply take an initial guess, let's say $x_0 = \frac{b}{2}$.

Then, we update our guess by setting $x_1 = x_0 - \frac{f(x_0)}{f'(x_0)}$.

We repeat this process such that $x_{n+1} = x_n - \frac{f(x_n)}{f'(x_n)}$.

This is easy to code in MATLAB. Naively, we'll code it straightforward:

b = 7;
x = b/2;
err = inf;
tol = 1e-6; % Stop when we're more accurate than this number
while err > tol
    x_new = x - (x^2-b)/(2*x); %compute the update
    err = abs(x_new-x); % compute the error
    x = x_new; %re-assign the new value
end
x
sqrt(7)
actual_err = abs(x-sqrt(7))