Reputation: 4373
Let say that I would like to get an random double value wich is:
This number must be random...
How can I do that?
Additional info:
Like you said... 0.440 is not in [-0.150, 0.150], but I need to generate an number close to that number in this range...
let say that I call:
getMyRandomNumber(-0.150, 0.150, 0.440)
I would like to get an number in the range [-0.150, 0.150] but that it isn't allways 0.150
I would like to get numbers like 0.139, 0.140, 0.121,...
If I call:
getMyRandomNumber(-0.150, 0.150, -0.440)
I would like to get numbers like -0.139, -0.140, -0.121,...
Upvotes: 0
Views: 442
Reputation: 5005
Random's NextDouble() returns a random number between 0.0 and 1.0
If you want to get a random number in the interval (a, b) based on the random number from NextDouble() then you need to map the (0.0, 1.0) interval you get to the (a, b) interval you need.
The simplest way is to use this formula:
result = a + (b - a) * X
where X
is the result from NextDouble()
If X
is 0 then result
will be a
, if X
is 1 then result
will be b
, for X
between 0.0 and 1.0 the result
will be between a
and b
.
If you want numbers close to a certain number (say 0.44) but no further than 0.15 away then you need to map the results into the (0.44 - 0.15, 0.44 + 0.15) interval.
Upvotes: 2
Reputation: 5103
Random g = new Random();
double max = double.MaxValue;
double a = g.NextDouble() * max - 0.150; // greater then -0.15
double b = -g.NextDouble() * max + 0.150; // less then 0.15
most close is not clearly definition
Upvotes: 0