Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Square root of a number
#1
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.
Quote
#2
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
micseydel and nilamo like this post
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Square Root on calculator MP1234593 1 2,386 Jun-06-2017, 06:58 PM
Last Post: nilamo

Forum Jump:


Users browsing this thread: 1 Guest(s)