Incorporate user-inputted function into code

So in the code i've written (don't be too judgemental, i'm really a beginner in c++), it takes a function, and asks the user which interval the user believes one of the zeroes/roots of the function is in. Then, after the program knows this interval, it proceeds to find the average of the upper bound and lower bound of the interval, and based on the sign (+ or -), of f(average), it closes in closer and closer to the zero of the function by taking consecutive averages.
(for those of you who know calculus, this is just application of the intermediate value theorem in calculus via the bissection method for finding roots).

Anyways, my problem is, I want the user to be able to input any function, and then an interval, and my program should be able to find the zero in that interval.
The question is, how do i get the program to incorporate a function that the user defines?

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
41
42
43
44
45
46
#include <iostream>
#include <cmath>
using namespace std;
int signum(float number) //defines the sign function (+ or - or 0)
{
    if (number>0)
        return 1;
    if (number<0)
        return -1;
    if (number==0)
        return 0;
}
float average(float number1,float number2) //defines the average function
{
    return((number1+number2)/2);
}
float f(float x) //IMPORTANT: defines f(x)
{
    return f(x)
}


int main ()
{
    float lowerbound,upperbound,lcopy,ucopy;
    cout<<"What is the upper bound of the interval? ";
    cin>>upperbound;
    cout<<endl<<"What is the lower bound of the interval? ";
    cin>>lowerbound;
    lcopy=lowerbound;
    ucopy=upperbound;
    cout<<endl;
    while (abs(upperbound-lowerbound)>.000001) //checks to see when the interval has become sufficiently small
    {
        if (signum(f(average(upperbound,lowerbound)))==1) //replaces upperbound with average
        {
            upperbound=(upperbound+lowerbound)/2;
        }
        if (signum(f(average(upperbound,lowerbound)))==-1) //replaces lowerbound with average
        {
            lowerbound=(upperbound+lowerbound)/2;
        }
    }
    cout<<"The root of f(x) in the interval ["<<lcopy<<","<<ucopy<<"] is approximately: "<<lowerbound;
}
Topic archived. No new replies allowed.