0
$\begingroup$

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?

$\endgroup$
2
  • $\begingroup$ 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? $\endgroup$ Commented Apr 17, 2020 at 23:35
  • $\begingroup$ yeah, I am aware of that! but the point is to explore some non-trivial use cases of binary search. $\endgroup$
    – Amin Ahmed
    Commented Apr 18, 2020 at 0:27

1 Answer 1

1
$\begingroup$

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())
$\endgroup$
2
  • $\begingroup$ 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! $\endgroup$
    – Amin Ahmed
    Commented Apr 17, 2020 at 17:58
  • 1
    $\begingroup$ @AminAhmed Must 2 search. 2x^2 - 8x + 1 = 0 has roots 0.87 and 3.87 (both positive) $\endgroup$
    – mqtdzklsb
    Commented Apr 18, 2020 at 5:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.