# -*- coding: cp936 -*- xOld = 0 xNew = 1 # The algorithm starts at x=6 moveDistance = 0.01 # step size precision = 0.00001 def evaluateEquation(x): """计算原函数在自变量为x时的值""" return x**4-3*x**3+2 def evaluateGradient(x): """计算梯度向量""" return 4 * x**3 - 9 * x**2 step=0 while abs(evaluateEquation(xNew) - evaluateEquation(xOld)) > precision: step+=1 xOld = xNew xNew = xOld - moveDistance * evaluateGradient(xNew) print "step",step,"xold=",xOld, "xnew=",xNew print("Local minimum occurs at ", xNew, "with minimum value",evaluateEquation(xNew)) print "step",step
>>> step 1 xold= 1 xnew= 1.05 step 2 xold= 1.05 xnew= 1.10292 step 3 xold= 1.10292 xnew= 1.1587338169 step 4 xold= 1.1587338169 xnew= 1.21734197218 step 5 xold= 1.21734197218 xnew= 1.27855469659 step 6 xold= 1.27855469659 xnew= 1.34207564416 step 7 xold= 1.34207564416 xnew= 1.40748858095 step 8 xold= 1.40748858095 xnew= 1.47424999816 step 9 xold= 1.47424999816 xnew= 1.54169100548 step 10 xold= 1.54169100548 xnew= 1.60903167429 step 11 xold= 1.60903167429 xnew= 1.67540991642 step 12 xold= 1.67540991642 xnew= 1.73992485396 step 13 xold= 1.73992485396 xnew= 1.80169165901 step 14 xold= 1.80169165901 xnew= 1.85990167873 step 15 xold= 1.85990167873 xnew= 1.91387933776 step 16 xold= 1.91387933776 xnew= 1.96312685144 step 17 xold= 1.96312685144 xnew= 2.00734969025 step 18 xold= 2.00734969025 xnew= 2.04645960885 step 19 xold= 2.04645960885 xnew= 2.08055667019 step 20 xold= 2.08055667019 xnew= 2.10989555269 step 21 xold= 2.10989555269 xnew= 2.13484344301 step 22 xold= 2.13484344301 xnew= 2.15583674372 step 23 xold= 2.15583674372 xnew= 2.17334219049 step 24 xold= 2.17334219049 xnew= 2.1878256603 step 25 xold= 2.1878256603 xnew= 2.19972976112 step 26 xold= 2.19972976112 xnew= 2.20945968856 step 27 xold= 2.20945968856 xnew= 2.21737593374 step 28 xold= 2.21737593374 xnew= 2.22379211672 step 29 xold= 2.22379211672 xnew= 2.22897629956 step 30 xold= 2.22897629956 xnew= 2.23315441132 step 31 xold= 2.23315441132 xnew= 2.23651475494 step 32 xold= 2.23651475494 xnew= 2.23921288183 step 33 xold= 2.23921288183 xnew= 2.24137637832 step 34 xold= 2.24137637832 xnew= 2.24310930133 step 35 xold= 2.24310930133 xnew= 2.24449613419 step 36 xold= 2.24449613419 xnew= 2.24560522103 step 37 xold= 2.24560522103 xnew= 2.24649169063 step 38 xold= 2.24649169063 xnew= 2.24719990952 step 39 xold= 2.24719990952 xnew= 2.24776551743 step 40 xold= 2.24776551743 xnew= 2.24821710187 step 41 xold= 2.24821710187 xnew= 2.2485775668 step 42 xold= 2.2485775668 xnew= 2.24886524544 ('Local minimum occurs at ', 2.2488652454412037, 'with minimum value', -6.542955721127889) step 42
Nykamp DQ, “Directional derivative on a mountain.” From Math Insight. http://mathinsight.org/applet/directional_derivative_mountain
Keywords: directional derivative

所有评论(0)