2
$\begingroup$

So I'm after a random number generator where the probabilities of a number occurring in some range is matched to some function. Only really looking at functions with nice integrals (for simplicity sake). For example, given some quadratic

$f(x)=2x^2 $ where x $ [0,2]$

a single number should be spat out, between 0 and 2, with a higher probability of something closer to 2 being generated.

This is my approach so far. Given the same $f(x)$ as above

lower L = 0, U upper = 2.

Get some uniform random number A between L and U. So let A = 0.8.

$$p = \frac{\int_L^A f(x) dx}{\int_L^U f(x) dx}$$ $$p = \frac{\int_0^{0.8} 2x^2 dx}{\int_0^2 2x^2 dx}$$ $$p = \frac{0.3413}{5.3333}$$ $$p = 0.064$$ Where $p$ = probability of A occurring over the range of the equation.

$$result = L + p(U-L)$$ $$result = 0 + 0.064(2-0)$$ $$result = 0.064(2)$$ $$result = 0.128$$

Where $result$ is the returned answer, in the range 0 to 2.

So the number that gets spat back out is 0.128. However, after doing 1000 iterations of it, and graphing by bins, it seems to be inverse... I thought my method above was right, but the results seem to say otherwise.

Is my maths sound enough (meaning my implementation is incorrect), or (more likely), is my maths way off the mark? Coming from a programming perspective here for reference.

$\endgroup$
1
$\begingroup$

You want to generate a random variable $B$ satisfying $\Pr(0<B<t) = t^3/8$ for $0 \le t \le 2$. You are given a random variable $A$ which satisfies $\Pr(0<A<t) = t/2$ for $0\le t \le 2$.

So rewrite the equation for $B$ as $\Pr(0<B<(4t)^{1/3}) = t/2$, or $\Pr(0 < B^3/4 < t) = t/2$. So $B^3/4$ is a uniform random number in the correct range. So set $B^3/4 = A$. Therefore $B = (4A)^{1/3}$ should do what you want it to do.

$\endgroup$
  • $\begingroup$ You went a bit fast for me sorry. I don't get how $Pr(0<B<t)=t^{3/8}$ (I'm guessing you're letting the function be $t^{3/8}$). Same with A. $\endgroup$ – HalfBit Jul 21 '15 at 3:35
  • $\begingroup$ $\Pr(u<B<v) = \frac{\int_u^v 2x^2 \, dx}{\int_0^2 2x^2 \, dx}$ whenever $0\le u \le v \le 2$, and $\Pr(u<A<v) = \frac{\int_u^v 1 \, dx}{\int_0^2 1 \, dx}$ whenever $0\le u \le v \le 2$. $\endgroup$ – Stephen Montgomery-Smith Jul 21 '15 at 3:38
  • $\begingroup$ Also @Rahul gave you a nice web page that explains it. $\endgroup$ – Stephen Montgomery-Smith Jul 21 '15 at 3:42
  • $\begingroup$ Also, it is $t^3/8 = \frac{t^3}8$, not $t^{3/8}$. $\endgroup$ – Stephen Montgomery-Smith Jul 21 '15 at 3:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.