Benford 定律:第一位數
Benford 定律指出,第一位數等於 d 的機率約為 (1 + 1/d) 的對數。
藉由繪製期望次數分佈,你會發現數字 1,…,9 並非等機率出現。
本練習屬於課程
R 的詐欺偵測
練習說明
- 以 10 為底的對數,將 Benford 定律實作為用於第一位數的函式
benlaw。 - 計算第一位數為 5 的期望機率。
- 建立一個 dataframe,其中一欄
digit放入 1 到 9 的數字,另一欄probability放入依 Benford 定律計算的對應機率。 - 送出以長條圖繪製數字 1、2、…、9 的期望機率分佈。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Implement Benford's Law for first digit
benlaw <- function(d) log10(___ + ___ / ___)
# Calculate expected frequency for d=5
benlaw(___)
# Create a dataframe of the 9 digits and their Benford's Law probabilities
df <- data.frame(digit = ___:___, probability = ___)
# Create barplot with expected frequencies
ggplot(df, aes(x = digit, y = probability)) +
geom_bar(stat = "identity", fill = "dodgerblue") +
xlab("First digit") + ylab("Expected frequency") +
scale_x_continuous(breaks = 1:9, labels = 1:9) +
ylim(0, 0.33) + theme(text = element_text(size = 25))