pythonmathpython-2.xsqrt

Why does Python give the "wrong" answer for square root? What is integer division in Python 2?


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.


Solution

  • 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.