Langfao - 1 month ago 9

Python Question

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/edits.py', runfile('C:/Users/100617828/Documents/CSCI1040U/edits.py', 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/edits.py', wdir='C:/Users/100617828/Documents/CSCI1040U')

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

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

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

OverflowError: (34, 'Result too large')

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

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 https://repl.it/DqZA/0