这段代码在deltanum = 0.0000000000001
时给出相当准确的结果,但在deltanum = 0.00000000000001
时进入无限循环(在deltanum
中再加一个零)。你知道吗
它只适用于非完美立方体,对1000个完美立方体也适用。为什么?你知道吗
我是编程新手,跟随奥苏。你知道吗
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))
大多数人会把它命名为
epsilon
,并用delta
表示cuberoot**3 - num
。你知道吗最后,你希望这个表达
将为您在每次迭代中获得大约多一点的精确性。 (接近开始时,每次大约将错误位数减半。)
您在抱怨IEEE-754 double在计算多维数据集时精度有限,而且存在差异。 53位给出了16位小数,而ε是
1e-14
。 但是一个输入num
只有几个数字长,就会消耗掉你的边距,正如你发现的那样。你知道吗对于更高精度的计算,您可能更喜欢使用Decimal。 或者,查看gmp库。你知道吗
你相信某种循环不变量成立, 数量
cuberoot
和cuberoot ** 3
在每次迭代中都会改变。 验证起来很简单。 只需将它们赋给临时变量,并验证它们是否更改。 如果他们没有提前终止循环。 更一般而言,要检测少数限制值之间的振荡,请将以前的值放入set
中,并在看到重复值时提前终止。你知道吗您使用的是
float
s。float
数学在精度方面有缺陷-您的增量可能太小,无法正常工作,并且您的解决方案在值之间翻转,而从未达到while
条件限制。请参阅Is floating point math broken?了解有关为什么float有时会“中断”的更多推理。你知道吗您也可以将其限制为一定的重复次数:
输出:
相关问题 更多 >
编程相关推荐