简体   繁体   中英

repetitive value assignment in a while loop, Python

Please look at following while loop code written in Python:

x=25
epsilon=0.01 
high=max(1.0,x)
low=0.0
*ans=(low+high)/2.0*

while abs(ans**2-x)>=epsilon:
    if ans2>x:
        high=ans
    else:
        low=ans
   *ans = (high + low)/2.0*
print("ans:",ans,)

This is a guess loop (exhaustion), it should find the approx for square root of a positive number within the margin error on 0,01. But I cant understand why we must define ans (ans=(low+high)/2.0) the second time, first before the loop and then again in the loop. Could someone tell me what purpose the second definition have since im seeing the first one being enough?

Thanks Arif

It's because you need to perform that calculation on each iteration of the loop including the very first iteration. Since your while test is the very first part of the loop, you need to do it once before the loop starts.

Here's a way to do it with just one statement:

while True:
   *ans = (high + low)/2.0*
    if abs(ans**2-x)>=epsilon:
        break
    if ans2>x:
        high=ans
    else:
        low=ans

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM