471,311 Members | 1,901 Online

# rand() between m and n

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

Aug 1 '06 #1
26 3920 Gary Wessle <ph****@yahoo.comwrites:
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
add three to the result.

For some code example see e.g.

HTH
--
Marco Wahl
http://visenso.com
Aug 1 '06 #2
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;
}

Aug 1 '06 #3

"Gernot Frisch" <Me@Privacy.netwrote in message
news:4j************@individual.net...
>
>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
Aug 1 '06 #4
"Chris Theis" <ch*************@nospam.cern.chwrites:
"Gernot Frisch" <Me@Privacy.netwrote in message
news:4j************@individual.net...
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;
}
}
Aug 1 '06 #5
Gary Wessle <ph****@yahoo.comwrote:
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) ;
Let's rearrange your spacing:

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
Aug 1 '06 #6
ri******@gehennom.invalid (Marcus Kwok) writes:
Gary Wessle <ph****@yahoo.comwrote:
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) ;

Let's rearrange your spacing:

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';
}
}
****************
****************
Aug 2 '06 #7
Gary Wessle <ph****@yahoo.comwrites:
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
Aug 2 '06 #8
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 '06 #9
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';
}
Aug 2 '06 #10
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
Aug 2 '06 #11
Marco Wahl <mw@visenso.dewrites:
Gary Wessle <ph****@yahoo.comwrites:
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) << " ";

}
Aug 2 '06 #12
"Gary Wessle" <ph****@yahoo.comwrote in message
news:87************@localhost.localdomain...
Marco Wahl <mw@visenso.dewrites:
>Gary Wessle <ph****@yahoo.comwrites:
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
Aug 2 '06 #13

<ar****************@gmail.comwrote in message
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
Aug 2 '06 #14
Chris Theis wrote:
>
<ar****************@gmail.comwrote in message
>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
Aug 2 '06 #15
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>::operator()(T min_, T max_){
_min = min_;
_max = max_;
_delta = RAND_MAX / (_max - _min);
return(operator()());}
template<typename T>
inline T Random<T>::operator()(){
return((rand() / _delta) + _min);}

