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

Asked

Viewed 90 times

2

Good night,

I’m 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 this: User log in with the function you want, ranges, desired tolerance and number 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);
  • What exactly is wrong with your code? if possible put in your question to facilitate who helps you find answer (: you are not updating your variable aux nowhere, which is possibly resulting in an infinite loop.

  • It would not be an error, but rather a problem (I believe). I want the end user to have the possibility to enter the desired function. For, by third party programs, they only put or modify the equation already within the code...

1 answer

0

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

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

To calculate a sine root for example you can do so:

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

Repair the @ in front of the function sin. This causes an Handler to the sine function to be passed so that the function is called inside rootBissect.

In this specific example 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 range provided).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.