Recursion function problem not returning correct answer

To give you a brief summary of the code it is basically trying to find the root of a function between two points using bisection.

My code works perfectly, but for some reason, it is not returning the variable "m" in the if statement "else if (b-a<precision)" but rather just returning the base case of 0. It doesn't make any sense to me because the if statement stops the recursive call and when I put a "cout << m;" under the if statement it prints out the correct value, but it just won't return it.

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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
//Nick Barry
//Homework 9
//12/2/19
//This code will find the root of a function between two points

#include <iostream>
#include <iomanip>
using namespace std;


double bisect(double f(double x), double a, double b, double precision);
// POST:  return approximate root of f between a and b

double f(double x);
// POST: function to be passed to bisect:  x^3 - 2x - 3


int main()
{
	double root;								// root of f() between a and b

	cout.setf(ios::fixed | ios::showpoint);		// set up output for fixed point with 10 decimals
	cout.precision(15);

	cout << "Bisection by Nick Barry\n\n";
	cout << "Trace of calls\n";
	cout << setw(20) << "a" << setw(20) << "m" << setw(20) << "b" << endl;

	root = bisect(f, 1.0, 2.0, 1.0e-15);		// find root of f between 1.0 and 2.0 with tolerance 10^-15

	cout << "\nThe root of x^3 - 2x - 3 between 1 and 2 is approximately " << root << endl << endl;

	return 0;
}

double bisect(double f(double x), double a, double b, double precision)
// POST:  return approximate root of f between a and b
{
    double m;
    m=(a+b)/2;//finds the midpoint of two values and sets it to m
    cout << setw(20) << a << setw(20) << m << setw(20) << b << endl;

    if (m==0) return m;//if midpoint is zero then root has been found

    else if (b-a<precision){//when precision is met return the midpoint
        return m;
    }

    else if (f(a)*f(m)<0) bisect(f, a, m, precision);//if result is equation is less than zero then root must be between the two points
                                                     //so call function again with m replacing a or b
    else if (f(m)*f(b)<0) bisect(f, m, b, precision);

    return 0.0;
}

double f(double x)
// POST: function to be passed to bisect:  x^3 - 2x - 3
{
	return x*x*x - 2.0*x - 3.0;
}
Last edited on
On lines 49 and 51 it should be
... return bisect ....
not just
... bisect ...


Unrelated, but it should also be
f(m)==0
not
m==0
on line 43
Last edited on
Oh duh, thank you!
Registered users can post here. Sign in or register to post.