Python Forum
Square root of a number - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Square root of a number (/thread-1002.html)



Square root of a number - mbestivert - Nov-24-2016

I learned that there are two ways to compute the square root of a number. One is by using ** operator and the other by importing math module. Now, just out of curiosity I tried to do it in this way

>>> 81**(1/2)
1
>>> 64**(1/2)
1
So I know 1/2 = 0.5 plus any number to the power 0.5 is equivalent to the square root of that number. So why does the output always yield the value 1?

I am using Python 2.6.6 (for Windows) for Python course.


RE: Square root of a number - casevh - Nov-24-2016

The default behavior in Python 2 for integer division is to return an integer result that is floating point result. So 1/2 returns 0 instead of 0.5. This is known as "floor division".

There are a couple of fixes.

Convert one of the values to a float.

>>> 81**(1.0/2)
9.0
>>>
Python 3 changes the behavior of "/" to return a float. If changing to Python 3 is not practical, you can change the behavior of Python 2 to match Python 3 by using "from __future__ import division".

>>> from __future__ import division
>>> 81**(1/2)
9.0