Velvet Star Monitor

Standout celebrity highlights with iconic style.

general

How to find a random number between $x$ and $y$

Writer Sebastian Wright
$\begingroup$

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?

$\endgroup$

1 Answer

$\begingroup$

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$.

$\endgroup$ 4

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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