遍历寻找or数学公式 | HJ107 求解立方根
# 最优解1 # 牛顿迭代法求解立方根的思路: # 令f(x) = x^3 - a,求解f(x) = x^3 - a = 0。 # 利用泰勒公式展开,即f(x)在x0处的函数值为: # f(x) = f(x0) +f'(x0)(x-x0) = (x0^3-a) + (3x0^2)(x-x0) = 0, # 解之得:x = x0 - (x0^3 - a)/(3x0^2)。 # 即 新x = 旧x - (f(x)-a)/f'(x) n= float(input()) x=1 while abs(x**3-n)>1e-7: x=x-(x**3-n)/(3*x**2) print(round(x,1)) # 最优解2 while True: try: a = float(input().strip()) epsilon = 0.0001 low = min(-1.0, a) high = max(1.0, a) ans = (low + high)/2 while abs(ans**3 - a) >= epsilon: if ans**3 < a: low = ans else: high = ans ans = (low + high)/2.0 print('%.1f' % ans) except: break # 我的代码 def func(num, neg): gen = 0 tmp = 0 dis = float('inf') num = (-1)*num if neg else num not_found = True while not_found: if abs(gen**3-num) < dis: dis = abs(gen**3-num) tmp = gen else: not_found = False break gen += 0.1 tmp = (-1)*tmp if neg else tmp print(round(tmp, 1)) while True: try: num = float(input()) func(num, num<0) except: break
华为笔试刷题 文章被收录于专栏
高质量题: 1~40:HJ16,HJ22,HJ24,HJ26,HJ27,HJ28,HJ35,HJ37,HJ39; 40~80:HJ41,HJ42,HJ43,HJ44,HJ48,HJ50,HJ52,HJ53,HJ57,HJ61,HJ63,HJ64,HJ70,HJ71,HJ74,HJ77; 80~108:HJ82,HJ85,HJ88,HJ89,HJ93,HJ95,HJ98,HJ103,HJ107