Generate random number

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
cout << RAND_MAX << endl; will give me
32767
on my compiler. It means that rand() will not generate numbers larger than that. And you sustract 32767 from generated number, so...

Use C++11 random generators.
This: http://cplusplus.com/reference/random/uniform_int_distribution/ should suit you.
You might try:
int n = rand() + rand() - RAND_MAX;

which should give a random number in the range
-RAND_MAX to +RAND_MAX
@Chervil
What you say is true but the random numbers will not have a uniform distribution. n is more likely to get values close to 0.
Last edited on
Unbiased scaling of random numbers is somewhat tricky.

MiiNiPaa's suggestion: +1
Topic archived. No new replies allowed.