14-p14_sqrt2

import math


def sqrt(a, epoches=4000, alpha=0.01):
    def y(x, a):
        return abs(x**2 - a)

    def dy_dx(x, a):
        dy = x**2 - a
        return 2 * x * (1 if dy > 0 else -1)

    def dx(x, a, alpha):
        return - dy_dx(x, a) * alpha

    x = 1.0
    for _ in range(epoches):
        x += dx(x, a, alpha)
    return x


if __name__ == '__main__':
    for n in range(2, 10+1):
        print('%s, %8.4f, %8.4f' % (n, math.sqrt(n), sqrt(n)))

D:\Anaconda\python.exe D:/AI20/06_codes/deeplearning_20/p14_sqrt2.py
2,   1.4142,   1.4333
3,   1.7321,   1.7507
4,   2.0000,   1.9740
5,   2.2361,   2.2257
6,   2.4495,   2.4111
7,   2.6458,   2.6119
8,   2.8284,   2.8295
9,   3.0000,   2.9449
10,   3.1623,   3.1903

Process finished with exit code 0

发布了88 篇原创文章 · 获赞 2 · 访问量 1302

猜你喜欢

转载自blog.csdn.net/HJZ11/article/details/104507046
14
今日推荐