简体   繁体   中英

Generating random positive double is returning negative double value

I have a strange issue (at least for me) with generating random double values.

I am doing this:

 Random rndparam = new Random();
 double param1 = rndparam.NextDouble() * (paramUpperBound - paramLowerBound) + paramLowerBound;
 MySheetWrite.Cells[i + 1, 1] = param1;

I am trying to generate more parameters like this (with positive values), however I am getting negative values for few of them (all values for these parameters are negative) and for other parameters, there are also few negative values. There are however few parameters that are generated correctly between upper and lower bound. I am pretty sure that paramUpperBound is allways greater than paramLowerBound.

Also, to generate another parameters I am using rndparam object and these parameters are generated in one for loop.

Why not just validate ? Often we're pretty sure, but ugly ground truth breaks our (very strongs) beliefs into shards:

// Do not re-create Random! You'll have badly skewed distributions
// Simple, but not thread safe solution - have one static instance for all 
private static Random rndparam = new Random();

...

// I've assumed paramLowerBound and paramUpperBound are parameters
if (paramLowerBound < 0)
  throw new ArgumentOutOfRangeException(
    "paramLowerBound", 
    "Lower bound must be non-negative");
else if (paramUpperBound < paramLowerBound)  
  throw new ArgumentOutOfRangeException(
    "paramUpperBound", 
    "Upper bound must not be less than lower bound");

...

double param1 = rndparam.NextDouble() * 
                (paramUpperBound - paramLowerBound) + 
                paramLowerBound;

MySheetWrite.Cells[i + 1, 1] = param1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM