+ 7
How does the random() function actually work?
I was wondering how does it produce a random output?
5 Respuestas
+ 11
XORs and shifts. From one of my private codes...the Javascript implementation in Python:
=================================
mask = 0xFFFFFFFFFFFFFFFF # 64 bits
xorshiftseed={
'x' : 0,
'y' : 1
} # start seeds
def method2():
global xorshiftseed
x,y = xorshiftseed['x'], xorshiftseed['y']
xorshiftseed['x'] = y
x ^= (x << 23) & mask # a
xorshiftseed['y'] = x ^ (x >> 17) ^ y ^ (y >> 26) # b,c
return (xorshiftseed['y'] + y) & mask
print(*[method2() for i in range(100)])
=================================
That's XORShift128p. I'm not linking the whole source because I hadn't finished reversing it ... :)
def reverse17(val): return val ^ (val >> 17) ^ (val >> 34) ^ ...
def reverse23(val): return (val ^ ( other diffs ...
def xs128p_backward(state0, state1):
...
The salient point: Shifts + XORs leak bits + are by nature ^that^ easily reversible, which is why PRNGs are NOT cryptographically secure.
+ 7
Most computer generated random numbers use pseudorandom number generators
https://en.m.wikipedia.org/wiki/Random_number_generation
+ 7
Kirk Schafer wow that's cool!
+ 4
Yash Kandalkar This is more complex than I had imagined!
+ 3
I wanted to add: pRNG's are deterministic. If you provide the same initialization (the 'seed'), they always generate the same "randomish" sequence.
In the code, the only independent is the initial seed config. After that, new seeds generate from the old ones in an unbroken chain.
Like crypto, the algorithms are public; know the seed, predict the sequence.
That's why this code works (the seed is just 42 for an unbroken chain of rnd calls):
https://code.sololearn.com/cUvmAKbgz5T3/?ref=app
*** Significance ***
~ Public seeds make the Microsoft version trivial (c#; sync up with no analysis)
~ c/c++ default to a 0 seed (so devs forget)
~ javascript uses "auto un-settable private seeds" (but they're derivable)
~ Devs overwhelmingly use the system timer for a seed
+ pRNGs are designed to be fast (good for bruteforcing)
+ ...then if you can guess a system's/process's uptime (whoops)