Python二分法实现平方根
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 30 15:14:44 2019
@author: h50008097
"""
def binary_search(num):
y = num/2
low = 0
up = num
count = 1
while abs(y**2-num)>0.0001:
count += 1
if y**2>num:
up = y
y = low + (up - low)/2
elif y**2<num:
low = y
y = up - (up - low)/2
print(count)
return y
def main():
num = 5
print(binary_search(num))
if __name__ == '__main__':
main()
输出结果:
17 #迭代次数
2.2360610961914062 #平方根结果