关于MIT 6.00课程lec06--牛顿法
我尝试用自己的方式编码,但发现我得到了错误的答案。
我已阅读此页面。并尝试启动该过程:
f(x)=x^2-e
数学:
所以这是我的代码:
def sqrtRootNR(num, count, epsl):
"""
for test
"""
num = float(num)
guess = num / 2.0
diff = guess ** 2.0 - num
_cnt = 0
while abs(diff) > epsl and _cnt < count:
guess = guess - (guess ** 2.0 + epsl) / (guess * 2.0)
diff = guess ** 2.0 - num
_cnt = _cnt +1
print guess, _cnt
sqrtRootNR(2, 100, 0.0001)
但是,我得到了错误的答案。
该函数的输出是:
D:\poc>python sq.py
0.0595177826557 100
I have tried to code in my own way, but found I got the wrong answer.
I have read this page. And try to start the process:
f(x)=x^2-e
The math:
So there is my code:
def sqrtRootNR(num, count, epsl):
"""
for test
"""
num = float(num)
guess = num / 2.0
diff = guess ** 2.0 - num
_cnt = 0
while abs(diff) > epsl and _cnt < count:
guess = guess - (guess ** 2.0 + epsl) / (guess * 2.0)
diff = guess ** 2.0 - num
_cnt = _cnt +1
print guess, _cnt
sqrtRootNR(2, 100, 0.0001)
However, I got the wrong answer.
The output of this function is:
D:\poc>python sq.py
0.0595177826557 100
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
编程的一项重要技能是知道哪些信息最有用。如果添加一些简单的调试信息:
您可以看到您的程序很快就会出错:
每次迭代似乎都会将数字减半,直到变为负数,此时行为很难一眼看出。但你可以明显看出,最初的几次迭代是错误的。
对我来说看起来很可疑的东西:
(guess ** 2.0 + epsl)
在评估牛顿平方根方法时,您实际上不应该使用 epsilon - 毕竟,您试图确保您的误差小于epsilon。
One important skill in programming is knowing which information where will be most useful. If you add some simple debugging information:
You can see that your program goes wrong quickly:
It appears to halve the number every iteration until it goes negative, when the behavior gets very difficult to tell just at a glance. But you can obviously tell that the very first few iterations are wrong.
Something that looks quite fishy to me:
(guess ** 2.0 + epsl)
You shouldn't actually use epsilon when evaluating Newton's method for square roots -- after all, you're trying to make sure your error is less than epsilon.
看起来您正在寻找函数 f = x^2+eps1 的零点。如果 eps1 为正,则不会有实数零。这意味着您的程序将在某个点之后永远围绕 0 振荡,如您所见。如果将 eps1 设置为负值,我希望您会找到根。
牛顿方法并非万无一失,在某些情况下它可能会发散。
It looks like you are looking for zeroes of the function f = x^2+eps1. If eps1 is positive, there will be no real zeroes. This means that your program will oscillate around 0 forever after a certain point, as you saw. If you set eps1 to a negative value, I expect you would find a root.
Newton's method isn't bullet-proof, and there are cases where it can diverge.
将方程中的
(guess ** 2.0 + epsl)
更改为(guess ** 2 - num)
。您希望每一步调整您的估计,调整量与您的错误成正比,即。你的diff
变量。Change
(guess ** 2.0 + epsl)
to(guess ** 2 - num)
in your equation. You want to adjust your estimate every step by an amount proportional to your error, ie. yourdiff
variable.您还可以使用
guess = 0.5 * (guess + num/guess)
You also can use
guess = 0.5 * (guess + num/guess)