badCoder - 1 month ago 4

Python Question

I am trying to write a program that finds cubed root using delta and epsilon but i'm stuck because i cant figure out why my program runs in an infinite loop

`num = 100`

epsilon = 0.01

guess = num/3.0

while abs(guess**3 - num) >= epsilon:

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

if guess**3 > num:

guess = (guess - delta)

if guess**3 < num:

guess = (guess + delta)

print("Guess:", guess)

Answer

First thing, you should use `if/elif`

instead of separate `if`

blocks.

Consider the following:
when `guess**3 > num`

is `True`

, you update `guess`

by reducing its value so that `guess**3 < num`

(the next if condition) becomes `True`

again, which reverses the initial update. In summary, the value of `guess`

is never changed in that loop, and the loop whirls to infinity.

Secondly you want to regularize the `delta`

value (penalize it) as it can be come alarming large as the value of `num`

increases.

```
num = 100
epsilon = 0.01
guess = num/3.0
while abs(guess**3 - num) >= epsilon:
delta = abs(guess**3 - num)/num
if guess**3 > num:
guess = (guess - delta*epsilon**0.5)
elif guess**3 < num:
guess = (guess + delta*epsilon**0.5)
print("Guess:", guess)
```

Source (Stackoverflow)

Comments