Bisection Method Problems

I am writing a code to implement the bisection method and have completed what I thought would work but am having problems. There are no errors when building but it is not giving me the correct answers, can anyone point me in the right direction on how to fix it?



#include<iostream>
#include<math.h>
using namespace std;

double f(double x);
double bisection(double a, double b);

int main(){
double a,b;
cout<<"Please enter the lower limit:";
cin>>a;
cout<<"Please enter the upper limit:";
cin>>b;
return bisection(a,b);
}

double f(double x){
double y;

y = pow(x,2)+2*pow(x,1)-4;
return y;
}

double bisection(double a, double b){
double midpoint, ay, my;

ay = f(a);
while (b - a > 0.001) {
midpoint = (a + b) / 2;
my = f(midpoint);
if (my = 0.0)
break;
else if (ay*my > 0) {
a = midpoint;
}
else {
b = midpoint;
}
}
return midpoint;
}
http://www.cplusplus.com/articles/z13hAqkS/
= is the assignment operator, == is comparison for equality.
Thanks, I meant to have that included actually. Even with ==, the program is still not returning the correct answers though
Well, if you expect someone to fully read your code, then this still applies:
http://www.cplusplus.com/articles/z13hAqkS/

It would also help if you mentioned what the "correct answers" are supposed to be and what the program returns instead.
1
2
3
4
5
double bisection(double a, double b);
int main(){
//...
return bisection(a,b);
}


Also, don't test for equality with floating point numbers.
Last edited on
Topic archived. No new replies allowed.