1.讲解了浮点数的性质,着重解释了浮点数并不精确的原因。
2.给出了二分法的函数实现。
在实现的过程中学会使用断言assert,确保用户输入、函数的formal parameters满足要求。如果满足,则不执行断言,否则就会提示断言错误,并结束程序。
函数的代码实现:
def bisection(x,epsilon):
"""this function is to return a square root of
x within 100 times iteration and may not
figure out the true answer"""
assert x>=0
assert epsilon>0
low=0
high=x
guess=(low+high)/2.0
cnt=1
while abs(guess*guess-x)>=epsilon and cnt<=100:
if guess*guess-x>0:
high=guess
else:
low=guess
guess=(low+high)/2.0
cnt+=1
assert cnt<=100
print("iteration:%d,square root:%f"%(cnt,guess))