0
$\begingroup$

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?

$\endgroup$
0
$\begingroup$

$\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))
$\endgroup$
  • $\begingroup$ Wow, this makes things so much more clear. Thanks! How do I introduce each variable? and at the beginning of the program I need to write: function value=(program name) correct? $\endgroup$ – Kailee Oct 9 '14 at 22:36
  • $\begingroup$ If you copy-paste what I wrote into MATLAB, either directly into the command window, or into a .m script file, it will run and compute the square root of 7. If you're looking for more general MATLAB help, there are lots of MATLAB tutorials available online. Math.SE isn't the best place to understand the basics, because the nature of this community is to provide specific answers to specific questions. $\endgroup$ – Emily Oct 9 '14 at 22:41
  • $\begingroup$ Ok, well I appreciate the help. One last question, is there any specific reason why you picked 7 or just as an example? $\endgroup$ – Kailee Oct 9 '14 at 22:43
  • $\begingroup$ Just an example. You can replace 7 with any positive number you so choose. And you can also replace the initial guess of $x$ with any number you choose. $\endgroup$ – Emily Oct 9 '14 at 22:44
  • $\begingroup$ Awesome, thank you again. $\endgroup$ – Kailee Oct 9 '14 at 22:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.