generate random numbers

Mar 14, 2013 at 6:49am
srand (time(NULL));
for(int i=0; i<N; i++)
{
points[i].x=(rand()%(32767-(-32767)))+(-32767);
points[i].y=(rand()%(32767-(-32767)))+(-32767);
cout<<"x="<<points[i].x<<endl;
cout<<"y="<<points[i].y<<endl;
}

Im trying to generate random numbers between -32767 and +32767, some help as to where im going wrong would be helpful as this code generates only negative numbers
Mar 14, 2013 at 7:38am
for rnd numbers in the range of a to b, do:
rand()%(b-a)+a;

yours looks correct, but i would just use + instead of -- and - instead of +-
don't have a pc around to tedt it, so what excactly is your problem?
Mar 14, 2013 at 8:07am
i tired that as well, it just outputs negative numbers, like not a single value is positive
Mar 14, 2013 at 10:22am
The problem could be that RAND_MAX is too small. If RAND_MAX is 32767 (smallest guaranteed value) then you will only get negative numbers if you use the formula posted by Darkmaster.

You could combine the values from two calls to rand() to make a bigger random number. (rand() << 15) ^ rand() will return a value between 0 and at least 1073741823.
Mar 14, 2013 at 5:54pm
Hi peter87, i didnt really understand what ur trying to say, if you could elaborate it would be better as i cnt understand understand what ur saying i should try doing
Topic archived. No new replies allowed.