-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsimpleRandomWalk.R
More file actions
113 lines (62 loc) · 2.22 KB
/
simpleRandomWalk.R
File metadata and controls
113 lines (62 loc) · 2.22 KB
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
rm(list = ls())
#simple random walk simulation
simpleRandomWalk <- function(initialState, n, theta){
yt = numeric(n);
yt[1] = initialState; #initial state
if(theta > 1 || theta < 0){ #probabilities are between 0 and 1
return('Invalid value for theta')
} else {
#stepSize := et = 1 or -1 with P(stepSize = 1) = theta, and P(stepSize = -1) = 1-theta
stepSize = sample(c(1, -1), size = n, prob = c(theta, 1-theta), replace = TRUE);
for(i in 2:length(yt)){
yt[i] = yt[i-1] + stepSize[i];
}
return(yt);
}
}
expectedValueSRW <- function(initialState, n, theta){
if(theta > 1 || theta < 0){
return('Invalid value for theta')
} else {
#expected value of Xn given xo in a simple random walk
expectedValueXn = initialState + abs(n)*(2*theta - 1);
return(expectedValueXn);
}
}
expectedValueVectorSRW <- function(initialState, n, thetas){
#initialise an empty expected values vector that's going to
#store a collection of expected values for different values of
#theta
expectedValueVector = numeric();
for (i in 1:length(thetas)) {
expectedValueVector[i] = expectedValueSRW(initialState, n, thetas[i]);
}
return(expectedValueVector);
}
simExpectedValueSRW <- function(initialState, n, theta){
simulatedExpectedValue = numeric();
for (i in 1:n) {
simulatedExpectedValue[i] = mean(simpleRandomWalk(initialState, n, theta));
}
#return a simulated Expected value of Xn given Xo
return(mean(simulatedExpectedValue));
}
varianceSRW <- function(n, theta){
if(theta > 1 || theta < 0){
return('Invalid value for theta')
} else {
#variance of Xn given xo in a simple random walk
varianceXn = 4*n*theta*(1 - theta);
return(varianceXn);
}
}
varianceVectorSRW <- function(n, thetas){
#initialise an empty variance vector that's going to
#store a collection of variances for different values of
#theta
varianceVector = numeric();
for(i in 1:length(thetas)){
varianceVector[i] = varianceSRW(n, thetas[i]);
}
return(varianceVector);
}