以.Machine $ double.xmax为边界的runif

标签 r random precision uniform-distribution

我想生成一个随机的实数(我想是有理数)。

为此,我想使用runif(1, min = m, max = M),我的想法是将m; M(绝对值)设置为尽可能大,以便使间隔尽可能大。这使我想到我的问题:

M <- .Machine$double.xmax
m <- -M
runif(1, m, M)
## which returns
[1] Inf

为什么不返回数字?选择的时间间隔是否太大?

PS
> .Machine$double.xmax
[1] 1.797693e+308

最佳答案

正如mt1022所暗示的,原因是在runif C source中:

double runif(double a, double b)
{
    if (!R_FINITE(a) || !R_FINITE(b) || b < a)  ML_ERR_return_NAN;

    if (a == b)
    return a;
    else {
    double u;
    /* This is true of all builtin generators, but protect against
       user-supplied ones */
    do {u = unif_rand();} while (u <= 0 || u >= 1);
    return a + (b - a) * u;
    }
}

return参数中,您可以看到公式a + (b - a) * u,它在用户提供的时间间隔[a,b]中统一转换为[0,1],生成随机值。在您的情况下,它将为-M + (M + M) * u。因此,如果M + M生成1.79E308 + 1.79E308,则Inf。 IE。 finite + Inf * finite = Inf:
M + (M - m) * runif(1, 0, 1)
# Inf

关于以.Machine $ double.xmax为边界的runif,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49346202/

相关文章:

c# - 哪种方式更准确?

r - 拟合 beta 分布时出错 : the function mle failed to estimate the parameters with error code 100

python - 沿给定轴打乱 NumPy 数组

string - 从给定字符生成固定长度的随机字符串的最 Pythonic 方式

用于任意数字精度的 .NET Framework 库

python - 如何在 TensorFlow 中模拟降低精度的 float ?

r - 如果你已经有了 Rstudio,那么 RTVS 有什么用?

r - 如何在ggplot2中设置固定的连续颜色值

r - 用ggplot2绘制 "inverted V"函数

java - 具有不同种子的 Java Random 实例是否真的会产生不同的序列,或者它们是否从同一序列的不同位置开始?