Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random double between given numbers

Tags:

c#

I'm looking for some succinct, modern C# code to generate a random double number between 1.41421 and 3.14159. where the number should be [0-9]{1}.[0-9]{5} format.

I'm thinking some solution that utilizes Enumerable.Range somehow may make this more succinct.

like image 206
dotnetandsqldevelop Avatar asked Jul 22 '13 11:07

dotnetandsqldevelop


People also ask

How do you find a random double value?

In order to generate Random double type numbers in Java, we use the nextDouble() method of the java. util. Random class. This returns the next random double value between 0.0 (inclusive) and 1.0 (exclusive) from the random generator sequence.

Is math random a double?

random() returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. This new pseudorandom-number generator is used thereafter for all calls to this method and is used nowhere else.


2 Answers

You can easily define a method that returns a random number between two values:

private static readonly Random random = new Random();

private static double RandomNumberBetween(double minValue, double maxValue)
{
    var next = random.NextDouble();

    return minValue + (next * (maxValue - minValue));
}

You can then call this method with your desired values:

RandomNumberBetween(1.41421, 3.14159)
like image 199
Erik Schierboom Avatar answered Oct 06 '22 20:10

Erik Schierboom


Use something like this.

Random random = new Random()
int r = random.Next(141421, 314160); //+1 as end is excluded.
Double result = (Double)r / 100000.00;
like image 40
dognose Avatar answered Oct 06 '22 20:10

dognose