Python练习(4):牛顿拉复生算法求解根

用这种算法求解的答案收敛速度远远快于二分法!,而且不需要顾及到x小于1的情况.

def NRSquareroot(x,ellipson):
    assert(x>0)
    assert(ellipson > 0)
    ellipson = min(x/1e3,ellipson)#ensure the epplison is appropriate
    guess = x/2
    ctr = 0
    while(abs(guess*guess-x)>ellipson):
        guess = guess - (guess*guess-x)/(2*guess)
        print(guess)
        ctr += 1
    assert(ctr<100)
    print('ans' , guess)
NRSquareroot(1e-6,0.0001)

用来求n次根(只考虑x大于0的情况,其余情况就和二分法一样用一个变量记录符号就可以了,就不重复写了)

def NRSquareroot(x,n,ellipson):
    assert(x>0)
    assert(ellipson > 0)
    ellipson = min(x/1e3,ellipson)#ensure the epplison is appropriate
    guess = x/2
    ctr = 0
    while(abs(guess**n-x)>ellipson and ctr<100):
        guess = guess - (guess**n-x)/(n*(guess**(n-1)))
        print(guess)
        ctr += 1
    print('ans',guess)
NRSquareroot(1e6,3,0.0001)

你可能感兴趣的:(Python练习(4):牛顿拉复生算法求解根)