2

I have tried to compute this algorithm with python and it doesn't seem to work:

lt = False
x = 5
g = 2

while lt == False:
    if g*g > (x-0.1) and g*g < (5.1):
        lt = True
    print(g+"IS THE SQUARE ROOT")
else:
    g = (g + x/g)/2
    print(g)

In the else loop, I printed g to see the outcome of my algorithm in each loop because I was experiencing slow computation previously and wanted to see what the problem was, and now print(g) seems to consistently be returning 2. I'm new to python and the problem is probably staring me in the face but I can't seem to figure it, any help would be much appreciated!

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
  • 1
    Is the indentation you're showing in the question correct (meaning, is it actually what's in your code)? It currently looks like the `else` block is attached to the `while` loop, rather than the `if`. – Blckknght Feb 28 '14 at 23:10
  • What version of python are you using? It seems to be using integer division instead of floating point. `(2 + 5/2)/2 = (2+2)/2 = 2` Look here for more information: http://stackoverflow.com/questions/2958684/python-division – clcto Feb 28 '14 at 23:11
  • What's wrong with using `g ** .5`? – hd1 Feb 28 '14 at 23:12

5 Answers5

2
x = float(5)
g = float(2)

Python rounds int in v2.x. Hope this helps.

1

You are getting 2 because python is rounding the numbers because you are using integers, you need to use floats like so:

x = float(5)
g = float(2)

Now:

>>g = (g + x/g)/2
>>print(g)
2.25
Michael Burns
  • 630
  • 2
  • 5
  • 10
  • 2
    +1 but, this is only true in python 2.x. Python3 does floating point division by default and `//` is integer division. – clcto Feb 28 '14 at 23:16
0

Swap the else: clause and block and the print() call.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

The problem is your mix of tabs and spaces. Python expects you to be consistent, and it is preferred to use four spaces for indents. Tabs are a different character altogether, and do not always appear the same width. In some environments they are 4 characters wide. Python interprets them as 8 characters wide.

These two lines are using spaces:

if g*g > (x-0.1) and g*g < (5.1):
    lt = True

All other lines are using tabs.

mhlester
  • 22,781
  • 10
  • 52
  • 75
0

The problem is that python rounds integers. You need to enter set x and g as floats instead

x = float(5)
g = float(2)

This should work, good luck! :)

This works in python 2.x but I don't know what version you are using so this is the best answer I can provide.

Dark Leviathan
  • 489
  • 7
  • 19