I'm looking to create a library for dealing with probability in C#. My current system takes an ordered array of probabilities as an input then generates a random double. It then accumulates each double in the array until the accumulated values are greater than the randomly selected one. Like this (Samples
is the array of probabilities and Sample
is the random value) :
int i;
for
(
(i, double accumulator) = (0, Samples[0].Probability);
i < Samples.Length && accumulator > Sample;
accumulator += Samples[++i].Probability
);
return i==Samples.Length? null:Samples[i];
Is this the fastest way of doing this? Also are there any good well-known probability libraries out there? Thanks guys :)
.AsSpan()
can speed up the loop and even usingforeach
instead offor
can do so (which was quite unexpected for me). But every case is different. So, the only way to speed up your code is to do benchmarks with different code variants. Use BenchmarkDotNet for your benchmarks. \$\endgroup\$accumulator > Sample
) I do not see a way to do this in parallel. Btw., the condition in the for should bei < Samples.Length && accumulator <= Sample
because this is the condition for not stopping. \$\endgroup\$