'Binary Search on

I am trying to apply a binary search on the following:

### START FUNCTION
def binary_search(f,domain, MAX = 1000):

### END FUNCTION
f = lambda x:(np.sin(x)**2)*(x**2)-2
domain = (0,2)
x=binary_search(f,domain)
x

1.43 Expected output

binary_search(lambda x:(np.sin(x)**2)*(x**2)-2,(0,2))==1.43

How do I apply a binary search to the above?



Solution 1:[1]

Assuming that you're looking for f(x) == 0, you use the same method as for any binary search:

  • Examine the midpoint of the domain
  • If f(x) is zero, you have found x
    • In your case: if you have done MAX iterations, take x as your approximation
  • Otherwise, halve the domain and search again in the appropriate half depending on whether f(x) is negative or positive

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 molbdnilo