Skip to content

Instantly share code, notes, and snippets.

@dispensable
Created December 5, 2015 09:44
Show Gist options
  • Save dispensable/905a644d063c2972f298 to your computer and use it in GitHub Desktop.
Save dispensable/905a644d063c2972f298 to your computer and use it in GitHub Desktop.
# _*_coding:utf-8_*_
#!/usr/bin/env python
# define a function which can compute the squareroot of the number
def squarerootbi(number, epsilon):
"""
利用二分法计算给定数字和精度的近似平方根
:rtype: float
:param number:给定的数字
:param epsilon:要求的平方根的精确度
:return:返回给定数字和精度的平方根
"""
assert number > 0, 'number must > 0' + str(number)
assert epsilon > 0, 'epsilon must > 0' + str(epsilon)
# high = number 假设给定数的平方根在0-数字本身之间,然而小数并不是这样
high = max(number, 1)
low = 0
count = 0
guess = (high + low) / 2.0
while (abs(guess ** 2 - number) > epsilon) and count <= 100:
if guess ** 2 > number:
high = guess
elif guess ** 2 < number:
low = guess
guess = (high + low) / 2.0
count += 1
assert count <= 100, 'iter up to 100 the counter is:' + str(count)
print 'the squareroot of this number is: ' + str(guess) + ' ' + 'count:' + str(count)
def testsuqarerootbi():
squarerootbi(9, 0.00000000001)
# squarerootbi(-1, 0.001)
# squarerootbi(1, -0.1)
squarerootbi(9, 0.00000001)
squarerootbi(0.25, 0.0000001)
testsuqarerootbi()
# 使用函数来测试,而不是每次都调用测试对象,可以减少重复
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment