Precision in numerical methods using Octave

149 Views Asked by At

I have created an algorithm for the bisection method using Octave and tested it on two different functions. The fist one worked flawlessly within the required tolerance. The second, however, won't give me a more precise result even when I increase the tolerance, despite it never coming close to the maximum number of iterations. I have included the code below without its commentary since it's not in english. That being said, in order to be clear:

$f$ is a continuous real function defined in $[a,b]$

$a$ is the lower bound

$b$ is the upper bound

$tol$ is the minimum error tolerance for the solution

$max\_iteracoes$ is the maximum number of iterations the program is allowed to run.

function [valor_approx,total_de_iteracoes] = metodo_da_bissecao(f,a,b,tol,max_iteracoes)

  if sign(f(a))*sign(f(b))>0
    printf('Error')
    return
  endif

  iteracoes = 1;

  while iteracoes <= max_iteracoes 
    p_i=a+(b-a)/2; 
    f_p_i=f(p_i); 
    valor_approx = p_i; 
    total_de_iteracoes = iteracoes; 

    if f_p_i==0 || abs((b-a))/2<tol 
      printf('The root of the function is : %d \n',valor_approx);
      printf('The number of iterations was: %d \n',total_de_iteracoes);
      return
    endif

    iteracoes = iteracoes+1; 

    if sign(f(a))*sign(f(p_i))>=0 
      a = p_i;
    else
      b = p_i;
    endif
  endwhile

  if iteracoes > max_iteracoes 
    printf('Fail! \n')
    return
  endif

 endfunction

Here are the functions I used to test it out:

f = @(x) exp(x) - x - 1

g = @(x) 3*x^3 + sqrt(2)*x^2 - pi*x + 0.4

format long

metodo_da_bissecao(f,-1,0,1.e-09,100);

metodo_da_bissecao(g,-2,-1,1.e-09,100);

function $f$ returns the following solution: $-1.49012e-08$ within $26$ iterations.

which I double-check, $f(-1.49012e-08) = 0$

function $g$ returns: $-1.33243$ within $24$ iterations.

which I double-check, $g(-1.33243) = 3.664661882629705e-05$

I've tried increasing the tolerance all the way to $1.e-15$, but the solution never changes nor does it reach the maximum number of iterations.

I'm puzzled as to what might be the problem with function $g$'s root.