乐趣区

求解平方根

求解平方根,是多项式求解的一个最简单的特例。
分别采用梯度下降和牛顿迭代解法如下。
其中梯度下降的步进如何选择有点不解,迭代次数比牛顿多太多了。

import sys 
import math

def gradient_descent(y):
    x = 1 
    alpha = 0.001
    delta = 1 
    count = 0 
    while abs(delta) > 0.000001:
        delta = 4 * x * (x ** 2 - y)
        x -= alpha * delta
        count += 1
        #print("y=%f\tcount=%d\tx=%f\tdelta=%f\n"%(y, count, x, delta))
    return x,count

def niudun(y):
    x = 1 
    delta = abs(x ** 2 - y)
    count = 0;
    while delta > 0.000001:
        x = (x + y/x) / 2 
        delta = abs(x * x - y)
        count += 1
        #print("y=%f\tcount=%d\tx=%f\tdelta=%f\n"%(y, count, x, delta))
    return x,count


while True:
    try:
        print "select mode, 1-gradient_descent, 2-niudun, and input y to sqrt"
        m, y = map(float, sys.stdin.readline().split(' '))
        if m == 1:
            x, cnt = gradient_descent(y)
        else:
            x, cnt = niudun(y)
        print("mode=%d, sqrt(%f)=%f, delta=%f, cnt=%d" % (m, y,x, x-math.sqrt(y), cnt))
    except RuntimeError, e:
        print("exception:", e)
        continue
       
退出移动版