//Find the root of the equation (x^2)-2 by bisection method.
#include<iostream>
using namespace std;
double a,x;
double f(double x)
{
return ((x*x)-2);
} //Suppose the function is (x*x)-2.
void calcx(double a1,double b1)
{
x = (a1+b1)/2;
while((f(x)*f(a))!=0) //If f(x)*f(a)=0, then the root is 'x' itself!
{
if(f(x)*f(a) < 0)
{
if(x==1.41421509) //The answer should be 1.414... so given like this!
{
cout<<"Process completed!";
cout<<"Result is: "<<x;
}
a1=x; //The value 'a' is replaced by x and 'b' remains the same.
calcx(a1,b1); //Then, we'll do recurrsion for range (x,b)
}
else if(f(x)*f(a) > 0)
{
if(x==1.41421509)
{
cout<<"Process completed!";
cout<<"Result is: "<<x;
}
b1=x;
calcx(a1,b1); //Here, recurrsion is done for range (a,x).
}
}
}
int main()
{
double b,res;
cout<<"Enter the values of 'a' and 'b': ";
cin>>a>>b; //The range already given.
calcx(a,b);
return 0;
}
OUTPUT:
Segmentation fault
Q. Can i know why this kind of message is being displayed?