rand generator - immer gleiche sequence
-
hi,
warum erzeut folgender rand generator immer die gleiche sequence bei programstart, obwohl ich einen seed verwendet habe?struct RandGenerator { init() { timeval t1; gettimeofday(&t1, NULL); srand(t1.tv_usec * t1.tv_sec); } float generate(const float min, const float max) { float f = (float)rand() / RAND_MAX; return min + f * (max - min); } };
-
wei bekomme ich da floats raus? und wie setze ich den seed richtig so das bei programstart eine neue sequenz erzeugt wird?
#include <stdio.h> #include <sys/time.h> void init() { struct timeval t1; gettimeofday(&t1, NULL); srand(t1.tv_usec * t1.tv_sec); } float generate(const int min, const int max) { return rand() % (max - min) + min; } int main(void) { // your code goes here init(); for (int i = 0; i < 10; i++) { printf("%f\n", generate(0, 10)); } return 0; }
-
Vielleicht ist tv_usec auf deinem System immer 0.
Vielleicht solltest du statt der Multiplikation eine passendere Verknüpfung verwenden. Wie z.B. ^ oder auch einfach +.newbb schrieb:
wei bekomme ich da floats raus?
Äh.
Google hilft?
-
woran kann es sonst liegen?
Vielleicht ist tv_usec auf deinem System immer 0.
try1:
t1.tv_usec: 308866 t1.tv_sec: 1427957185 try2: t1.tv_usec: 490829 t1.tv_sec: 1427957195
void init() { timeval t1; gettimeofday(&t1, NULL); srand(t1.tv_usec * t1.tv_sec); } float generate(const float min, const float max) { float f = (float)rand() / (float)RAND_MAX; return min + f * (max - min); }
-
Hast Du dir überlegt, ob das so mit den Datentypen das ist, was Du willst?
Was hat zB. t1.tv_usec, t1.tv_sec, das Produkt und das Argument von srand? (Die richtige Antwort ist: da blickt kein Mensch durch.)Ich würde mir beim seed einfach weniger Mühe geben und ne Multiplikation weglassen oder so ...
-
srand will ein unsigned int.
folgendes erzeugt auch immer die gleiche sequenz:srand((unsigned int)(t1.tv_usec))
-
Und was macht es, wenn du nur die Sekunden nimmst?
srand((unsigned int)(t1.tv_sec));
-
ich hab das nun mal in c++ getestet:
funktioniert nicht:
[code="cpp"]
class RandGenerator {
public:
RandGenerator() {
srand((unsigned int)time(NULL));
}float generate(const float min, const float max) {
return ((max-min)*((float)rand()/RAND_MAX))+min;
}
};funktioniert:
class RandGenerator {
public:
RandGenerator() {
}float generate(const float min, const float max) {
static int is_first = 1;
if (is_first) {
is_first = 0;
srand((unsigned int)time(NULL));
}
return ((max-min)*((float)rand()/RAND_MAX))+min;
}
};
-
hab das nun mal mit c++ getestet:
funktioniert nicht: class RandGenerator { public: RandGenerator() { srand((unsigned int)time(NULL)); } float generate(const float min, const float max) { return ((max-min)*((float)rand()/RAND_MAX))+min; } }; funktioniert: class RandGenerator { public: RandGenerator() { } float generate(const float min, const float max) { static int is_first = 1; if (is_first) { is_first = 0; srand((unsigned int)time(NULL)); } return ((max-min)*((float)rand()/RAND_MAX))+min; } };