How do I calculate square root in Python?

Merlin picture Merlin · Mar 7, 2012 · Viewed 468.8k times · Source

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.

Answer

smessing picture smessing · Mar 7, 2012

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.