Bisection Method Problems

Sep 15, 2011 at 12:29pm
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;
}
Sep 15, 2011 at 12:37pm
http://www.cplusplus.com/articles/z13hAqkS/
= is the assignment operator, == is comparison for equality.
Sep 15, 2011 at 2:33pm
Thanks, I meant to have that included actually. Even with ==, the program is still not returning the correct answers though
Sep 15, 2011 at 2:36pm
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.
Sep 15, 2011 at 3:02pm
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 Sep 15, 2011 at 3:03pm
Topic archived. No new replies allowed.