Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Best approach, no crazed values, <a href="https://stackoverflow.com/questions/609501/generating-a-random-decimal-in-c/610228#610228">distributed with respect to the representable intervals on the floating-point number line</a> (removed "uniform" as with respect to a continuous number line it is decidedly non-uniform):</p> <pre><code>static float NextFloat(Random random) { double mantissa = (random.NextDouble() * 2.0) - 1.0; double exponent = Math.Pow(2.0, random.Next(-126, 128)); return (float)(mantissa * exponent); } </code></pre> <p>Another approach which will give you some crazed values (uniform distribution of bit patterns), potentially useful for fuzzing:</p> <pre><code>static float NextFloat(Random random) { var buffer = new byte[4]; random.NextBytes(buffer); return BitConverter.ToSingle(buffer,0); } </code></pre> <p>Least useful approach:</p> <pre><code>static float NextFloat(Random random) { // Not a uniform distribution w.r.t. the binary floating-point number line // which makes sense given that NextDouble is uniform from 0.0 to 1.0. // Uniform w.r.t. a continuous number line. // // The range produced by this method is 6.8e38. // // Therefore if NextDouble produces values in the range of 0.0 to 0.1 // 10% of the time, we will only produce numbers less than 1e38 about // 10% of the time, which does not make sense. var result = (random.NextDouble() * (Single.MaxValue - (double)Single.MinValue)) + Single.MinValue; return (float)result; } </code></pre> <p>Floating point number line from: <a href="http://www.randelshofer.ch/fhw/gri/float.html" rel="noreferrer">Intel Architecture Software Developer's Manual Volume 1: Basic Architecture.</a> The Y-axis is logarithmic (base-2) because consecutive binary floating point numbers do not differ linearly. </p> <p><img src="https://3.bp.blogspot.com/_XnHVrPnrx7o/TFHUXopxYNI/AAAAAAAABrs/2H_tT_VuUOk/s1600/distribution.png" alt="Comparison of distributions, logarithmic Y-axis"></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload