-
Notifications
You must be signed in to change notification settings - Fork 0
/
README.Rmd
executable file
·83 lines (65 loc) · 2.46 KB
/
README.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
---
title: "dfdr — automatic differentiation of simple functions in R"
author: "Thomas Mailund"
output:
md_document:
variant: markdown_github
---
[![Travis-CI Build Status](https://travis-ci.org/mailund/dfdr.svg?branch=master)](https://travis-ci.org/mailund/dfdr)
[![Coverage Status](https://img.shields.io/codecov/c/github/mailund/dfdr/master.svg)](https://codecov.io/github/mailund/dfdr?branch=master)
[![Coverage Status](https://coveralls.io/repos/github/mailund/dfdr/badge.svg?branch=master)](https://coveralls.io/github/mailund/dfdr?branch=master)
# dfdr — Automatic differentiation of simple functions in R
The `dfdr` package implements a simple version of automatic differentiation. It takes functions that consist of a single expression and construct the derivative with respect to a specific variable.
To install `dfdr` you can use `devtools`.
```r
install.packages("devtools")
devtools::install_github("mailund/dfdr")
```
and then load the library with
```{r}
library(dfdr)
```
To compute the derivative of a function, you use the function `d`. It takes two arguments, the function to compute the derivative of and the variable to compute the derivative with respect to.
```{r}
f <- function(x) x^2 + sin(x)
df <- d(f, "x")
df
```
We can plot a function together with selected tangents to see how it works:
```{r}
plot_tangent <- function(f, var, at, L = 1, df = NULL) {
if (is.null(df)) {
x <- substitute(var)
df <- d(f, x)
}
a <- df(at)
w <- L / sqrt(1 + a^2)
v <- a * w
x <- c(at - w, at + w)
y <- c(f(at) - v, f(at) + v)
lines(x, y, lty = "dashed", col = "darkred")
points(at, f(at), pch = 20)
}
x <- seq(-1.5, 0.9, length.out = 100)
plot(x, f(x), type = "l", asp = 1)
plot_tangent(f, x, -1)
plot_tangent(f, x, -0.2)
plot_tangent(f, x, 0.1)
plot_tangent(f, x, 0.7)
```
```{r}
plot(x, sin(x), type = "l", asp = 1)
plot_tangent(sin, x, -2)
plot_tangent(sin, x, -1)
plot_tangent(sin, x, 0.5)
plot_tangent(sin, x, 2.5)
```
```{r}
plot(x, exp(x), type = "l")
plot_tangent(exp, x, -2, L = 1)
plot_tangent(exp, x, 0.0, L = 1)
plot_tangent(exp, x, 1.5, L = 3)
plot_tangent(exp, x, 2.5, L = 4)
```
The body of the deriatives are simplified to a certain extend, but in a depth-first approach with no rewriting of expressions, so thehy sometimes can be more complex than you would normally see them.
Currently, it just handles arithmetic expressions and a few builtin functions, but I will implement handling of functions in the expressions as well, soon.