good_evening
good_evening

Reputation: 21749

Generating the list of random numbers with certain average difference

I have to generate a list of random numbers and they have to have a given average difference. For example, a given average difference is 10, so these numbers are good: 1 3 5 9 15 51. What I do, is multiply the given average difference by 2 and add 1. Like this:

    while (i <= 50000)
    {
        i += Math.random() * givenAverageDiff * 2 + 1;
        list.add(i);
    }

But I never get 5000 or more. In fact, it's always 4,850 or less. Why? Let's say givenAverageDiff is 10. What's my mistake? How can I fix it?

P.S. Implementation in C or PHP is also good for me.

Upvotes: 2

Views: 1073

Answers (2)

Rob Watts
Rob Watts

Reputation: 7146

Think about it in terms of the ranges you create. With your current calculation,

i += Math.random() * givenAverageDiff * 2 + 1;

you are adding between 1 and 2*givenAverageDiff to your number. The sum of 1 through 2x is (2x)(2x+1)/2, and since there are 2x options we divide by 2x to get (2x)(2x+1)/(2*2x) = (2x+1)/2 = x + 0.5.

So what you want is to have 2x+1 options, which is easiest by using a range of [0,2*x]. You can get that by adding parenthesis:

i += Math.random() * (givenAverageDiff * 2 + 1);

If you want it to always increase, then you either need use a non-uniform distribution, or a uniform distribution with a smaller range. To get a range [n,2*x-n] use

i += Math.random() * ((givenAverageDiff - n) * 2 + 1) + n;

If you use a negative value for n you can widen the range, making it possible for numbers to decrease as well.

Upvotes: 1

ElKamina
ElKamina

Reputation: 7807

Because you are doing "+ 1".

Let us calculate the expected difference:

E(2*10*x+1)= 2*10*E(x)+1 = 2*10*0.5+1 = 10+1. So, on an average you will get 50000/11 numbers.

You need to pick something whose expected value is equal to 10. Change it to the following and it should work:

while (i <= 50000)
    {
        i += Math.random() * (givenAverageDiff-1) * 2 + 1;
        list.add(i);
    }

Upvotes: 1

Related Questions