How to normalize the weights of elements in an array

313 Views Asked by At

I'm trying to write a function to normalize the relative weights of elements in an array.

For example:

Input:    [1, 1]
Output:   [0.5, 0.5]
In * Out: [0.5, 0.5] == 1

Input:    [2, 1]
Output:   [0.4, 0.2]
In * Out: [0.8, 0.2] == 1

Input:    [3, 2, 1]
Output:   [0.2142, 0.1428, 0.0714]
In * Out: [0.6426, 0.2856, 0.0714] == 1

Input:    [3, 1, 1, 1]
Output:   [0.2499, 0.0833, 0.0833, 0.0833]
In * Out: [0.7497, 0.0833, 0.0833, 0.0833] == 1

The catch is: you need to be able to multiply output by input to produce a new array whose elements sum to 1.

How can I achieve this?


p.s. apologies in advance -- I am no math whiz -- so would be great to see examples in code! I'm also terribly sorry if I've voilated the tags on this question; more than happy to change them :)

p.p.s. Examples 3 and 4 catch me out, since both inputs have a [0]=3 and sum=6... so is not as simple as it first looks (to me at least!)

1

There are 1 best solutions below

1
On BEST ANSWER

Let $N$ be the sum of the squares of the inputs, then output should be the input but with each entry divided by $N $. This works because the sum of the products will be a sum of things like $a*(a/N)=\dfrac{a^2}{N}$ so you'll have (sum of squares)$/N$, which is $1$ by choice of $N $.