Tuesday, May 2, 2017

Bisection Code implementation in Matlab

Bisection Code implementation in Matlab

Find the root of the following function using bisection method where user ca take upper, lower limit and exact integral from user. Function is  x^2 - 3;

You can use any function here..

f = @(x) x^2 - 3;
l = input('Enter Lower Limit : ');
u = input('Enter Upper Limit : ');
prev_approximation = 0;

root = (l + u)/2;
f_root = feval(f, root);
given_absoulte_error = input('Enter absolute error : ');
absolute_error = abs((root - prev_approximation) / root) * 100;
disp(absolute_error);

fprintf('\nStep a\tb\tf(a)\tf(b)\troot\tError_abs\n');
while(absolute_error > given_absoulte_error)
    f_root = feval(f, root);
    f_l = feval(f, l);
    f_u = feval(f, u);
    
    if(f_l * f_root > 0)
        l = root;
    else
        u = root;
    end;
    
    root = (l + u)/2;
    absolute_error = abs((root - prev_approximation) / root) * 100;
    prev_approximation = root;
    
    fprintf('Step %f Error %f\n', root, absolute_error);
    fprintf('\nStep a\tb\tf(a)\tf(b)\troot\tError_abs\n');
    
end;

disp('-------------------------------');
fprintf('Final Root = %f and absolute error = %f', root, absolute_error);

No comments:

Post a Comment