jeudi 16 avril 2020

Binary Search : Equation Solving

How to solve for x up to 6 decimal places in this equation: n**x + x = 0 using Binary Search?

I used the below code to get square root of positive integer n in a similar problem :

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