程序找到一个数字的cuberoot

时间:2017-05-24 15:28:15

标签: python

所以我是一个完整的初学者(比如不到一周),并在python中编写了这段代码。如果解是一个整数,它应该找到一个数字的cuberoot,否则接近它。它完成两者而不是一个或另一个。我现在已经尝试了多种方式,但它不起作用。有什么建议吗?

cube=int(input("what number's cube root do you want to find"))
epsilon = 0.01
increment = 0.0001
num_guesses = 0
for guess in range(cube+1):
if guess**3 == cube:
    guess += 1
    print (guess)
else:
guess1 = 0.0
    while abs(guess1**3 - cube) >= epsilon:
        guess1 += increment
        num_guesses += 1
        print('num_guesses =', num_guesses) 

    else:
        print(guess1)

5 个答案:

答案 0 :(得分:2)

问题是你的缩进。 “else”语句中的所有内容都需要缩进以显示它位于“else”语句中。您的代码中也有一些逻辑错误。如果你找到了一个数字,当它是一个所需的数字时,你应该打印那个数字,而不是那个数字加1.如果你找到了解决方案,那么你的程序就应该停在那里。

for guess in range(cube+1):
    if guess**3 == cube:
        print (guess)
        return
guess1 = 0.0

答案 1 :(得分:1)

以下是工作解决方案:

cube=int(input("what number's cube root do you want to find: "))
epsilon = 0.01
increment = 0.0001
num_guesses = 0
int_result_found = False
for guess in range(cube+1):
    if guess**3 == cube:
        print guess
        int_result_found = True
        break

if not int_result_found:
    guess1 = 0.0
    while abs(guess1**3 - cube) >= epsilon:
        guess1 += increment
        num_guesses += 1
        #print 'num_guesses =', num_guesses 

    print(guess1)

正如Erik所说,您的代码中存在一些错误。关键点是在找到整数解后停止,我已经使用了布尔标志int_result_found

答案 2 :(得分:1)

代码的一个问题是缩进。 Python需要特定的间距才能正常工作。

避免同时获得答案的最简单方法是创建一个布尔变量(我使用" found_answer")来检查是否有必要运行第二个代码。

我修复了你的代码,尽可能少地修改它:

cube=int(input("what number's cube root do you want to find"))
found_answer = False

for guess in range(cube+1):
    if guess**3 == cube:
        print ("integer answer:", guess)
        found_answer = True

if found_answer == False:
    epsilon = 0.01
    increment = 0.0001
    num_guesses = 0
    guess1 = 0.0
    while abs(guess1**3 - cube) >= epsilon:
        guess1 += increment
        num_guesses += 1
        print('num_guesses =', num_guesses)
    print("approximate answer:", guess1)

答案 3 :(得分:0)

当谈到"猜** 3 ==立方体",我认为你需要"打破"

试试这个:

cube=int(input("what number's cube root do you want to find"))

epsilon = 0.01
increment = 0.0001

for i in range(cube + 1):
    if i**3 == cube:
        # break the loop
        break 
    elif (i+1)**3 > cube > i**3:  # this is to reduce unnecessary calculations
        while (abs(i**3 - cube) >= epsilon):
            i += increment
        break
print(i)

我想把它变成一个功能:

cube=int(input("what number's cube root do you want to find"))

epsilon = 0.01
increment = 0.0001

def cuberoot(cube):
    for i in range(cube + 1):
        if i**3 == cube:
            break
        elif (i+1)**3 > cube > i**3:
            while (abs(i**3 - cube) >= epsilon):
                i += increment
            break
    return i

print(cuberoot(cube))

更简单:

def cuberoot(cube):
    return cube**(1/3)

答案 4 :(得分:0)

为了您的兴趣,这里有一个更有效的求解器:

# target function: y = x**3
def cube(x):
    return x * x * x

def diff(f, epsilon = 0.001):
    """
    Given function f, return a numeric approximation function for f'(x)
    """
    def df(x):
        return (f(x + epsilon) - f(x)) / epsilon
    return df

def newton_solver(target_y, f, df = None, start_x = None, epsilon = 0.001, max_reps = 40):
    """
    Newton Raphson approximation

    Given real target_y and function f,
      return real x such that f(x) = target_y +/- epsilon
    """
    # if no differential function is provided, use a numeric approximation
    if df is None:
        df = diff(f)
    # if no starting point is given, guess f(x) ='= x
    if start_x is None:
        x = target_y
    else:
        x = start_x
    for _ in range(max_reps):
        y = f(x)
        err = y - target_y
        if abs(err) < epsilon:
            # close enough
            return x
        else:
            # project the tangent to find a closer approximation
            x -= err / (df(x) or epsilon)
    # no answer found, bail out
    raise ValueError("max_reps exceeded, no solution found")

def main():
    y = int(input("What integer do you want to find the cube root of? "))

    # find x such that y == x**3
    approx_x = newton_solver(y, cube)

    # round to the nearest integer
    int_x = round(approx_x)
    if cube(int_x) == y:
        print("The exact cube root of {} is {}.".format(y, int_x))
    else:
        print("The cube root of {} is approximately {}.".format(y, approx_x))

if __name__ == "__main__":
    main()