views:

132

answers:

7

I know I have done this before, but now I'm struggling with it again. I am trying to set a random number on either side of 1: .98, 1.02, .94, 1.1, etc. If I get a random number between 0 and 100, how can I use that to get within the range I want?

The programming language doesn't really matter here. I'm using Pure Data. Just looking for the math involved.

A: 

Divide by 100 and add 1. (I assume you are looking for a range from 0 to 2?)

Upper Stage
+3  A: 
return 0.9 + rand(100) / 500.0

or am I missing something?

erikkallen
A: 

low + (random() / 100) * range

So for example:

0.90 + (random() / 100) * 0.2

Caleb
+1  A: 

How near? You could use a Guassian (a.k.a. Normal) distribution with a mean of 1 and a small standard deviation.

A Gaussian is suitable if you want numbers close to 1 to be more frequent than numbers a bit further away from 1.

Some languages (such as Java) will have support for Gaussians in the standard library.

Dan Dyer
+1  A: 

If rand() returns you a random number between 0 and 100, all you need to do is:

(rand() / 100) * 2

to get a random number between 0 and 2.

If on the other hand you want the range from 0.9 to 1.1, use the following:

0.9 + ((rand() / 100) * 0.2)
Daniel Vassallo
+4  A: 

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
Nick Fortescue
Uniform? p(0.9) != p(0.9001). I admit it's a non-trivial problem with IEEE754.
MSalters
fair point - but given the lack of precision in the question I doubt this will matter to the questioner. Would pesudo-uniform be fair? :-)
Nick Fortescue
A: 

You want a range from -1 to 1 as output from your rand() expression.

( rand(2) - 1 )

Then scale that -1 to 1 range as needed. Say, for a .1 variation on either side:

(( rand(2) - 1 ) / 10 )

Then just add one.

(( rand(2) - 1 ) / 10 ) + 1
zen