2017-09-05 1 views
0

コインを30回フリップすると、10,000回のシミュレーションで最長ランの平均を求めようとしています。私はRでシミュレートする必要があります。上記の実験は10,000回で、最長の実行時間をメモします。ベイズ統計:上記の実験を10000回実行し、毎回最長ランの長さをメモしてください

はここで、これまでに私のコードです:

coin <- sample(c("H", "T"), 10000, replace = TRUE) 
table(coin) 
head(coin, n = 30) 
rle(c("H", "T", "T", "H", "H", "H", "H", "H", "T", "H")) 
coin.rle <- rle(coin) 
str(coin.rle) 

万のシミュレーションで最長の平均を見つけるためにどのように?

+0

質問にコードを入力するときは、各行の前に4つのスペースを追加して、うまくフォーマットするようにしてください(または、コードを強調表示してCrtl + Kを押すか、エディタの '{} 'ボタンをクリックしてください)。 – PaSTE

答えて

1

コインフリップのすべてが(すなわち1つのフリップの結果が別のフリップに影響を与えない)は、互いに独立しています。このため、すべてのシミュレーションのコインをまとめてフリップし、30回のフリップトライアルを簡単にまとめられるようにフォーマットすることができます。ここで私はこれにどのようにアプローチするかです。

# do all of the flips at once, this is okay because each flip 
# is independent 
coin_flips <- sample(c("heads", "tails"), 30 * 10000, replace = TRUE) 

# put them into a 10000 by 30 matrix, each row 
# indicates one 'simulation' 
coin_matrix <- matrix(coin_flips, ncol = 30, nrow = 10000) 

# we now want to iterate through each row using apply, 
# to do so we need to make a function to apply to each 
# row. This gets us the longest run over a single 
# simulation 
get_long_run <- function(x) { 
    max(rle(x)$length) 
} 

# apply this function to each row 
longest_runs <- apply(coin_matrix, 1, get_long_run) 

# get the number of simulations that had a max run >= 7. Divide this 
# by the number of simulations to get the probability of this occuring. 
sum(longest_runs >= 7)/nrow(coin_matrix) 

あなたは18-19%の間に何かを取得する必要がありますが、これはこのシミュレーションを試すたびに少しずつ変化します。

2

私は次のことがあなたの後にあると思います。

n_runs <- 10000 
max_runs <- numeric(n_runs) 
for (j in 1:n_runs) { 
coin <- sample(c("H", "T"), 30, replace = TRUE) 
max_runs[j] <- max(rle(coin)$length) 
} 
mean(max_runs) 
coinの小さなセグメントを検査するコードの最良の説明について

(等coin[20])とのrlerle(coin[20]))。実行の各セグメントについて長さが計算されるため、max(rle(coin)$length)は最大実行を与えます。

EDIT:続いて速くなる可能性が

len <- 30 
times <- 10000 

flips <- sample(c("H", "T"), len * times, replace = TRUE) 
runs <- sapply(split(flips, ceiling(seq_along(flips)/len)), 
        function(x) max(rle(x)$length)) 
mean(runs) # average of max runs 
sum(runs >= 7)/ times # number of runs >= 7 
+0

あなたのシミュレーションに基づいて30コインフリップで7以上のラ​​ンを獲得する確率はどのようにしてわかりますか? –

+1

各シミュレーションは10000ではなく30フリップです。このコードは、コインを10000回反転させた5回のシミュレーションから最大長を取得します。 –

+0

@M_Fidino、私はそれを修正しました。 – Suren

関連する問題