-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEx07_KOECH_EV.Rmd
159 lines (125 loc) · 5.45 KB
/
Ex07_KOECH_EV.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
---
title: "Introduction to R"
subtitle: "Homework 6"
author: "Koech Andrew"
date: "`r format(Sys.Date(), '%d %B, %Y')`"
mainfont: Calibri Light
output: pdf_document
geometry: margin=1in
header-includes:
- \usepackage{amsfonts}
- \usepackage{amssymb}
- \usepackage{mathtools}
- \usepackage{braket}
---
\newpage
## Homework task 1
Plot the density functions of the gamma distributions with the parameters shape (ranging
from 1 to 10) and scale=1 in a common graph. Use different colors or/and line types.
```{r}
k <- 1:10
plot(0, type = "n", xlim = c(0, 10), ylim = c(-0.01, 1.0), xlab = "x", ylab = "Density", main = "Gamma Distributions with shapes (1 to 10)")
for (shape in k) {
x <- seq(0, 10, by = 0.01)
y <- dgamma(x, shape = shape, scale = 1)
lines(x, y, col = shape, lwd = 1, lty = shape)
}
legend("topright", legend = as.character(k), col = k, lty = k, lwd = 1, title = "Shapes")
```
<!-- EV: 3/3 -->
## Homework task 2
a. Write a function my.pi depending on the parameter B that calculates $\pi$ with the
described method above.
The area of a circle is calculated by $\pi r^2$, and the area of the bounding square is $(2r)^2=4r^2$. Dividing the area of the circle by the area of the square we get the ratio of the two areas:
$\frac{area\ of\ circle}{area\ of\ square}=\frac{\pi r^2}{4r^2}=\frac{\pi}{4}$
This means we can estimate $\pi$ using the formula:
$\pi\approx4*\frac{simulated\ points\ within\ circle}{total\ number\ of\ simulated\ points}$
```{r}
my.pi <- function(B) {
set.seed(528164)
#Generating the (x,y) points
x <- runif(B, min = -1, max = 1)
y <- runif(B, min = -1, max = 1)
sum_xy_sq<-sqrt(x^2+y^2)
points_in_circle<-length(which(sum_xy_sq<=1))
pi_est <- 4 * points_in_circle / B
return(pi_est)
}
## EV: adding control
my.pi(10^8)
```
<!-- EV: 6/6 -->
b. Create a plot that looks identical to that in Figure 1 (the positioning of the text,
for example, does not have to be exact, of course).
```{r}
plot(x = seq(-1,1,0.01), y = seq(-1,1,0.01), type = "n", xlab = "x", ylab = "y", main = expression(paste("Illustration of the procedure to approximate ", pi, " via Monte Carlo simulations")))
# Add the rectangle
rect(-1, -1, 1, 1, border = "black")
set.seed(123)
x <- runif(1000, min = -1, max = 1)
y <- runif(1000, min = -1, max = 1)
r<- x^2 + y^2
points(x[r>1], y[r>1], pch = 16,cex=0.5, col = "black")
points(x[r<=1], y[r<=1], pch = 16,cex=0.5, col = "blue")
curve(sqrt(1 - x^2),-1,1,lwd=2, add = TRUE, col = "blue")
curve(-sqrt(1 - x^2),-1,1,lwd=2, add = TRUE, col = "blue")
abline(h=0,col="red")
abline(v=0,col="red")
#Legend
legend("topright", legend = expression("x"^2 + "y"^2 <= "1","otherwise"), pch = 16, col = c("blue","black"),box.lwd = 0, cex = 0.8)
## EV: the solution is the same as another student's solution.
## Please clarify, otherwise I cannot grant any points for this exercise.
```
<!-- EV: ?/4 -->
c. Plot your $\pi$-estimates against the number of points b (for example for b ranging
from 1.000 to 10.000). Don't forget to annotate your axes and specify a header.
Add a red line for indicating the actual value of $\pi$. Save this plot as a pdf or png
called "mypi_yourname" and hand it in as well when submitting your homework.
(Normally, computation time shouldn't be too long here but if it is, just use a range
with smaller numbers or simply hand in the code without running it. The goal here
is not to get insanely close to $\pi$ but to actually create the plot.)
```{r}
png("../mypi_koech.png", width = 1080, height = 720, res = 96)
est_pi<- function(B) {
set.seed(528164)
df <- data.frame(x <- runif(B, min =-1, max = 1),
y <- runif(B, min = -1, max = 1))
df$iteration <- 1:B
df$points_in_circle <- ifelse(sqrt(x^2 + y^2) <= 1, 1, 0)
df$pi_est <- 4 * cumsum(df$points_in_circle) / df$iteration
return(df$pi_est)
}
B<-10000
pi_est<-est_pi(B)
plot(x = 1:B, y = pi_est,ylim = c(3.1,3.2),xlim = c(1000,B), xlab = "number of points b (iterations)",col="blue",cex=0.1, ylab = expression(paste("estimated value of ",pi)), main = expression(paste("Approximation of ", pi)))
abline(h=22/7,col="red")
dev.off()
## EV: Why are you not using the function you defined above?
# Also: See comment to b).
##### EV: ?/3 #####
```
## Homework task 3
Write a function StringSim that takes three arguments: Two strings s and p (like
"Hello") and a number m. The function should return a list with two elements:
1. A length-m-vector consisting of m random permutations of the string s, where each
character of the string should be permuted. For instance, possible permutations of
"People" are "ePopel" or "eloepP" (and technically also "People" itself). Name
this list element permutations.
2. A text showing the user how many times any of the created permutations are
exactly equal to the second string p. Call this list element TimesEqual.
```{r}
set.seed(528164)
StringSim<-function(s,p,m){
permutations<-replicate(m,
paste0(
sample(strsplit(s,"")[[1]],
replace = FALSE), collapse = ""))
TimesEqual<-sum(permutations==p)
result<-list(permutations=permutations,TimesEqual=TimesEqual)
return(result)
}
StringSim("People","eePolp",6)
## EV: Exactly the same solution as another student submitted. Please explain.
##### EV: ?/4 #####
```
<!-- Total 9+x/20 -->