akira_lm

04-17-2001, 01:25 PM

that basically my question?

View Full Version : How to specify a range for rand() in c?

akira_lm

04-17-2001, 01:25 PM

that basically my question?

rts

04-17-2001, 01:27 PM

Use mod:

rand() % 10 <-- random number from 0 to 9.

Hope this helps.

rand() % 10 <-- random number from 0 to 9.

Hope this helps.

bsperlin

04-17-2001, 05:34 PM

Taking this farther than you may want to go:

rand() % 10 - 7 gives one of 10 random numbers from -7 to 2

( rand() % 10 -7 ) / 2.0 gives one of 10 random numbers from -3.5 to 1, etc.

Barry

rand() % 10 - 7 gives one of 10 random numbers from -7 to 2

( rand() % 10 -7 ) / 2.0 gives one of 10 random numbers from -3.5 to 1, etc.

Barry

DFrey

04-17-2001, 05:49 PM

Or even further, if the width of the range, n, is a power of two, you can use the following for example:

r = rand() & (n-1);

[This message has been edited by DFrey (edited 04-17-2001).]

r = rand() & (n-1);

[This message has been edited by DFrey (edited 04-17-2001).]

martin_marinov

04-18-2001, 01:17 AM

Hi

So the most general solution is maybe:

let [k..l] is the desired range (k < l)

then this expression

(l - k)*(double)rand()/(double)(RAND_MAX) + k

will return you not more than RAND_MAX different "random" values in [k..l].

However, when l-k <= RAND_MAX, I suggest you to use one of the above solutions, since this one is several times slower...

RAND_MAX is the standard define for the maximum random value, returned by rand().

Hope this helps

Martin

So the most general solution is maybe:

let [k..l] is the desired range (k < l)

then this expression

(l - k)*(double)rand()/(double)(RAND_MAX) + k

will return you not more than RAND_MAX different "random" values in [k..l].

However, when l-k <= RAND_MAX, I suggest you to use one of the above solutions, since this one is several times slower...

RAND_MAX is the standard define for the maximum random value, returned by rand().

Hope this helps

Martin

Powered by vBulletin® Version 4.2.3 Copyright © 2018 vBulletin Solutions, Inc. All rights reserved.