二分查找的概念与条件
1.概念:
相较于穷举法一般搜索步长不变,二分法每次迭代搜索步长均减半
新的猜想值取搜索范围的中间值
从而是搜索速度加快,时间复杂度为log2N(在大数据下优势明显)
2.条件
保证单调性且无重复元素
立方根求解(包括对负数,正数,大于小于1的小数,0的情况分析)
1.最一般情况,即大于1的正数求其立方根
cube = 27#以27为例
epsilon = 0.01
low = 0
high = cube
guess = (high + low)/2.0
while abs(guess**3 -cube) >= epsilon:
if guess**3 < cube :
low = guess
else:
high = guess
guess = (high + low)/2.0
print(guess, '是', cube, '立方根的近似解')
2.为负数
类比正数,与正数的差距只有一个符号
if cube>0:
print(guess,'是',cube,'立方根的近似解')
if cube<0:
print('-',guess,'是',cube,'立方根的近似解')
3.在0到1之间
修改上下界,在(cube,1)之间二分
low = abs(cube)
high = 1.0
guess = (high+low)/2.0
(此处仅给出在完整代码上的修改片段)
cube = float (input('请输入一个数:'))
epsilon = 0.0001
low = 1.0
high = abs(cube)
guess = (high+low)/2.0
if cube==0.0:
print(guess,'是',cube,'立方根的近似解')
if abs(cube)<1 and abs(cube)>0:
low = abs(cube)
high = 1.0
guess = (high+low)/2.0
while abs(guess**3-abs(cube))>=epsilon:
if guess**30:
print(guess,'是',cube,'立方根的近似解')
if cube<0:
print('-',guess,'是',cube,'立方根的近似解')
else:
while abs(guess**3-abs(cube))>=epsilon:
if guess**30:
print(guess,'是',cube,'立方根的近似解')
if cube<0:
print('-',guess,'是',cube,'立方根的近似解')
附录:
epsilon的精度问题
1.小数点后几位到底是如何确定的:与epsilon有关,即与步长有关,epsilon越小约精确,但耗时越长
2.为什么修改epsilon的值后求值的小数位不变:不仅与epsilon有关,还与二分次数有关
如何让代码更优美——调用函数!
def cube_root(cube,epsilon):
low = min(1.0,abs(cube)) #注意此处设置,大于1时不再从0.0开始二分,是为简化代码
high = max(1.0,abs(cube))
guess = (high+low)/2.0
if cube==0.0:
print(cube,'是',cube,'立方根的近似解')
while abs(guess**3-abs(cube))>=epsilon:
if guess**30:
print(guess,'是',cube,'立方根的近似解')
if cube<0:
print('-',guess,'是',cube,'立方根的近似解')
return guess
cube = float (input('请输入一个数:'))
epsilon = float (input('请输入一个数:'))
guess = cube_root(cube,epsilon)
(如有出错,欢迎指正!)