4.1

随机数

a = runif(10000,0,100)
mean(a)
## [1] 50.44472
max(a)
## [1] 99.99721

均匀分布

runif(1)
## [1] 0.4475556

设置随机数种子

set.seed(1)
runif(1)
## [1] 0.2655087

生成任意区间的随机数

runif(1,0,10)
## [1] 3.721239

正态分布 normal-distribution

rnorm(1,0,1)
## [1] 0.1836433
# rnorm(q,mu,sigma)

density(密度)

dnorm(0,0,1,log = TRUE)
## [1] -0.9189385

给定任何一个x,确定密度函数上对应的值

dnorm(0) == 1/sqrt(2*pi)
## [1] TRUE
dnorm(1.96)
## [1] 0.05844094

等距序列,求f(x)

x = seq(-5,5,0.01)
f = dnorm(x)
plot(x,f)

pnorm 累计概率

pnorm(-5)  #从负无穷到-5之间的面积
## [1] 2.866516e-07
1-2*pnorm(-5)
## [1] 0.9999994

累积分布图

f = pnorm(x)
plot(x,f)

plot(x,f,type = 'l', col = 'steelblue',lwd = 3)

g = runif(1001,-5,5)
g = sort(g)
plot(g,f)

hist(g)

hist(f)

验证分布函数服从均匀分布

x2 = rnorm(1000)
fx2 = pnorm(x2)
hist(fx2)

par(mfrow = c(2,2))
t.test(x)
## 
##  One Sample t-test
## 
## data:  x
## t = 1.1101e-15, df = 1000, p-value = 1
## alternative hypothesis: true mean is not equal to 0
## 95 percent confidence interval:
##  -0.1793153  0.1793153
## sample estimates:
##    mean of x 
## 1.014371e-16

分位数qnorm,求对应的自变量

qnorm(0.99)
## [1] 2.326348
qnorm(0.95)
## [1] 1.644854
qnorm(0.975)
## [1] 1.959964
par(mfrow = c(1,1))
a = runif(1000,0,1)
b = qnorm(a)
plot(b,a)

偶然发现的求导功能!!!

D(quote(sinpi(x^2)), "x") ## sinpi(x) = sin(pi*x)
## cospi(x^2) * (pi * (2 * x))
D(quote(exp(x^2)-1), "x")
## exp(x^2) * (2 * x)

似然函数

x = c(200,4000,20000,5,10)
likelyhood = function(x){
  mu = mean(x)
  sigma = sd(x)
  b = prod(1/(sigma*sqrt(2*pi))*exp(-(x-mu)^2/(2*sigma^2))) #一般写法的似然函数
  c = sum(dnorm(x,mu,sigma,log = TRUE)) #对数似然函数,减小精度损失
  d = prod(1/(log(sigma)*sqrt(2*pi))*exp(-(log(x)-log(mu))^2/(2*log(sigma)^2)))
  e = sum(log(dnorm(x,mu,sigma,log = FALSE)))  #顺序不同,就出错了
  return(data.frame(b,c,d,e))
}
likelyhood(x)
##              b         c            d         e
## 1 2.836483e-23 -51.91689 9.112099e-08 -51.91689

作业 画20个密度,80个图:直方图,曲线