Skip to content

Instantly share code, notes, and snippets.

@NikolaiT
Created November 17, 2015 11:47
Show Gist options
  • Save NikolaiT/367e73b75dd243e1cacf to your computer and use it in GitHub Desktop.
Save NikolaiT/367e73b75dd243e1cacf to your computer and use it in GitHub Desktop.
R Skript Stochastik Aufgabe 3 - Blatt 5
#!/usr/bin/env Rscript
# Diese Funktion berechnet die exakte und die approximierte Version
calc_exact_and_approx <- function(n, p, x1, x2) {
# exakte Berechnung:
sum <- 0
for(i in x1:x2) {
sum <- sum + ( choose(n, i) * p**i * (1 - p)**(n-i) )
}
# Gibt die exakte Loesung aus
print(sprintf("Exakte Loesung: %f", sum))
# Berechnung mit Normalapproximation mit Stetigkeitskorrektur:
# überprüfen ob die Approximation annährend gut ist:
# Am besten gilt: Varianz = np(1-p) >= 9.
# Aber es MUSS gelten: np >= 4.
approx_works = function(n, p) return(n * p * (1 - p) >= 9)
approx_must_work = function(n, p) return (n * p >= 4)
if (!approx_works(n, p)) {
stopifnot(approx_must_work(n, p))
}
mi = n * p
sigma = sqrt( n * p * (1 - p) )
sum_approx = pnorm((x2 + 0.5 - mi) / sigma) - pnorm((x1 - 0.5 - mi) / sigma)
print(sprintf("Approx Loesung: %f", sum_approx))
print('')
}
# P(9 <= Y <= 11) fuer Y = Bin(20, 0.5)
calc_exact_and_approx(20, 0.5, 9, 11)
# "Exakte Loesung: 0.496555"
# "Approx Loesung: 0.497665"
# P(90 <= Y <= 110) fuer Y = Bin(200, 0.5)
calc_exact_and_approx(200, 0.5, 90, 110)
# "Exakte Loesung: 0.862633"
# "Approx Loesung: 0.862436"
# P(20 <= Y <= 40) fuer Y = Bin(200, 0.15)
calc_exact_and_approx(200, 0.15, 20, 40)
# "Exakte Loesung: 0.963120"
# "Approx Loesung: 0.962411"
# P(0 <= Y <= 20) fuer Y = Bin(200, 0.05)
calc_exact_and_approx(200, 0.05, 0, 20)
# "Exakte Loesung: 0.998840"
# "Approx Loesung: 0.999342"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment