Search code examples
pythonpython-3.xuuid

Execute repeatable weighted coin toss based on UUID


I am generating UUID using uuid.uuidv4()

I need to execute a repeatable weighted coin toss based on that uuid and a success rate. By repeatable I mean the result should always be the same if the success rate and the uuid are the same.

This is what I came up with:

def execute_weighted_coin_toss(uuid_key, success_rate):
    # extracts only numbers from uuid to get a number from 0 to 1
    uuid_as_number = float('0.' + ''.join(filter(str.isdigit, str(uuid_key))))
    return uuid_as_number < success_rate

My question is: does that function gives uniform random distribution based on the uuid?

Final edit: I added the following test and it worked really well.



def start():
    for success_rate in range(5, 100, 5):
        trials = 1000000
        result = []
        for i in range(trials):
            result.append(execute_coin_toss(uuid_key=uuid.uuid4(), success_rate=success_rate / 100))
        actual_success_rate = (sum(result) / trials) * 100
        print(f'expected_success_rate={success_rate}%,actual_success_rate={actual_success_rate}%')


def execute_coin_toss(uuid_key, success_rate):
    as_repeatable_random_number = float('0.' + ''.join(filter(str.isdigit, str(uuid_key))))
    return as_repeatable_random_number < success_rate


if __name__ == '__main__':
    start()

Solution

  • Let's prove it using a simple Monte Carlo:

    import uuid
    
    trials = 100000
    rate = 0.6
    result = []
    for i in range(trials):
       result.append(execute_weighted_coin_toss(uuid.uuid4(), rate))
    
    print(sum(result)/trials)
    

    Answer: in short, yes