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.
5 Answers
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.
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) 0/ 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) 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