Take the 2-minute tour ×
Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. It's 100% free, no registration required.

I need a formula which will fill an array of X slots with values (from $0$ to $1$). The sum of all array values should be $1$. The values should look like this:

^
|
|
|
0.2
|
|
|         .....
|      ..       ..
|    .             .
|  .                 .
| .                   .
|.                     .
|.                     .
+------------------------array-slot->

Which means that for an array of size 7 I'd approximatelly want something like:

i[0]=0.09
i[1]=0.14
i[2]=0.17
i[3]=0.20 
i[4]=0.17
i[5]=0.14
i[6]=0.09

which add to exactly $1$ and look like gaussian (or something).

Accuracy is not very important but I'd like it to sum to $1$ and not look linear.

thanks

share|improve this question

3 Answers 3

Just use the binomial probability density for $p=1/2$ and $n$ equal to the size of your array minus 1.

share|improve this answer
    
Could you just show me a formula which will do that? I'm not a mathematician. –  cherouvim Feb 19 '11 at 17:43
    
The formula is on the page I linked to. –  Raskolnikov Feb 19 '11 at 18:23
    
Doesn't really help me since my maths knowledge is not in good shape. Thanks anyway. –  cherouvim Feb 20 '11 at 7:20

Let's f(x) = a . exp((x-b)²/(2.c²)) with :
- a having any value (explained later)
- b = (n-1)/2
- c having any value (proportional to n would make sense though)

Then :
int sum=0;
for (int i=0; i smaller than n; i++)
{
a[i] = f(i);
sum+=a[i];
}
for (int i=0; i smaller than n; i++)
{
a[i]/=sum;
}

I haven't tried but it seems to make sense. Maybe there'll be a problem of offset but you'll see it when testing.

share|improve this answer
    
Thanks. I used the sum and divide to normalize the values. –  cherouvim Feb 20 '11 at 7:26
up vote 0 down vote accepted

I used a good old sine implementation for this which solved my problem.

public static double[] getProbabilities(int size) {
    double[] result = new double[size];
    double sum = 0;
    for (int i = 0; i < size; i++) {
        result[i] = Math.sin((i+1)/((double)size+1) * Math.PI);
        sum+=result[i];
    }
    for (int i = 0; i < size; i++) {
        result[i] /= sum;
    }
    return result;
}

The first loop assigns values and also calculates the sum. The second loop normalizes all values so the end sum is 1.

For size 7 it produces:

0.07612046748871325
0.140652283836026
0.18377106498543178
0.198912367379658
0.18377106498543178
0.140652283836026
0.07612046748871326

Which is symetrical, adds up to 1 and looks like the graph I mentioned in my question.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.