如何在 R 中创建分布函数?
How to create a distribution function in R?
给出以下函数:
f(x) = (1/2*pi)(1/(1+x^2/4))
如何识别它的分布并在 R 中编写此分布函数?
这就是你现在的函数(希望你知道如何编写 R 函数;如果不知道,请检查 writing your own function):
f <- function (x) (pi / 2) * (1 / (1 + 0.25 * x ^ 2))
f
是在 (-Inf, Inf)
上定义的,因此在此范围内积分得到不定积分。幸运的是,它以x ^ (-2)
的速度逼近Inf
,因此积分定义明确,可以计算:
C <- integrate(f, -Inf, Inf)
# 9.869604 with absolute error < 1e-09
C <- C$value ## extract integral value
# [1] 9.869604
那么你要归一化f
,我们知道一个概率密度应该积分为1:
f <- function (x) (pi / 2) * (1 / (1 + 0.25 * x ^ 2)) / C
您可以通过以下方式绘制它的密度:
curve(f, from = -10, to = 10)
Now that I have the probably distribution function I was wondering how to create a random sample of say n = 1000
using this new distribution function?
一个题外话的问题,但可以在不创建新线程的情况下回答。很有用,因为它很微妙。
比较
set.seed(0); range(simf(1000, 1e-2))
#[1] -56.37246 63.21080
set.seed(0); range(simf(1000, 1e-3))
#[1] -275.3465 595.3771
set.seed(0); range(simf(1000, 1e-4))
#[1] -450.0979 3758.2528
set.seed(0); range(simf(1000, 1e-5))
#[1] -480.5991 8017.3802
所以我觉得e = 1e-2
是合理的。我们可以绘制样本,制作(缩放的)直方图和叠加密度曲线:
set.seed(0); x <- simf(1000)
hist(x, prob = TRUE, breaks = 50, ylim = c(0, 0.16))
curve(f, add = TRUE, col = 2, lwd = 2, n = 201)
给出以下函数:
f(x) = (1/2*pi)(1/(1+x^2/4))
如何识别它的分布并在 R 中编写此分布函数?
这就是你现在的函数(希望你知道如何编写 R 函数;如果不知道,请检查 writing your own function):
f <- function (x) (pi / 2) * (1 / (1 + 0.25 * x ^ 2))
f
是在 (-Inf, Inf)
上定义的,因此在此范围内积分得到不定积分。幸运的是,它以x ^ (-2)
的速度逼近Inf
,因此积分定义明确,可以计算:
C <- integrate(f, -Inf, Inf)
# 9.869604 with absolute error < 1e-09
C <- C$value ## extract integral value
# [1] 9.869604
那么你要归一化f
,我们知道一个概率密度应该积分为1:
f <- function (x) (pi / 2) * (1 / (1 + 0.25 * x ^ 2)) / C
您可以通过以下方式绘制它的密度:
curve(f, from = -10, to = 10)
Now that I have the probably distribution function I was wondering how to create a random sample of say
n = 1000
using this new distribution function?
一个题外话的问题,但可以在不创建新线程的情况下回答。很有用,因为它很微妙。
比较
set.seed(0); range(simf(1000, 1e-2))
#[1] -56.37246 63.21080
set.seed(0); range(simf(1000, 1e-3))
#[1] -275.3465 595.3771
set.seed(0); range(simf(1000, 1e-4))
#[1] -450.0979 3758.2528
set.seed(0); range(simf(1000, 1e-5))
#[1] -480.5991 8017.3802
所以我觉得e = 1e-2
是合理的。我们可以绘制样本,制作(缩放的)直方图和叠加密度曲线:
set.seed(0); x <- simf(1000)
hist(x, prob = TRUE, breaks = 50, ylim = c(0, 0.16))
curve(f, add = TRUE, col = 2, lwd = 2, n = 201)