-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathParrondo3.R
141 lines (93 loc) · 2.47 KB
/
Parrondo3.R
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
#Version5
#Periodic sequence XXYY
#if its x run coinA with pA of 0.5 - e
#if its y
#and capital mod 3 == 0 then its coinB with pB of 1/10 - e
#or capital mod /= 0 the its coinC with pC of 3/4 - e
#saves output into rolling average
#constants
e <- 0.005
coinA <- 0.5 - e
coinB <- 0.1 - e
coinC <- 0.75 - e
ccA <- 0
ccB <- 0
ccC <- 0
M <- 3
playMax <- 100
runMax <- 30000
#global variables
#masterTable <- data.frame(Run=integer(), Play=integer(), State=character(), Coin=character(), Capital=integer(), Point=integer(), Value=double())
totalSheet <- vector()
totalSheet <- c(totalSheet, 1:playMax)
run <- 0
play <- 0
plays <- seq(1, playMax)
state <- NULL
coin <- NULL
capital <- 0
point <- NULL
value <- NULL
#prepping for sequence
sequ <- "xyyy"
sequLen <- nchar(sequ)
#dice function to assign capital value according to random output
dice <- function(coinInput){
#sets value and coin
value <<- runif(1)
coin <<- deparse(substitute(coinInput))
#counts coin input
if (coinInput == coinA) {
ccA <<- ccA + 1
}
else if (coinInput == coinB) {
ccB <<- ccB + 1
}
else if (coinInput == coinC) {
ccC <<- ccC + 1
}
#give selects point
if (value < coinInput) {
point <<- 1
}
else{
point <<- -1
}
#adds point to capital
capital <<- capital + point
scoreSheet <<- c(scoreSheet, capital)
}
#running the programme
while (run < runMax) {
run <- run + 1
play <- 0
capital <- 0
scoreSheet <- vector()
while (play < playMax) {
#prepares run
play <- play + 1
mod <- (play %% sequLen) + 1
state <- substr(sequ, mod, mod)
#assigning values
if (state == "x") {
dice(coinA)
}
else if (state == "y") {
if (abs(capital) %% M == 0) {
dice(coinB)
}
else {
dice(coinC)
}
}
}
#adds scoreSheet to totalSheet
totalSheet <- totalSheet + scoreSheet
#indicates programme is running
if (run %% 100 == 0) {
print(run)
}
}
#prepare data for graph making
averageSheet <- totalSheet / run
plot(plays, averageSheet, main = "Graph of Average Capital against Play Number", sub = paste("for sequence ", sequ," with 30,000 trials"), xlab = "Plays", ylab = "Average Capital")