Fix Python – Why does Python give the “wrong” answer for square root? What is integer division in Python 2? [duplicate]

Question

Asked By – Merlin

x = 16

sqrt = x**(.5)  #returns 4
sqrt = x**(1/2) #returns 1

I know I can import math and use sqrt, but I’m looking for an answer to the above. What is integer division in Python 2? This behavior is fixed in Python 3.

Now we will see solution for issue: Why does Python give the “wrong” answer for square root? What is integer division in Python 2? [duplicate]


Answer

In Python 2, sqrt=x**(1/2) does integer division. 1/2 == 0.

So x(1/2) equals x(0), which is 1.

It’s not wrong, it’s the right answer to a different question.

If you want to calculate the square root without an import of the math module, you’ll need to use x**(1.0/2) or x**(1/2.). One of the integers needs to be a floating number.

Note: this is not the case in Python 3, where 1/2 would be 0.5 and 1//2 would instead be integer division.

This question is answered By – smessing

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0