// Bisection Method

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

#define true    1
#define false   0
#define ZERO 1.0E-20

double func(double x);

void main()
{
   int i=0, ok;
   double fa, fb, c, p, fp;
   double left_end = 0.1;       // ¿ÞÂÊ °æ°èÄ¡ 
   double right_end = 1.0;      // ¿À¸¥ÂÊ °æ°èÄ¡
   double tolerance = 0.0001;   // ¿ÀÂ÷ÀÇ ÇѰè
   double num = 40;             // °è»êÀÇ È½¼ö
            
   printf("This is the Bisection Method.\n");
   printf("  i         P                Func(P)\n");

   while((i < num) && ok) {
      c = ( right_end - left_end ) / 2.;
      p = left_end + c;

      fp = func(p);

      printf("%3d   %15.8e   %15.7e \n", i+1, p, fp);

      // ÇÔ¼ö°ªÀÌ ¾ÆÁÖ ÀÛ°Ô ³ª¿À°Å³ª ¿ÀÂ÷ÀÇ ÇѰ躸´Ù ÀÛ°Ô ³ª¿À¸é °è»ê ³¡³¿. 
      if ((fabs(fp) < ZERO) || (c < tolerance)) {
         printf("\nApproximate solution P = %11.8f \n", p);
         printf("with Func(P) = %12.8f\n", fp);
         printf("Number of iterations = %3d", i+1);
         printf("    Tolerance = %15.8e\n", tolerance);

	 ok = false;

      } else {

         i++;

         if(fa * fp > 0.) {
            left_end = p;
            fa = fp;
         } else {
            right_end = p;
            fb = fp;
         }
      }
   }

   if (ok) {
      printf("\nIteration number %3d", num);
      printf(" gave approximation %12.8f\n", p);
      printf("Func(P) = %12.8f not within tolerance : %15.8e\n", fp, tolerance);
   }
}

// ÇØ¸¦ ±¸ÇÏ·Á´Â ÇÔ¼ö
double func(double x)
{
   return (600*x*x*x*x-550*x*x*x+200*x*x-20*x-1);
}