Hi guys I am trying to implement golden section search method to obtain n-th root of any number.I am testing it by finding the square root of 25 in range [4,6].the function to minimise is:x^2-25.
#include<iostream>
#include<cmath>
using namespace std;
int fnc(float &,float &);
float n,num;
int main()
{
float a,b;
a=4;
b=6;
n=2;
num=25;
fnc(a,b);
return 0;
}
int fnc(float & x1,float & x2)
{
float valx1,valx2;
float a,b;
a=x1+(0.618*x1);
b=x2-(0.618*x2);
valx1=fabs(pow(a,n)-num);
valx2=fabs(pow(b,n)-num);
if(fabs(b-a)<0.00001)
{
cout<<(x1+x2)/2;
return 1;
}
else
{
if(valx2>valx1)
{
x2=a;
fnc(x1,x2);
}
else
{
x1=b;
fnc(x1,x2);
}
}
}
You can read more about golden section search:http://en.wikipedia.org/wiki/Golden_section_search
The bug is int the recursion part in the function "fnc" I am getting an infinite loop.
HOW???
PLZ help....