// False Position ¹æ¹ý

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

#define true    1
#define false   0

double func(double x);

void main()
{
   int i, ok;
   double q0, q1, q, p;
   double p0 = 0.1;       // ¿ÞÂÊ °æ°èÄ¡
   double p1 = 1.0;       // ¿À¸¥ÂÊ °æ°èÄ¡
   double tolerance = 0.0001;   // ¿ÀÂ÷ÀÇ ÇѰè
   double num = 40;             // °è»êÀÇ È½¼ö
            
   printf("This is the Method of False Position.\n");

   q0 = func(p0); // f0 ¿¡ ÁÂÃø °æ°è ÇÔ¼ö°ª ÀÔ·Â
   q1 = func(p1); // f1 ¿¡ ¿ìÃø °æ°è ÇÔ¼ö°ª ÀÔ·Â

   printf("  i            p              Func(p)\n");
   
   i = 1;

   while((i < num) && ok) {

      p = p1 - q1 * (p1 - p0) / (q1 - q0);
      q = func(p);

      printf("%3d   %15.9e   %15.9e \n", i+1, p, q);

      // ¿ÀÂ÷ÇѰ躸´Ù ÀÛ°Ô ³ª¿À¸é °è»ê ³¡³¿. 
      if ((fabs(p - p1) < tolerance)) {
         printf("\nApproximate solution P = %12.9f \n", p);
         printf("with Func(P) = %12.9f\n", q);
         printf("Number of iterations = %3d\n", i+1);
         printf("Tolerance = %12.9e\n", tolerance);

	 ok = false;

      } else {

         i++;
         if((q*q1) < 0.) {
	    p0 = p1; q0 = q1;
         }
	 p1 = p;  q1 = q;
      }
      
   }

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

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