pete <pf*****@mindspring.com> writes:

pete wrote:

int X_prob(double x)

{

return RAND_MAX * x >= rand();

}

Dingo's post made me think that either 0.0 or 1.0

would probably be handled better as a special case.

return x >= 1.0 ? 1 : RAND_MAX * x > rand();

The multiplication isn't quite right; fencepost error.

The probabilities will be a little off.

Fixing up the fencepost error gets rid of the need for

special casing the boundary conditions:

int

X_prob( double x ){

assert( 0 <= x && x <= 1 );

return (RAND_MAX + 1.0) * x - 0.5 > rand();

}

Now any probability less than 1 / (2 * (RAND_MAX + 1.0))

will always yield zero, and any probability greater than

1 - (1 / (2 * (RAND_MAX + 1.0))) will always yield one, which

is the best that can be done under the circumstances. (That

is, "best" in sense of delivering the closest probability

possible, given that the function doesn't save any state

and calls rand() only once.)