Categories:
.NET (357)
C (330)
C++ (183)
CSS (84)
DBA (2)
General (7)
HTML (4)
Java (574)
JavaScript (106)
JSP (66)
Oracle (114)
Perl (46)
Perl (1)
PHP (1)
PL/SQL (1)
RSS (51)
Software QA (13)
SQL Server (1)
Windows (1)
XHTML (173)
Other Resources:
Each time I run my program, I get the same sequence of numbers back from rand
Each time I run my program, I get the same sequence of numbers back from rand
✍: Guest
It's a characteristic of most pseudo-random number generators (and a defined property of the C library rand) that they always start with the same number and go through the same sequence. (Among other things, a bit of predictability can make debugging much easier.) When you don't want this predictability, you can call srand to seed the pseudo-random number generator with a truly random (or at least variable) initial value. Popular seed values are the time of day, or a process ID number, or the elapsed time before the user presses a key, or some combination of these. Here's an example call, using the time of day as a seed:
#include <stdlib.h>
#include <time.h>
srand((unsigned int)time((time_t *)NULL));
(There remain several difficulties: the time_t returned by time might be a floating-point type, hence not portably convertible to unsigned int without the possibility of overflow. Furthermore, if time of day is available with 1-second resolution, using it by itself means that successive runs of the program can easily get the same seed. Subsecond resolution, of time-of-day or keystroke presses, is hard to achieve portably;
Note also that it's rarely useful to call srand more than once during a run of a program; in particular, don't try calling srand before each call to rand, in an attempt to get ``really random'' numbers.
2015-07-29, 1184👍, 0💬
Popular Posts:
What are the five levels in CMMI? There are five levels of the CMM. According to the SEI, Level 1 – ...
How To Increment Dates by 1? - Oracle DBA FAQ - Understanding SQL Basics If you have a date, and you...
How To Set Background to Transparent or Non-transparent? - CSS Tutorials - HTML Formatting Model: Bl...
What Are Data Pump Export and Import Modes? - Oracle DBA FAQ - Loading and Exporting Data Data pump ...
What is CAR (Causal Analysis and Resolution)? The basic purpose of CAR is to analyze all defects, pr...