runif with .Machine $ double.xmax as borders

I wanted to generate a random real (I think rational) number.

For this, I wanted to use runif(1, min = m, max = M) and my thoughts should have set m; M m; M m; M m; M (absolute) as large as possible to make the interval as large as possible. Which brings me to my question:

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

Why doesn't he return the number? Is the selected interval too long?

PS

 > .Machine$double.xmax [1] 1.797693e+308 
+8
source share
1 answer

As mt1022 suggested, the reason is in the runif source of C :

 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; } } 

In the return argument, you can see the formula a + (b - a) * u which uniformly generates [0, 1] a random value in the user-provided interval [a, b]. In your case it will be -M + (M + M) * u . Thus, M + M if 1.79E308 + 1.79E308 generates Inf . Those. finite + Inf * finite = Inf :

 M + (M - m) * runif(1, 0, 1) # Inf 
+1
source

Source: https://habr.com/ru/post/1275939/


All Articles