Take the 2-minute tour ×
Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. It's 100% free, no registration required.

Given some random number function rand, and some numbers $x$ and $y$, how do you find a random number $r$ such that $r\geq x \wedge r \leq y$?

Previously i've tried (and somewhat failed) with formulas like $$ r = \text{rand()}\bmod \frac{x}{y} $$ or $$ r = \text{rand()}\bmod x + 1 $$ or, given that $y>x$, $$ r = (\text{rand()}\bmod (y-x))+x $$ Is there a better or truer way to do this?

share|improve this question
add comment

1 Answer

up vote 7 down vote accepted

Let $x \lt y$. The usual pseudo-random number generators produce a number between $0$ and $1$. Multiply the result by $y-x$, and then add $x$.

This also works fine if $y \lt x$.

share|improve this answer
    
Could you go into further detail about why this works? I have asked this as a seperate question here. –  JW01 Nov 19 '12 at 3:02
    
@JW01: By number here we mean real number, not integer. If we multiply a number between $0$ and $1$ by $c\ne 0$, we certainly get a number between $0$ and $c$. Suppose moreover the random numbers between $0$ and $1$ are uniformly distributed $[0,1]$. Let $U$ be a random variable with uniform distribution on $[0,1]$. Let $X=cU$, where for simplicity $c$ is positive. Then for $0\le x\le c$, $\Pr(X\le x)=\Pr(cU\le x)=\Pr(U\le x/c=x/c$. This means $X$ has uniform distribution on $[0,c]$. If you wish, differentiate the cdf $x/c$ to get constant density function $1/c$. –  André Nicolas Nov 19 '12 at 3:14
    
Thanks. Its explained very succinctly. I think I get the gist. p.s I assume that there should be a closing parenthesis just before the final sentence ".This means..." ? –  JW01 Nov 19 '12 at 3:37
    
There should be a closing parenthesis just before the $=$ sign, a few characters before "This means." –  André Nicolas Nov 19 '12 at 3:50
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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