randomuniform-distribution

Sample two random variables uniformly, in region where sum is greater than zero


I am trying to figure out how to sample for two random variables uniformly in the region where the sum of the two is greater than zero. I thought a solution might be to sample for X~U(-1,1) and then sample for Y~U(-x,1) where x would be the current sample for X.

But this resulted in a distribution that looks like this.

This doesn't look uniformly distributed as the density of points at the top left is higher and keeps reducing as we move to the right. Can someone point out where the flaw in my reasoning is and how to possibly fix this?

Thank you


Solution

  • You just need to make sure that adjust the density of x points away from the "top-left" corner appropriately. I'd also suggest generating in [0,1] and then transforming into [-1,1] afterwards.

    For example:

    import numpy as np
    
    # generate points, sqrt takes care of moving points away from zero
    n = 50000
    x = np.sqrt(np.random.uniform(size=n))
    y = np.random.uniform(1-x)
    
    # transform to -1,1
    x = x * 2 - 1
    y = y * 2 - 1
    

    plotting these gives:

    matplotlib output

    which looks reasonable to me. Note I've colored the [-1,1] square to show where it should fit.