We mentioned in class that Newton’s method can work very slowly when finding minima of certain functions. The problem arises when more than one derivative vanishes at the minimum. Remember that if x ∗ is the minimum of a smooth function f(x), then f ' (x ∗ ) is zero. If f ''(x ∗ ) is also zero, then Newton’s method will take longer to converge. If f ''(x ∗ ) and f '''(x ∗ ) are both zero, then Newton’s method will take longer still. We will explore this phenomenon in the following problem. In each part, you should use a tolerance of 10^−8 and an initial guess of x_0 = 2.
(1) The function f(x) = x^2 has a minimum at x ∗ = 0. It is easy to check that f ' (0) = 0 but that f ''(0) 6= 0. Use Newton’s method to approximate this minimum. Save the number of iterations it takes, with the initial iteration counting as an iteration, in a variable named A4. Save the final iteration in a variable named A5.
(2) Repeat the process above with f(x) = x^500. Save the number of iterations Newton’s method took in A6 and save the final iteration in A7.
(3) Repeat the process above with f(x) = x^1000. Save the number of iterations Newton’s method took in A8 and save the final iteration in A9. (Your final iteration for this and the previous part may look strange, but you should be able to confirm that f 0 is very close to zero for these iterations.)
从x = 2开始计算,精确到1e-8,求迭代次数和最终值
失败的代码
i = 0
x = 2
n = 1
for i in range(499999):
if abs(x)<=1e-8:
break
else:
x = (1- 1/500)*x
n = n + 1
print(x)
失败的代码是指代码运行不了,还是达不到预期目标呢。
建议print(x)放到循环内部打印x值的变化看看。
如果达不到效果,可以考虑增加循环次数。
题主的迭代直线方程是错误的,所以得不到正确的结果。我把直线的斜率k和截距b都写出来, 下面的结果应该是可信的。
>>> n, x = 0, 2
>>> while abs(x) > 1e-8:
k, b = 500*pow(x,499), -499*pow(x, 500)
x = -b/k
n += 1
>>> x
0.0
>>> n
1089
如果把整个迭代过程记录下来,也许更有意思。
>>> x = [2]
>>> while abs(x[-1]) > 1e-8:
k, b = 500*pow(x[-1],499), -499*pow(x[-1], 500)
x.append(-b/k)
>>> len(x) - 1 # 迭代次数,减一是因为有一个初始值
1089
>>> x[-1] # 最终值
0.0
>>> x[-3:] # 最后的3个迭代值
[0.2273327032136106, 0.2246806282722513, 0.0]
>>> x[:3] # 最初的3个迭代值
[2, 1.996, 1.9920079999999998]
您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~
如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~
ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632
非常感谢您使用有问必答服务,为了后续更快速的帮您解决问题,现诚邀您参与有问必答体验反馈。您的建议将会运用到我们的产品优化中,希望能得到您的支持与协助!
速戳参与调研>>>https://t.csdnimg.cn/Kf0y