How to generate a random int in C?
Note: Don't use
rand()
for security. If you need a cryptographically secure number, see this answer instead.
#include <time.h>
#include <stdlib.h>
srand(time(NULL)); // Initialization, should only be called once.
int r = rand(); // Returns a pseudo-random integer between 0 and RAND_MAX.
On Linux, you might prefer to use random and srandom.
generate a random number between 1 and 10 in c
You need a different seed at every execution.
You can start to call at the beginning of your program:
srand(time(NULL));
Note that % 10
yields a result from 0
to 9
and not from 1
to 10
: just add 1
to your %
expression to get 1
to 10
.
Generate Random Number Using C
As per details in link What is time(NULL) in C?
You can pass in a pointer to a time_t object that time will fill up with the current time (and the return value is the same one that you pointed to). If you pass in NULL, it just ignores it and merely returns a new time_t object that represents the current time.
time(NULL)
simply returns the current time details.
srand()
is used for generating a random number.
srand(time(NULL))
just creates a random number, using the current time details as input.
Generate random numbers with rand() except number zero
Very simple
int r = 1 + rand() % 25 /* random int between 1 and 25 */
but you should use this
int r = (int)(1.0 + 25.0 * rand() / RAND_MAX)
as mentioned in the comments, the second is the more robust way to generate random numbers see this link
Generating random numbers in C
You should call srand() before calling rand to initialize the random number generator.
Either call it with a specific seed, and you will always get the same pseudo-random sequence
#include <stdlib.h>
int main ()
{
srand ( 123 );
int random_number = rand();
return 0;
}
or call it with a changing sources, ie the time function
#include <stdlib.h>
#include <time.h>
int main ()
{
srand ( time(NULL) );
int random_number = rand();
return 0;
}
In response to Moon's Comment
rand() generates a random number with an equal probability between 0 and RAND_MAX (a macro pre-defined in stdlib.h)
You can then map this value to a smaller range, e.g.
int random_value = rand(); //between 0 and RAND_MAX
//you can mod the result
int N = 33;
int rand_capped = random_value % N; //between 0 and 32
int S = 50;
int rand_range = rand_capped + S; //between 50 and 82
//you can convert it to a float
float unit_random = random_value / (float) RAND_MAX; //between 0 and 1 (floating point)
This might be sufficient for most uses, but its worth pointing out that in the first case using the mod operator introduces a slight bias if N does not divide evenly into RAND_MAX+1.
Random number generators are interesting and complex, it is widely said that the rand() generator in the C standard library is not a great quality random number generator, read (http://en.wikipedia.org/wiki/Random_number_generation for a definition of quality).
http://en.wikipedia.org/wiki/Mersenne_twister (source http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html ) is a popular high quality random number generator.
Also, I am not aware of arc4rand() or random() so I cannot comment.
Generate a random number between range (-0.5 , 0.5) in C
Let's analyze the expression (rand() % 2001 - 1000) / 2.e3
:
the
rand()
function defined in<stdlib.h>
returns a pseudo random integer of typeint
in the range0
toRAND_MAX
inclusively.RAND_MAX
is a constant also defined in<stdlib.h>
whose value is at least32767
.rand() % 2001
computes the remainder of the division by2001
. Sincerand()
is positive, the result is a pseudo random number in the range0
to2000
inclusive, with a small bias caused by2001
not dividingRAND_MAX
evenly.rand() % 2001 - 1000
is evaluated as(rand() % 2001) - 1000
, the range of the result is shifted by 1000 toward the negatives, namely between-1000
and1000
inclusively.to evaluate
(rand() % 2001 - 1000) / 2.e3
, the value obtained from the previous steps is converted to typedouble
and divided by2.e3
, which would be more readable as2000.0
. Hence the result is a floating point value of typedouble
with 2001 possible distinct values between-0.5
and0.5
inclusively.a = (rand() % 2001 - 1000) / 2.e3;
converts thisdouble
value tofloat
, the type ofa
. Thefloat
value will be implicitly converted back to typedouble
when passed toprintf
, this conversion does not produce exactly the same number in many cases.note that there is no reason to define
a
as astatic
variable.
Here is an alternative implementation that produces more distinct values in the same inclusive range with a slightly less biased distribution:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL));
for (int i = 0; i < 20; ++i) {
double a = rand() / (double)RAND_MAX - 0.5;
printf("%f ", a);
}
printf("%\n");
return 0;
}
How do I generate random numbers without rand() function?
If you're after an ultra-simple pseudo-random generator, you can just use a Linear Feedback shift Register.
The wikipedia article has some code snippets for you to look at, but basically the code for a 16-bit generator will look something like this (lightly massaged from that page...)
unsigned short lfsr = 0xACE1u;
unsigned bit;
unsigned rand()
{
bit = ((lfsr >> 0) ^ (lfsr >> 2) ^ (lfsr >> 3) ^ (lfsr >> 5) ) & 1;
return lfsr = (lfsr >> 1) | (bit << 15);
}
Related Topics
Serializing Opencv Mat_<Vec3F>
Where in Qt Creator Do I Pass Arguments to a Compiler
Assembly Adc (Add with Carry) to C++
How to Create a Temporary Directory in C++
How to Include Compiler Flags in Visual Studio Code
How to Use Dynamic Name for Variables in C++
2D Diamond (Isometric) Map Editor - Textures Extended Infinitely
Is There an Online Name Demangler for C++
Address-Of Operator (&) VS Reference Operator(&)
C++ - <Unresolved Overloaded Function Type>
Why Does a Push_Back on an Std::List Change a Reverse Iterator Initialized with Rbegin
Is There a Limit of Stack Size of a Process in Linux
How to Extract the Mantissa of a Double
Base Pointer to Array of Derived Objects
Overload Operators as Member Function or Non-Member (Friend) Function