Fabio Lamanna
Fabio Lamanna

Reputation: 21552

Iteratively subtract values in array

Starting from a simple numpy array like:

a = np.array([1,1,0,2,1,0])

my goal is to iteratively subtract values from this till a certain threshold. For instance, think of a including number of users. In this case 5 users are distributed with:

d = a/a.sum()

Now I want to subtract 4 users at the time from this initial distribution, keeping always values > 0 in the resulting array. I can construct a random array to subtract with:

b = np.random.multinomial(4,d)

that generates (in a single run):

array([0, 1, 0, 3, 0, 0])

The result like a-b leads to:

array([ 1,  0,  0, -1,  1,  0])

How can I constraint that the generated array never produces a negative value in the resulting (a-b) operation? So far I thought in doing the things from the other side, generating a random distribution of:

r = np.random.multinomial(total users - deleted users,d)

according to the initial distribution of users d, but since I have to apply some metrics on the vector, results might vary in the latter approach.

Upvotes: 1

Views: 376

Answers (1)

Daniel F
Daniel F

Reputation: 14399

If you want to randomly decrement a.sum() by n without any element of a becoming negative, this is one way to do it:

def rnd_decrement(a, n):
    c = np.cumsum(np.r_[0, a])
    if n < c[-1]:
        r = np.random.choice(np.arange(c[-1]) + 1, n, replace = False)
        d = np.sum(r[:,None] <= c[None,:], axis=0)
        return np.diff(c-d)
    else:
        return np.zeros_like(a)

Upvotes: 2

Related Questions