gpt4 book ai didi

python - 尝试通过二分搜索查找非完美立方体的立方根时出现无限循环

转载 作者:太空宇宙 更新时间:2023-11-04 02:03:07 25 4
gpt4 key购买 nike

这段代码在 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 数学在精度方面存在缺陷 - 您的 delta 可能太小而无法正常工作,并且您的解决方案在值之间翻转而从未达到您的 while 条件限制。参见 Is floating point math broken?有关为什么 float 有时会“损坏”的更多原因。

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

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

关于python - 尝试通过二分搜索查找非完美立方体的立方根时出现无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55315519/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com