这段代码在deltanum = 0.0000000000001时给出了非常准确的结果,但是在deltanum = 0.00000000000001时陷入了无限循环(在deltanum中添加了另一个零)。

它仅适用于非完美的多维数据集,适用于完美的多维数据集(例如1000)。为什么?

我是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))

最佳答案

您正在使用floatfloat数学在准确性方面有缺陷-您的增量可能太小而无法正常工作,并且您的解决方案在值之间翻转而从未达到while条件的限制。有关为何有时会“中断”浮动的更多原因,请参见Is floating point math broken?

您也可以将其限制为一定的重复次数:

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))


输出:

Unstable solution reached after  100000 tries
Cube root: 4.641588833612779 yields 100.00000000000003
Number of iterations: 100001

10-07 19:11
查看更多