题解 | #求解立方根#
求解立方根
http://www.nowcoder.com/practice/caf35ae421194a1090c22fe223357dca
二分法缩减左右边界
两个注意点:
1.负数立方根还是负数,可以先转化为正数,最后返回时再加回负号
2.如果目标绝对值 f 小于1,则左边界为 f ,右边界为1;如果目标绝对值 f 大于1,则左边界为1,右边界为 f
class Solution:
def calCubRoot(self, tar: str)-> float:
fl = float(tar)
f = abs(fl)
if f==float(0) or abs(f)==float(1):
return (round(f,1))
#初始化边界和结果变量
elif abs(f)>1:
left,right = 1,f
else:
left,right = f,1
res = (right - left)/2+left
#二分法缩短两边距离
while round(res**3,5) != round(f,5):
mid = (right - left)/2+left
if abs(mid*mid*mid) > abs(f):
right = mid
else:
left = mid
res = (right - left)/2+left
#加回负号
return round(res if fl>0 else -res,1)
s = Solution()
print(s.calCubRoot(input()))