Python Forum
Square root of a number
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.
Reply
#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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Finding square roots using long division. jahuja73 10 5,301 Feb-24-2021, 01:25 PM
Last Post: jahuja73
  Magic square! frequency 1 2,506 Dec-17-2018, 06:35 PM
Last Post: micseydel
  Square reverse sum(overloaded) shihomiyano 6 4,026 Aug-18-2018, 06:27 AM
Last Post: micseydel
  Perfect Square program forumer444 4 8,884 Sep-01-2017, 09:32 PM
Last Post: forumer444
  Magic Square Puzzle Harnick 1 4,843 Aug-09-2017, 04:51 PM
Last Post: nilamo
  Square Root on calculator MP1234593 1 7,862 Jun-06-2017, 06:58 PM
Last Post: nilamo
  List of square roots python py7 6 6,298 Apr-08-2017, 11:26 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020