bisection method's values

92 Views Asked by At

I've implemented bisection method. When I run the function, the values keep increasing, and there's never a negative value. also, if condition is altered either value of a or b won't change.

function [root] = Bisection(f, a, b, tol)
f = inline('f');
fa = f(a);
fb = f(b);

if fa*fb < 0.0
   disp("Error: f(a) and f(b) must be opposite signs.");
   return;
end

disp('  n        a           b           p          f(p)')
for i = 1:100
   p = (a + b)/2;
   fp = f(p);
   fprintf('%3i %11.6f %11.6f %11.6f %11.6f\n',i,a,b,p,fp)

   if i == 100
       disp('No solution')
       break;
    end

    if fp*fa > 0
       a = p;
       fa = fp;
    else
       b = p;
    end

    err = abs(b-a);
    if err < tol 
       break;
    end

  end
end

one of examples that I used: f = x^3 + 4*x^2 - 10, a = 1, b = 2, tol = 0.00001

screenshot of result

1

There are 1 best solutions below

1
On BEST ANSWER

1. Problem

f = inline('f');

This takes the string 'f' and parses it. It contains one variable f and does nothing further, the value of the string is its input variable, it returns the unchanged value. Thus it is the identity function. The two letters f in the assignment are at different levels or scopes so that there is no syntactic problem. Independent of what you pass as argument f in the function call, after this assignment you have f(x)=x, as you can also see in the output table.

2. Problem

if fa*fb < 0.0
    disp("Error: f(a) and f(b) must be opposite signs.");

This is obviously the opposite behavior, the same-sign condition is fa*fb > 0.