How do I calculate square root in Python?

Solution 1:

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.

Solution 2:

You have to write: sqrt = x**(1/2.0), otherwise an integer division is performed and the expression 1/2 returns 0.

This behavior is "normal" in Python 2.x, whereas in Python 3.x 1/2 evaluates to 0.5. If you want your Python 2.x code to behave like 3.x w.r.t. division write from __future__ import division - then 1/2 will evaluate to 0.5 and for backwards compatibility, 1//2 will evaluate to 0.

And for the record, the preferred way to calculate a square root is this:

import math
math.sqrt(x)