Fixing code to do bisection properly
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (1)
John D'Errico
am 16 Sep. 2019
Bearbeitet: John D'Errico
am 16 Sep. 2019
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 Kommentare
Siehe auch
Kategorien
Mehr zu Startup and Shutdown finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!