用梯度下降的方法求平方根

y = x y=\sqrt{x} y=x ,则有 y 2 = x y^2=x y2=x

两边对 x x x 求导,得到:
d ( y 2 ) d x = d ( x ) d x 2 y d y d x = 1 d y d x = 1 2 y = 1 2 x \begin{align} \frac{d(y^2)}{dx} &= \frac{d(x)}{dx} \\ 2y\frac{dy}{dx} &= 1 \\ \frac{dy}{dx} & = \frac{1}{2y} = \frac{1}{2\sqrt{x}} \end{align} dxd(y2)2ydxdydxdy=dxd(x)=1=2y1=2x 1
其实正常算就行。上面是chatgbt的脑回路。
y = x = x 1 / 2 求导为 1 2 x − 1 / 2 = 1 2 ∗ 1 x \begin{align} y=\sqrt{x} = x^{1/2} \\ 求导为 \frac{1}{2} x^{-1/2} = \frac{1}{2}* \frac{1}{\sqrt{x} } \end{align} y=x =x1/2求导为21x1/2=21x 1
因此,平方根函数的导数为 1 2 x \frac{1}{2\sqrt{x}} 2x 1

搞错了,没用,其实就是让y_hat无限接近真实值a。

#!/usr/bin/python
# -*- coding:utf-8 -*-

import math

# 平方根函数为 y = x^(1/2)
if __name__ == "__main__":
    learning_rate = 0.01
    a = 37
    y_hat = 0
    for i in range(100):
        y_hat -= learning_rate*(y_hat**2 - a)
        print(y_hat)
    print(' %d的平方根(近似)为:%.8f,真实值是:%.8f' % (a, y_hat, math.sqrt(a)))

0.37
0.738631
1.10317524245839
1.4610052863026588
1.8096599218366156
2.1469112315095984
2.4708189531497777
2.779769490157336
3.07249830597324
3.3480958475711557
3.6059983895259236
3.845966145673288
4.068051589736638
4.27256115236905
4.460013364361719
4.631096172258867
4.786625654691759
4.927507803110227
5.054704471613105
5.16920409865965
5.271997388523653
5.364057823877651
5.446326660498621
5.51970191957004
5.585030826760988
5.643105133402283
5.694658777935971
5.740367391964739
5.780849214017418
5.8166670376653595
5.848330883394732
5.876301142178046
5.900991991042416
5.922774926258948
5.941982297987732
5.958910761691736
5.97382458703368
5.986958785067198
5.998522030126265
6.008699364667164
6.017654684117648
6.025533005144817
6.032462525183922
6.038556484006438
6.043914839901077
6.048625773981312
6.052767036444602
6.056407148469899
6.059606472989526
6.0624181669145605
6.064889026609204
6.067060237558357
6.06896803829674
6.070644307798066
6.072117084680055
6.073411025779421
6.074547810898831
6.075546499829873
6.076423847113922
6.077194579416175
6.077871639855322
6.078466403149745
6.078988865007544
6.079447808798687
6.079850952199616
6.08020507618999
6.080516138504724
6.08078937339856
6.0810293793621915
6.08124019623553
6.081425372992423
6.081588027319663
6.081730897979284
6.081856390824925
6.081966619238745
6.0820634396634015
6.082148482822499
6.082223181151499
6.082288792898132
6.08234642329599
6.082397043166174
6.082441505259008
6.082480558610033
6.082514861151343
6.0825449907900735
6.0825714551402195
6.082594700071353
6.082615117217992
6.082633050575904
6.082648802296321
6.082662637775552
6.082674790125646
6.0826854641013455
6.082694839549448
6.082703074438633
6.082710307520781
6.082716660668585
6.082722240928834
6.082727142325931
6.0827314474460445
 37的平方根(近似)为:6.08273145,真实值是:6.08276253

你可能感兴趣的:(深度学习)