Python - 无限循环

时间:2018-02-03 22:11:40

标签: python python-3.x if-statement while-loop

我不明白为什么底部的while循环是一个无限循环。

# User enters a positive integer number
user_input = int(input('Please enter a positive integer number: '))

# Make the epsilon value a constant
EPSILON_VALUE = 0.0001

# Choose an initial estimate -  set the initial estimate e=x
estimate = user_input

# Evaluate the estimate - dividing the value x by your estimate e,
result = user_input / estimate

# Calculate the difference 
difference = abs(estimate) - abs(result)

# If the difference is smaller than your epsilon value, then you've found the answer!
if difference <= EPSILON_VALUE:
    print('Square Root')
    print(result)
# Else the algorithm must iterate until it reaches the result
else:
    while difference > EPSILON_VALUE:
        result = ((user_input / estimate) + estimate) / 2
        difference = abs(estimate) - abs(result)
        print(difference)

3 个答案:

答案 0 :(得分:1)

这是因为你没有改变条件值。您的while循环正在比较differenceEPSILON_VALUE,但这些值都没有在您的循环中发生变化,因此条件将始终评估相同(true)。

答案 1 :(得分:0)

您忘了从估算中减去差异:

# User enters a positive integer number
user_input = int(input('Please enter a positive integer number: '))

# Make the epsilon value a constant
EPSILON_VALUE = 0.0001

# Choose an initial estimate -  set the initial estimate e=x
estimate = user_input

# Evaluate the estimate - dividing the value x by your estimate e,
result = user_input / estimate

# Calculate the difference 
difference = abs(estimate) - abs(result)

# If the difference is smaller than your epsilon value, then you've found the answer!
if difference <= EPSILON_VALUE:
    print('Square Root')
    print(result)
# Else the algorithm must iterate until it reaches the result
else:
    while difference > EPSILON_VALUE:
        result = ((user_input / estimate) + estimate) / 2
        difference = abs(estimate) - abs(result)
        estimate -= difference  # change our estimate
        print(difference)

答案 2 :(得分:0)

while difference > EPSILON_VALUE:
    result = ((user_input / estimate) + estimate) / 2
    difference = abs(estimate) - abs(result)
    print(difference)

在代码的第1行中,检查差异是否大于epsilon。

然后,将结果设置为某个数字,并根据此数字设置差异。

如果不改变差异是否大于epsilon,那么它将结果设置为与已经相同的数字。您不会更改影响计算结果或差异的任何内容。这些数字总是保持不变,或者不会改变,让我们永远处于循环中。