if (!require(ggplot2)) {
install.packages("ggplot2")
library(ggplot2)
} else {
library(ggplot2)
}
Problem 1: Coin Tosses
Question: What is the probability of getting exactly 3 heads in 5 tosses of a fair coin?
Solution: - Number of trials (n) = 5 - Probability of success (p) = 0.5 (for heads) - Number of successes (k)
=3
P (X = k) = nk pk (1 − p)n−k
P (X = 3) = 53 (0.5)3 (0.5)5−3
5! 3 2
P (X = 3) = 3!(5−3)! (0.5) (0.5)
5·4
P (X = 3) = 2·1 · 0.125 · 0.25
P (X = 3) = 10 · 0.03125
P (X = 3) = 0.3125
# Parameters
n <- 5
p <- 0.5
k <- 3
# Calculate probability
prob <- dbinom(k, n, p)
print(paste("Probability of getting exactly", k, "heads in", n, "tosses is", round(prob, 4)))
## [1] "Probability of getting exactly 3 heads in 5 tosses is 0.3125"
k <- 0:n
# Calculate probabilities for all k
prob <- dbinom(k, n, p)
# Create a data frame
df <- data.frame(k, prob)
# Plot using ggplot2
ggplot(df, aes(x = factor(k), y = prob)) +
geom_bar(stat = "identity", fill = "skyblue") +
geom_text(aes(label = round(prob, 4)), vjust = -0.3) +
labs(title = "Binomial Distribution: 5 Coin Tosses",
x = "Number of Heads",
1
, y = "Probability") +
theme_minimal()
Binomial Distribution: 5 Coin Tosses
0.3125 0.3125
0.3
0.2
Probability
0.1562 0.1562
0.1
0.0312 0.0312
0.0
0 1 2 3 4 5
Number of Heads
Problem 2: Defective Items
Question: In a batch of 20 items, the probability of each item being defective is 0.1. What is the probability
of finding exactly 2 defective items?
Solution: - Number of trials (n) = 20 - Probability of success (p) = 0.1 (defective item) - Number of
successes (k) = 2
P (X = 2) = 20
2 20−2
2 (0.1) (0.9)
20! 2 18
P (X = 2) = 2!(20−2)! (0.1) (0.9)
20·19
P (X = 2) = 2·1 · 0.01 · 0.1503
P (X = 2) = 190 · 0.001503
P (X = 2) = 0.2856
# Parameters
n <- 20
p <- 0.1
k <- 2
# Calculate probability
prob <- dbinom(k, n, p)
2