How do I calculate square root in Python?
sqrt=x**(1/2)
is doing integer division. 1/2 == 0
.
So you're computing x(1/2) in the first instance, x(0) in the second.
So it's not wrong, it's the right answer to a different question.
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 mathmath.sqrt(x)
import mathmath.sqrt( x )
It is a trivial addition to the answer chain. However since the Subject is very common google hit, this deserves to be added, I believe.