int main(){
Random<floatrandFloat(-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<intrandInt(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/

Aug 2 '06 #16
Gary Wessle <ph****@yahoo.comwrote:
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
Aug 2 '06 #17

"Kai-Uwe Bux" <jk********@gmx.netwrote in message
news:ea**********@murdoch.acc.Virginia.EDU...
Chris Theis wrote:
>>
<ar****************@gmail.comwrote in message
>>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
Aug 2 '06 #18
Chris Theis wrote:
"Kai-Uwe Bux" <jk********@gmx.netwrote in message
news:ea**********@murdoch.acc.Virginia.EDU...
>>
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.
That is, indeed, one of the assertions made about random number
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.
Aug 2 '06 #19
Chris Theis wrote:
"Gary Wessle" <ph****@yahoo.comwrote in message
news:87************@localhost.localdomain...
>>
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.
Aug 2 '06 #20
Chris Theis wrote:
>
"Kai-Uwe Bux" <jk********@gmx.netwrote in message
news:ea**********@murdoch.acc.Virginia.EDU...
>Chris Theis wrote:
>>>
<ar****************@gmail.comwrote in message
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
No mapping of [0,RAND_MAX+1) to [0,n) can produce truly uniform results
unless n divides RAND_MAX+1. To give correct probabilities you need to
throw away some results from rand().

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
That's my point exactly. I do not oppose the statement that there are rand
implementations where modding is significantly worse than rescaling.
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".
As a general statement, this seems false: simple scaling gives preference to
high order bits. If the rand() implementation uses a random number
generator whose higher order bits are less random than its lower order
bits, rescaling is worse than taking remainders. (Rumor has it, though,
that such weakness is less common among random number generators than crapy
low-order bits:-)
In opposition to this the modulo mapping can affect the randomness because
you're introducing a limitation.
[snip]

Best

Kai-Uwe Bux

Aug 3 '06 #21
"Pete Becker" <pe********@acm.orgwrote in message
news:ZM******************************@giganews.com ...
>
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.
Hi Pete,

you're of course right about the introduction of a bias in both cases
(remainder and the floating point approach). However, I'm a bit sceptical
with respect to simply throwing away numbers above a certain threshold.
Depending on the situation (and the range) you might virtually shorten the
period of your RNG, which could introduce another problem. But I want to
emphasize that this depends very much on the situation.

There is one question that you might probably be able to answer. All RNG's
(Mersenne twister, RANMAR etc.) that we are using in the development of our
Monte Carlo simulations return values in the range from [0,1) which makes
sense from a mathematical point of view. I never quite figured why rand()
returns integer values. Probably you could shed some light on that.

Cheers
Chris
Aug 3 '06 #22

"Pete Becker" <pe********@acm.orgwrote in message
news:9-******************************@giganews.com...
Chris Theis wrote:
>"Kai-Uwe Bux" <jk********@gmx.netwrote in message
news:ea**********@murdoch.acc.Virginia.EDU...
>>>
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.
[SNIP]

Sorry, but I'm not quite sure I understand what you mean by "using floating
point". If you do the scaling as I've said in one of my previous posts I
very much doubt that I would get one of the slots twice as often as the
others. Running a simple program like the one below shows a (more or less)
uniform distribution. Of course this is no relevant hypothesis test for
distributions nor one of the DIE-hard tests for RNGs!

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

int main() {
map<int, unsigned longHisto;
srand( 0 );
for( unsigned long i = 0; i < 10000000; ++i)
Histo[ randam( 0, 6)]++;

for( map<int, unsigned long>::iterator Iter = Histo.begin(); Iter !=
Histo.end(); ++Iter )
cout << Iter->first << ": " << Iter->second << endl;

return true;
}

Probably I missunderstood your point with respect to the statement that one
of the slots should come up twice as often.

Cheers
Chris
Aug 3 '06 #23
In article <87************@localhost.localdomain>, ph****@yahoo.com
says...

[ ... ]
I need help to generate some random numbers between 2 and 8.
This has been discussed a number of times in the past. One method
that works reasonably well looks like this:

#include <stdlib.h>

int rand_lim(int limit) {
int divisor = RAND_MAX/(limit+1);
int retval;

do {
retval = rand() / divisor;
} while (retval limit);

return retval;
}

int rand_lim(int lower, int upper) {
int range = abs(upper-lower);

return rand_lim(range) + lower;
}

This doesn't use floating point, doesn't introduce skew, and normally
uses the more significant bits of the value returned by rand(), which
are generally at least as random as the less significant bits (in
some cases they're about equal, with a linear congruential generator,
the upper bits are usually more random). Yes, in theory you _could_
create a generator in which the upper bits were inferior, (if nothing
else by simply swapping bits) but I've never actually seen such a
thing.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Aug 3 '06 #24
Chris Theis wrote:
>
Probably I missunderstood your point with respect to the statement that one
of the slots should come up twice as often.
That was in regard to the specific example I gave. Try it.
Aug 4 '06 #25
Kai-Uwe Bux wrote:
>
As a general statement, this seems false: simple scaling gives preference to
high order bits. If the rand() implementation uses a random number
generator whose higher order bits are less random than its lower order
bits, rescaling is worse than taking remainders. (Rumor has it, though,
that such weakness is less common among random number generators than crapy
low-order bits:-)
Not rumor, well established fact. Of course, it's possible that things
have changed in the twenty years or so since the usually-quoted tests
Aug 4 '06 #26
Chris Theis wrote:
>
There is one question that you might probably be able to answer. All RNG's
(Mersenne twister, RANMAR etc.) that we are using in the development of our
Monte Carlo simulations return values in the range from [0,1) which makes
sense from a mathematical point of view. I never quite figured why rand()
returns integer values. Probably you could shed some light on that.
It's fast and simple. And the canonical implementation of mersenne
twister also returns integer values. Floating-point math will rarely be
as fast as integer math, so when speed matters, integral random number
generators will usually be better.
Aug 4 '06 #27

### This discussion thread is closed

Replies have been disabled for this discussion.