MATLAB Answers

0

Fixing code to do bisection properly

Asked by David Zubiate on 16 Sep 2019 at 22:25
Latest activity Edited by John D'Errico
on 16 Sep 2019 at 23:29
I am trying to use the bisection method to find the root of a function on cody. The question is: Write your own code that implements the bisection method to find 1/29, with accuracy to 4 sig figs. This number can be found be finding the root of 1/x- 29 = 0. This is what I have right now, but get the follwoing errors. What can I do to fix this?
function root = mybisect29th(a,b)
es = 0.00005;
f = @(x) (1/x) - 29;
ea = 100;
root = roots([-1 -29]);
oldm = (a+b)/2;
while ea >= es
if sign(f(a)) == sign(f(b))
a = oldm;
else b = oldm;
end
m = (a + b)/2;
oldm = m;
ea = abs((m - oldm)/oldm) * 100;
end
end

  0 Comments

Sign in to comment.

1 Answer

回答者: John D'Errico
2019 年 9 月 16 日 23:25
編集済み: John D'Errico
2019 年 9 月 16 日 23:29

Um, look closely at the code that you wrote. Hey, it is your code. You should know what is in it.
First, what does your function return?
function root = mybisect29th(a,b)
It returns the variable root.
Where do you compute root?
root = roots([-1 -29]);
And then root is never used afterwards. As it is, I'm not at all sure what you think that line in your computation does. But it does not use bisection. And worse, it does not even compute the correct value. Root will be the solution of the equation
-x - 29 == 0,
So root will be -29.
The funny thing is, your code might actually work, IF you returned the variable m as a result, not that strange thing in root.
(Actually, I predict your code will fail, because the test inside the wile loop:
if sign(f(a)) == sign(f(b))
is the wrong thing to test. You actually wanted to compare f(a) to f((a+b)/2) at that point.
But at least your bisection code was getting close to working.

  0 Comments

Sign in to comment.