rand() and random()
I have some code here that isnt mine, and it uses a function random(). When I compile the sole error I get is with this function, basically its undefined. I assume then thats is some standard C/C++ built in, but then why is the linker unable to find it?
When I use the rand() func in its place the program compiles...but freezes when it runs...
I *vaguely* remember using a function called random() in a previous project, but I cant remember if it was a built in or if it was given to us in the code. I vaguely remember it being given to us, but it used rand() itself...but I cant be sure.
This time its definitely not given, so is random() a std:: or stdlib built in?
Reading this Linux man page random() certainly is a stdlib function...looking through my stdlib.h its not there.
What I dont get is why using rand() in this program freezes it...
What I dont get is why using rand() in this program freezes it...
Yeah I am taking a look at this. random() by the way is standard in Unix implementations I have found out.
Not having seen the code, it could be that, of course, rand() is returning an unsigned integer, whereas the unknown function random() is an external function that converts rand() to a double, something like:
There are some very efficient gaussian and exponential generators out there that use both unsigned int and double in the same algorithm.
--random
double random(){ return rand()/(1.0 + RAND_MAX); // you might need a static_cast<>(double) here.}
There are some very efficient gaussian and exponential generators out there that use both unsigned int and double in the same algorithm.
--random
This random() function can be either the Linux-stdlib function or a user-implemented function that is missing. But in the most likely first case, it should behave like rand() according to that same man page.
Greetz,
Illco
Greetz,
Illco
rand() produces values clamped between 0 and MAX_RAND in stlib.h. random() on the other hand is between 0 and (2^31)-1.
I am emulating random() with rand() by doing the following:
Apparently random() is also "more random" than rand() as well...hmmm
I am emulating random() with rand() by doing the following:
int GetRand(void){ int n; while(1) { n = rand()*rand()*rand(); if((n > 2147483647) || (n < 0)) ; else break; } return n;}
Apparently random() is also "more random" than rand() as well...hmmm
The reason for values between 0 and (2^31)-1 is to avoid undefined behaviour when using the base random values in lognormal or some forms of exponential or gamma generators.
The function random() that I gave above is for the interval [0,1). Are you sure that your data types are correct within the context of your code?
--random
The function random() that I gave above is for the interval [0,1). Are you sure that your data types are correct within the context of your code?
--random
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement