Reputation: 37
I tried to write a program of bisection method with recursive apporach but it seems not working.
The function is f(x) = ax^2 + bx + c. The parameters in findroot: a b and c are values of a b and c in f(x) p and q indicate the interval (p,q). Assume the input are valid(can always find an answer). Here is my attempt
int sign(float a, float b,float c,float d)
{
if (a*d*d + b*d + c > 0) {return 1;}
if (a*d*d + b*d + c < 0) {return -1;}
else {return 0;}
}
float find_root(float a, float b, float c, float p, float q)
{
if (sign(a,b,c,(p+q)/2) == 0){return (p+q)/2;}
else if (! sign(a,b,c,(p+q)/2) == sign(a,b,c,p))
{return find_root(a,b,c,p,(p+q)/2);}
else
{return find_root(a,b,c,(p+q)/2,q);}
}
Any correction or advice is appreciated!
Upvotes: 0
Views: 1366
Reputation: 206567
I have a feeling this line is the problem:
else if (! sign(a,b,c,(p+q)/2) == sign(a,b,c,p))
Perhaps you meant to use:
else if (! (sign(a,b,c,(p+q)/2) == sign(a,b,c,p)))
or
else if ( sign(a,b,c,(p+q)/2) != sign(a,b,c,p) )
Upvotes: 2