I do not understand why the while loop at the bottom is an infinite loop.
# 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)
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.
来源:https://stackoverflow.com/questions/48602596/python-infinite-while-loop