#include <iostream>
#include <math.h>

double func(double x)
{ return x*x-2.0;}

double false_position(double xa,double xu)
{
//Modified False position root finding
double test;
double p=0;
double es,ea;
double fa,fp,fu;
int maxit=100,iter=0;
es=0.000001;
ea=1.1*es;
int ia=0,iu=0;
fa=func(xa);
fu=func(xu);
p=xu;
double xpold;
while(iter<maxit && ea>es)
{
xpold=p;	
p=xu-fu*(xa-xu)/(fa-fu);
fp=func(p);
iter++;
if(p!=0) ea=fabs((p-xpold)/p)*100.0;
test=fa*fp;
if(test<0) {xu=p;fu=func(xu);iu=0;ia++;if(ia>=2) fa/=2.0;}
else if(test>0) {xa=p;fa=func(xa);ia=0;iu+=1;if(iu>=2)fu/=2.0;}
else ea=0;
}
if(iter>=maxit) std::cout <<("Maximum number of iteration is exceeded \n result might not be valid");
return p;
}

int main()
{  double a,b,r;
   std::cout << " INPUT LOWER LIMIT OF SEARCH AREA a : ";
   std::cin >>a;
   std::cout << " INPUT UPPER LIMIT OF SEARCH AREA b : ";
   std::cin >>b;
   r=false_position(a,b);
   std::cout<<"r="<<r;
   return 0;
}
