PDA

View Full Version : [C++] generazione di numeri casuali


robs05
18-09-2008, 09:03
salve

vorrei implementare Quick sort random

in effetti devo creare la funzione random(int p, int u)
che mi restituisce un numero casuale tra p e u


int random(int p, int u)
{
srand(time(NULL));
return p+rand()%(u-2);
}


adesso volevo fare una prova


for(int i = 0; i < 10; i++)
{
cout << random(3,10) << endl;
}

cout << random(3,10) << endl;
cout << random(3,10) << endl;
cout << random(3,10) << endl;
cout << random(3,10) << endl;
cout << random(3,10) << endl;



mi genera sempre lo stesso numero, cambia solo ogni volta che faccio rieseguire il programma

l'output e' :
9
9
9
9
9
9
9
.
.
.
9
9

io vorrei:

3
5
2
3
10
4
5

come mai?

robs05
18-09-2008, 09:07
un aggiornamento:

eliminando srand(time(NULL))

ottengo quello che volevo ma il problema è che poi ad ogni esecuzione genera sempre gli stessi numeri e quindi non posso valutare l'efficienza degl'algoritmi

come posso fare?

banryu79
18-09-2008, 09:13
Non sono un esperto di C++ e funzioni/strutture dati affini, ma leggendo questo mi sono fatto un'idea:

void srand ( unsigned int seed );



<cstdlib>

Initialize random number generator

The pseudo-random number generator is initialized using the argument passed as seed.

For every different seed value used in a call to srand, the pseudo-random number generator can be expected to generate a different succession of results in the subsequent calls to rand.
Two different initializations with the same seed, instructs the pseudo-random generator to generate the same succession of results for the subsequent calls to rand in both cases.

If seed is set to 1, the generator is reinitialized to its initial value and produces the same values as before any call to rand or srand.

In order to generate random-like numbers, srand is usually initialized to some distinctive value, like those related with the execution time. For example, the value returned by the function time (declared in header <ctime>) is different each second, which is distinctive enough for most randoming needs.


Quel ciclo for sicuramente non dura un secondo, ma molto molto meno ;) e visto che la granularità della funzione time è di un secondo, probabilmente l'argomento passato a srand genera sempre lo stesso seme, e questo spiegherebbe la generazione degli stessi valori.

Usa una funzione di timestamp più fine (non so quale) per generare l'argomento da passare a srand().

Ciao :)

robs05
18-09-2008, 09:23
ho risolto eliminando la srand all'interno della function e richiamdola nel main così mi vale per tutti i test dove ho bisogno di numeri casuali e funziona correttamente.

tomminno
18-09-2008, 09:31
Se usi VS2008 puoi installare il Feature Pack e usare la classe uniform_int definita nel TR1.
Oppure usare funzioni specifiche dell'OS per la generazione del seme tipo GetTickCount o ftime (lo so che non sono analoghe ma per lo meno acquisiscono una unità di tempo al millisecondo)