Categories:
.NET (961)
C (387)
C++ (185)
CSS (84)
DBA (8)
General (31)
HTML (48)
Java (641)
JavaScript (220)
JSP (109)
JUnit (31)
MySQL (297)
Networking (10)
Oracle (562)
Perl (48)
Perl (9)
PHP (259)
PL/SQL (140)
RSS (51)
Software QA (28)
SQL Server (5)
Struts (20)
Unix (2)
Windows (3)
XHTML (199)
XML (59)
Other Resources:
I need a random number generator.
I need a random number generator.
✍: Guest
The Standard C library has one: rand. The implementation on your system may not be perfect, but writing a better one isn't necessarily easy, either.
Here is a portable C implementation of the ``minimal standard'' generator :
#define a 16807
#define m 2147483647
#define q (m / a)
#define r (m % a)
static long int seed = 1;
long int PMrand()
{
long int hi = seed / q;
long int lo = seed % q;
long int test = a * lo - r * hi;
if(test > 0)
seed = test;
else seed = test + m;
return seed;
}
(The ``minimal standard'' is adequately good; it is something ``against which all others should be judged''; it is recommended for use ``unless one has access to a random number generator known to be better.'')
This code implements the generator
X <- (aX + c) mod m
for a = 16807, m = 2147483647 (which is 2**31-1), and c = 0. The multiplication is carried out using a technique described by Schrage, ensuring that the intermediate result aX does not overflow. The implementation above returns long int values in the range [1, 2147483646]; that is, it corresponds to C's rand with a RAND_MAX of 2147483646, except that it never returns 0. To alter it to return floating-point numbers in the range (0, 1), change the declaration to
double PMrand()
and the last line to
return (double)seed / m;
For slightly better statistical properties, now recommend using a = 48271.
2015-08-03, 1370👍, 0💬
Popular Posts:
What is triple constraint triangle in project management ? Project Management triangle is depicted a...
Which one of the following statements is TRUE in regard to overloading the ++ operator? 1 You cannot...
How To Process Query Result in PL/SQL? - Oracle DBA FAQ - Introduction to PL/SQL You can run queries...
How To Dump the Contents of a Directory into an Array? - PHP Script Tips - Working with Directoris a...
How To Call a Sub Procedure? - Oracle DBA FAQ - Creating Your Own PL/SQL Procedures and Functions To...