Мне понравился ответ lavinio, но смещение бит добавляет некоторую сложность. Часто существует выбор движущихся битов при соблюдении знакового бита или при этом не соблюдающий знаковый бит. Это выбор между обработкой чисел как подписанных (от -8 до 7 для nibble, от -128 до 127 для байтов) или беззнаковых чисел с полным диапазоном (от 0 до 15 для nibbles, от 0 до 255 для байтов).
Вот слегка измененная функция.
n_homerun <- function(N = 100, p_homerun = 0.2) {
x <- sample(c("Base", "Out"), N, replace = TRUE, prob = c(0.32, 0.68))
maxN <- which(cumsum(x == "Out") == 40)[1]
if (length(maxN) == 0)
stop("Sample has less than 40 Out's, increase N.")
round(sum(x[1:maxN] == "Base") * p_homerun)
}
Теперь мы можем использовать replicate
для генерации эмпирического распределения хоум-ранов
Nrep <- 10000
res <- replicate(Nrep, n_homerun(), simplify = TRUE)
. Построим распределение
library(tidyverse)
data.frame(res = res) %>%
count(res) %>%
mutate(freq = n / Nrep) %>%
ggplot(aes(res, freq)) +
geom_col() +
scale_x_continuous(breaks = 1:10)
Вы можете установить поднабор x
, когда в сэмпле будет достигнуто значение 40 «Outs». Попробуйте изменить свою функцию на
Player = function(n) {
x = sample(c("Out","Base"), n , prob = c(.68,.32) ,replace = TRUE)
inds <- cumsum(x == "Out") >= 40
if (any(inds))
x <- x[1:which.max(inds)]
hit_sum = sum(x =="Base")*.20
out_sum = sum(x =="Out")
return(hit_sum)
}
#I am also new with "R". Browsing the internet, I came across this paper by Cal
#Morris.
#I was trying to compute the game by hand, then realized I could make an "R"
#program.
#Here it is
#######################
#Walking Team*
H=0
D=0
T=0
HR=0
SAC=0
BB=20.33383331
AB=27
PA= AB + BB
OBA=(H+BB)/PA
PA= AB + BB
P0= (1-OBA)^3
P1=3*OBA*(1-OBA)^3
P2=6*OBA^2*(1-OBA)^3
P3=1-P1-P2
hr =HR/(H +BB)
w= BB/(H +BB)
d= D/(H +BB)
t=T/(H +BB)
s=1-hr-w-d-t
d1= .576*d
d2=.424d
s1=.324*s
s2=.412*s
s3=.264*s
L1= 1-hr
L2=L1*w +(w+s)*(s + d1) +d*s1
L3= L2*w +((w+s)*(w+s1+s2) +d*w)*s1
LOB =(1-P0)*L1 +(1-P0-P1)*L2+(1-P0-P1-P2)*L3
Eruns=3*OBA/(1-OBA)
9*(Eruns-LOB) #averages 4.5 runs per game.
#Just play around with singles, doubles, triples, HRs to get the number of runs per
#game you want. 31.5 at bats, 4.5 home runs per game, the rest outs will also get you
#4.5 runs #per game, or 10.003816 singles, everything else zero will get 4.5 runs per
#game.
] #Updating my prior respose, I'm sure you want a random number of runs per inning,
#based on probability. I found this program for half an inning,
#https://gist.github.com/bayesball/36fba464d294944268f09630aa65ab61
#I replaced "prob" line with
prob <- c(27,0,0,0,0,4.3) # inputs in parenthesis are (outs, bases on
#balls, singles, doubles, triples, home runs)
#I added the following to the online 1/2 inning program
st <- runs_setup()
R <- replicate(99999, simulate_half_inning(st)) # for complete 9 inning game make
#number in parenthesis divisible by 9. I picked 99999
round(prop.table(table(R)), 6)
b<-matrix(R,11111,9) # this divides the 99999 random innings into 11111 games
hrteam<-apply(b,1,sum)
round(prop.table(table(hrteam)),6)
graph<-round(prop.table(table(hrteam)),6)