# 符號微分

``````> f=expression(x^2, 'x')
> D(f, 'x')
2 * x
> df = D(f, 'x')
> df
2 * x
> D(df, 'x')
[1] 2
> f=expression(sin(5*x), 'x')
> D(f, 'x')
cos(5 * x) * 5
> D(D(f, 'x'), 'x')
-(sin(5 * x) * 5 * 5)
> f=expression(exp(x), 'x')
> f
expression(exp(x), "x")
> D(f, 'x')
exp(x)
> D(D(f,'x'),'x')
exp(x)
>```
```

``````> D(expression(x^n),"x")
x^(n - 1) * n
> D(expression(exp(a*x)),"x")
exp(a * x) * a
> D(expression(1/x),"x")
-(1/x^2)
> D(expression(x^3),"x")
3 * x^2
> D(expression(pnorm(x)),"x")
dnorm(x)
> D(expression(dnorm(x)),"x")
-(x * dnorm(x))```
```

``````> foo <- expression((sin(x)^3+y)/(x+atan(y)))
> D(D(foo, "x"), "y")
-(3 * (cos(x) * sin(x)^2) * (1/(1 + y^2))/(x + atan(y))^2 + (1/(x +
atan(y))^2 - (sin(x)^3 + y) * (2 * (1/(1 + y^2) * (x + atan(y))))/((x +
atan(y))^2)^2))```
```

# 數值積分

``````> integrate(dnorm,-Inf,Inf)
1 with absolute error < 9.4e-05
> integrate(dnorm,-1.96,1.96)
0.9500042 with absolute error < 1.0e-11
> integrate(dnorm,-1.64,1.64)
0.8989948 with absolute error < 6.8e-14
# we can also store the result in an object
> ci90 <- integrate(dnorm,-1.64,1.64)
> ci90\$value
[1] 0.8989948
> integrate(dnorm,-1.64,1.64)\$value
[1] 0.8989948```
```

``````> library(adapt)
> ir2pi <- 1/sqrt(2*pi)
> fred <- function(z) { ir2pi^length(z) * exp(-0.5 * sum(z * z))}
>
> adapt(2, lo = c(-5,-5), up = c(5,5), functn = fred)
value       relerr       minpts       lenwrk        ifail
1.039222 0.0007911264          231           73            0
> adapt(2, lo = c(-5,-5), up = c(5,5), functn = fred, eps = 1e-4)
value       relerr       minpts       lenwrk        ifail
1.000237 1.653498e-05          655          143            0
> adapt(2, lo = c(-5,-5), up = c(5,5), functn = fred, eps = 1e-6)
value      relerr      minpts      lenwrk       ifail
1.000039 3.22439e-07        1719         283           0```
```

# 使用 Ryacas 套件

Symbolic computation in R?

Yes. There is the Ryacas package which is hosted on Google Code here. Ryacas has recently been expanded/converted to the rMathpiper package which is hosted here. I have used Ryacas and it is straightforward, but you will need to install Yacas in order for it to work (Yacas does all the heavy lifting; Ryacas is just an R interface to Yacas).

There is also the rSymPy project hosted on Google Code here. I haven't tried this one. The idea is similar, though, link to the sympy CAS which does the symbolic work.

# 參考文獻

1. Using R for Introductory Calculus and Statistics
2. Plotting, Derivatives, and Integrals for Teaching Calculus in R, Daniel Kaplan, March 23, 2012

page revision: 15, last edited: 16 Jan 2014 02:20