二元搜索:方程求解 [英] Binary Search : Equation Solving

查看:141
本文介绍了二元搜索:方程求解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想求解等式中的x(最多6个小数位):n ** x + x =0.我想使用二进制搜索来做到这一点.

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.

我使用以下代码获取正整数'n'的平方根.需要采用相同的逻辑以某种方式解决上述问题.

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))

推荐答案

平方根方法利用了平方根的特定属性.您应该尝试使用Newton-Raphson方法intead

The square root method leverages specific properties of a square root. You should try the Newton-Raphson method intead

def findOrigin(fn,x0=-1,x1=1,precision=0.000001):    
    while abs(x1-x0)>precision:
        x0,x1 = x1,x1 - fn(x1)*(x1-x0)/(fn(x1)-fn(x0))
    return x1 if abs(fn(x1))<precision else None

输出:

r = findOrigin(lambda x:0.5**x-x)

print(r) # 0.6411857445049735


r = findOrigin(lambda x:2**x-x)

print(r) # None

请注意,当函数返回None时,它可能意味着没有解决方案,或者该方法无法收敛到函数的根(您可能还需要为启动提供更好的猜测点x0,x1)

这篇关于二元搜索:方程求解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