Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

How to generate random number in C++?

Status
Not open for further replies.

ehsanelahimirza

Full Member level 6
Joined
Feb 24, 2006
Messages
334
Helped
28
Reputation
56
Reaction score
7
Trophy points
1,298
Activity points
3,570
hi all

plz tell me how to generate number in random order.in a given range.

plz give the code and libraries,
how to write in c++(syntax)

thanks
 

Re: random number in c++

Try this

#include <cstdlib>
#include <cstdio>

int main (void) {
int lim = 100;
fprintf(stdout, "%d, %d, %d\n", random() / ((unsigned int)RAND_MAX / lim), random() / ((unsigned int)RAND_MAX / lim), random() / ((unsigned int)RAND_MAX / lim));
return 0;
}
 

Re: random number in c++

Hows this?

Code:
#include <iostream> 
#include <ctime> 
#include <cstdlib> 

using namespace std; 

int generate_random_number( int uLowest, int uHighest, bool bSeed )
{
	// Seed the random number generated if requried.
	if ( true == bSeed )
	{
		srand((unsigned)time(0));
	}

	// Create a range value between which a number will be generated.
	int nRange = (uHighest-uLowest) + 1;
	
	// Generate the random number.
	int nRandomInteger = uLowest + int( nRange * rand() / (RAND_MAX + 1.0) ); 
	
	return nRandomInteger;
}

int main() 
{ 
	cout << generate_random_number( 1, 1000, true ) << endl;
	cout << generate_random_number( 1, 1000, false ) << endl;
	cout << generate_random_number( 1, 1000, false ) << endl;
	cout << generate_random_number( 1, 1000, false ) << endl;

	return 0;
	
}

Hope that helps ;)
 

Re: random number in c++

polus said:
Hows this?

Code:
#include <iostream> 
#include <ctime> 
#include <cstdlib>

Hope that helps ;)


yes its working but plz tell me the syntax only bcz i cant understand in this whole that what is the actual code and how to set the range. actually i want to use random number generated in my code
 

Re: random number in c++

The function random() will always return an integer between 0 and RAND_MAX. So what I have done is divide the generated number by RAND_MAX and then multiply it with the required 'lim' value. So the number won't be larger than 'lim'. Then the range will be 0 <= R <= lim.

If you want to set the range like lim1 <= R <= lim2 then add a number lim1 with it. But then multiplication should be by (lim2 - lim1). ie: 'lim1 + (lim2 - lim1) * random() / RAND_MAX;'

What polus have done is a kind of randomization of random number. It will generate even more randomized numbers using the timestamp as the random seed.
 
Re: random number in c++

Here is what i use to generate a random numder within a given range

Code:
#include <iostream>
#include <ctime>
using namespace std;


int main(){
    
  int rannum;          // define variables
  bool found = 1;
  long sec;
  
  time( &sec);      // use time function to get number of seconds from 1/1/1970
  
  srand((unsigned)sec); // use this number to seed the srand() function
  
  while (found == 1){         // use loop to look for desired number
        rannum = rand();
        if ( rannum >= 0 && rannum <= 15){  // turn off the loop when number is found
            found = 0;}
            }
        cout << rannum; // display the number
        cin.get();
}

to generate random number you use srand() function and you put seed number into it and then use rand() to put it in a variable, see code below for example

Code:
int seed, rannum;
cin >> seed;
cin.ignore();
srand (seed);
rannum = rand();
cout << rannum;
cin.get();

but when you use the same number for seed you get the same sequence of numbers (and that's not quite random) so you use time function to get number of secons since 1/1/1970 and this will give you quite random number generator

Code:
long sec;
time( &sec);
srand ( (unsigned)sec);

the very first code, uses a loop and if statement to keep generating numbers until the right one is found. in my code it generates the number between 0 and 15

best of luck;
 

Re: random number in c++

There are two problems with this code.
1) Its not much different from what polus have already posted.
2) putting that loop there is highly inefficient. Because thats un-necessary. Scaling the random number by RAND_MAX is much better than this. All it does is wasting a lot of time in that loop.

Even better way was to add another level of randomization. May be we can seed the 'random' with time. Then get the random number and then seed it again with that number. Then again get the random number.

