How can I resample the random number until a given condition is met?

Viewed 54

Here's part of the code I'm working on:

def get_noise(measures, errors):
    noisy_measures = []
    for i,j in zip(measures, errors):
        added = i + np.random.normal(scale = j)
        while added < 0:
            added = i + np.random.normal(scale = j) # Question Here!
        noisy_measures.append()
    return noisy_measures

The number added is a sum of fixed number measures and a random number sampled from a normal distribution, which might be negative. I wonder how can I add some conditions to make added non-negative? I'm trying to do something marked in the code but it seems like that doesn't work.

How can I resample the random value until added is non-negative?

1 Answers

A simple possibility is to "cap" the added final value at 0 by using added = max(added, 0).

This way, you'll exactly solve your issue. However, it means that you could have a "cluster" at the value zero.

I'd recommend reducing the noise, or trying to scale down the noise on the negative side, depends on your actual model of course.

To do the other possibility, the resampling you asked for, you'll need to resample "as long at it is invalid", like this:

    for i,j in zip(measures, errors):
        added = -1
        while added < 0: 
            added = i + np.random.normal(scale = j)

        # ok, 'added' must be non-negative here

This implies the distribution will be skewed as well (of course), but maybe more "uniformly" around the measure.

Related