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....

It looks to me like you are calling the function fnc with the exact same values every single time you call it so an infinite (till it crashes) loop makes sense since it's doing the same thing every time. You're passing fnc parameters x1 and x2, which never change. Do you want to do that?

Scratch that. It changes x1 and x2 the first couple of times you call fnc, but then they stay the same forever.

Also I believe you are overshooting when you are dividing your sections. You end up having a and b outside of your original range, which is not legal in this algorithm. Instead, try this:

a=x1+(0.618* (x2 - x1));
b=x2-(0.618* (x2 - x1));

This keeps a > b and a and b both between x1 and x2. The range will get continuaully more narrow. You'll have to also adjust a few things in your outer and inner "else" loop within fnc. With those adjustments, I got the program to run successfully and exit.

hey i debugged it the bugs were:
1.I went by vernondezier
a=x1+(0.618* (x2 - x1));
b=x2-(0.618* (x2 - x1));a=x1+(0.618* (x2 - x1));
b=x2-(0.618* (x2 - x1));
Thanx.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.