您的位置:首页 > 理论基础

学习日记-MIT[计算机科学与编程导论]-6

2015-07-21 12:46 211 查看


二分法,牛顿-拉夫逊方法,对于列表的简介

1.二分法(续):在上一堂课中,程序存在bug,对于x在(0,1)的情形将无法在迭代的过程中求出平方根,因为范围的调整不适用。

此处修正方法:将语句high=x修改为high=max(x,1)即可。

2. ​Newton-Raphson method 牛顿拉夫逊法

对于sqrt(x)的求取,本质是对f(guess)=guess*guess-x=0的求取。

猜想数guess处做切线,斜率为2x,与x轴的交点值会比猜想数更接近解sqrt(x)。

所以新的猜想点迭代公式为:guess(i+1)=guess(i)-f[guess(i)]/[2*guess(i)]

代码如下:​

def  squarerootNR(x,epsilon):

"""this function is to return a square root of

x within 100 times iteration and may not

figure out the true answer"""

assert x>=0

assert epsilon>0

x=float(x)

guess=x/2.0

diff=guess**2-x

cnt=1

while abs(diff)>=epsilon and cnt<=100:

guess=guess-diff/(2*guess)

diff=guess**2-x

cnt+=1

assert cnt<=100

print("The square root of %f=%f,iteration:%d"%(x,guess,cnt))


经过测试可知,NR法较二分法更有效率。

3.​列表的相关知识

​ 1)append、remove方法

2)可嵌套,可变性​
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: