Why does Python give the "wrong" answer?
x = 16
sqrt = x**(.5) #returns 4
sqrt = x**(1/2) #returns 1
Yes, I know import math
and use sqrt
. But I'm looking for an answer to the above.
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)
This might be a little late to answer but most simple and accurate way to compute square root is newton's method.
You have a number which you want to compute its square root (num)
and you have a guess of its square root (estimate)
. Estimate can be any number bigger than 0, but a number that makes sense shortens the recursive call depth significantly.
new_estimate = (estimate + num / estimate) / 2
This line computes a more accurate estimate with those 2 parameters. You can pass new_estimate value to the function and compute another new_estimate which is more accurate than the previous one or you can make a recursive function definition like this.
def newtons_method(num, estimate):
# Computing a new_estimate
new_estimate = (estimate + num / estimate) / 2
print(new_estimate)
# Base Case: Comparing our estimate with built-in functions value
if new_estimate == math.sqrt(num):
return True
else:
return newtons_method(num, new_estimate)
For example we need to find 30's square root. We know that the result is between 5 and 6.
newtons_method(30,5)
number is 30 and estimate is 5. The result from each recursive calls are:
5.5
5.477272727272727
5.4772255752546215
5.477225575051661
The last result is the most accurate computation of the square root of number. It is the same value as the built-in function math.sqrt().
If you want to do it the way the calculator actually does it, use the Babylonian technique. It is explained here and here.
Suppose you want to calculate the square root of 2:
a=2
a1 = (a/2)+1
b1 = a/a1
aminus1 = a1
bminus1 = b1
while (aminus1-bminus1 > 0):
an = 0.5 * (aminus1 + bminus1)
bn = a / an
aminus1 = an
bminus1 = bn
print(an,bn,an-bn)
import math
and thenx = math.sqrt(25)
which will assign the value5.0
to x. – Eric Leschinski