C
C#Vlad

Feeding Random into itself - does it "corrupt the randomness"?

If I am to reinitialize an instance of System.Random after every .NextDouble() using the return value as a seed, would that make the randomness worse in some way? I want to do this in order to be able to persist and unpersist a System.Random, via knowing the seed at every step of the way.
A
Angius17d ago
Worse? Probably not. Creating a bunch of Random instances is more likely to make randomness worse. Can't you just use a single Random instance, with a single seed, and reuse that? I'd maybe generate, like, 100k values using this method of yours and check if they follow normal distribution
A
ACiDCA717d ago
i understood his footnote like he wants the randomfunction to be deterministic i guess for replayability?
JI
Joreyk ( IXLLEGACYIXL )17d ago
if you create a random on the approximately same time without special seed it will yields the exact same random values as it has teh same seed: the time
A
Angius17d ago
You just need one seeded instance for it to be deterministic
V
Vlad17d ago
this, yeah the point is to be able to save and resume the randomness, like in a game's save file for instance
A
Angius17d ago
Save the seed, then?
V
Vlad17d ago
I don't think you can extract the seed
J
Jimmacle17d ago
you start with a known one
A
Angius17d ago
^
V
Vlad17d ago
yes, but as soon as you random once, the seed is now different
J
Jimmacle17d ago
no
A
Angius17d ago
No
J
Jimmacle17d ago
that's not what a seed is
V
Vlad17d ago
I misspoke, let me rephrase
A
Angius17d ago
You create an instance of Random with a given seed. You reuse that instance everywhere It's guaranteed to be deterministic for the same seed
V
Vlad17d ago
every time you call next you are now "1 random pull" past the initial seed, therefore even if you use the same seed unless you keep track of how many randoms you pulled you cannot resume back to the same state
J
Jimmacle17d ago
so you need to keep track of how many numbers you've generated
V
Vlad17d ago
hmm I guess that could work, but wouldnt calling Next 1000 times be kind of slow?
J
Jimmacle17d ago
1000? probably instantaneous
V
Vlad17d ago
I mean as time goes on "loading the save" would get slower and slower
J
Jimmacle17d ago
or you could look into persisting the Random internals
V
Vlad17d ago
alright, well I might do that then
A
Angius17d ago
Save the generated values in the save ¯\_(ツ)_/¯
V
Vlad17d ago
I did look into it, but it seems they've changed a couple times over the years and I rather not depend on undocumented behavior not sure what you mean
A
Angius17d ago
Instead of regenerating the values from the seed, save them in the savegame That way you won't have to skip 1000 random results
J
Jimmacle17d ago
that doesn't help him
V
Vlad17d ago
ah, you misunderstand - the idea is to have the next random be the same when you reload
A
Angius17d ago
Ah, right I misunderstood, then
V
Vlad17d ago
^^
J
Jimmacle17d ago
the goal is to persist Random so when the game is loaded again it's as if it was never quit at all
V
Vlad17d ago
I'll just keep track of how many randoms were pulled and hope it never becomes a problem xd thanks for the help ZZZZ and Jimm
J
Jimmacle17d ago
personally i'd just assume the implementation of random won't change, the existing changes were made backwards compatible anyway or implement your own random class that you can control the implementation of
V
Vlad17d ago
that was going to be my next try 😄
J
Jimmacle17d ago
i'm sure there are a pile of PRNG algorithms out there that you can copy and paste
V
Vlad17d ago
easier to get that past code review than reflection of random underscore properties
J
Jimmacle17d ago
looks like the current Random uses a port of http://prng.di.unimi.it/xoshiro256starstar.c
UU
Unknown User17d ago
A
Angius17d ago
Benchmarked it, btw:
| Method | Seed | Mean | Error | StdDev |
|------------ |------------ |--------------:|--------------:|--------------:|
| One | -2147483648 | 6.185 ns | 0.3347 ns | 0.9710 ns |
| Hundred | -2147483648 | 1,011.573 ns | 21.5309 ns | 63.1465 ns |
| Thousand | -2147483648 | 9,059.311 ns | 58.3614 ns | 45.5647 ns |
| TenThousand | -2147483648 | 92,219.667 ns | 1,793.3376 ns | 1,993.2900 ns |
| One | 2147483647 | 5.445 ns | 0.2605 ns | 0.7516 ns |
| Hundred | 2147483647 | 959.814 ns | 19.1163 ns | 47.2508 ns |
| Thousand | 2147483647 | 8,902.830 ns | 172.3596 ns | 143.9281 ns |
| TenThousand | 2147483647 | 88,445.468 ns | 785.1084 ns | 612.9610 ns |
| Method | Seed | Mean | Error | StdDev |
|------------ |------------ |--------------:|--------------:|--------------:|
| One | -2147483648 | 6.185 ns | 0.3347 ns | 0.9710 ns |
| Hundred | -2147483648 | 1,011.573 ns | 21.5309 ns | 63.1465 ns |
| Thousand | -2147483648 | 9,059.311 ns | 58.3614 ns | 45.5647 ns |
| TenThousand | -2147483648 | 92,219.667 ns | 1,793.3376 ns | 1,993.2900 ns |
| One | 2147483647 | 5.445 ns | 0.2605 ns | 0.7516 ns |
| Hundred | 2147483647 | 959.814 ns | 19.1163 ns | 47.2508 ns |
| Thousand | 2147483647 | 8,902.830 ns | 172.3596 ns | 143.9281 ns |
| TenThousand | 2147483647 | 88,445.468 ns | 785.1084 ns | 612.9610 ns |
D
Decrypted17d ago
I got resumable rand class somewhere, let me try to find it
A
Angius17d ago
Safe to assume that no, generating a lot of random values won't be an issue
A
ACiDCA717d ago
quick calculation even if you generate 60 randoms a second for 50h based on the benchmark above its just around 0.1s to calculate them from new in one batch
D
Decrypted17d ago
public class Rng
{
public byte[] State => _state;

private byte[] _state = new byte[32];

public Rng(int seed)
{
var rand = new Random(seed);

// fill state from seed
rand.NextBytes(_state);
}

public Rng(byte[] state)
{
_state = state;
}

public int Next()
{
// Hash new state
if (!SHA256.TryHashData(_state, _state, out _))
{
throw new InvalidOperationException();
}

var bigInt = new BigInteger(_state);

return (int)(bigInt % int.MaxValue);
}
}
public class Rng
{
public byte[] State => _state;

private byte[] _state = new byte[32];

public Rng(int seed)
{
var rand = new Random(seed);

// fill state from seed
rand.NextBytes(_state);
}

public Rng(byte[] state)
{
_state = state;
}

public int Next()
{
// Hash new state
if (!SHA256.TryHashData(_state, _state, out _))
{
throw new InvalidOperationException();
}

var bigInt = new BigInteger(_state);

return (int)(bigInt % int.MaxValue);
}
}
This uses SHA256 to hash the state on top of itself You can then persist the 32 byte state and resume from it when required. Not sure if this is the best way to do this. I don't even know if the bigInt % int.MaxValue is safe operation for converting to int..
J
Jimmacle17d ago
without actually benchmarking it that looks slow i'd also want to see some proof that this generates a good distribution of random numbers since you're attempting to use SHA256 as a PRNG algorithm definitely better to just use a proper PRNG implementation in a way that you have access to the internal state to persist
| Method | Mean | Error | StdDev |
|----------- |------------:|----------:|----------:|
| Random100k | 698.7 us | 9.77 us | 12.71 us |
| Rng100k | 25,313.9 us | 391.05 us | 346.65 us |
| Method | Mean | Error | StdDev |
|----------- |------------:|----------:|----------:|
| Random100k | 698.7 us | 9.77 us | 12.71 us |
| Rng100k | 25,313.9 us | 391.05 us | 346.65 us |
distribution aside, that implementation is 36 times slower than plain Random
V
Vlad17d ago
damn thanks for taking the time to benchmark it
J
Jimmacle17d ago
i'd just copy the implementation from https://source.dot.net/#System.Private.CoreLib/src/libraries/System.Private.CoreLib/src/System/Random.Xoshiro256StarStarImpl.cs,cf33c3a42d4a8ee6 and tweak it to your needs or see https://prng.di.unimi.it/ for all the generators like it in case a different algorithm is more appropriate
Want results from more Discord servers?
Add your server
More Posts
Update and add to Resource.resx file via code.We are adding localization to our product and want to automate the process of updating the resx fileWinform project saves the Image with a black backgroundIt works perfectly except it creates a black background which isn't shown in the picturebox preview,✅ Theoretical question. MediatR and DTO and onion structureHello, THe following is just theoretical and I do not need any code In the programming world, transfStack overflow exception when closing one formCan't seem to find the issue.. I have a startscreen, and when any key is pressed on startscreen it tAdvice / Guidance on VM application services (Windows Server 2016)Has anyone every come across a virtual machine (3 virtual 2.6Ghz processors, 12GB Ram) where a singlCan anyone help me with the odd prime numbers program?Facing difficulty in college assignment.IndexOutOfRange Leetcode helpHey, having an issue with my leetcode problem. I know that its supposed to be a bitwise XOR operatiovisual studio .net core ironPDFi have problem with export to pdf files. It's works perfectly( create a files and change keyword), bVisual Studio + WPF: "Could Not Load Assembly" despite dlls being available and reference correctThis has been driving me nuts for a day now. It's an intermittent error as had this working fine at how to export datas to json file from mysqlI have datas in mysql I want to move them to a json file. How can I do that?Licensing my programHi, i’m developing a Point Of Sale software and would like to find out possible solutions to manage ✅ Unhandled exception. Cannot print exception string because Exception.ToString() failed.justwhy this error always come in dotnet webapi application version ----- dotnet --version ✅ How to use Dapper with Query ParametersI work a lot with SQL databases such as MySQL, SQLite and PSQL and usually I write my Queries like t✅ transaction in transaction issueI have this error: `The connection is already in a transaction and cannot participate in another trHelp making login function c#Im currently trying to code a login function I have the registration my user is getting saved in thProblems with docker and my app imageI already posted a question that more or less manage to solve but now i have other problem, the thiAttempting to get value from different JSON files with variable keyHello o/ I am attempting to deserilize and obtain the value from a variety of JSON files that contaiHow to display only department fields associated with a selected department in student automationhi, I'm facing a challenge while working on the student automation system. After selecting the deparHelp with DiscordGameSDK in a C# project (no Unity)I am currently trying to develop a plugin for a Unity game. For this I created a C# project, where IMarshal.GetActiveObject("Word.Application") fall in exceptionI'm working on a `.NET Framework` console application, I have added the `Microsoft.Office.Interop.W