19

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.

Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
  • 1
    You are asking for a decimal but answers give you different ways to generate random double numbers. If you are looking for a random decimal number [this](http://stackoverflow.com/questions/609501/generating-a-random-decimal-in-c-sharp) may help. – Mechanical Object Jul 22 '13 at 11:56
  • @MechanicalObject at this scale and precision there is no difference between `double` and `decimal`, both systems can represent all 6 digit numbers in that range. – Scott Chamberlain Jul 22 '13 at 11:58
  • @ScottChamberlain : Yes, I know this thank you. But what I do not know is if dotnetandsqldevelop has limited the numbers after '.' for question's sake or not. 3.14159 seems like PI and given the fact that he asked for a decimal, I thought that the link might be useful. – Mechanical Object Jul 22 '13 at 12:02
  • @MechanicalObject He does have limited numbers, the `{5}` in the `[0-9]{1}.[0-9]{5}` means he will always have exactly 5 digits to the right of the decimal place. – Scott Chamberlain Jul 22 '13 at 12:12
  • @ScottChamberlain: You are right! I didn't pay attention to that. I was focused on the beginning of number PI :) Thanks. – Mechanical Object Jul 22 '13 at 12:19
  • @MechanicalObject, btw, 1.41421 is the root of 2. – dotnetandsqldevelop Jul 22 '13 at 12:33
  • Anyone who landed here wanting to generate random `decimal` (not `double`) should read this question: http://stackoverflow.com/q/609501/24874 – Drew Noakes Sep 06 '16 at 21:15

7 Answers7

34

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)
Erik Schierboom
  • 16,301
  • 10
  • 64
  • 81
11

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;
kame
  • 20,848
  • 33
  • 104
  • 159
dognose
  • 20,360
  • 9
  • 61
  • 107
6
Random r = new Random();
var number = r.Next(141421, 314160) / 100000M;

Also you can't force decimal number to match your pattern. E.g. if you have 1.5 number it will not match 1.50000 format. So, you should format result as string:

string formattedNumber = number.ToString("0.00000");
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
  • between 1.41421 and 3.14159 – dognose Jul 22 '13 at 11:51
  • @dognose ah thanks. I thought it should match [0-9]{1}.[0-9]{5} format – Sergey Berezovskiy Jul 22 '13 at 11:51
  • `System.Decimal` can have trailing zeroes. For example with `var x = 1.50000M;` the call `x.ToString()` **will** return `"1.50000"`. Maybe the division `150000 / 100000M` even gives trailing zeroes? – Jeppe Stig Nielsen Aug 25 '13 at 22:29
  • To myself: That division doesn't give trailing zeroes in itself. One can ensure at least five trailing zeroes (unless total number of figures exceeds 28 or 29 which will be no problem in our case) by multiplying by `1.00000M`. Then in some cases five trailing zeroes are too many, and one can truncate the zeroes with `Math.Round` (even if it doesn't round anything, it chops off zeroes). So something like `number = Math.Round(number * 1.00000M, 5);` will ensure that `number` has the wanted number of trailing zeroes. – Jeppe Stig Nielsen Aug 26 '13 at 11:01
1

I used this. I hope this helps.

Random Rnd = new Random();

double RndNum = (double)(Rnd.Next(Convert.ToInt32(LatRandMin.Value), Convert.ToInt32(LatRandMax.Value)))/1000000;
Dave Hogan
  • 3,201
  • 6
  • 29
  • 54
1

Check out the following link for ready-made implementations that should help:

MathNet.Numerics, Random Numbers and Probability Distributions

The extensive distributions are especially of interest, built on top of the Random Number Generators (MersenneTwister, etc.) directly derived from System.Random, all providing handy extension methods (e.g. NextFullRangeInt32, NextFullRangeInt64, NextDecimal, etc.). You can, of course, just use the default SystemRandomSource, which is simply System.Random embellished with the extension methods.

Oh, and you can create your RNG instances as thread safe if you need it.

Very handy indeed!

Ben Stabile
  • 173
  • 1
  • 4
1

here my solution, it's not pretty but it works well

Random rnd = new Random(); double num = Convert.ToDouble(rnd.Next(1, 15) + "." + rnd.Next(1, 100)); Console.WriteLine(num); Console.ReadKey();

1
JMH BJHBJHHJJ const int SIZE = 1;
        int nnOfTosses,

            headCount = 0, tailCount = 0;
        Random tossResult = new Random();

        do
        {
            Console.Write("Enter integer number (>=2) coin tosses or 0 to Exit: ");
            if (!int.TryParse(Console.ReadLine(), out nnOfTosses))
            {
                Console.Write("Invalid input");
            }
            else
            {

                //***//////////////////
                // To assign a random number to each element
                const int ROWS = 3;
                double[] scores = new double[ROWS];
                Random rn = new Random();

                // Populate 2D array with random values
                for (int row = 0; row < ROWS; row++)
                {
                    scores[row] = rn.NextDouble();
                }
                //***//////////////////////////

                for (int i = 0; i < nnOfTosses; i++)
                {

                    double[] tossResult = new double[i];
                    tossResult[i]= tossResult.nextDouble();

                }
                Console.Write("Number of Coin Tosses = " + nnOfTosses);
                Console.Write("Fraction of Heads = ");
                Console.Write("Fraction of Tails = ");
                Console.Write("Longest run is ");
            }
        } while (nnOfTosses != 0);

        Console.ReadLine();
alexander.polomodov
  • 5,396
  • 14
  • 39
  • 46
BHGB
  • 11
  • 1