473,804 Members | 2,132 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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
26 4113
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.dew rites:
Gary Wessle <ph****@yahoo.c omwrites:
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<uns igned(time( NULL )) );
int N = 8;
int x;
for (unsigned i=0; i<5; i++){
x = static_cast<int >(static_cast<d ouble>(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<dou ble>(rand()) / (static_cast<do uble>(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<dou ble>(rand())/
(static_cast<do uble>(RAND_MAX) + 1))+from;
}

int main() {

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

}
Aug 2 '06 #12
"Gary Wessle" <ph****@yahoo.c omwrote in message
news:87******** ****@localhost. localdomain...
Marco Wahl <mw@visenso.dew rites:
>Gary Wessle <ph****@yahoo.c omwrites:
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<uns igned(time( NULL )) );
int N = 8;
int x;
for (unsigned i=0; i<5; i++){
x = static_cast<int >(static_cast<d ouble>(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<dou ble>(rand()) /
(static_cast<d ouble>(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<dou ble>(rand())/
(static_cast<do uble>(RAND_MAX) + 1))+from;
}

int main() {

// print out 5 random numbers between 2 and 8
srand( static_cast<uns igned(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.comw rote in message
news:11******** **************@ h48g2000cwc.goo glegroups.com.. .
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.comw rote in message
news:11******** **************@ h48g2000cwc.goo glegroups.com.. .
>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<typena me 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<typena me T>
inline Random<T>::Rand om(T min_, T max_)
:_min(min_),
_max(max_){
srand(time(0));
srand(time(0));
_delta = RAND_MAX / (_max - _min);}
template<typena me T>
inline T Random<T>::oper ator()(T min_, T max_){
_min = min_;
_max = max_;
_delta = RAND_MAX / (_max - _min);
return(operator ()());}
template<typena me T>
inline T Random<T>::oper ator()(){
return((rand() / _delta) + _min);}

int main(){
Random<floatran dFloat(-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<intrandI nt(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.c omwrote:
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<uns igned(time( NULL )) );
int N = 8;
int x;
for (unsigned i=0; i<5; i++){
x = static_cast<int >(static_cast<d ouble>(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.com wrote in message
news:11******* *************** @h48g2000cwc.go oglegroups.com. ..
>>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.c omwrote 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<dou ble>(rand())/
(static_cast<do uble>(RAND_MAX) + 1))+from;
}

int main() {

// print out 5 random numbers between 2 and 8
srand( static_cast<uns igned(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

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
4228
by: Tom McCallum | last post by:
Can any tell me why rand() is such a bad pseudo-random number generator. In all the articles I have read they say that you can predict the outcome of rand() but when I used its output with NIST's random number testsuite it passed all of the tests thrown at it for randomness. Can anyone suggest a test I could use that it would fail? A pointer to a suitable article would be appreciated. Thanks for your help in advance, Tom
7
3251
by: Chris Gordon-Smith | last post by:
I have a simulation program that calls the rand() function at various points while it executes. For the user interface that displays statistics etc. while the program runs, I use the Lazarus GUI library, which is based on GTK. Depending on which libraries I link in, I can have either a GTK1 or GTK2 user interface. I'm finding that the simulation behaves differently depending on whether I link with GTK1 or GTK2.
36
7144
by: Ben Justice | last post by:
For a program in c, I need some random numbers for a system were people are placing bets. This is not a commerical project btw. Generally, I tend to rely on things from the standard library, because they're written by people with skills far above mine. Hence, I've always used rand() and FALSELY assumed it could produce unpredictable random numbers and could be used in many situations even if security was an issue. Firstly, lets assume...
36
2696
by: Profetas | last post by:
Hi, I want to generate a random 8 bit number using rand(0 is that possible? to expecifu the base and the lenght? thanks
8
4399
by: Jack | last post by:
When I use rand(), is the RAND_MAX value how long I am guaranteed that the same value will not appear twice? And is this a floating window? For example, if RAND_MAX is 32767, and I make 500,000 consecutive rand calls then is the rand() algorithm going to guarantee me that no floating window of calls over that 500,000 rand calls will have the same value twice? The only way that would work is if the series was identical everytime.
4
2798
by: Siam | last post by:
Hi all, I'm writing a shell language in c++ that supports the generation of random numbers, and by its nature, each command must be executed in a new thread. The call to the random function from my language simply propogates up to the rand( ) function from c++. For some reason, C++ will give each thread independent use of their own rand( ) function, so that a rand( ) call from one thread won't affect another thread's call to rand( )....
13
3673
by: Spiros Bousbouras | last post by:
The standard says that rand() should return a pseudo-random number but what does pseudorandom mean ? If an implementation of rand() always returned the same number would it be conforming ? What if it always alternated between 2 values ? On the practical side do you have any thoughts on what one could realistically expect from the behaviour of rand() ? Could for example one expect that eventually any value in the range will be returned ?
5
2326
by: ds | last post by:
Hi all, rand() is not thread safe, a fact that may not be so bad after all.. However, I face the following problem: a piece of code uses rand() to get a random sequence, but always seeds with the same seed for reproducibility of the results. Now I am porting this (old C89) code and have setup a nice app with threads that drives on one thread the old code and on another the new code, so that I can compare the results and see that nothing...
10
3023
by: Rafael Cunha de Almeida | last post by:
Hi, I've found several sites on google telling me that I shouldn't use rand() % range+1 and I should, instead, use something like: lowest+int(range*rand()/(RAND_MAX + 1.0))
15
3949
by: Rich Fife | last post by:
Quick rand() question: I know you're not supposed to use "rand() % 1024" for instance, because it focuses on the lower bits. However, it seems to me that given that the argument is not a power of two (or near a power of two), that this is not an issue. The upper bits will participate equally in the result with the lower. Am I missing something? Thanks!
0
9715
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9595
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10603
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10099
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9176
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6869
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5536
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4314
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3003
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.