# rand() between m and n

Discussion in 'C++' started by Gary Wessle, Aug 1, 2006.

1. ### Gary WessleGuest

Hi

I need help to generate some random numbers between 2 and 8.

#include <cstdlib>
using std::rand;

the following was out of my range,

int main() {

for (int i = 0; i < 50; i++){
int x = (int(rand())/444489786)*8;
cout << x << '\t' << endl;
}
}

it can be any quality random number.

thanks

Gary Wessle, Aug 1, 2006

2. ### Marco WahlGuest

Gary Wessle <> writes:
> I need help to generate some random numbers between 2 and 8.

So you need random numbers out of 3, 4, 5, 6, 7, right?

> the following was out of my range,

Did you get all zeros?

> int main() {
>
> for (int i = 0; i < 50; i++){
> int x = (int(rand())/444489786)*8;
> cout << x << '\t' << endl;
> }
> }
>
> it can be any quality random number.

So the rand function should suffice.

Converting the result of the rand function to float
allows you to normalize the rand result into the
interval [0, 1] as floating point number. Then you can
multiply with five (you want to pick a number from a
range of five numbers, don't you?) and then round and

For some code example see e.g.

HTH
--
Marco Wahl
http://visenso.com

Marco Wahl, Aug 1, 2006

3. ### Gernot FrischGuest

> I need help to generate some random numbers between 2 and 8.
>
> #include <cstdlib>
> using std::rand;
>
> the following was out of my range,
>
> int main() {
>
> for (int i = 0; i < 50; i++){
> int x = (int(rand())/444489786)*8;
> cout << x << '\t' << endl;
> }
> }

// return random number elm[from; upto]
int rnd_range( int from, int upto)
{
return (rand() % (upto - from + 1)) + from;
}

Gernot Frisch, Aug 1, 2006
4. ### Chris TheisGuest

"Gernot Frisch" <> wrote in message
news:...
>
>> I need help to generate some random numbers between 2 and 8.
>>
>> #include <cstdlib>
>> using std::rand;
>>
>> the following was out of my range,
>>
>> int main() {
>>
>> for (int i = 0; i < 50; i++){
>> int x = (int(rand())/444489786)*8;
>> cout << x << '\t' << endl;
>> }
>> }

>
> // return random number elm[from; upto]
> int rnd_range( int from, int upto)
> {
> return (rand() % (upto - from + 1)) + from;
> }
>

This works absolutely fine, but still the other approach using a random
number between r out of [0,1) ( x = Min + r * (Max-Min) ) is favorable
because it doesn't tamper with the "randomness" of the generator and has no
influence on the period of the generated sequence.

Cheers
Chris

Chris Theis, Aug 1, 2006
5. ### Gary WessleGuest

"Chris Theis" <> writes:

> "Gernot Frisch" <> wrote in message
> news:...
> >
> >> I need help to generate some random numbers between 2 and 8.
> >>
> >> #include <cstdlib>
> >> using std::rand;
> >>
> >> the following was out of my range,
> >>
> >> int main() {
> >>
> >> for (int i = 0; i < 50; i++){
> >> int x = (int(rand())/444489786)*8;
> >> cout << x << '\t' << endl;
> >> }
> >> }

> >
> > // return random number elm[from; upto]
> > int rnd_range( int from, int upto)
> > {
> > return (rand() % (upto - from + 1)) + from;
> > }
> >

>
> This works absolutely fine, but still the other approach using a random
> number between r out of [0,1) ( x = Min + r * (Max-Min) ) is favorable

do you mean
int x = from + rand() * (to-from) ?

> because it doesn't tamper with the "randomness" of the generator and has no
> influence on the period of the generated sequence.
> Cheers
> Chris

I am not sure what wrong I am doing, followed the link provided by
Marco, which was

the following puts out zeros on my screen. only zeros no mater how
many times I run it.

#include <ctime>
using std::time;

int main() {

int x;
const int N = 100;
srand( static_cast<unsigned> (time( NULL )) );
for (int i = 0; i < 4; i++) {
x = static_cast<int> ( N*rand())/(RAND_MAX+1) ;
cout << x << endl;
}
}

Gary Wessle, Aug 1, 2006
6. ### Marcus KwokGuest

Gary Wessle <> wrote:
> I am not sure what wrong I am doing, followed the link provided by
> Marco, which was
>
> the following puts out zeros on my screen. only zeros no mater how
> many times I run it.

#include <iostream>

> #include <ctime>
> using std::time;

using std::cout;

> int main() {
>
> int x;
> const int N = 100;
> srand( static_cast<unsigned> (time( NULL )) );
> for (int i = 0; i < 4; i++) {
> x = static_cast<int> ( N*rand())/(RAND_MAX+1) ;

x = static_cast<int>(N*rand()) / (RAND_MAX+1);

So, you are taking the value of N*rand(), and then casting it to an int.
Then you are dividing it by (RAND_MAX+1), which is also an int.
Therefore you have an int/int, so the division truncates, resulting in a
zero.

I would try casting the result of N*rand() to a double, then performing
the (floating-point) division, then casting THAT result to an int:

x = static_cast<int>(static_cast<double>(N*rand()) / (RAND_MAX+1));

Of course, you could break this up into smaller steps.

> cout << x << endl;
> }
> }

--
Marcus Kwok
Replace 'invalid' with 'net' to reply

Marcus Kwok, Aug 1, 2006
7. ### Gary WessleGuest

lid (Marcus Kwok) writes:

> Gary Wessle <> wrote:
> > I am not sure what wrong I am doing, followed the link provided by
> > Marco, which was
> >
> > the following puts out zeros on my screen. only zeros no mater how
> > many times I run it.

>
> #include <iostream>
>
> > #include <ctime>
> > using std::time;

>
> using std::cout;
>
> > int main() {
> >
> > int x;
> > const int N = 100;
> > srand( static_cast<unsigned> (time( NULL )) );
> > for (int i = 0; i < 4; i++) {
> > x = static_cast<int> ( N*rand())/(RAND_MAX+1) ;

>
>
> x = static_cast<int>(N*rand()) / (RAND_MAX+1);
>
> So, you are taking the value of N*rand(), and then casting it to an int.
> Then you are dividing it by (RAND_MAX+1), which is also an int.
> Therefore you have an int/int, so the division truncates, resulting in a
> zero.
>
> I would try casting the result of N*rand() to a double, then performing
> the (floating-point) division, then casting THAT result to an int:
>
> x = static_cast<int>(static_cast<double>(N*rand()) / (RAND_MAX+1));
>
> Of course, you could break this up into smaller steps.
>
> > cout << x << endl;
> > }
> > }

>
> --
> Marcus Kwok
> Replace 'invalid' with 'net' to reply

do you mean this, it still puts out all zeros, could you try it on
your machine and report back? thanks

****************
****************
#include <iostream>
#include <cstdlib>

using namespace std;

int main() {

srand( static_cast<unsigned> (time( NULL )) );
int N = 8;
int x;
for (unsigned i=0; i<5; i++){
x = static_cast<int>(static_cast<double>(N*rand()) / (RAND_MAX+1));
cout << x << '\t';
}
}
****************
****************

Gary Wessle, Aug 2, 2006
8. ### Marco WahlGuest

Gary Wessle <> writes:

> do you mean this, it still puts out all zeros, could you try it on
> your machine and report back? thanks
>
>
> #include <iostream>
> #include <cstdlib>
>
> using namespace std;
>
> int main() {
>
> srand( static_cast<unsigned> (time( NULL )) );
> int N = 8;
> int x;
> for (unsigned i=0; i<5; i++){
> x = static_cast<int>(static_cast<double>(N*rand()) / (RAND_MAX+1));
> cout << x << '\t';
> }
> }

I checked and also get all 0s. The output looks more interesting when using the line

x = static_cast<int>(N * static_cast<double>(rand()) / (static_cast<double>(RAND_MAX) + 1));

There is an overflow on my machine at least when calculating RAND_MAX+1.

HTH
--
Marco Wahl
http://visenso.com

Marco Wahl, Aug 2, 2006
9. ### Guest

Hello all,
why you are going far away?
first use srand() to randomize radom number, srand get a parameter as
seed, like:
srand(3); or you can use srand(time(0));
then use this method to have randome number in a certain range:
x=minum number +rand()% maximum number;
for example: x=1+rand()%6; gives you a random number between 1 to 6;
Also you mist use srand() before using rand, you can use it at the
first of main()

, Aug 2, 2006
10. ### Gary WessleGuest

the thing is if you need to generate say 5 random numbers between 2
and 8 then this will not work, run this

for (int i= 0; i< 5; i++){
srand( time( 0));
int x= 2+ rand() %8;
cout << x << '\n';
}

Gary Wessle, Aug 2, 2006
11. ### Kai-Uwe BuxGuest

Gary Wessle wrote:

> the thing is if you need to generate say 5 random numbers between 2
> and 8 then this will not work, run this
>
> for (int i= 0; i< 5; i++){
> srand( time( 0));
> int x= 2+ rand() %8;

int x = 2 + rand() % 6;

> cout << x << '\n';
> }

Best

Kai-Uwe Bux

Kai-Uwe Bux, Aug 2, 2006
12. ### Gary WessleGuest

Marco Wahl <> writes:

> Gary Wessle <> writes:
>
> > do you mean this, it still puts out all zeros, could you try it on
> > your machine and report back? thanks
> >
> >
> > #include <iostream>
> > #include <cstdlib>
> >
> > using namespace std;
> >
> > int main() {
> >
> > srand( static_cast<unsigned> (time( NULL )) );
> > int N = 8;
> > int x;
> > for (unsigned i=0; i<5; i++){
> > x = static_cast<int>(static_cast<double>(N*rand()) / (RAND_MAX+1));
> > cout << x << '\t';
> > }
> > }

>
> I checked and also get all 0s. The output looks more interesting when using the line
>
> x = static_cast<int>(N * static_cast<double>(rand()) / (static_cast<double>(RAND_MAX) + 1));
>
> There is an overflow on my machine at least when calculating RAND_MAX+1.
>
>
> HTH
> --
> Marco Wahl
> http://visenso.com

here is the final code for future readers.

****************************************************************
int randam(int from, int to) {
int f = from;
int t = to;
int a = to-from+1;
return static_cast<int> (a * static_cast<double>(rand())/
(static_cast<double>(RAND_MAX) + 1))+from;
}

int main() {

// print out 5 random numbers between 2 and 8
srand( static_cast<unsigned> (time( NULL )) );
for(int i=0; i<5; i++) cout << randam(2,8) << " ";

}

Gary Wessle, Aug 2, 2006
13. ### Chris TheisGuest

"Gary Wessle" <> wrote in message
news:...
> Marco Wahl <> writes:
>
>> Gary Wessle <> writes:
>>
>> > do you mean this, it still puts out all zeros, could you try it on
>> > your machine and report back? thanks
>> >
>> >
>> > #include <iostream>
>> > #include <cstdlib>
>> >
>> > using namespace std;
>> >
>> > int main() {
>> >
>> > srand( static_cast<unsigned> (time( NULL )) );
>> > int N = 8;
>> > int x;
>> > for (unsigned i=0; i<5; i++){
>> > x = static_cast<int>(static_cast<double>(N*rand()) /
>> > (RAND_MAX+1));
>> > cout << x << '\t';
>> > }
>> > }

>>
>> I checked and also get all 0s. The output looks more interesting when
>> using the line
>>
>> x = static_cast<int>(N * static_cast<double>(rand()) /
>> (static_cast<double>(RAND_MAX) + 1));
>>
>> There is an overflow on my machine at least when calculating RAND_MAX+1.
>>
>>
>> HTH
>> --
>> Marco Wahl
>> http://visenso.com

>
> here is the final code for future readers.
>
> ****************************************************************
> int randam(int from, int to) {
> int f = from;
> int t = to;
> int a = to-from+1;
> return static_cast<int> (a * static_cast<double>(rand())/
> (static_cast<double>(RAND_MAX) + 1))+from;
> }
>
> int main() {
>
> // print out 5 random numbers between 2 and 8
> srand( static_cast<unsigned> (time( NULL )) );
> for(int i=0; i<5; i++) cout << randam(2,8) << " ";
>
> }

Hi Gary,

> do you mean int x = from + rand() * (to-from) ?

Yes, that's what I mean. It a simple scaling and adding an offset to the
result of a random number in the [0,1).

The code above should give you what you are looking for. In a more compact
form you can write it like this:

return static_cast<int>( from + ( (to - from) * (rand() / (RAND_MAX +
1.0)) ));

But be careful - the statement above is different than writing

return static_cast<int>( from + ( (to - from) * (rand() / (RAND_MAX +
1)) ));

The "beast" that you were running into was the integer division of rand() by
another much larger integer. The result of this integer devision is always 0
and that's why you obtained zeros (or the offset from). However, by using
1.0 instead of 1 in the calculation you implicitly convert the divisor to a
float and consequently the division is performed and results in a float.

HTH
Chris

Chris Theis, Aug 2, 2006
14. ### Chris TheisGuest

<> wrote in message
news:...
> Hello all,
> why you are going far away?
> first use srand() to randomize radom number, srand get a parameter as
> seed, like:
> srand(3); or you can use srand(time(0));
> then use this method to have randome number in a certain range:
> x=minum number +rand()% maximum number;

Yes, that surely works but brings back my original comment. Using the modulo
operation you interfere with the randomness and don't make use of the full
period of the random generator. Anyway, it depends on your application
whether this matters or not.

Cheers
Chris

Chris Theis, Aug 2, 2006
15. ### Kai-Uwe BuxGuest

Chris Theis wrote:

>
> <> wrote in message
> news:...
>> Hello all,
>> why you are going far away?
>> first use srand() to randomize radom number, srand get a parameter as
>> seed, like:
>> srand(3); or you can use srand(time(0));
>> then use this method to have randome number in a certain range:
>> x=minum number +rand()% maximum number;

>
> Yes, that surely works but brings back my original comment. Using the
> modulo operation you interfere with the randomness

How, and why?

> and don't make use of the full period of the random generator.

Huh? I see that that can happen. However, I do not see why the alternative
of chopping [0,RAND_MAX] into n intervals of equal length it a priory
better.

As far as I can see, any kind of mapping N values to n < N values can tamper
with the period or other measures of randomness. Whether a particular
mapping fares better or worse depends on the underlying random number
generator.

> Anyway, it depends on your application whether this matters or not.

True, and I think up-thread it was stated that quality does not matter.

Best

Kai-Uwe Bux

Kai-Uwe Bux, Aug 2, 2006
16. ### =?iso-8859-1?q?Lars_Rune_N=F8stdal?=Guest

Gary Wessle wrote:
> Hi
>
> I need help to generate some random numbers between 2 and 8.
>
> #include <cstdlib>
> using std::rand;
>
> the following was out of my range,
>
> int main() {
>
> for (int i = 0; i < 50; i++){
> int x = (int(rand())/444489786)*8;
> cout << x << '\t' << endl;
> }
> }
>
> it can be any quality random number.
>
>
> thanks

This is one way of doing it:

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

template<typename T>
class Random {
public:
Random(T min_, T max_);

T operator()(T min_, T max_); ///< Set new range for random numbers,
and return a random number.

T operator()(); ///< Return a random number.

private:
T _min, _max;
T _delta;
};

template<typename T>
inline Random<T>::Random(T min_, T max_)
:_min(min_),
_max(max_){
srand(time(0));
srand(time(0));
_delta = RAND_MAX / (_max - _min);}

template<typename T>
inline T Random<T>:perator()(T min_, T max_){
_min = min_;
_max = max_;
_delta = RAND_MAX / (_max - _min);
return(operator()());}

template<typename T>
inline T Random<T>:perator()(){
return((rand() / _delta) + _min);}

int main(){
Random<float> randFloat(-10, -20);

cerr << "5 random floating point numbers between -10 and -20: ";
for(int i = 0; i < 5; i++)
cerr << fixed << randFloat() << " ";
cerr << endl;

randFloat(-100, 100);

cerr << "5 random floating point numbers between -100 and 100: ";
for(int i = 0; i < 5; i++)
cerr << fixed << randFloat() << " ";
cerr << endl;

Random<int> randInt(20000, 10000);

cerr << "5 random integers between 20000 and 10000: ";
for(int i = 0; i < 5; i++)
cerr << fixed << randInt() << " ";
cerr << endl;

randInt(-10, 10);

cerr << "5 random integers between -10 and 10: ";
for(int i = 0; i < 5; i++)
cerr << fixed << randInt() << " ";
cerr << endl;
return 0;}

lars@ibmr52:~/programming/c\$ g++ -g -Wall random.cpp -o random &&
../random
5 random floating point numbers between -10 and -20: -15.719680
-10.247149 -10.654663 -16.673820 -13.213199
5 random floating point numbers between -100 and 100: 63.869286
-77.031998 -25.940384 -4.096813 -49.285671
5 random integers between 20000 and 10000: 14281 19753 19346 13327
16787
5 random integers between -10 and 10: 6 -8 -3 -1 -5

--
mvh, Lars Rune Nøstdal
http://lars.nostdal.org/

=?iso-8859-1?q?Lars_Rune_N=F8stdal?=, Aug 2, 2006
17. ### Marcus KwokGuest

Gary Wessle <> wrote:
> do you mean this, it still puts out all zeros, could you try it on
> your machine and report back? thanks
>
>
> ****************
> ****************
> #include <iostream>
> #include <cstdlib>
>
> using namespace std;
>
> int main() {
>
> srand( static_cast<unsigned> (time( NULL )) );
> int N = 8;
> int x;
> for (unsigned i=0; i<5; i++){
> x = static_cast<int>(static_cast<double>(N*rand()) / (RAND_MAX+1));
> cout << x << '\t';
> }
> }
> ****************
> ****************

Interesting, on my machine (Windows XP, VS .NET 2003), after I added
#include <ctime>, my output for repeated runs was (using spaces instead
of tabs):

