ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
rand() --> Gives you a number between 0 and RAND_MAX
rand() % N --> Gives you a number between 0 and (N - 1)
M + rand() % N --> This shifts the above statement M numbers, so you get a number between M and (N - 1) + M
rand() tends to give you crappy random numbers. a better way is to read from /dev/urandom just open the file and read a character at a time then typecast it as a int and mod it by 100.
These are some of the best suggestions i've seen so far for creating a RNG but...
If you compile this:
Code:
#include <stdlib.h>
#include <time.h>
int main() {
int x;
srand(time(NULL));
x = 1 + rand() % 100;
printf("%d\n", x);
return 0;
and then run it, u get the same number if it's run twice (or more) in the same second (roughly)... K thats probably me being fussy but if ya need something to continuously chuck you random numbers for 5 seconds you're screwed
There must be a better way than using time(), hmmm i'm gonna sleep on it lol
So use something that get you millisecond values. Such as the ftime function found in sys/timeb.h. It gives you a timeb structure, which gives you a time_t time, and a millitm, which is the number of seconds since the time_t, so you need to add them something like so:
Code:
#include <sys/timeb.h>
int main()
{
unsigned int ms;
struct timeb t;
ftime(&t);
ms = t.time * 1000 + t.millitm;
return 0;
}
Note: I'm sure there are probably better functions for getting millisecond values in Linux, but I'm still not all that familiar with all the standard libraries generally available with Linux. In Windows, I would use the API function timeGetTime(). Anyone know of a similar method for Linux?
It depends on what you're doing with it. For encryption it's out of the question. For number guessing games like 'pick a number from 1 to 20'
it's fine. As several posters pointed out, if you call srand() with a seed value that changes (like some kind of fine-grained time value) you avoid the problem of the sequence of numbers being the same.
Linux provides lrand48 (man drand48) that is as easy to use as rand() and is considered a much better PRNG - depending on what you are doing.
For most of what beginning programmers do rand() is just fine.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.