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:
#include <iostream>
#include <cmath>
#include <cstdlib>
usingnamespace 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;
}
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/