DGMS89 DGMS89 - 1 month ago 15
Python Question

Generating an array of random variables (positive and negative) that sum up to 1

I am trying to create a numpy array with random variables that sum up to 1, but I also want to include negative values.

I am trying:

size =(50,1)
w = np.array(np.random.random(size))

to create the array and populate with numbers (negative and positive), and this works fine.

Now I am trying to make them sum up to 1 with:

w /= np.sum(w)

But this changes my values to be all positive (eliminating the negative values).

What is the proper way to do an array like this?

Edit: I already tried random.int and random.uniform, but the problem is that those don't sum up to 1. and if I use
w /= np.sum(w)
to make sure they sum up to one, it just returns positive values.

Answer Source

Your problem isn't your normalization, it's your random generator. np.random.random always generates positive floats from (0,1). If you want negative numbers, you'll have to change that.

w = np.random.random(size)*2-1
w /= w.sum()


array([[ 0.05377353],
       [ 0.11272973],
       [ 0.00789277],
       [ 0.06874176],