이분법을 사용하여 제곱근을 구합니다.
def sqrtBI(x, epsilon): assert x>0, 'X must be non-nagtive, not ' + str(x) assert epsilon > 0, 'epsilon must be postive, not ' + str(epsilon) low = 0 high = x guess = (low + high)/2.0 counter = 1 while (abs(guess ** 2 - x) > epsilon) and (counter <= 100): if guess ** 2 < x: low = guess else : high = guess guess = (low + high)/2.0 counter += 1 return guess
확인하세요.
>>> sqrtBI(2,0.000001)
>>> 1.41421365738
위 방법은 X
>>> sqrtBI(0.25,0.000001)
>>> 0.25
그럼 0.25의 제곱근은 어떻게 구할까요?
위 코드를 살짝만 바꿔보세요. 코드의 6행과 7행을 참고하세요.
def sqrtBI(x, epsilon): assert x>0, 'X must be non-nagtive, not ' + str(x) assert epsilon > 0, 'epsilon must be postive, not ' + str(epsilon) low = 0 high = max(x, 1.0) ## high = x guess = (low + high)/2.0 counter = 1 while (abs(guess ** 2 - x) > epsilon) and (counter <= 100): if guess ** 2 < x: low = guess else : high = guess guess = (low + high)/2.0 counter += 1 return guess
확인:
>>> sqrtBI(0.25,0.000001)
>>> 0.5