This code gives pretty accurate result when deltanum = 0.0000000000001
but gets into an infinite loop when deltanum = 0.00000000000001
(adding another zero into deltanum
).
It occurs only for non-perfect cubes, it works fine for perfect cubes like 1000. Why?
I am new to programming, following OSSU.
num = 100
high = num
low = 0
icount = 0
cuberoot = (high + low)/2 #cuberoot of num
deltanum = 0.00000000000001
while abs(cuberoot**3 - num)>=deltanum:
icount+=1
print(icount)
if cuberoot**3 > num:
high = cuberoot
elif cuberoot**3 < num:
low = cuberoot
else:
break
cuberoot = (high + low)/2
print("Cube root: " + str(cuberoot))
print("Number of iterations: " + str(icount))
You are using float
s. float
math is flawed precision wise - your delta might be to small to work correctly and your solution flipps between values without ever reaching your while
conditions limit. See Is floating point math broken? for more reasoning about why float is sometimes "broken".
You can limit it to a certain amount of repeats as well:
num = 100
high = num
low = 0
icount = 0
maxcount = 100000
cuberoot = (high + low)/2 #cuberoot of num
deltanum = 0.00000000000001
while abs(cuberoot**3 - num)>=deltanum:
icount+=1
print(icount)
if cuberoot**3 > num:
high = cuberoot
elif cuberoot**3 < num:
low = cuberoot
else:
break
cuberoot = (high + low)/2
if icount > maxcount:
print("Unstable solution reached after ",maxcount, "tries")
break
print("Cube root: " + str(cuberoot) + " yields " + str(cuberoot**3))
print("Number of iterations: " + str(icount))
Output:
Unstable solution reached after 100000 tries
Cube root: 4.641588833612779 yields 100.00000000000003
Number of iterations: 100001