help with using loops to find a maximum

I am trying to make a program that finds the maximum of a function f(x) over an interval a<=x <=b by starting at x=a with a step size of Δx.I want to evaluate f1=f(x) and f2= f(x+Δx. If f1<f2, I should replace x with x+Δx and continue; otherwise, I should reduce the step size by half and repeat the comparison. The program should terminate successfully when Δ<10^-6.

I'm not sure exactly how to have the program look for the maximum. Also, I'm not sure if the loops I have so far are right.
Here's the code I've written so far.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <cmath>

using namespace std;


int main()
{
    int a, b;
   for(a<= x, x<= b, x++;)
   {f1=f(x);
   f2=f(x+ x++);
   if( f1<f2)
   {x=x+ x++;}
   elseif(f1 >= f2)
   {x++= x++/2;}
   if(x++ < pow(10, -6))
   {system "PAUSE"}
   return 0;
}


Any suggestions?
1. Format your code a bit more.

2. 'x++' is definitely not what you intend.

3. Consider case, where f(t)==1, f(t+d)==3, f(t+2d)==2 and f(t+d/2)==4. Your idea will look for the peak from between d and 2d.

4. What if the function has multiple local minima?
Topic archived. No new replies allowed.