dichotomie 1

Ex3 Dichotomie

#include `<stdlib.h>`
#include `<stdio.h>`
#include `<math.h>`

double f(double x)
{
  return x*x-4.;
}

double fonction_dichotomie(double a, double b, double epsilon)
{
  double m;
  while ( (b-a) >= 2*epsilon )
  {
     printf("dichotomie: a = %f, b=%f, b-a = %f 2*epsilon = %f f(a) = %f f(b) = %f\n", a, b, b-a, 2*epsilon, f(a), f(b));
     m = (a+b)/2.;
     if ( f(m) > 0 )
     {
       a = a;
       b = m;
     }
     if ( f(m) <= 0 )
     {
       a = m;
       b = b;
     }
  }
  printf("fin dichotomie: a = %f, b=%f, b-a = %f 2*epsilon = %f\n", a, b, b-a, 2*epsilon);
  return (a+b)/2.;
}

void test(double a, double b, double epsilon)
{
   double zero;
   printf("recherche du zero d'une fonction entre %f et %f\n", a, b);
   printf("f(a) = f(%f) = %f\n", a, f(a));
   printf("f(b) = f(%f) = %f\n", b, f(b));
   printf("precision demandee: %f\n", epsilon);
   zero = fonction_dichotomie(a, b, epsilon);

   printf("Le nombre qui annule la fonction vaut: %f\n", zero);
   printf(" f(%f) = %f\n", zero, f(zero));
   printf("solution mathematique: %f\n", sqrt(4.));
   printf("solution numerique   : %f\n", zero);
   printf("difference           : %f\n", zero-sqrt(4.));
}

int main()
{
/*
   test(1.0, 3., 1e-1);
   test(1.0, 3., 1e-2);
   test(1.0, 3., 1e-3);
   test(1.0, 3., 1e-4);
   test(1.0, 3., 1e-5);
   test(1.0, 3., 1e-6);

*/
   test(1.0, 3., 1e-5);
   return EXIT_SUCCESS;
}