CodingBeginner CodingBeginner - 4 months ago 16
Python Question

How to change the code to find an approximation to the cube root of both negative and positive numbers?

So I'm entirely new to coding and I'm taking the MIT Openwarecourse to get started (and I'm using the book Introducing to Computation and Programming using Python)

Also since I'm new here I'm a bit afraid that my question is low quality so please point out if you think I should improve the manner on how I asks questions.

At 3.4 I'm given the code:

x = int(input("Please enter an integer: "))
epsilon = 0.01
numGuesses = 0
low = -100
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 ("numGuesses =", numGuesses)
print (ans, "Is close to square root of", x)


So what I tried to do first is understand each line of the code and what it exactly does. I've been given the hint: "Think about changing low to ensure that the answer lies within the region being searched.)

I've tried to change low to a negative number and I tried to add if low is less than 0, then low = -low like this:

x = int(input("Please enter an integer: "))
epsilon = 0.01
numGuesses = 0
low = 0.0
if low < 0:
low = -low
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 ("numGuesses =", numGuesses)
print (ans, "Is close to square root of", x)


However I'm probably taking a wrong approach...

Answer

There is no such thing as the square or cubic root of a negative number.

Your algorithm is a numerical search through dichotomy method applied to X^2-x=0, it converges (quite fast actually) towards the solution X=sqrt(x) as long as low is lower than the solution, and high is higher than the solution.

In your case x is always higher than sqrt(x) and 0 is always lower than sqrt(x). The answer will always lie within the region being searched, there is no point in changing the initialisation of low. If you lower it to negative values, it will only require a few more step, roughly log2(abs(low))

change

 ans**2

to

ans**3 

and your algorithm converges to the cubic root of x.

The cubic root of negative value is ill-posed, I guess what they mean is -(abs(x)^(1/3)), one of the three solutions of X^3-x = 0. If x<0, replace x by abs(x), run the algorithm and return the opposite result.

Comments