# can we do binary search to solve quadratic equation?

Suppose i have a quadratic equation like this, 2x^2 - 4x - 5 = 0, the solution here is x1=2.87 and x2=-0.87. I tried this python snippet to find the non-negative solution(2.87) by setting range 0 to 1000 and it worked but how to find the negative one too?. I tried the range -1000 to 0, but no luck!

def solve():
low, high=0,1000
while (high-low)>10e-5:
x = (low+high)/2
fx = 2*(x**2)-4*x-5
if fx>0:
high=x
else:
low=x

return low

print(solve())


Or I am doing this whole thing wrong? What is the strategy to work with negative ranges and floating numbers in binary search?

• I'm a bit confused. The equation $ax^2+bx+c=0$ has solutions $(-b\pm\sqrt{b^2-4ac})/2a$. Why not use that? Apr 17 '20 at 23:35
• yeah, I am aware of that! but the point is to explore some non-trivial use cases of binary search. Apr 18 '20 at 0:27

Consider the value of fx on line 6.

def solve():
low, high=-1000,0
while (high-low)>10e-5:
x = (low+high)/2
fx = 2*(x**2)-4*x-5
if fx<0:
high=x
else:
low=x

return low

print(solve())


or

def solve():
low, high=-1000,0
while (high-low)>10e-5:
x = (low+high)/2
fx = 2*(x**2)-4*x-5
if fx>0:
low=x
else:
high=x

return low

print(solve())

• Ohh! i forgot to change the < to >. Thanks mate! But is there any way to find x1 and x2 in one go? giving range like -1000 to +1000? or do we have to do two search? one in positive and one negative! Apr 17 '20 at 17:58
• @AminAhmed Must 2 search. 2x^2 - 8x + 1 = 0 has roots 0.87 and 3.87 (both positive) Apr 18 '20 at 5:34