2 5 1 1 1
2 6 6 7 2
2 6 2 2 7

etc.

--
Marcus Kwok
Replace 'invalid' with 'net' to reply

Marcus Kwok, Aug 2, 2006
18. ### Chris TheisGuest

"Kai-Uwe Bux" <> wrote in message
news:eaqde5\$q22\$...
> Chris Theis wrote:
>
>>
>> <> wrote in message
>> news:...
>>> Hello all,
>>> why you are going far away?
>>> first use srand() to randomize radom number, srand get a parameter as
>>> seed, like:
>>> srand(3); or you can use srand(time(0));
>>> then use this method to have randome number in a certain range:
>>> x=minum number +rand()% maximum number;

>>
>> Yes, that surely works but brings back my original comment. Using the
>> modulo operation you interfere with the randomness

>
> How, and why?
>
>> and don't make use of the full period of the random generator.

>
> Huh? I see that that can happen. However, I do not see why the alternative
> of chopping [0,RAND_MAX] into n intervals of equal length it a priory
> better.
>

Well we're getting into a hot topic here which has been discussed
extensively. On one hand using modulo you might skew the results towards
lower values and on the other hand you can have an effect on the randomness.
The reason is that the modulo operation uses low order bits and depending on
the type of random generator the high-order bits might show better
randomness. However, this is something which depends on the implementation
of rand and is the subject of endless discussions! For a thorough discussion
on this including the mathematics you might refer to Knuth's book The Art of
computer programming Vol.2 and/or Numerical Recipes.

