当前位置:网站首页>Does C language srand need to reseed? Should srand be placed in the loop? Pseudo random function Rand
Does C language srand need to reseed? Should srand be placed in the loop? Pseudo random function Rand
2022-07-02 12:36:00 【My first wife】
List of articles
First contact rand() function
I learned three sorting algorithms before :1. Selection sort ;2. Bubble sort ; 3. Insertion sort ; Use three algorithms to sort the elements in the array . When initializing an array at first, you use 0 ~ n Ascending assignment , Then sort it in descending order into n ~ 0, Later I felt almost interesting , In order to reflect “ Authenticity ”, Decide to use rand()
Assign values to arrays .
At this time, I don't know rand()
It's pseudorandom , Only know that it can “ Random ” Count , Later, I gradually learned rand()
You need to initialize the seed before calling srand(seed)
( Even if not initialized , The system will also default seeds seed by 1 ), And the seed function srand()
Actually, there are many “ Random number sequence ” A collection of , So be a seed seed When it's certain , Every time the program starts , call rand()
Returned “ Random number sequence ” It's also certain .
Under the same seed rand() The sequence of random numbers returned
For example, write a program randTest :
#include <stdio.h>
#include <stdlib.h>
int main()
{
short i;
srand(1);
for(i=0; i<1000; i++)
printf("%d, ", rand());
return 0;
}
Every compilation 、 Run the program , The results are the same . Although the computer restarts 、 To turn it off , Will not change the seeds seed by 1 Of rand()
Output result of :
41, 18467, 6334, 26500, 19169, 15724, 11478, 29358, 26962, 24464, 5705, 28145, 23281, 16827, 9961, 491, 2995, 11942, 4827, 5436, 32391, 14604, 3902, 153, 292, 12382, 17421, 18716, 19718, 19895, 5447, 21726, 14771, 11538, 1869, 19912, 25667, 26299, 17035, 9894, 28703, 23811, 31322, 30333, 17673, 4664, 15141, 7711, 28253, 6868, 25547, 27644, 32662, 32757, 20037, 12859, 8723, 9741, 27529, 778, 12316, 3035, 22190, 1842, 288, 30106, 9040, 8942, 19264, 22648, 27446, 23805, 15890, 6729, 24370, 15350, 15006, 31101, 24393, 3548, 19629, 12623, 24084, 19954, 18756, 11840, 4966, 7376, 13931, 26308, 16944, 32439, 24626, 11323, 5537, 21538, 16118, 2082, 22929, 16541, 4833, 31115, 4639, 29658, 22704, 9930, 13977, 2306, 31673, 22386, 5021, 28745, 26924, 19072, 6270, 5829, 26777, 15573, 5097, 16512, 23986, 13290, 9161, 18636, 22355, 24767, 23655, 15574, 4031, 12052, 27350, 1150, 16941, 21724, 13966, 3430, 31107, 30191, 18007, 11337, 15457, 12287, 27753, 10383, 14945, 8909, 32209, 9758, 24221, 18588, 6422, 24946, 27506, 13030, 16413, 29168, 900, 32591, 18762, 1655, 17410, 6359, 27624, 20537, 21548, 6483, 27595, 4041, 3602, 24350, 10291, 30836, 9374, 11020, 4596, 24021, 27348, 23199, 19668, 24484, 8281, 4734, 53, 1999, 26418, 27938, 6900, 3788, 18127, 467, 3728, 14893, 24648, 22483, 17807, 2421, 14310, 6617, 22813, 9514, 14309, 7616, 18935, 17451, 20600, 5249, 16519, 31556, 22798, 30303, 6224, 11008, 5844, 32609, 14989, 32702, 3195, 20485, 3093, 14343, 30523, 1587, 29314, 9503, 7448, 25200, 13458, 6618, 20580, 19796, 14798, 15281, 19589, 20798, 28009, 27157, 20472, 23622, 18538, 12292, 6038, 24179, 18190, 29657, 7958, 6191, 19815, 22888, 19156, 11511, 16202, 2634, 24272, 20055, 20328, 22646, 26362, 4886, 18875, 28433, 29869, 20142, 23844, 1416, 21881, 31998, 10322, 18651, 10021, 5699, 3557, 28476, 27892, 24389, 5075, 10712, 2600, 2510, 21003, 26869, 17861, 14688, 13401, 9789, 15255, 16423, 5002, 10585, 24182, 10285, 27088, 31426, 28617, 23757, 9832, 30932, 4169, 2154, 25721, 17189, 19976, 31329, 2368, 28692, 21425, 10555, 3434, 16549, 7441, 9512, 30145, 18060, 21718, 3753, 16139, 12423, 16279, 25996, 16687, 12529, 22549, 17437, 19866, 12949, 193, 23195, 3297, 20416, 28286, 16105, 24488, 16282, 12455, 25734, 18114, 11701, 31316, 20671, 5786, 12263, 4313, 24355, 31185, 20053, 912, 10808, 1832, 20945, 4313, 27756, 28321, 19558, 23646, 27982, 481, 4144, 23196, 20222, 7129, 2161, 5535, 20450, 11173, 10466, 12044, 21659, 26292, 26439, 17253, 20024, 26154, 29510, 4745, 20649, 13186, 8313, 4474, 28022, 2168, 14018, 18787, 9905, 17958, 7391, 10202, 3625, 26477, 4414, 9314, 25824, 29334, 25874, 24372, 20159, 11833, 28070, 7487, 28297, 7518, 8177, 17773, 32270, 1763, 2668, 17192, 13985, 3102, 8480, 29213, 7627, 4802, 4099, 30527, 2625, 1543, 1924, 11023, 29972, 13061, 14181, 31003, 27432, 17505, 27593, 22725, 13031, 8492, 142, 17222, 31286, 13064, 7900, 19187, 8360, 22413, 30974, 14270, 29170, 235, 30833, 19711, 25760, 18896, 4667, 7285, 12550, 140, 13694, 2695, 21624, 28019, 2125, 26576, 21694, 22658, 26302, 17371, 22466, 4678, 22593, 23851, 25484, 1018, 28464, 21119, 23152, 2800, 18087, 31060, 1926, 9010, 4757, 32170, 20315, 9576, 30227, 12043, 22758, 7164, 5109, 7882, 17086, 29565, 3487, 29577, 14474, 2625, 25627, 5629, 31928, 25423, 28520, 6902, 14962, 123, 24596, 3737, 13261, 10195, 32525, 1264, 8260, 6202, 8116, 5030, 20326, 29011, 30771, 6411, 25547, 21153, 21520, 29790, 14924, 30188, 21763, 4940, 20851, 18662, 13829, 30900, 17713, 18958, 17578, 8365, 13007, 11477, 1200, 26058, 6439, 2303, 12760, 19357, 2324, 6477, 5108, 21113, 14887, 19801, 22850, 14460, 22428, 12993, 27384, 19405, 6540, 31111, 28704, 12835, 32356, 6072, 29350, 18823, 14485, 20556, 23216, 1626, 9357, 8526, 13357, 29337, 23271, 23869, 29361, 12896, 13022, 29617, 10112, 12717, 18696, 11585, 24041, 24423, 24129, 24229, 4565, 6559, 8932, 22296, 29855, 12053, 16962, 3584, 29734, 6654, 16972, 21457, 14369, 22532, 2963, 2607, 2483, 911, 11635, 10067, 22848, 4675, 12938, 2223, 22142, 23754, 6511, 22741, 20175, 21459, 17825, 3221, 17870, 1626, 31934, 15205, 31783, 23850, 17398, 22279, 22701, 12193, 12734, 1637, 26534, 5556, 1993, 10176, 25705, 6962, 10548, 15881, 300, 14413, 16641, 19855, 24855, 13142, 11462, 27611, 30877, 20424, 32678, 1752, 18443, 28296, 12673, 10040, 9313, 875, 20072, 12818, 610, 1017, 14932, 28112, 30695, 13169, 23831, 20040, 26488, 28685, 19090, 19497, 2589, 25990, 15145, 19353, 19314, 18651, 26740, 22044, 11258, 335, 8759, 11192, 7605, 25264, 12181, 28503, 3829, 23775, 20608, 29292, 5997, 17549, 29556, 25561, 31627, 6467, 29541, 26129, 31240, 27813, 29174, 20601, 6077, 20215, 8683, 8213, 23992, 25824, 5601, 23392, 15759, 2670, 26428, 28027, 4084, 10075, 18786, 15498, 24970, 6287, 23847, 32604, 503, 21221, 22663, 5706, 2363, 9010, 22171, 27489, 18240, 12164, 25542, 7619, 20913, 7591, 6704, 31818, 9232, 750, 25205, 4975, 1539, 303, 11422, 21098, 11247, 13584, 13648, 2971, 17864, 22913, 11075, 21545, 28712, 17546, 18678, 1769, 15262, 8519, 13985, 28289, 15944, 2865, 18540, 23245, 25508, 28318, 27870, 9601, 28323, 21132, 24472, 27152, 25087, 28570, 29763, 29901, 17103, 14423, 3527, 11600, 26969, 14015, 5565, 28, 21543, 25347, 2088, 2943, 12637, 22409, 26463, 5049, 4681, 1588, 11342, 608, 32060, 21221, 1758, 29954, 20888, 14146, 690, 7949, 12843, 21430, 25620, 748, 27067, 4536, 20783, 18035, 32226, 15185, 7038, 9853, 25629, 11224, 15748, 19923, 3359, 32257, 24766, 4944, 14955, 23318, 32726, 25411, 21025, 20355, 31001, 22549, 9496, 18584, 9515, 17964, 23342, 8075, 17913, 16142, 31196, 21948, 25072, 20426, 14606, 26173, 24429, 32404, 6705, 20626, 29812, 19375, 30093, 16565, 16036, 14736, 29141, 30814, 5994, 8256, 6652, 23936, 30838, 20482, 1355, 21015, 1131, 18230, 17841, 14625, 2011, 32637, 4186, 19690, 1650, 5662, 21634, 10893, 10353, 21416, 13452, 14008, 7262, 22233, 5454, 16303, 16634, 26303, 14256, 148, 11124, 12317, 4213, 27109, 24028, 29200, 21080, 21318, 16858, 24050, 24155, 31361, 15264, 11903, 3676, 29643, 26909, 14902, 3561, 28489, 24948, 1282, 13653, 30674, 2220, 5402, 6923, 3831, 19369, 3878, 20259, 19008, 22619, 23971, 30003, 21945, 9781, 26504, 12392, 32685, 25313, 6698, 5589, 12722, 5938, 19037, 6410, 31461, 6234, 12508, 9961, 3959, 6493, 1515, 25269, 24937, 28869, 58, 14700, 13971, 26264, 15117, 16215, 24555, 7815, 18330, 3039, 30212, 29288, 28082, 1954, 16085, 20710, 24484, 24774, 8380, 29815, 25951, 6541, 18115, 1679, 17110, 25898, 23073, 788, 23977, 18132, 29956, 28689, 26113, 10008, 12941, 15790, 1723, 21363, 28, 25184, 24778, 7200, 5071, 1885, 21974, 1071, 11333, 22867, 26153, 14295, 32168, 20825, 9676, 15629, 28650, 2598, 3309, 4693, 4686, 30080, 10116, 12249
Replant , Make the random number generated by each compilation run of the program different
Because when the seed is determined , rand()
Back to “ Random number sequence ” Also the same , That's why we need to be in rand()
Reseed before , That is to say srand(time(NULL))
.
time() function
time()
The function is contained in the header file time.h in , You need to import this header file before calling : #include <time.h>
.
time()
The prototype of a function is : time_t time(time_t *seconds)
,time_t Its size is long Size ( namely 8 byte ), You can initialize a time_t Data type variables sec , Store the current time , Such as :time_t sec=time(NULL);
time(seconds)
Return from 1970-01-01 00:00:00 Play a parameter seconds Time passed , In seconds , The return value is long type , Parameters seconds The data type of is also long type .
time()
Function is generally used to find 1970-01-01 00:00:00 Up to now ( When parameters seconds by 0 or ‘NULL’ when ).
time() example
1. return 1970-01-01 00:00:00 Up to now (2022-02-11 16:49:20) Days of 、 Hours 、 Minutes 、 Number of seconds :
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
time_t sec; // Or you could write it as long sec;
sec=time(NULL);
printf("1970-01-01 00:00:00 Up to now %ld God ; common %ld Hours ; common %ld minute ; common %ld second ", sec/86400, sec/3600, sec/60, sec));
return 0;
}
Output results :
1970-01-01 00:00:00 Up to now 19034 God ; common 456824 Hours ; common 27409489 minute ; common 1644569360 second
Process returned 0 (0x0) execution time : 0.011 s
Press any key to continue.
2. utilize void Sleep(DWORD dwMilliseconds)
function , Output every second time(NULL) , Sleep Function contained in windows.h Header file , Parameters are in milliseconds , Parameter type is DWORD (double word, Size two bytes , amount to short Size ):
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
int main()
{
printf("%ld\n", time(NULL));
Sleep(1000);
printf("%ld\n", time(NULL));
Sleep(1000);
printf("%ld\n", time(NULL));
return 0;
}
Output results :
1644572287
1644572288
1644572289
Process returned 0 (0x0) execution time : 2.043 s
Press any key to continue.
srand(time(NULL))
So much bedding , Finally, the protagonist srand(time(NULL))
, Through the previous knowledge, we know time(NULL)
It will change over time , As long as the program does not run twice in the same second , Then the seeds will not be the same . The seeds are different , The resulting random number sequence will not be the same , There will be no first program randTest The same situation .
Put the program randTest Minor modifications , Add header file #include <time.h>
and #include <windows.h>
, Change the seed into time(NULL)
, Check whether the two random number sequences are the same :
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
int main()
{
short i;
/* First seeded rand Sequence */
srand(time(NULL));
for(i=0; i<1000; i++)
printf("%d, ", rand());
/* It is sown again after dormancy for a second rand Sequence */
printf("\n\n The random number of the second sowing :\n");
Sleep(1000);
srand(time(NULL));
for(i=0; i<1000; i++)
printf("%d, ", rand());
return 0;
}
From the output results, we can see that twice srand The random number sequences produced are different :
Don't be careful srand(time(NULL)) Write in for In circulation
After learning 、 Practice and think , elementary analysis rand and srand
Just know srand Corresponding to a sequence of random numbers , But because of knowing 、 The depth of thinking is not enough , Mistakenly think that only every time rand Different seeds , To do it “ Really random ”.
in fact ,rand It is a pseudo-random number generator , It can return “ random number ” The value is between 0 To RAND_MAX ( By looking at stdlib.h Source code discovery ,RAND_MAX Is defined as 0x7fff ) Between , And the seed function srand Inside “ Random number sequence ” According to the seed seed From formula calculus ,“ Random number sequence ” Looks like “ disorder ” Of , But it conforms to certain rules ( Because it is seed Through formula calculus ).
stdlib.h Source code ( Any project main Right click the function #include <stdlib.h>, Click on Open #include file: ‘stdlib.h’, open D:\CodeBlocks\MinGW\x86_64-w64-mingw32\include\stdlib.h):
Just because I know srand It's based on seed Calculated “ Random number sequence ”, Know the same seed rand It can be calculated ( Although it may not be predicted by the human brain ), Just think about every call rand()
Call different seeds , The following is a demonstration of mistakes :
int a[100]={
};
char n=100;
char i;
for(i=0; i<n; i++)
{
srand(time(NULL));
a[i]=rand();
}
Output results :
21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765 21765
Process returned 0 (0x0) execution time : 0.039 s
Press any key to continue.
Parse error
In my opinion now , There are two mistakes in the above code ;
1. time()
Functions should not be placed in loops .
2. srand()
Functions may not be placed in loops , Although the starting point is to get more “ Random ” The sequence of assigns values to the array .
For questions 1, As can be seen from the output , The whole program only uses 0.039s It's over , Visible cycle 100 It can't be used once 1 second , Even a thousand times 、 Tenthousand times won't be long ( The running speed is also related to the hardware ), and time()
The precision of the function is 1s , For those who want to change seeds in each cycle , You should use Sleep(1000)
, In every time rand()
Hang up after 1s Only then can we start the next sowing ; Or use millisecond precision GetTickCount()
Time function 、 And microsecond accuracy QueryPerformanceFrequency()
Time function , Instead of time(NULL)
.
For questions 2,srand Whether it is not suitable to put in the cycle , From questions 1 set out , Think further , Even if you use Sleep()
function 、 Even if a more accurate time function is used , If the cycle reaches 100000 、 One million , There is still waste in every seeding step 0.01s, Then a cycle of 100000 will be wasted here 1000s, It's too scary .
Return to heart ,srand Why put it in the loop , It's because I think rand Not enough “ Random ”, I have to use more “ Random 、 disorder ” The way to make rand The number produced is more “ Random ”, that , Even without considering the waste of time , I put rand Is it more random to put it in the loop ? Replace seeds and re rand Is it more random ?
Test ideas : First step : Check the continuous seeds rand Whether the same number will appear in the same position , Even if rand It's pseudorandom , It can also be enough “ Random ”. obtain time(NULL)
The value of is assigned to long Type variable sec0, Record the seed as sec0、sec1=sec0+1、sec2=sec0+2、sec3=sec0+3 Of rand value , Assign values of length 1000 Of int Type of the array a、b、c、d, Contrast one by one a、b、c、d Are the elements the same .
The second step : Test on four seeds sec0、sec1、sec2、sec3 Under the change of order ,rand The values appear in sequence a、b、c、d The first i Item value , Or every time I refresh the seed, I will start from 0 Item start fetching , It won't be like what I originally thought “ More random number ”. There are... In the loop 4 Seeding function , The seeds are sec0、sec1、sec2、sec3, Print rand 1000 Results of , Compare... In Notepad a、b、c、d Value .
Step one code :
1. First get sec0 to sec3 Value :
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
time_t sec0, sec1, sec2, sec3;
sec0=time(NULL);
sec1=sec0+1;
sec2=sec0+2;
sec3=sec0+3;
printf("sec0:%ld\nsec1:%ld\nsec2:%ld\nsec3:%ld\n\n",sec0, sec1, sec2, sec3); // Print seeds sec0、sec1、sec2、sec3 Value
return 0;
}
Output results :
sec0:1644594655
sec1:1644594656
sec2:1644594657
sec3:1644594658
Process returned 0 (0x0) execution time : 0.030s
Press any key to continue.
2. Manually assign the value just obtained to sec0 to sec3, Then start the array assignment 、 Compare whether there is repetition :
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int a[1000]={
};
int b[1000]={
};
int c[1000]={
};
int d[1000]={
};
time_t sec0, sec1, sec2, sec3;
short i;
sec0=1644594655;
sec1=1644594656;
sec2=1644594657;
sec3=1644594658;
/* Array a To d assignment */
srand(sec0);
for(i=0; i<1000; i++)
a[i]=rand();
srand(sec1);
for(i=0; i<1000; i++)
b[i]=rand();
srand(sec2);
for(i=0; i<1000; i++)
c[i]=rand();
srand(sec3);
for(i=0; i<1000; i++)
d[i]=rand();
/* Print a、b、c、d */
for(i=0; i<1000; i++)
printf("%-6d%-6d%-6d%-6d\n", a[i], b[i], c[i], d[i]);
/* Compare whether there is repetition */
for(i=0; i<1000; i++)
if(a[i]==b[i] || a[i]==c[i] || a[i]==d[i] || b[i]==c[i] || b[i]==d[i] || c[i]==d[i])
printf(" In subscript %d There are similarities \n", i);
return 0;
}
Output results :( Partial screenshots )
beginning :
The ending part :
It can be seen from the comparison results , Continuous seeds ,rand There is no duplicate number under the same subscript , explain rand In a certain range, it can be regarded as “ random number ”.
Step 2 code :
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
time_t sec0, sec1, sec2, sec3;
short i;
sec0=1644594655;
sec1=1644594656;
sec2=1644594657;
sec3=1644594658;
for(i=0; i<1000; i++)
{
srand(sec0);
printf("%-6d", rand());
srand(sec1);
printf("%-6d", rand());
srand(sec2);
printf("%-6d", rand());
srand(sec3);
printf("%-6d", rand());
printf("\n");
}
return 0;
}
Output results : The results are very obvious , This is simply a random number of failures
Another kind “ Random ”rand guess :
There is also a guess that the seeds are constantly changing :srand(rand() + i + rand())
, Even if rand Is to take srand The first number , As long as the seeds keep changing ,rand When you arrive, you won't repeat , Can it also be regarded as “ random number ”? In fact, I think it's a little like “ The ostrich Deceive oneself and others ”, Obviously, your seed is different from that of the last program run , You can get a bunch of programmers designed almost random 、 Disordered sequence , You only need to rand Just take out the numbers in the sequence , Every time “ Random ” seeds ,rand The result will be more “ Random ”? Don't forget rand Before You have to initialize srand, For the first time srand(rand() + i + rand())
Must be equivalent to srand(41 + i + 41)
Summary
The above is the latest use srand and rand Problems found in the process , I don't know if it's complete , It was found in the process that srandom and srandom Seem to be more than srand and rand To use , Continue to work hard !!!
边栏推荐
- Deep understanding of P-R curve, ROC and AUC
- Simple use of drools decision table
- Day12 control flow if switch while do While guessing numbers game
- drools执行String规则或执行某个规则文件
- Writing method of then part in drools
- CV2 in OpenCV VideoWriter_ Fourcc() function and cv2 Combined use of videowriter() function
- Adding database driver to sqoop of cdh6
- 中国交通标志检测数据集
- Input box assembly of the shutter package
- Find the common ancestor of any two numbers in a binary tree
猜你喜欢
Heap (priority queue)
Go学习笔记—多线程
刷题---二叉树--2
The blink code based on Arduino and esp8266 runs successfully (including error analysis)
Lekao: 22 year first-class fire engineer "technical practice" knowledge points
(C language) input a line of characters and count the number of English letters, spaces, numbers and other characters.
2.7 binary tree, post order traversal - [FBI tree]
Adding database driver to sqoop of cdh6
分布式机器学习框架与高维实时推荐系统
[ybtoj advanced training guidance] cross the river [BFS]
随机推荐
Leetcode - Sword finger offer 51 Reverse pairs in an array
Lekao.com: experience sharing of junior economists and previous candidates in customs clearance
[old horse of industrial control] detailed explanation of Siemens PLC TCP protocol
CDA数据分析——AARRR增长模型的介绍、使用
(C language) input a line of characters and count the number of English letters, spaces, numbers and other characters.
PR 2021 quick start tutorial, learn about the and functions of the timeline panel
post请求体内容无法重复获取
BOM DOM
What is the relationship between NFT and metauniverse? How to view the market? The future market trend of NFT
BOM DOM
怎样写一篇赏心悦目的英文数学论文
drools中then部分的写法
js 迭代器 生成器 异步代码处理 promise+生成器 -> await/async
Why do programmers have the idea that code can run without moving? Is it poisonous? Or what?
Those logs in MySQL
CDA data analysis -- Introduction and use of aarrr growth model
Programmers can't find jobs after the age of 35? After reading this article, you may be able to find the answer
Gaode map test case
FBX import under ue4/ue5 runtime
Leetcode739 daily temperature