How to make a generic implementation of the bisection method in MATLAB?

Good Night,

I am having the following problem:

  • The code developed in Matlab to calculate roots of the equation using bisection method is bugging, perhaps in the calculation process (loops);

  • The idea is as follows: The user enters with the function they want, ranges, desired tolerance and the amount of iterations.

clc
clear


%Recebe a Função desejada
disp('Insira a sua função');
f = input('=> ','s');

%Recebe os Intervalos desejados
disp('Insira os valor do Intervalo Xa');
Xa = input('=> '); %Recebe o valor do intervalo A
disp('Insira os valor do Intervalo Xb: ');
Xb = input('=> '); %Recebe o valor do intervalo B

%Recebe a Tolerancia desejada
disp('Insira a Tolerancia desejada');
tolerancia_desejada = input('=>'); %Recebe o valor do erro desejado

%Recebe a quantidade de Operações
disp('Insira o numero de interações');
iteracoes_desejada = input('=> '); %Recebe o valor da quantidade de iterações que o usuário deseja

%Processamento dos Dados
aux = 1;

if((subs(f,Xa))*(subs(f,Xb))>0)
    fprintf('Essa função não existe');
else
    if((subs(f(Xa))*(subs(f,Xb))<0))
        fprintf('Essa função tem raiz');
    end
end

while(aux<iteracoes_desejada)
    media = (Xa+Xb)/2;
    if(subs((f(Xa))*(subs(f(media))<0)))
        Xb = media;
    else
        Xa = media;
    end
    if abs(subs((f(media))<tolerancia_desejada))
        break
    end
end

%Exibindo Resultado da Operação
fprintf('A Raiz é: %f',media);
Author: Eric Chiesse, 2019-08-23

1 answers

It is possible to isolate the method in MATLAB. For this you need to use function handlers

The following function implements the bisection method:

function [x, err] = rootBissect(fn, xMin, xMax, tol)
    a = xMin;
    b = xMax;
    err = b-a;
    while err > tol
        x = (b+a)/2;
        if fn(x) * fn(a) > 0 
            a = x;
        else
            b = x;
        end
        err = b - a;
    end
end

Notice that I am passing the function as parameter (fn).

To calculate a sine root for example you can do like this:

[x, err] = rootBissect(@sin, 3, 3.2, 0.001)

Fix the @ in front of the function sin. This causes a handler for the sine function to be passed so that the function is called inside rootBissect.

In this example specific you will get the answer:

x =

    3.1414


err =

   7.8125e-04

Which makes sense because pi is one of the sine roots (and the one we were looking for in the interval provided).

 0
Author: Eric Chiesse, 2019-11-20 05:59:13