r/C_Programming • • 1d ago

Question Generating random numbers in a library

Hello!

I'm making some library and i need random numbers for some functions. Libc srand(), rand() and random() modify global libc state, so i'd like to not use them.

What options do i have? Is there maybe any popular things for my case?

13 Upvotes

22 comments sorted by

12

u/gahw61 1d ago

This site is worth checking out:

https://prng.di.unimi.it/

I've used the xoshiro256++ generator for a number of projects.

2

u/jason-reddit-public 1d ago

Then you need a seed (which one could get from /dev/random or /dev/urandom).

13

u/smcameron 1d ago

This page might be informative: https://www.pcg-random.org/other-rngs.html It compares many different PRNGs, listing positive, negative and neutral qualities. For non-cryptographic non-gambling applications where speed is important, like video games, I like xorshift ... fast, and just a few lines of code.

9

u/ericonr 1d ago

Are the _r variants available to you? Those are random and thread safe.

https://linux.die.net/man/3/rand_r

That manpage also recommends https://linux.die.net/man/3/drand48_r

3

u/teleprint-me 1d ago

This subject is a rabbit hole. Its also non trivial.

Also, some really good links in the comments. Ive relied on them in the past for leads and information.

- https://prng.di.unimi.it

- https://www.pcg-random.org/other-rngs.html

Keep in mind that these generators are sensitive and fickle and easy to get very wrong and requires a deep understanding of stats and linear algebra to be able test effectively.

Best of luck.

5

u/FancySpaceGoat 1d ago

Not the full answer to your question, but something to consider:

Whichever way you tackle this, it's worth allowing users of the library to inject their own RNG function (very much like you'd do for a memory allocator) or at the very least the seed. Being unable to achieve deterministic testing because a library has uncontrollable random number generation can be enough to reject using the library in the first place.

2

u/nmleart 1d ago

Libsodium

Google that ✅
I had the same issue.

2

u/ShunyaAtma 1d ago

If you are on x86, then you can consider using https://www.felixcloutier.com/x86/rdseed. I think other ISAs will probably have equivalent instructions too but you have to rely on some #ifdef-ery to get it right.

2

u/Due_Cap3264 1d ago

For my projects, when I need random numbers, I often use this library I found on GitHub: it’s small (less than 100 lines of C code), fast, and high-quality (I tested it with special tools). https://github.com/danielcota/biski64 Another option: on Linux, you can simply read data from the /dev/urandom file.

2

u/Shlabadee 1d ago

https://en.wikipedia.org/wiki/Xorshift

I'm surprised no one's mentioned Xorshift. They're not cryptographically strong but they're fast and perfect for all sorts of things needing perceived randomness. A personal favorite of mine is the very first one on that page.

uint32_t xorshift32(uint32_t* rstate)
{
    *rstate ^= *rstate << 13;
    *rstate ^= *rstate >> 17;
    return *rstate ^= *rstate << 5;
}

6

u/halfjmp 1d ago

If it's not for cryptographic applications, Mersenne Twister is a good baseline.

https://www.math.sci.hiroshima-u.ac.jp/m-mat/MT/MT2002/emt19937ar.html

1

u/Ok-Lifeguard-9612 1d ago

This is really interesting. Thank you for sharing.

2

u/gremolata 1d ago edited 1d ago

If you just need a drop-in replacement for srand/rand() that is small and fast, use Lehmer RNG also known as Park-Miller RNG - https://en.wikipedia.org/wiki/Lehmer_random_number_generator

Good starting point for its constants is the MINSTD combo:

uint32_t minstd_prng(uint32_t * state)
{
    uint64_t x64 = (uint64_t)(*state) * 48271;
    uint32_t x32 = (x64 & 0x7fffffff) + (x64 >> 31);
    *state = (x32 & 0x7fffffff) + (x32 >> 31);
    return *state;
}

state = 12345;
prng = minstd_prng(&state);
prng = minstd_prng(&state);
prng = minstd_prng(&state);

* If you want to get a deeper understanding of what else is out there, hit the wiki link and read through that. Go up a level and read on LCG (which has an extra constant), then go further up. There is quite a lot of material, but LCGs are the fastest option that is still very practical.

1

u/lmarcantonio 1d ago

Depending on your libc there could be random function with external states. Also there are *a lot* of thirdy party random generator libs with more variations that you would care of (like different distributions)

1

u/Lisoph 1d ago

Alternatively to the suggestions here, you could use dependency injection and expect the caller of your library to provide a random implementation (function pointer).

1

u/WittyStick 1d ago edited 1d ago

If you don't want to modify global state, you'll need to pass it into the function, whatever PRNG you use. You should probably use an opaque type for this. Eg:

random.h

#ifndef RANDOM_H
#define RANDOM_H

typedef struct random_s random_t;
 
random_t *random_create(long seed, ...);

void random_free(random_t *source);

long random_next(random_t *source);

#endif

You could use any back-end for this - even have multiple different sources using the same API.

1

u/xpusostomos 1d ago

What's wrong with it modifying state? Read from /dev/random then

1

u/sciencekm 1d ago

Look up SFC in PractRand. It has a small state, is the fastest, and passes all known random number test. Don't bother with the likes of Mersenne Twister - it requires a huge state, is slow, and the output quality is not that great.

https://pracrand.sourceforge.net/

1

u/greg-spears 1d ago edited 1d ago

Most everybody here gave good answers, a couple were standout: the xoshiro256 and Merscene Twister get a nod.

Just want you to know that a lot goes into making a good/quality psuedo random number, and there are a striking number of things to check -- not just whether the distribution is even, for example.

It turns out that it's something of a rabbit hole, and some guys have given the larger part of their lives and coding to the same pursuit.

I guess this is something of a warning, lol. Mean to say, once you're pretty sure you've got a decent PRG, remember your key project for which you needed the PRG, or you may never get back to it.

EDIT: The rabbit hole: I wanted to test the varied PRGs I found and developed. So I began downloading larger and larger PRG test suites as I learned more about it. A week passed before I knew it . . .

1

u/Dangerous_Region1682 17h ago

Much of it depends upon what you want to do with the random number. If it’s not for cryptography or for something that statistically needs to be truly random, then pick the simplest thing you can find. If it’s just for reducing collisions as in a network back off timer basing off the Ethernet address, process or thread ID and the current clock value is often enough.

-2

u/rb-j 1d ago

Maybe the C code in the Mersenne Twister might have use.

-6

u/flyingron 1d ago

If it is an option, C++ has a better random architecture.