We are talking C#, so I'll assume .NET. Thus you would either use System.Random.Next
which works with integers, or System.Random.NextDouble
which - as the name suggest - works with double. There no method in System.Random
that uses float
.
From System.Random
it is preferible to use System.Random.NextDouble
. This is how it works: first generate a pseudo random number between 0
and Int32.MaxValue
(with uniform distribution), then convert it to double
, and scale it down to the range between 0.0
and 1.0
.
Contrast with System.Random.Next
, which will do all those steps and then scale and shift the result to the requested range and cast back to int
. If performance is your concern, then know that System.Random.Next
has extra steps.
Thus, use System.Random.NextDouble
and represent chances use values between 0.0
and 1.0
. For example 25% is 0.25
, which I'd argue is both easy to read and correct.
As per maintenance, declare a method that wraps whatever you choose to use (System.Random.NextDouble
for example), and takes whatever is more convenient to you. Doing this, it is easier to replace System.Random
with something else if the need arrives. In fact, you probably want the method to take a chance value and return bool
.
As per representing the chance, both int
and float
are 32 bits, so no memory saved there… I'd say prefer a non-integer type, because your chances are not integer. There could, perhaps be a difference in performance if you are parsing the values from text, but unlikely to be relevant below the millions of values (profile if it is a concern).
Can System.Random
be a bottle neck anyway? Yes. It happened to me while testing some voxel renderer and decided to simply pick each voxel at random (not what you want in practice), making each voxel a call to System.Random
. Why did I do that? Because I didn't have any world generator code in place at the time, and wanted to test the renderer. It ran slow, and profiler pointed to System.Random
. Reminder: use a profiler. So I replaced System.Random
with a custom solution (which I suppose didn't have as good statistical properties - I never tested - but was faster and good enough that I didn't see patterns at a glance).