-
Notifications
You must be signed in to change notification settings - Fork 0
/
L2.Rmd
97 lines (74 loc) · 1.59 KB
/
L2.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
---
title: "L2"
author: "Xiaoting Chen"
date: "2023-08-08"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(dplyr)
library(ggplot2)
library(gridExtra)
library(scales)
```
## Exponential function
### compound interest
```{r}
```
practice:\
bacteria double in size every 4h. a culture starts with 1000, the population after 10h/24h?
```{r}
bac_growth <- function(initial_p, time) {
p_i <- initial_p
t <- time
p_n <- p_i * 2^(t/4)
p_n
}
bac_growth(1000, 10)
bac_growth(1000, 24)
```
### the number e
```{r}
```
## Logarithmic function
LSE
```{r}
LSE <- function(x) {
c <- max(x)
y <- c + log(sum(exp(x - c)))
y
}
X <- c(1e3, 1e3 + 1, 1e3 + 2)
LSE(X)
```
softmax_log
```{r}
softmax_log <- function(x) {
x_new <- x - LSE(x)
x_new
}
softmax_log(X)
sum(exp(softmax_log(X)))
```
## derivatives
```{r}
n <- 100
t <- seq(0, pi, length = n)
x <- sin(t) * cos(t)
dxdt <- cos(t)^2 - sin(t)^2 # derived derivative
d <- tibble(t, x, dxdt)
p <- ggplot(d, aes(t, x))
p + geom_line() + geom_line(aes(y = dxdt), col = 'red')
```
approximate the derivative
```{r}
s <- pi / (n - 1) # choose the same step s as the increment in the t sequence
all.equal(s, diff(t)[1]) # check that the above statement is true
appr_dxdt <- diff(x)/s # derivative ≈ rise / run
d <- d %>%
mutate(appr_dxdt = c(NA, appr_dxdt))
p <- ggplot(d, aes(t, x))
p + geom_line() + geom_line(aes(y = dxdt), col = 'red') +
geom_line(aes(y = appr_dxdt), col = 'blue', size = 5, alpha = 1/5)
# the approximated derivative value (blue band) cover the true value (red line)
```