python 使用二分法计算平方根

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 使用二分法计算平方根相关的知识,希望对你有一定的参考价值。

python 使用二分法计算平方根


from math import sqrt
def mysqrt(num,small):
    assert num>0
    assert small>0
    low = 0.0
    high = max(num,1)
    loops=1
    while True and loops<=100:
        a = (high + low) / 2
        test = a ** 2
        if abs(test-num)<small:
            break
        elif test > num:
            high = a
        else:
            low = a
        loops+=1
    return a

if __name__ == '__main__':
    num = input("number:")
    small=0.0000000001
    print mysqrt(num,small),"my sqrt "        #对比我写的这个和math库的计算值的差别
    print sqrt(num),"math sqrt"

以上是关于python 使用二分法计算平方根的主要内容,如果未能解决你的问题,请参考以下文章

python 二分法求方程的根

python算法题 python123网站单元四题目

二分法03:x 的平方根

使用牛顿-拉弗森法定义平方根函数(Newton-Raphson method Square Root Python)

二分查找求平方根

69. x 的平方根-二分查找