#Rolled a small descrete rng, plz rate

38 messages · Page 1 of 1 (latest)

night bay
#

I rolled a small random number generator that should be able to handle weighted probabilities as a test to compare the code size of hand rolling to C++'s discrete rng, plz rate it and suggest how it can be made better, been a while since I did anything in C

https://godbolt.org/z/cr6sE9M8d

night bay
#

@native root

#

Hippity hoppity please review

#

I want to be yelled at

thorn wren
#

It might be helpful to plot this rng output on a graph or generate a large image of random grayscale colors to try and find patterns. rand() is usually an LCG which is fast but very bad at avoiding patterns, so it'd be a good test to see if your adaptation mitigates those patterns

#

Oh wait this is simply adapting rand to a custom curve you "draw" with equally spaced buckets having different probabilities

#

It seems fine from a code perspective, using modulo will skew the results slightly but it's difficult to fix and you're already using rand which is bad enough

#

But after the last loop, is that even reachable? Maybe it would make sense to raise an assertion error there

#

If it is reachable, maybe just return the index of the last bucket

night bay
thorn wren
#

Rand is ...not great quality

#

Especially the lower bits (which are what you get with modulo) have extremely predictable patterns

night bay
#

Is there a better rng for C then?

thorn wren
#

Not in the stdlib

#

arc4random is good from bsd, libsodium has rng so good it's usable for crypto, pcg is good and easy to copy paste as it's 1 short function

night bay
#

I'll check those out, I started this as a classmate was showing the C++ discrete randoms and mentioning how he didn't know you could that

#

Which led me to making this

thorn wren
#

Apparently arc4random is also crypto secure

night bay
#

Hence why it's kinda trash

#

But now I gotta make this good

#

I'll keep these in mind and fix it up

#

Danke

native root
night bay
#

Wouldn't an endless loop of cryptographic (or even non cryptographic) hashes be sufficient to break that kind of uniformity?

#

Ie hash the stored value then save the hash as the new value

native root
#

Sure

#

Cryptographically secure random number generators are generally based on block ciphers

night bay
#

Then why are LCGs used?

#

Is the speed diff that important?

native root
#

LCGs aren't even fast 😅

#

(Faster than a csprng probably, but very slow compared to better non-crypto prngs)

#

It's just that's what was used in the 80's when C was a thing so obviously it must still be used now because we can't move on from mistakes of the past

night bay
#

Based

#

Danke

#

Kinda wanna make this an actual library now