# 用R语言实现牛顿迭代求最优点

2017/03/10 12:26

→f'(x) = f'(x0)+f''(x0)*(x-x0)  #一阶导为零是极值

→x = x0 - f'(x0)/f''(x0)         #公式

x = 5  #初始值，自己定
diedai   = 40 #迭代次数
g        = function(x){x^2+2} #目标函数
g.prime  = function(x){2*x}    #一阶导
g.2prime = function(x){2}      #二阶导

#公式
for(i in 1:diedai){x = x - g.prime(x)/g.2prime(x)}
x



> x
[1] 5
>
>
> x = 5  #初始值，自己定
> diedai   = 40 #迭代次数
> g        = function(x){x^2+2} #目标函数
> g.prime  = function(x){2*x}    #一阶导
> g.2prime = function(x){2}      #二阶导
>
> #公式
> for(i in 1:diedai){x = x - g.prime(x)/g.2prime(x)}
> x
[1] 0

---------------------------------------------------------------------------------------------------------

x = 5  #初始值，自己定
diedai   = 40 #迭代次数
g        = function(x){sin(x)^3+log(cos(x))+x^(-1)} #目标函数
x=5
g.prime  = function(x){
fun = expression(sin(x)^3+log(cos(x))+x^(-1))
D(fun,'x')
f = deriv(D(fun,'x'),'x',func=T)
f(x)}    #一阶导
g.2prime = function(x){
D(D(fun,'x'),'x')
f = deriv(D(D(fun,'x'),'x'),'x',func=T)
f(x)}      #二阶导

#公式
for(i in 1:diedai){x = x - g.prime(x)/g.2prime(x)}
x


--------------------------------------------------------------------------------------------------------

0
0 收藏

0 评论
0 收藏
0