Python練習(4):ニュートンラ復生アルゴリズム解根

2311 ワード

このアルゴリズムで解く答えの収束速度は二分法よりはるかに速い!また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より大きい場合のみを考慮し、残りは二分法と同様に1つの変数で記号を記録すればよいので、繰り返し書かない)
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)