I'm working on a program from Guttag's book, specifically altering the code from page 33 to work with negative numbers. The program is trying to find the square root of a number by using bisection search.
My problem in short:
>>> print(ans)
-12.0
>>> print(ans**2)
144.0
>>> print(-12**2)
-144
>>> -12.0**2
-144.0
Squaring a number (in this case -12) gives the correct answer that I expect when put in IDLE as a number. However, when it comes from a variable it suddenly turns positive. Any idea why this is happening and how to fix it?
My problem in the longer version in case I have understood something else wrong too:
x = float(input("Enter an integer, which square root you want to find: "))
epsilon = 0.01
numGuesses = 0
low = min(0.0, x)
high = max(1.0, x)
ans = (high + low)/2.0
while abs(ans**2 - x) >= epsilon:
print("low =", low, "high =", high, "ans =", ans)
numGuesses += 1
if (ans**2) < x:
low = ans
else:
high = ans
ans = (high + low)/2.0
print("Number of guesses =", numGuesses)
print(ans, "is close to square root of", x)
So where the while loop is deciding whether to assign the variable ans to high or low, it can't do so if working with a negative number from the beginning. If I, for example, run this program with x = -25, it will print out the following:
Enter an integer, which square root you want to find: -25
low = -25.0 high = 1.0 ans = -12.0
low = -25.0 high = -12.0 ans = -18.5
Though ans (-12) squared should be -144, which would assign that to "low" rather than to high and making the program work.
All advice appreciated.