# S 5
sample(1:6, 1, replace=T)

sample(1:6, 10, replace=T)
mean(sample(1:6, 10, replace=T))

wuerfel <- NULL
for(j in 1:5000){
ergebnis = mean(sample(1:6, 10, replace=T))
wuerfel = c(wuerfel, ergebnis)
}

# S 6
mean(wuerfel)

# S 8
proben <- function(unten=1, oben = 6, k = 10, N = 50)
{
# default: wir werfen 10 Wuerfel 50 Mal
alle <- NULL
for(j in 1:N){
ergebnis = mean(sample(unten:oben, k, replace=T))
alle = c(alle, ergebnis)
}
alle
}


# S 9
o = proben(0, 99, 10, 50)
hist(o, col=3)

# S 10
hist(o, col=3, freq=F)


# S 12
osehrviele = proben(0, 99, 10, 50000)
h4 = hist(osehrviele, col=3, freq=F, breaks=200)

# S 14
nex = read.table(file.path(pfadu, "normexample.txt"))
boxplot(werte ~ Verteilung, data = nex)

aggregate(nex$werte, list(nex$Verteilung), sd)
# oder
with(nex, aggregate(werte, list(Verteilung), sd))


# S 15
sigma <- function(unten=1, oben = 6)
{
x = unten:oben
n = length(x)
m = mean(x)
sqrt((sum(x^2)/n - m^2))

}
# S. 17
sigma()


# S. 19
o = proben(0, 99, 10, 50)
hist(o, col=3, freq=F)
mu = mean(0:99)
SE = sigma(0, 99)/sqrt(10)

curve(dnorm(x, mu, SE), add=T)


# S. 20
o2 = proben(0, 99, 10, 5000)
hist(o2, col=3, freq=F)
curve(dnorm(x, mu, SE), add=T)


# S. 25
curve(dnorm(x), xlim=c(-3, 3), xlab="Werte", ylab = "Wahrscheinlichkeitsdichte")
x = seq(-4, 1.2, length=1000)
y = dnorm(x)
lines(x, y, type="h", col="turquoise")

# S. 26
mu = mean(0:99)
SE = sigma(0, 99)/sqrt(10)
curve(dnorm(x, mu, SE), xlim = c(20, 80), ylab="Wahrscheinlichkeitsdichte", xlab = "Zahlen-Mittelwert", main = "Theoretische Verteilung der Mittelwerte")
x = seq(15, 38, length=1000)
y = dnorm(x, mu, SE)
lines(x, y, type="h", col="turquoise")

pnorm(38, mu, SE)

# p. 30
qnorm(0.025, mu, SE)
# [1] 31.60895
qnorm(0.975, mu, SE)
