Why does Python give the "wrong" answer for square root? What is integer division in Python 2?

PythonMathPython 2.xSqrt

Python Problem Overview


x = 16

sqrt = x**(.5)  #returns 4
sqrt = x**(1/2) #returns 1

I know I can import math and use sqrt, but I'm looking for an answer to the above. What is integer division in Python 2? This behavior is fixed in Python 3.

Python Solutions


Solution 1 - Python

In Python 2, sqrt=x**(1/2) does integer division. 1/2 == 0.

So x(1/2) equals x(0), which is 1.

It's not wrong, it's the right answer to a different question.

If you want to calculate the square root without an import of the math module, you'll need to use x**(1.0/2) or x**(1/2.). One of the integers needs to be a floating number.

Note: this is not the case in Python 3, where 1/2 would be 0.5 and 1//2 would instead be integer division.

Solution 2 - Python

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)

Solution 3 - Python

/ 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

Solution 4 - Python

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)

Solution 5 - Python

Perhaps a simple way to remember: add a dot after the numerator (or denominator)

16 ** (1. / 2)   # 4
289 ** (1. / 2)  # 17
27 ** (1. / 3)   # 3

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMerlinView Question on Stackoverflow
Solution 1 - PythonsmessingView Answer on Stackoverflow
Solution 2 - PythonÓscar LópezView Answer on Stackoverflow
Solution 3 - PythonNiklas B.View Answer on Stackoverflow
Solution 4 - PythongfortuneView Answer on Stackoverflow
Solution 5 - PythonVikrantView Answer on Stackoverflow