Rで微分積分

help(deriv)
# 2変数の数式sin(cos(x+y^2))をexpressionモードのオブジェクトtrig.expに代入する
trig.exp <- expression(sin(cos(x + y^2)))
# 変数xで偏微分する
D.scx <- D(trig.exp, "x")
# deriv()関数を用いることもできる
D.scx2 <- deriv(trig.exp,"x")
# D()は数式表現を返す
# deriv()はexpressionモードのオブジェクトとして返す
# 変数yで偏微分する
D.scy <- D(trig.exp, "y")
# 2変数で微分する
# 2変数の場合にD()は使えない
dxy <- deriv(trig.exp, c("x", "y"))
# 微分の値がほしいときは、微分の結果を関数にして、その関数に変数の値を与えよう
dxyfx<-deriv(trig.exp,c("x","y"),func=TRUE)
dxyfx(0,1) # x=0,y=1のときの値
# たくさんの値を一度に
x<-seq(from=0,to=10,by=0.01)
y<-seq(from=0,to=20,by=0.01)
xy<-expand.grid(x,y)
derivXYout<-dxyfx(xy[,1],xy[,2])
image(x,y,matrix(derivXYout,length(x),length(y)))
integrate(dnorm, -1.96, 1.96)
integrate(dnorm, -Inf, Inf)

## a slowly-convergent integral
integrand <- function(x) {1/((x+1)*sqrt(x))}
integrate(integrand, lower = 0, upper = Inf)