Reputation: 679
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.
Upvotes: 0
Views: 122
Reputation: 186698
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;
Upvotes: 1