126
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.

Merlin
  • 24,552
  • 41
  • 131
  • 206

5 Answers5

278

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.

Merlin
  • 24,552
  • 41
  • 131
  • 206
smessing
  • 4,330
  • 1
  • 22
  • 19
133

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)
ChrisF
  • 134,786
  • 31
  • 255
  • 325
Óscar López
  • 232,561
  • 37
  • 312
  • 386
14

/ 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
Niklas B.
  • 92,950
  • 18
  • 194
  • 224
7

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)
gfortune
  • 2,589
  • 14
  • 14
0

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
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Vikrant
  • 125
  • 8