python - getting not-full answer as the output of the function -


i wrote code function implements sqrt function using technique known babylonian function. approximates square root of number, n, repeatedly performing calculation using following formula:

nextguess = (lastguess + (n / lastguess)) / 2

when nextguess , lastguess close, nextguess approximated square root. initial guess can positive value (e.g., 1). value starting value lastguess. if difference between nextguess , lastguess less small number, such 0.0001, nextguess approximated square root of n. if not, nextguess becomes lastguess , approximation process continues.

def babyl(n):     lastguess=1.0     while true:         nextguess=float(lastguess+float(n/lastguess))/2.0         if abs(lastguess-nextguess)<0.0001:             return nextguess         else:             lastguess=nextguess             nextguess=float(lastguess+float(n/lastguess))/2.0             if abs(lastguess-nextguess)<0.0001:                 return nextguess 

the output of function is:

>>> babyl(9) 3.000000001396984 >>> babyl(16) 4.000000000000051 >>> babyl(81) 9.000000000007091 >>>  

very long after dot see.

i want write test program user enters positive integer , functions return approx. sqrt value.

so coded:

n=input("please sir, enter positive integer number , you'll approximated sqrt:") print babyl(n) 

and answer short:

>>>  please sir, enter positive integer number , you'll approximated sqrt:16 4.0 >>> ================================ restart ================================ >>>  please sir, enter positive integer number , you'll approximated sqrt:4 2.0 >>> ================================ restart ================================ >>>  please sir, enter positive integer number , you'll approximated sqrt:9 3.0000000014 >>>  

can tell me difference between function , test?

the console uses repr( ) show result. print uses str( )

>>> import math; f = math.sqrt(10) >>> str(f) '3.16227766017' >>> repr(f) '3.1622776601683795' >>> print f 3.16227766017 

it's strange miss precision in output. epsilon 0.0001, several digits shorter, result in poor precision, @ least these small numbers. why worry output then?


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -