rand() between m and n

G

Gary Wessle

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
 
M

Marco Wahl

Gary Wessle said:
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.

http://cplus.about.com/od/advancedtutorials/l/aa041303c.htm


HTH
 
G

Gernot Frisch

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;
}
 
C

Chris Theis

Gernot Frisch said:
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
 
G

Gary Wessle

Chris Theis said:
Gernot Frisch said:
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
http://cplus.about.com/od/advancedtutorials/l/aa041303c.htm

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;
}
}
 
M

Marcus Kwok

Gary Wessle said:
I am not sure what wrong I am doing, followed the link provided by
Marco, which was
http://cplus.about.com/od/advancedtutorials/l/aa041303c.htm

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

#include said:
#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.
 
G

Gary Wessle

using std::cout;


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.


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';
}
}
****************
****************
 
M

Marco Wahl

Gary Wessle said:
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
 
A

arash.koushkestani

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()
Hope I could help you;
 
G

Gary Wessle

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';
}
 
K

Kai-Uwe Bux

Gary said:
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
 
G

Gary Wessle

Marco Wahl said:
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

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) << " ";

}
 
C

Chris Theis

Gary Wessle said:
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
 
C

Chris Theis

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
 
K

Kai-Uwe Bux

Chris said:
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
 
?

=?iso-8859-1?q?Lars_Rune_N=F8stdal?=

Gary said:
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>::eek:perator()(T min_, T max_){
_min = min_;
_max = max_;
_delta = RAND_MAX / (_max - _min);
return(operator()());}


template<typename T>
inline T Random<T>::eek: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
 
M

Marcus Kwok

Gary Wessle said:
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.
 
C

Chris Theis

Kai-Uwe Bux said:
Chris said:
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.
True, and I think up-thread it was stated that quality does not matter.


Best

Kai-Uwe Bux

Cheers
Chris
 
P

Pete Becker

Chris said:
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.
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.
 
P

Pete Becker

Chris said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top