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 math
math.sqrt(x)
import math
math.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.
/
performs an integer division in Python 2:
>>> 1/2
0
If one of the numbers is a float, it works as expected:
>>> 1.0/2
0.5
>>> 16**(1.0/2)
4.0
What you're seeing is integer division. To get floating point division by default,
from __future__ import division
Or, you could convert 1 or 2 of 1/2 into a floating point value.
sqrt = x**(1.0/2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With