Help with finding 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, it should replace x with x+Δx and continue; otherwise, it should reduce the step size by half and repeat the comparison. The program should terminate successfully when Δ<10^-6

Something in my program isn't right, I think it has to do with the user entering the equation, but I'm not sure how to fix it. Any suggestions? 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
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <cmath>
#include <cstdlib>

using namespace std;

int main()
{
    int a, b, delta, fx, x, y;
    int max = 0;
    
    cout <<"Please complete the equation to be evluated f(x)= " << endl;
    cin >> fx;
    cout <<"Please enter the first number of the interval to be checked: " << endl;
    cin >> a;
    cout << "Please enter the last number of the interval to be checked: " << endl;
    cin >> b;
    cout << "Please enter the desired initial step size: " << endl;
    cin >> delta;
    
      for(x = a; x <= b; x = x+delta) 
                                   
    {
        y = fx;     
        if (y > max)  
        { 
            max = y;  
            cout <<"The maximum over the interval from " << a <<"to " << b <<"is " << delta;
        }
        else
        {
            delta= delta/2;
        }
        if (delta <  pow( 10, -6))
        {system ("PAUSE");}
    }      
    
    
    return 0;
}
Last edited on
Unfortunately, you can't store functions inside int variables, so you'll have to use a library that can parse math expressions.
A quick Google search comes up with this (though there are others out there as well): http://muparser.beltoforion.de/
Topic archived. No new replies allowed.