Random Number C++ in Some Range

Random number c++ in some range

You can use the random functionality included within the additions to the standard library (TR1). Or you can use the same old technique that works in plain C:

25 + ( std::rand() % ( 63 - 25 + 1 ) )

How to generate a random number within a range once in C?

The code for random number generation is inside the loop that runs 31 times.

for (c = 0; c<=30; c++)   //c = 0 to 31 -> runs 31 times
{
myVar = rand() % n + 1;
printf("%d\n", myVar);
}

If you want the random number to be generated only once, remove the for loop.

How to generate a random integer number from within a range

All the answers so far are mathematically wrong. Returning rand() % N does not uniformly give a number in the range [0, N) unless N divides the length of the interval into which rand() returns (i.e. is a power of 2). Furthermore, one has no idea whether the moduli of rand() are independent: it's possible that they go 0, 1, 2, ..., which is uniform but not very random. The only assumption it seems reasonable to make is that rand() puts out a Poisson distribution: any two nonoverlapping subintervals of the same size are equally likely and independent. For a finite set of values, this implies a uniform distribution and also ensures that the values of rand() are nicely scattered.

This means that the only correct way of changing the range of rand() is to divide it into boxes; for example, if RAND_MAX == 11 and you want a range of 1..6, you should assign {0,1} to 1, {2,3} to 2, and so on. These are disjoint, equally-sized intervals and thus are uniformly and independently distributed.

The suggestion to use floating-point division is mathematically plausible but suffers from rounding issues in principle. Perhaps double is high-enough precision to make it work; perhaps not. I don't know and I don't want to have to figure it out; in any case, the answer is system-dependent.

The correct way is to use integer arithmetic. That is, you want something like the following:

#include <stdlib.h> // For random(), RAND_MAX

// Assumes 0 <= max <= RAND_MAX
// Returns in the closed interval [0, max]
long random_at_most(long max) {
unsigned long
// max <= RAND_MAX < ULONG_MAX, so this is okay.
num_bins = (unsigned long) max + 1,
num_rand = (unsigned long) RAND_MAX + 1,
bin_size = num_rand / num_bins,
defect = num_rand % num_bins;

long x;
do {
x = random();
}
// This is carefully written not to overflow
while (num_rand - defect <= (unsigned long)x);

// Truncated division is intentional
return x/bin_size;
}

The loop is necessary to get a perfectly uniform distribution. For example, if you are given random numbers from 0 to 2 and you want only ones from 0 to 1, you just keep pulling until you don't get a 2; it's not hard to check that this gives 0 or 1 with equal probability. This method is also described in the link that nos gave in their answer, though coded differently. I'm using random() rather than rand() as it has a better distribution (as noted by the man page for rand()).

If you want to get random values outside the default range [0, RAND_MAX], then you have to do something tricky. Perhaps the most expedient is to define a function random_extended() that pulls n bits (using random_at_most()) and returns in [0, 2**n), and then apply random_at_most() with random_extended() in place of random() (and 2**n - 1 in place of RAND_MAX) to pull a random value less than 2**n, assuming you have a numerical type that can hold such a value. Finally, of course, you can get values in [min, max] using min + random_at_most(max - min), including negative values.

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 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 type int in the range 0 to RAND_MAX inclusively. RAND_MAX is a constant also defined in <stdlib.h> whose value is at least 32767.

  • rand() % 2001 computes the remainder of the division by 2001. Since rand() is positive, the result is a pseudo random number in the range 0 to 2000 inclusive, with a small bias caused by 2001 not dividing RAND_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 and 1000 inclusively.

  • to evaluate (rand() % 2001 - 1000) / 2.e3, the value obtained from the previous steps is converted to type double and divided by 2.e3, which would be more readable as 2000.0. Hence the result is a floating point value of type double with 2001 possible distinct values between -0.5 and 0.5 inclusively.

  • a = (rand() % 2001 - 1000) / 2.e3; converts this double value to float, the type of a. The float value will be implicitly converted back to type double when passed to printf, this conversion does not produce exactly the same number in many cases.

  • note that there is no reason to define a as a static 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;
}

Generate a random number within range?

This is actually a bit harder to get really correct than most people realize:

int rand_lim(int limit) {
/* return a random number between 0 and limit inclusive.
*/

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

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

return retval;
}

Attempts that just use % (or, equivalently, /) to get the numbers in a range almost inevitably introduce skew (i.e., some numbers will be generated more often than others).

As to why using % produces skewed results: unless the range you want is a divisor of RAND_MAX, skew is inevitable. If you start with small numbers, it's pretty easy to see why. Consider taking 10 pieces of candy (that we'll assume you can't cut, break, etc. into smaller pieces) and trying to divide it evenly between three children. Clearly it can't be done--if you hand out all the candy, the closest you can get is for two kids to get three pieces of candy, and one of them getting four.

There's only one way for all the kids to get the same number of pieces of candy: make sure you don't hand out the last piece of candy at all.

To relate this to the code above, let's start by numbering the candies from 1 to 10 and the kids from 1 to 3. The initial division says since there are three kids, our divisor is three. We then pull a random candy from the bucket, look at its number and divide by three and hand it to that kid -- but if the result is greater than 3 (i.e. we've picked out candy number 10) we just don't hand it out at all -- we discard it and pick out another candy.

Of course, if you're using a modern implementation of C++ (i.e., one that supports C++11 or newer), you should usually use one the distribution classes from the standard library. The code above corresponds most closely with std::uniform_int_distribution, but the standard library also includes uniform_real_distribution as well as classes for a number of non-uniform distributions (Bernoulli, Poisson, normal, maybe a couple others I don't remember at the moment).

C: filling an array with random numbers in a range

As mentioned in comments , if you want number in range 1 to 10 :

array0[i]= rand()%10 + 1;

I suggest int array1[10]={0}; instead of this loop:

for(int i = 0 ; i < 10 ; i++)
{
array1[i]= 0;
}

and here is complete code with printing:

int main()
{
int n;
printf("How many elements in array?:");
scanf("%d",&n);
int array0[n];
for(int i = 0 ; i < n ; i++)
{
array0[i]= rand()%10 + 1;//for your range
}

int array1[10]={0};

/*for(int i = 0 ; i < 10 ; i++)
{
array1[i]= 0;
}*/
int index;
for(int i = 0 ; i < n ; i++)
{
index = array0[i];
array1[index-1]++;
}
for (int i = 0; i < 10; i++)
{
printf("number %d appears:%d\n", i + 1, array1[i]);
}
}

also as @Ardent Coder said add srand(time(NULL)); bfeore rand() to generate different random numbers at different runtimes.



Related Topics



Leave a reply



Submit