> As far as I can see, any kind of mapping N values to n < N values can
> tamper
> with the period or other measures of randomness. Whether a particular
> mapping fares better or worse depends on the underlying random number
> generator.
>

Yes and no. Of course you will never get good results if your random
generator is crap. However, the simple scaling and offsetting does not
interfere with any property of the RNG and therefore does not affect the
"randomness". In opposition to this the modulo mapping can affect the
randomness because you're introducing a limitation.

>
>> Anyway, it depends on your application whether this matters or not.

>
> True, and I think up-thread it was stated that quality does not matter.
>
>
> Best
>
> Kai-Uwe Bux

Cheers
Chris

Chris Theis, Aug 2, 2006
19. ### Pete BeckerGuest

Chris Theis wrote:
> "Kai-Uwe Bux" <> wrote in message
> news:eaqde5\$q22\$...
>
>>
>>Huh? I see that that can happen. However, I do not see why the alternative
>>of chopping [0,RAND_MAX] into n intervals of equal length it a priory
>>better.
>>

>
>
> Well we're getting into a hot topic here which has been discussed
> extensively. On one hand using modulo you might skew the results towards
> lower values and on the other hand you can have an effect on the randomness.
> The reason is that the modulo operation uses low order bits

That's not the reason. Consider a drastically simplified case: a rand()
function that produces values between 0 and 5 inclusive, and an attempt
to generate values from 0 to 4 inclusive. Using the remainder operator
(C and C++ do not have a modulus operator, but for positive arguments
remainder and modulus do the same thing), the generated value 0, 1, 2,
3, and 4 each map to themselves, and the generated value 5 maps to 0. So
you get twice as many 0's in the output.

