"Hunter Bray" <bestgamester@yahoo.com> wrote in message <kvp4td$ai4$1@newscl01ah.mathworks.com>...
> Hey guys I'm working on a matlab problem for school and I had a couple questions about this function I wrote. It's supposed to use the "divide and average" method to find the square root of a number whether it is positive, negative, or zero and display it with the error. Is there a more correct way to get the answer for the negative square root than just multiplying by 1i in the output rtanderr? Also, this method gives the correct answer when I run it but the format of the answer is weird. This is what it gives me:
>
> rtanderr4 =
> 0 + 2.000000000000000i 0
>
> And here is my function:
>
> function rtanderr = sroot(a)
> x = abs(a)/2;
> error = 1000;
> if a > 0
> while error >= 0.0001
> xnew =((x+(a/x))/2);
> error = abs((xnew  x)/xnew);
> if error > 0.0001
> x = xnew;
> else
> rtanderr = [x,error];
> end
> end
> elseif a == 0
> rtanderr = [0,0];
> else
> while error > 0.0001
> xnew =((x+(abs(a)/x))/2);
> error = abs((xnew  x)/xnew);
> if error > 0.0001
> x = xnew;
> else
> rtanderr = [x*1i,error];
> end
> end
> end
>
> I appreciate any help that can be given.
>
> Thanks,
> Hunter
I usually avoid homework questions, but you did this one
reasonably well.
I would suggest avoiding duplicating code just to handle
the case of the negative square root.
Instead, save the sign, then take the absolute value. After
the square part is done, multiply by 1i as you have done
if the saved sign was negative. (Yes, to answer your
question, that is the simplest way to do it. Anyway, even
if there was something just slightly better here, don't waste
time optimizing that part for something so trivial.)
Next, I'd suggest not bundling both the root and the error
in one vector. These are very different things, so don't try
to be falsely efficient by bundling them into one vector.
Just return two arguments from your function.
Whenever you write a function, ALWAYS comment it.
Put in comments that describe the purpose of each block
of code. I'd like to have one comment per line, but I
usually end up with a comment per every 35 lines that
describes what I am doing in that block of code. The idea
is to make your code easy to read. This will help when you
need to debug something nasty a year from now, and you
have no idea what you did in there.
As importantly, add help (that first contiguous block of
comments.) Yes, I know for a homework assignment, who
cares? But get used to doing it. List the inputs and outputs.
Tell the user what shapes they must be, and what constraints
apply to the inputs. And add an H1 line. This is the very first
line of your comment. It should describe your code, giving
an idea of what it does, with a few keywords in there that
lookfor can then search on. For example, that line for the
function mean.m is:
% mean Average or mean value.
HTH,
John
