What's wrong with my random number generation?

M

Mark Healey

Here's the code:

signed char xMove, yMove, subx, suby;

[a bunch of stuff snipped]

xMove=(3*((float)rand()/(float)RAND_MAX))-1;
yMove=(3*((float)rand()/(float)RAND_MAX))-1;

I run srand() in main. When I run it without the -1 I get 0-2 as expected
but when I run it with them I get 0 and 1.

Why?
 
W

Walter Roberson

Here's the code:
signed char xMove, yMove, subx, suby;
[a bunch of stuff snipped]
xMove=(3*((float)rand()/(float)RAND_MAX))-1;
yMove=(3*((float)rand()/(float)RAND_MAX))-1;

I run srand() in main. When I run it without the -1 I get 0-2 as expected
but when I run it with them I get 0 and 1.

rand() will rarely come out as RAND_MAX, so the division is almost
always going to come out as something less than 1. When you multiply
it by 3, you are almost always going to come out with something less than 3.
Subtract 1 and you are almost always dealing with something less than 2.
You then convert that to an integer value by truncation instead of
rounding, so the maximum value will almost always be 1.

About 1/3 of the time, the float division of rand() by RAND_MAX will
come out less than 1/3; multiplied by 3 that would come out less than 1;
subtract 1 and the result will be less than 0. You then convert that
to a signed integer value. Check your results again: you are
probably generating some -1's.

Note by the way that the constants 3 and 1 in your expression
are operating on float values, so you might as well use float constants,
e.g. 3.0f and 1.0f .
 
R

Richard Bos

rand() will rarely come out as RAND_MAX, so the division is almost
always going to come out as something less than 1. When you multiply
it by 3, you are almost always going to come out with something less than 3.
Subtract 1 and you are almost always dealing with something less than 2.
You then convert that to an integer value by truncation instead of
rounding, so the maximum value will almost always be 1.

The solution to this problem is to use the right way to get a random
number within a range, as detailed in the FAQ:
<http://www.c-faq.com/lib/randrange.html>.

Richard
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,183
Messages
2,570,965
Members
47,511
Latest member
svareza

Latest Threads

Top