The following code is from:
https://www.douban.com/note/618668311/
The following is the R code for the strong law of numbers:
n <- 1000; m <- 50; e <- 0.05 s <- cumsum(1*(rbinom(n, size=1, prob=0.5) - 0)) plot(s/seq.int(n)-0.5, type = "l", ylim = c(-0.4, 0.4)) abline(h = c(-e,e), lty = 2) paste("---------------------")
Ctrl+a to select all the code, then Ctrl+Enter to run it in Rstudio,
operation result:
Code Explanation:
rbinom (n, size, prob) n represents the number of random numbers generated, size represents the number of Berkli tests performed, and prob represents the probability of a successful Berkli test.
ylim refers to the upper and lower limit settings of the y-axis
h (horizontal): Represents a horizontal horizontal line. In the code, it means to draw two horizontal lines horizontally. The function values corresponding to the horizontal lines are e and -e respectively.
lty: line type
---------------------------------------------------------------------------------------------
The following is the R code for the weak law of large numbers:
n<-1000 m<-50 x <- matrix(1*(rbinom(n*m, size=1, prob=0.5) - 0.0), ncol = m) print(x) y <- apply(x, 2, function(z)(cumsum(z)/seq_along(z))-0.5) matplot(y, type = "l", ylim = c(-0.4,0.4)) abline (h = c (-e, e), lty = 2, lwd = 2)
where u=0
Where cumsum(z)/seq_along(z) is the entire function body
Do m experiments. Each experiment has n samples.
For the vector a=(a1,...,an), cumsum(a) gets a1,a1+a2,a1+a2+a3,....a1+...+an
lwd is the width of the line
apply(x,2, function(z) cumsum(z)/seq_along(z)) means that each column value in the matrix is substituted into function(z)
Because it obeys Bernoulli distribution
The results are as follows:
The usage reference of apply:
http://blog.fens.me/r-apply/