2017-02-25 84 views
1

我想模擬兩個以上的學生在一個房間裏有n個人同時生日的概率。目前,我認爲我的代碼是分開工作正常,雖然我最初只是運行的第一行代碼來選擇我的N值,然後運行該代碼的其餘部分(見下文)生日悖論 - 帶輸入變量的函數

n = as.integer(readline(prompt = "Enter the number of students in a room:")) 

sims = 10000 
x = numeric(sims) 

for (i in 1:sims){ 
s = sample(1:365, n, replace=TRUE) 
x[i] = n - length(unique(s))} 

samebday = length(which(x>0))/length(x) 
samebday 

我怎麼收拾會這個變量是否包含在變量n內?只要我嘗試將其轉換爲如下函數:

bday.prob = function(n){...} 

然後錯誤開始發生。

回答

1

如果你想使用您之前編寫的代碼只是將其包裝到一個函數中,您可以通過讓nsims成爲用戶定義的輸入變量(如提到的@ 42)來執行此操作。

下面是我的解決方案,以最小的變化,從你提供了什麼:

bday.prob = function(n, sims){ 
    #' @param n is the number of students in a room; user-defined 
    #' @param sims is the number of trials; user-defined 

    x = numeric(sims) 
    for (i in 1:sims){ 
    s = sample(1:365, n, replace=TRUE) 
    x[i] = n - length(unique(s)) 
    } 
    samebday = length(which(x > 0))/length(x) 
    return(samebday) 
} 

使用功能如下:

bday.prob(n=<User choice>, sims=<User choice>) 

bday.prob(n=as.numeric(readline(prompt = "Enter the number of students in a room:")), sims=100) 
## Enter the number of students in a room: <User choice> 
3

你可能不知道,這個功能已經存在於統計軟件包:

pbirthday(30, classes = 365, coincident = 2) 
[1] 0.7063162 

還有一個位數版本:qbirthday

包裝在一個功能,但不加參數n參數列表,如果你還打算做函數內部屆einlut:

# copied from my console 
bfun <- function(){ n = as.integer(readline(prompt = "Enter the number of students in a room:")) 
+ print(pbirthday(n, classes = 365, coincident = 2)) 
+ } 
> bfun() 
Enter the number of students in a room:30 
[1] 0.7063162 
+0

謝謝!有用的是知道有巧合的功能。 – Aesler

+0

把它看作隨機樣品的替換功能。 –