repetitive value assignment in a while loop, Python -


please @ 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 guess loop (exhaustion), should find approx square root of positive number within margin error on 0,01. cant understand why must define ans (ans=(low+high)/2.0) second time, first before loop , again in loop. tell me purpose second definition have since im seeing first 1 being enough?

thanks arif

it's because need perform calculation on each iteration of loop including first iteration. since while test first part of loop, need once before loop starts.

here's way 1 statement:

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

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -