面试 -求解立方根(华为)

题目描述

求解立方根

解法:牛顿法(Python)

f ( x ) = x 3 − a f(x)=x^3-a f(x)=x3a,求解 f ( x ) = x 3 − a = 0 f(x)=x^3-a=0 f(x)=x3a=0

泰勒展开

f ( x ) = f ( x 0 ) + f ′ ( x 0 ) ( x − x 0 ) = x 0 3 − a + 3 x 0 2 ( x − x 0 ) = 0 f(x)=f(x_0)+f'(x_0)(x-x_0)=x_0^3-a+3x_0^2(x-x_0)=0 f(x)=f(x0)+f(x0)(xx0)=x03a+3x02(xx0)=0

解得

x = x 0 − x 0 3 − a 3 x 0 2 x=x_0-\frac{x_0^3-a}{3x_0^2} x=x03x02x03a

while True:
    try:
        a = float(input())
        e = 0.0001
        res = a
        while abs(res**3 - a) > e:
            res = res - (res**3 - a) * 1.0 / (3 * res**2)
        print("%.1f" % res)
    except: break

你可能感兴趣的:(面试)