Python - Infinite While Loop

点点圈 提交于 2019-12-02 13:17:22

It's because you're not changing the condition values. Your while loop is comparing difference and EPSILON_VALUE, but neither of those values is changing inside your loop, so the condition will always evaluate the same (true).

You forgot subtracting your difference from the estimate:

# 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)
while difference > EPSILON_VALUE:
    result = ((user_input / estimate) + estimate) / 2
    difference = abs(estimate) - abs(result)
    print(difference)

In line 1 of the code, you check to see if difference is larger than epsilon.

Then, you set result to be some number, and set difference based on this number.

If that doesn't change whether difference is bigger than epsilon, then it sets result to be the same number that it already was. You don't change anything that affects the calculation of what result or difference is. These numbers always stay the same, or don't change, leaving us forever in the cycle.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!