1

I'm trying to calculate square root using loops. I'm not sure what is wrong with my code, because it does not recognize the right answer.

x = 25.0
ans = 0.0
while ans**2 <= x: 
    ans += 0.5
if ans**2 == x: 
    print ans
    print ans**2

else:
    print "no square root"
    print ans
    print ans**2

When I run it, it displays following result:

no square root
5.5
30.25

and no, this is not homework, Im 32yrs old life learner

edit

Thank you all for answers. Ive modified a code a little bit, Ive changed while loop, and if statement, and my code now looks like this

x = 25.0
ans = 0.0
while ans**2 < x: 
    ans += 0.2



if ans**2 != x: 
    print "root not found"
    print ans
    print ans**2


else:
    print "found square root"
    print ans
    print ans**2

And when i try to run it, it prints following

root not found
5.0
25.0

Im puzzeld

astfgl
  • 23
  • 3

2 Answers2

2

The line if ans**2==x: will never be true because the previous loop while ans**2 <= x: will already have incremented ans.

Also to address your recent edit:

0.2 or 1/5 in binary is a repeating decimal and has no precise representation, hence you are seeing the results of rounding. after incrementing ans by 0.2 several times you don't arrive exactly at 5 although you are very close to it as a result ans**2 is not equal to 25. You need to check within a certain amount of precision for example:

precision = 0.0001
if math.fabs(ans**2 - x) <= precision:
    """then they are close enough for our purposes"""

Incidentally 0.5 DOES have a precise representation in binary (is non repeating), hence you wouldn't have a precision error so I didn't bother mentioning it when you were incrementing by 0.5.

Octopus
  • 8,075
  • 5
  • 46
  • 66
0

The problem with yours algorithm is simple, in the line while ans**2 <= x allowing them to be equal you pass the expected result by 1 iteration, change <= to < to fix it.

This is of course a very inexact way to do this, considere instead the Newton's method is pretty easy to do and understand, only take like 5 lines code to do it and is guaranteed to give you a result as precise as you want in one of the fast, if not the faster, way posible.

EDIT

what you are experience in yours second version is the Accuracy problems of floating point arithmetic, what you see as result is not really 5.0 but something more like 5.0000000000000017763568394002504646778106689453125 that when you print it python make some rounding to some default precision level and show it to you as 5.0 but internally is that ugly number, and when you square it you really get something like 25.00000000000001776356839400 that of course is different from 25.0

you can also check this video: Floating Point Numbers - Computerphile

Copperfield
  • 8,131
  • 3
  • 23
  • 29