1

I'm trying to generate a random double value that is between -1 and 1 and also includes both of them. Since there is the negative aspect I couldn't find any solution on internet.

  • Generating random double-precision numbers within an inclusive range is tricky: [How to generate a random double number in the inclusive (0,1) range?](https://stackoverflow.com/questions/66680283/how-to-generate-a-random-double-number-in-the-inclusive-0-1-range) Mathematically there are infinite real numbers in any given range, so the probability of selecting specifically any one of them is zero. – Theodor Zoulias Nov 19 '21 at 23:14

1 Answers1

2

Random.NextDouble provides values between 0 and 1. So just multiply by 2, then subtract one...

var betweenMinusOneAndOne = (new Random().NextDouble() * 2) -1;
lidqy
  • 1,891
  • 1
  • 9
  • 11
  • `Random.NextDouble` produces values in the range of `[0, 1)` - meaning greater than or equal to zero and ***less than one***. The OP specifically wants `1` included. `Random.NextDouble` can't do that. – Enigmativity Nov 19 '21 at 23:23
  • Having said that, though, the chances of getting a `1` for a random number generator that produces `double` precision values on `[0, 1]` is really really small, so for practical purposes `Random.NextDouble` does a good job. – Enigmativity Nov 19 '21 at 23:25