When you use floating point, you're still mapping six values into five
slots, and one of the slots will come up twice as often as the others.
Try it.

In general, this problem occurs whenever the number of values in the
range returned by the generator is not an exact multiple of the number
of values in the target range. The solution, regardless of how you
implement the range conversion, is to discard some values from the
generator, so that you end up with a range whose size is a multiple of
the size of the target range. In the case of the simple example above,
throw away every 5 that you get from the generator.

> and depending on
> the type of random generator the high-order bits might show better
> randomness. However, this is something which depends on the implementation
> of rand and is the subject of endless discussions! For a thorough discussion
> on this including the mathematics you might refer to Knuth's book The Art of
> computer programming Vol.2 and/or Numerical Recipes.

generators. The mismatch in range sizes is far more significant.

>
>
>>As far as I can see, any kind of mapping N values to n < N values can
>>tamper
>>with the period or other measures of randomness. Whether a particular
>>mapping fares better or worse depends on the underlying random number
>>generator.
>>

>
>
> Yes and no. Of course you will never get good results if your random
> generator is crap. However, the simple scaling and offsetting does not
> interfere with any property of the RNG and therefore does not affect the
> "randomness".

It does affect the randomness of the resulting sequence, as shown above.

Pete Becker, Aug 2, 2006
20. ### Pete BeckerGuest

