tags:

views:

1206

answers:

4

Hi, Looking to make a really simple random number generator method in C. The numbers should be between 0 and 24 and can be for example 14.5f.

Any help would be great, thanks!

+3  A: 

Have a look at linear congruential generators, they are quite simple to implement even with my inferior math knowledge.

Looks like I misunderstood the original question, I thought you wanted to roll your own generator (for homework, fun etc.)

Skurmedel
No no, you were on the mark :) Small uni assignment
Maybe you can choose this as the correct answer, then?
Rick Copeland
+7  A: 
float getRand() {
  float rnd = rand();
  rnd /= RAND_MAX;
  return rnd * 24.0f;
}

Make sure you seed the random number generator with srand before use.

Mehrdad Afshari
Note that rand is deprecated on some platforms (OS X, Ubuntu 8.04) in favour of the random, srandom, etc functions.
Dana the Sane
Seed before everytime its called? Also seed with what exactly?
No... absolutely not every time. Just once before the first call. You can seed with srand(time(0));
Mehrdad Afshari
@Dana: it's not comparable, only rand() is part of C.
Bastien Léonard
Working a treat, thanks very much :)
The functions are equivalent on newer systems, but for anything previous you should be accounting for the low order bit issue with rand(). We should be providing the best answer for any readers who use this question in the future.
Dana the Sane
See the Notes section http://www.kernel.org/doc/man-pages/online/pages/man3/rand.3.html
Dana the Sane
No rand() I've encountered on a recent system (no, not even MSVC) actually uses the lower bits of the generator's state word.
Joey
Ok, case closed then.
Dana the Sane
Not to mention that the code presented in this answer uses as many significant bits as it can from rand()'s return value, and would be as immune to the low bits problem as possible if rand() did return the low bits in a bad implementation.
RBerteig
+3  A: 

You can use C's built in random number generator to get an integer between 0 and 30 thousand something like this:

`srand(time(NULL));
    int x= rand();`

You would just need to do some division to get a decimal number instead of and integer.

CrazyJugglerDrummer
Note that rand is deprecated on some platforms (OS X, Ubuntu 8.04) in favour of the random, srandom, etc.
Dana the Sane
+4  A: 

The Mersenne_twister is not only very simple, but also very strong.

See the code on the link.

However, if you can use GPL License, use the The GNU Scientific Library (GSL) specific check Random-Number-Generator-Examples from Random-Number-Generation part of the manual

There are many things there, from simple uniform random numbers to other distributions.

Liran Orevi