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

高洛峰
Release: 2017-03-02 16:56:38
Original
1813 people have browsed it

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
Copy after login


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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!