How do I calculate square root in Python?


Question

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.

1
117
7/6/2019 10:46:15 PM

Accepted Answer

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.

218
8/17/2018 2:59:51 AM

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)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon