code題

1、實現sqrt()函數

  • 二分法
def sqrt_binary(x):
    low = 0
    high = max(1, x)
    guess = (low + high)/2
    count = 1
    while abs(guess**2 - x) > 0.000000001 and count < 100:
        if guess**2 < x:
            low = guess
        else:
            high = guess
        guess = (low + high) / 2
        count += 1
    return guess
  • 牛頓迭代法:

         原理:https://blog.csdn.net/ccnt_2012/article/details/81837154

         code:https://blog.csdn.net/Everywhere_wwx/article/details/80254286

class Solution(object):
    def mySqrt(self, x):
        """
        :type x: int
        :rtype: int
        """
        re = 1.0
        while abs(re*re - x)abs > 0.0001:
            re = (re + x/re)/2
        return int(re)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章