On Monday 16 February 2004 16:52, Stefan Peters wrote:
wie kann ich in C Zufallszahlen erzeugen die alle kleiner 20 sind. Die Bibliotheksfunktion rand(void) liefert nur integer, die weitaus größer sind.
Siehe "man rand":
"If you want to generate a random integer between 1 and 10, you should always
do it by using high-order bits, as in
j=1+(int) (10.0*rand()/(RAND_MAX+1.0));
and never by anything resembling
j=1+(rand() % 10);
(which uses lower-order bits)."
Weiter oben wird das allerdings auch gleich abgemildert:
"The versions of rand() and srand() in the Linux C Library use the same random
number generator as random() and srandom(), so the lower-order bits should be
as random as the higher-order bits."
Soll heißen:
x = rand() % 20 // 0..19
tut's auch, wenn Du nicht gerade Rücksicht auf Implementierungen von
Uralt-Systemen nehmen mußt:
"However, on older rand() implementations, the lower-order bits are much less
random than the higher-order bits."
Soll heißen, daß die Zahlen dann nicht gleichverteilt sein könnten.
CU
--
Stefan Hundhammer