Langfao Langfao - 1 year ago 140
Python Question

Calculating cube root: OverflowError: ('Result too large')

So I'm supposed to create a code that calculates the cube root of an inputted number with the approximation of up to 2 decimal places. This code above calculates the square root of a number with up to 2 decimal places:

epsilon = 0.01
guess = num/2.0
while abs(guess**2 - num) >= epsilon:
guess = guess - abs(guess**2 - num) / (2 * guess)
print("Guess:", guess)

So apparently I am able to do the cube root with that criteria by modifying this code that was given and using this in the code:

delta = abs(guess**3 - num) / 100.0

I tried using that line and modifying the code used for square root and I keep getting:

OverflowError: ('Result too large')

This is what my code looks like so far:

num = float(input("Enter a number: "))
epsilon = 0.01
guess = num/2.0
while abs(guess**3 - num) >= epsilon:
guess = abs(guess - (guess**3 - num)/100.0)
print("Guess:", guess)

When I run that code above this is what happens:

runfile('C:/Users/100617828/Documents/CSCI1040U/', runfile('C:/Users/100617828/Documents/CSCI1040U/', wdir='C:/Users/100617828/Documents/CSCI1040U')

Enter a number: 34 Traceback (most recent call last):

File "", line 1, in runfile('C:/Users/100617828/Documents/CSCI1040U/', wdir='C:/Users/100617828/Documents/CSCI1040U')

File "C:\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\", line 699, in runfile execfile(filename, namespace)

File "C:\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\", line 88, in execfile exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)

File "C:/Users/100617828/Documents/CSCI1040U/", line 11, in while abs(guess**3 - num) >= epsilon:

OverflowError: (34, 'Result too large')

enter image description here

This is what my assignment sheet is telling me to do but it seems I don't need to use
delta = abs(guess**3 - num)/100.0

Answer Source

The method you are using is called Newton-Raphson approximation, and you should use the first derivative of the function you are trying to solve as the denominator. Because the first derivative of x^3 is 3*x^2, the iteration line must be:

guess = guess - abs(guess**3 - num) / (3 * guess**2)

See the working code at

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download