Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a Random Number within a Range

Tags:

random

math

I have done this before, but now I'm struggling with it again, and I think I am not understanding the math underlying the issue.

I want to set a random number on within a small range on either side of 1. Examples would be .98, 1.02, .94, 1.1, etc. All of the examples I find describe getting a random number between 0 and 100, but how can I use that to get within the range I want?

The programming language doesn't really matter here, though I am using Pure Data. Could someone please explain the math involved?

like image 811
Tyler Avatar asked Dec 07 '09 15:12

Tyler


People also ask

Can Excel generate random numbers within a range?

Select the cell in which you want to get the random numbers. In the active cell, enter =RANDBETWEEN(1,100). Hold the Control key and Press Enter.

How can I generate a random number within a range but exclude some?

After generating the random number you've to put the "holes" back in the range. This can be achieved by incrementing the generated number as long as there are excluded numbers lower than or equal to the generated one. The lower exclude numbers are "holes" in the range before the generated number.

How do you generate a random number in a range in C++?

How to Generate Random Numbers in C++ Within a Range. Similar to 1 and 10, you can generate random numbers within any range using the modulus operator. For instance, to generate numbers between 1 and 100, you can write int random = 1+ (rand() % 100).


1 Answers

Uniform

If you want a (psuedo-)uniform distribution (evenly spaced) between 0.9 and 1.1 then the following will work:

  range = 0.2
  return 1-range/2+rand(100)*range/100

Adjust the range accordingly.

Pseudo-normal

If you wanted a normal distribution (bell curve) you would need special code, which would be language/library specific. You can get a close approximation with this code:

sd = 0.1
mean = 1
count = 10
sum = 0
for(int i=1; i<count; i++) 
  sum=sum+(rand(100)-50)
}
normal = sum / count
normal = normal*sd + mean
like image 53
Nick Fortescue Avatar answered Jan 03 '23 08:01

Nick Fortescue