randomwalk_1d <- function(number_of_steps,
step_sizes,
init_step_size_prob,
alpha = 0,
setseed=123,
plot=TRUE){
set.seed(setseed)
ssp <- sum(init_step_size_prob)
# param checking
if(ssp != 1)
stop(paste0("sum(init_step_size_prob) != 1, rather = ", ssp))
if(length(step_sizes) != length(init_step_size_prob))
stop(paste0("length of step size vector (",length(step_sizes),
") does not match length of step size probability vector (",
length(init_step_size_prob), ")"))
# calculate
steps <- numeric(number_of_steps)
alpha_matrix <- matrix(data = 0,
nrow = number_of_steps+1,
ncol = length(init_step_size_prob))
alpha_matrix[1,] <- init_step_size_prob
for(step in seq_len(number_of_steps))
{
steps[step] <- sample(step_sizes,
size=1,
replace=TRUE,
prob=alpha_matrix[step,])
alpha_matrix[step+1,] <- alpha_matrix[step,]
step_choice_id <- which(steps[step] == step_sizes)
alpha_matrix[step+1,step_choice_id] <- alpha_matrix[step+1,step_choice_id] + alpha
divisor_to_use <-sum( alpha_matrix[step+1,])
alpha_matrix[step+1,] <- alpha_matrix[step+1,] / divisor_to_use
}
(journey <- cumsum(steps))
max_pos = max(journey)
min_pos = min(journey)
absolute_min_pos = abs(min_pos)
if(abs(min_pos)>max_pos){
max_distance_from_origin <- min_pos
} else if(abs(min_pos)==max_pos){
max_distance_from_origin <- sample(c(min_pos,max_pos),size = 1)
} else {
max_distance_from_origin <- max_pos
}
#give outputs
if(plot){
par(mfrow=c(2,1),mar=c(1,4,1,4))
plot(steps)
plot(journey)}
list( alpha_matrix=alpha_matrix,
steps=steps,
journey=journey,
max_distance_from_origin = max_distance_from_origin)
}
# example of useage
randomwalk_1d(number_of_steps = 100,
step_sizes = c(-1,1),
alpha=0,
init_step_size_prob = c(.5,.5))
#get the max distance from 100 experiments on alpha zero
(res_a0 <- map_dbl(1:100,~randomwalk_1d(setseed = .x,
plot = FALSE,
number_of_steps = 100,
step_sizes = c(-1,1),
alpha=0,
init_step_size_prob = c(.5,.5))$max_distance_from_origin))
#get the max distance from 100 experiments on alpha 1
(res_a1 <- map_dbl(1:100,~randomwalk_1d(setseed = .x,
plot = FALSE,
number_of_steps = 100,
step_sizes = c(-1,1),
alpha=1,
init_step_size_prob = c(.5,.5))$max_distance_from_origin))
table(res_a0)
table(res_a1)
par(mfrow=c(2,1),mar=c(3,4,2,4))
plot(table(res_a1),col="red")
plot(table(res_a0),col="blue")