Chris Theis wrote:

> "Gary Wessle" <> wrote in message
> news:...
>
>>
>>here is the final code for future readers.
>>
>>****************************************************************
>>int randam(int from, int to) {
>> int f = from;
>> int t = to;
>> int a = to-from+1;
>> return static_cast<int> (a * static_cast<double>(rand())/
>> (static_cast<double>(RAND_MAX) + 1))+from;
>>}
>>
>>int main() {
>>
>>// print out 5 random numbers between 2 and 8
>> srand( static_cast<unsigned> (time( NULL )) );
>> for(int i=0; i<5; i++) cout << randam(2,8) << " ";
>>
>>}

>
>
> The code above should give you what you are looking for. In a more compact
> form you can write it like this:
>

As I pointed out in another message, this doesn't compensate for
mismatched range sizes. The bias is less obvious than when using
remainainder because remainder puts the excess values down at the low
end of the target range, while the floating-point approach distributes
them more evenly. But try that code with a custom rand function that
generates values between 0 and 8, inclusive. One of the values will turn
up twice as often as the others. (I haven't done the analysis to figure
out which one.)

To avoid this bias, compute the largest multiple of the number of values
in the target range (m * (to - from + 1)) that is less than or equal to
the number of values in the generator's range (loosely, RAND_MAX+1, but
beware of overlows). Each time you call rand, check whether the value is
greater than or equal to this largest multiple; if it is, call rand again.

Pete Becker, Aug 2, 2006