• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 8265
  • Last Modified:

C# Random double between min and max

How can I create an random number (double) between     .23   and  3.2?
2 Solutions
Mike TomlinsonMiddle School Assistant TeacherCommented:
Just use the generic formula:

    Random.NextDouble() * (maximum - minimum) + minimum;

        private Random R = new Random();

        private void button1_Click(object sender, EventArgs e)
            double dbl = R.NextDouble() * (3.2 - .23) + .23;

Open in new window

käµfm³d 👽Commented:
Use the NextDouble method of the Random class and a little bit of math magic:

Random r = new Random();
double d = r.NextDouble();

d = ((d * (3.2 - .23)) + .23);

Open in new window


Since Idle_Mind is faster at the keys than I am, it seems all I have left is to augment my answer a bit.  (Great to see you back Idle!)

The reason this works is because NextDouble will always return a value between 0 and 1. The max - min gives the difference between the two values. If the call to NextDouble returned 0, anything multiplied by zero is zero, so the subsequent addition of the min will yield your lower bound.

Now if NextDouble returned 1, then you have the difference of max and min multiplied by 1. Anything multiplied by 1 is itself, so you end up with that difference. Adding back in the min gives you max, which is your upper bound on your range.

Anything else that NextDouble returns causes the resulting arithmetic to fall trivially in the range of min and max.
Mike TomlinsonMiddle School Assistant TeacherCommented:
Awesome explanation.  It's good to be back.  =)
AndyAinscowFreelance programmer / ConsultantCommented:
Just don't forget to check (and adjust if necessary) that the maximum entered is actually greater than the minimum entered else the above will give garbage results.
Erol DemirciCommented:
I believe your answers could be incorrect??? on the upper bound (Now if NextDouble returned 1, submitted by kaufmed).

C# random DOUBLE generator var.NextDouble() will generate values (0, 1], notice the bracket on the right?  It does NOT include 1, which means, his upper bound will never be reached.

Please read:
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now