题解 | #求解立方根#
求解立方根
https://www.nowcoder.com/practice/caf35ae421194a1090c22fe223357dca
import sys def cube_root(x, epsilon=0.001, max_iterations=100): if x == 0: return 0 guess = x / 3 # 初始猜测值为 x/3 for _ in range(max_iterations): next_guess = (2 * guess + x / (guess * guess)) / 3 # 二次迭代法公式 if abs(next_guess - guess) < epsilon: return round(next_guess,1) guess = next_guess return round(guess,1) for line in sys.stdin: a = line.rstrip() print(cube_root(float(a)))
有待研究,下面两种时间效率不够。
def cube_root(x, epsilon=0.0001):if x == 0:return 0
import sys def cube_root(x, epsilon=0.01): if x == 0: return 0 low = 0 high = max(1, x) guess = (low + high) / 2 while abs(guess ** 3 - x) > epsilon: if guess ** 3 < x: low = guess else: high = guess guess = (low + high) / 2 return round(guess,1) for line in sys.stdin: a = line.rstrip() print(cube_root(float(a))) ############################ import sys def cube_root(x, epsilon=0.01): low = 0 high = x guess = (low + high) / 2 while abs(guess ** 3 - x) > epsilon: if guess ** 3 < x: low = guess else: high = guess guess = (low + high) / 2 return round(guess,1) for line in sys.stdin: a = line.rstrip() print(cube_root(float(a)))