Why does Python give the "wrong" answer?
x = 16 sqrt = x**(.5) returns 4 sqrt = x**(1/2) returns 1
Yes, I know
import math and use
sqrt. But I'm looking for an answer to the above.
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
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
And for the record, the preferred way to calculate a square root is this:
import math math.sqrt(x)