Fixing code to do bisection properly

조회 수: 3 (최근 30일)
David Zubiate
David Zubiate 2019년 9월 16일
편집: John D'Errico 2019년 9월 16일
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

답변 (1개)

John D'Errico
John D'Errico 2019년 9월 16일
편집: John D'Errico 2019년 9월 16일
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.

카테고리

Help CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by