Home  >  Article  >  Backend Development  >  Python implements finding the square root of an integer based on binary search

Python implements finding the square root of an integer based on binary search

高洛峰
高洛峰Original
2017-03-02 16:56:381849browse

The example in this article describes the method of finding the square root of an integer in Python based on binary search. Share it with everyone for your reference, the details are as follows:

x=int(raw_input('please input a int:'))
if x<0: 
  retrun -1
low=0
high=x
ans=(low+high)/2.0
sign=ans
while ans**2 !=x:
  if ans**2>x:
    high=ans
  else:
    low=ans
  ans=(low+high)/2.0
  if sign==ans:
    break
print ans


For more related articles about finding the square root of an integer in Python based on binary search, please pay attention to PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn