About Rand (), srand () generate Random number Learning Summary

Source: Internet
Author: User
Tags define function random seed

See Summer snow on the winter of Rand () and srand () produce random number of summary, very good, study, and then have Baidu other people's results, the system summarizes. This article turns from Summer snow winter: Http://www.cnblogs.com/heyonggang/archive/2012/12/12/2814271.html,Peng lv:http://www.cnblogs.com/ Lvpengms/archive/2010/02/03/1663066.html#commentform.

To generate a random number of computers like the dice, every step of the computer is to execute a bunch of code, which is arranged in advance, so the computer generated behavior is not random and predictive (of course, here is the current computer system, to the future of the computer system, unknown), So the random number generated by the computer is not a real random number, but a pseudo-random number, he takes a true value (also known as a seed) as the initial condition, and then uses a certain algorithm to iteratively generate random numbers.

In the library function, the system provides two functions for generating random numbers: Srand () and Rand ();

rand function:

Header Files <stdlib.h>

define function: int rand (void),

function function: Generate random number,

Function Description: Because Rand's interior is made of linear and congruential, not true random numbers, but because the period is so long that it can be considered random within a certain range, rand () returns a random value between 0 and Rand_max, before calling this function to produce a random number. The random number seed must be set with Srand (), and if no random number seed is set, rand () automatically sets the random number seed to 1 when called.

Return value: Returns the integer value between 0 and Rand_max, Rand_max in the range of at least 32767 (int), or double-byte (16-bit).  If the unsigned int double byte is 65535, and 0-rand_max each number is selected, the random rate is the same. Rand () produces false random numbers, which are the same each time they are executed, and to initialize with different values, the initialized function is Srand ().

srand function :

Header file <stdlib.h>,

Define function: void srand (unsigned int seed);

function declaration: Srand () is used to set the random number seed when rand () produces a random number, the parameter seed must be an integer, and the return value of time (0) can usually be used as seed. If each seed sets the same value, rand () generates random values every time.

Srand (unsigned) time (NULL) uses the system timer/counter value as a random seed for each seed corresponding to a set of pre-generated random numbers based on the algorithm, so in the same platform environment, the random number generated at different times is different, if the corresponding will be Srand ( unsigned) Tima (NULL) to any constant , the random number generated by the Srand is a pseudo-random number, regardless of when it is run and the number of times the resulting run is a specific set of sequences. However, the so-called "pseudo-random number" refers not to false random numbers, in fact, the absolute technology is only a hypothetical state of random numbers, the computer can only generate a relative random number, and these random numbers are both random and regular, part of a certain regularity, part of the non-compliance with any law, In summary, the computer generates pseudo-random numbers instead of absolute random numbers (Note: This content from: Baidu Encyclopedia-rand function)

Each time a random sequence is generated, a different seed is specified, so that the computed random sequence is not exactly the same, and calling Rand () with the same number of identical numbers causes the same sequence of random numbers to be generated.

Cases:

Generates a random number between 0 and 100:

#include <stdlib.h>   <stdio.h>   <time.h>   Main ()   {      int  i,k;   Srand ((unsigned) time (NULL));      for 0 i++ )   {      k=rand ()% +1;   // rand ()%100 represents a random number within 100, that is, after taking a random number and then taking the  remainder     to 100 " k=%d\n " , k);   } }

Since the random number generated by Rand is 0 to Rand_max, and Rand_max is a large number, a random number from X to Y can be generated as follows: S=rand ()% (x-y+1) +y, which represents a random number from the X to Y range

The system automatically calls Srand () after calling Rand (), and if the user calls Srand () before Rand () to specify a value for the parameter seed, rand () will use the value of seed as the initial value for generating a pseudo-random number if the user is in rand () Srand () is not called before, the system defaults to 1 as the initial value of the pseudo-random number, if given a fixed value, each time rand () produces a sequence of random numbers is the same, so in order to avoid this situation, usually with srand ((unsigned time (0)) or Srand (( unsigned) time (null) to produce a seed, and if you feel that the interval is too small, you can multiply it by one of the appropriate values (unsigned) (0) or (unsigned) times (null), such as Srand ((unsigned) times (NULL) *10).

In addition, you can use j= (int) (N*rand ()/rand_max+1) to produce integers between 0 and N:

#include <stdio.h>#include<time.h>#include<stdlib.h>intMainvoid){    inti,j;  for(i=0;i<Ten; i++) {J=1+(int)(Ten*rand ()/(rand_max+1)); printf ("%d", J); } printf ("\ n"); return 0; } 

Generate random Number:

questions about int x = rand ()% n and j= (int) (N*rand ()/(rand_max+1.0)):

j= (int) (N*rand ()/(rand_max+1.0)) is a random floating-point number that does not include n between 0 and N, and then cast to an integer between 0 and 9, which is different from x = rand () n, which is the result of multiple random occurrences, The former theory is more average, the latter just and N to obtain the results of the remainder, without the previous average.

Modulo operation% is to avoid in some cases, some pseudo-random number generator generated number, low enough random problem, here is related to the binary problem, because the modulo in the binary sense may represent to get low.

However, in response to their own needs, the random number can meet the required circumstances, int x = rand ()% n is completely possible to replace j= (int) (N*rand ()/(rand_max+1.0)), after all, the former is better time performance.

The RAND function is a true random number generator, and Srand () sets the seed for the random number used by Rand (). If Srand () is not called before the first call to Rand (), then the system will automatically call Srand () for you. The following programs:

#include <stdlib.h>   <stdio.h>   <time.h>   Main ()   {      int  i,k;        for 0 i++ )   {      k=rand ()% +1;   // rand ()%100 represents a random number within 100, that is, after taking a random number and then taking the  remainder     to 100 " k=%d\n " , k);   } }

can produce random numbers between 0 and 100.

In addition, srand this function to be placed outside the loop, or the outside of the loop call, otherwise the call is the same number. Look at the following example:

#include <time.h>#include<stdlib.h>#include<stdio.h>Main () {inti,j;  for(i=0;i<Ten; i++) {Srand (int) Time (0)); J=1+int(Rand () *100.0/(rand_max+1.0)); printf ("%d", J); }} 

At the end of execution, it will be found that all A[i] are the same, srand in the loop, each generated a random number before the call Srand, because the computer is running very fast, this code does not perform a total of 1s, and srand () return is in seconds, So each time to get the same timing, which is equivalent to using the same seed to produce a random sequence, so each generation of the same random number, so the occurrence of all A[i] is the same, should put srand outside the loop.

If the initial value (seed) of the pseudo-random number sequence is the same, then the computed pseudo-random sequence is identical, and the characteristic is decrypted by some software encryption, and the data is processed by a sequence of pseudo-random numbers produced by a certain seed. When decrypted, the seed number is used to produce a pseudo-random sequence to restore the encrypted data. (See: http://www.cnblogs.com/heyonggang/archive/2012/12/12/2814271.html)

About Rand (), Srand () generates a random number learning summary

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.