Lucifre said:
Here is what i use to generate a random numder within a given range

Code:
#include <iostream>
#include <ctime>
using namespace std;


int main(){
    
  int rannum;          // define variables
  bool found = 1;
  long sec;
  
  time( &sec);      // use time function to get number of seconds from 1/1/1970
  
  srand((unsigned)sec); // use this number to seed the srand() function
  
  while (found == 1){         // use loop to look for desired number
        rannum = rand();
        if ( rannum >= 0 && rannum <= 15){  // turn off the loop when number is found
            found = 0;}
            }
        cout << rannum; // display the number
        cin.get();
}
/quote]
 

Re: random number in c++

Hi, For all those guy's that need a true random generator: DO NOT USE C/C++ random generator functions. What ever you do with a seed (time/key strokes) its not true random but pseudo random as they call it. If you have a large number of random numbers from the generator you can calculate the next and all that will follow !!!.. If you need a true random source go to google and find "CPRNG" = cryptographic PRNG
 

Re: random number in c++

Yes you are almost right. Most of the random number generators repeat their flow with some period. But we can always include more randomness in to this usual flow by randomly deciding the place form which random number is chosen. Also the characterstic of random number generators is specific to each computer. Thus in most conditions it wont make any problem because its unique.
 

Re: random number in c++

Hi, You incorrect !. C random number generator is a simple PRNG and is the same for all computers the code in compiled on. I know since I check it for a project !. Its not secure in any way !!.

Paul.
 

Re: random number in c++

Not exactly. Because not all systems implement the random number generation in the same way. There are systems which hardware random number generators. Also most of the PSEUDO RANDOM sequences repeates with a specific period. Haven't you seen those hardware pseudo random sequence generators ?. I think in computers also its applicable. May be thats atleast true for old computer implementations. Because I have seen books referring to this repeatability problem and its uniqueness specific computer.

PaulHolland said:
Hi, You incorrect !. C random number generator is a simple PRNG and is the same for all computers the code in compiled on. I know since I check it for a project !. Its not secure in any way !!.

Paul.
 

Re: random number in c++

What you refer to is called the normal way of generating PRNG it is done in hardware and the same way in software. NO computer I have seen in the last 30 Years did have a random generator implemented. The only thing that was done in the DOS days in borland C was using the not used counter as a random source !. That is all. But I leave it here since YOU seem to know better than all of the worlds cryptgraphic experts including me that has been working on cryptogathic military sistems for over 20 Years :).

Paul.
 

Re: random number in c++

Hello Paul,
I am not an expert in neither cryptography nor about random numbers. But there are strong reasons to believe that there exists hardware random generators in machines other than those military grade computers.

Take a look at the LINUX kernel source code. At the character drivers section there is option to enable hardware random number generators in Intel i8xx and AMD 76x based motherboards. Also there is support for VIA Nehemia CPU hardware random number generator.
 

Re: random number in c++

if you ask me, srand() and rand() with time seed are random enough.
 

Re: random number in c++

Hi,
For this question, Steve Summit has concluded with a detailed discussion on the pros and cons of the ordinary random number generating mechanis.

You can search the pdf file named "c faq" with google!


Good Luck,

Thomson
 

random number in c++

If you are doing large signal programming with random noise then srand and rand should not be used.
if you want a quick random number between 0 and 1000 as an example then rand and srand would work just fine.
 

Re: random number in c++

I disagree that the RNG inside the chips are real random numbers. The technology used is actually some shift registers and counters and does not have any fundamental difference from a pseudo-random number generated by software.

There are true random generated numbers which does not require seeds and that are based on some brownian nature of quantum mechanics and some exotic phenomena that creates some "white noise" that can be amplified and counted for and presented as a number within a range.

For most applications, slot machines, encryption and the likes, it is more realistic to have a pseudo random number and have a proper seed protection and generation scheme. Protection in such a way that there is no way to sneak peek into the variable and generation in such an arrangement that does not use time of the day or any repeated circunstance to be created.

I like the scheme where you track mouse position for a while and have some of the points captured or the values of the typed characters in the keyboard. Something that actually has a brownian nature and is not easily reproduced.
 

Status
Not open for further replies.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top