vendredi 17 avril 2020

Solve for x : n**x + x = 0 using binary search

I want to solve for x (up to 6 decimal places) in the equation: n**x + x = 0. I want to do this using Binary Search.

I used the below code to get the square root of a positive integer, 'n'. Need to apply the same logic to solve the above problem somehow.

n=int(input())

#find square root of n here
def sqroot(n):
    l = 0
    r = n
    while abs(l-r) > 10**(-5):
        mid = (l+r)/2
        if mid**2 > n:
            r = mid
        else:
            l = mid
    return round(mid,4)
print('%.4f' % sqroot(n))

Aucun commentaire:

Enregistrer un commentaire