r/C_Programming • • 8d 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?

14 Upvotes

30 comments sorted by

14

u/gahw61 8d 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 7d ago

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

15

u/smcameron 8d 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.

12

u/ericonr 8d 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

0

u/BudgetEye7539 5d ago

They don't obey a uniform distribution and fail the birthday spacings test at some settings.

4

u/teleprint-me 7d 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.

3

u/Due_Cap3264 7d 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.

3

u/Shlabadee 7d 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;
}

0

u/BudgetEye7539 5d ago

Its period too small. The bare minimum will be something like xorshift64*. Also MWC64X is simple and fairly high quality.

2

u/Shlabadee 4d ago

That depends on what you need RNG for. This RNG's period encompasses 2^32-1 possible states (0 must be avoided). That's quite large for DSP and video games. Another benefit to this RNG is its computational simplicity—literally just bitwise operations. Granted, non-cryptographic RNG is cheap as dirt these days (and even 20 years ago). But hey, preferences.

1

u/BudgetEye7539 4d ago

For games and DSP - why not? But when I think about general purpose PRNG for simulation/standard libraries I think that stream ciphers are nice as a default choice. If we need something very fast and without multiplication - something like xoroshiro++ (a modification of xorshift with higher period) will be nice.

2

u/Shlabadee 4d ago

So then use those instead? I don't get what the problem is. Just use whatever tool you think is right for the job.

1

u/BudgetEye7539 4d ago

Selecting the tool is nice. But I see that developers of C standard libraries don't supply proper non-cryptographic PRNGs because of this "random enough" and "depends on the task" viewpoint. If we don't know the task - it should be a stream cipher or at least something that passes TestU01 and PractRand.

1

u/Shlabadee 4d ago

But my argument is if you know what the task is, you should be able to use what you think is best. That besides, it's highly not recommended to use the standard `rand()` function. The only good thing I can say about it is it's convenient. Something like even a basic Xorshift RNG solves a lot of problems on its own. I'll grant that my needs are different from yours. Without knowing anything about you beyond this conversation, my best guess is you don't write games or DSP software. Again, I have no idea who you are or what you do (and it's probably none of my business). But things like noise generation, enemy behaviors, damage calculation jitter, and so on are solvable with an RNG with minimal dependency. On the other hand, I'm contradicting myself since RNG is stupid fast even on older machines.

5

u/FancySpaceGoat 8d 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.

7

u/[deleted] 8d 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 8d ago

This is really interesting. Thank you for sharing.

2

u/nmleart 8d ago

Libsodium

Google that ✅
I had the same issue.

2

u/sciencekm 8d 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/

2

u/ShunyaAtma 8d 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/greg-spears 7d ago edited 3d 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 . . .

EDIT2: I also bought 10,000,000 bits of random data from random.org, lol

3

u/gremolata 8d ago edited 7d 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.

0

u/BudgetEye7539 5d ago

minstd is too small, it fails the basic uniformity tests. Good modern minstd replacement is something like MWC64X by Thomas. Vigna found better multipliers for them: https://arxiv.org/abs/2610.27313

1

u/lmarcantonio 8d 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 8d 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 8d ago edited 8d 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 8d ago

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

1

u/Dangerous_Region1682 7d 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 8d ago

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

-6

u/flyingron 8d ago

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