############## # 関数形を与えてグラフを描き極値を求めるには # f1(x)を微分形で定義して # その導関数 attr(f1(x),"gradient")をf2 とし # f1(x) f2(x)のグラフを描き # unirootで f2(x)=0 の解を求め 範囲に注意 # 解はx=***$rootである # その解にあたるf1(x)が極値である f1 <- deriv(~2*sin(x)-x+2, "x", func=T) curve(f1(x),-6,6,col=4) sol <- uniroot(f1, c(2, 4)) # c の範囲で方程式f1(x)=0を解く sol arrows(sol$root, 3, sol$root, 0,col=4) f2 <-function(x) attr(f1(x),"gradient") curve(f2(x),col=2,add=T) abline(v = 0, col = 5) # x 軸を描く abline(h = 0, col = 5) # y 軸を描く so1 <- uniroot(f2, c(-6, -4)) # c の範囲で方程式f2(x)=0を解く #so1 so2 <- uniroot(f2, c(-2, 0)) # c の範囲で方程式f2(x)=0を解く #so2 arrows(so1$root, f1(so1$root)-2, so1$root, f1(so1$root)) arrows(so2$root, f1(so2$root)+2, so2$root, f1(so2$root)) so1$root;f1(so1$root) so2$root;f1(so2$root) text(so1$root,6,round(so1$root,3)) text(so1$root,5,round(f1(so1$root),3)) text(so2$root,6,round(so2$root,3)) text(so2$root,5,round(f1(so2$root),3)) text(sol$root,4,paste("f(x)=0 の解 ",round(sol$root,3)),col=4) mtext("その導関数",3,0,col=2) title("f(x) = 2*sin(x)-x+2")