基于 UUID 执行可重复的加权抛硬币

Execute repeatable weighted coin toss based on UUID

我正在使用 uuid.uuidv4()

生成 UUID

我需要根据该 uuid 和成功率执行可重复的加权硬币抛掷。我所说的可重复是指如果成功率和 uuid 相同,结果应该始终相同。

这是我想出的:

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

我的问题是:该函数是否根据 uuid 给出均匀随机分布?

最终编辑: 我添加了以下测试,效果非常好。



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()

让我们用一个简单的 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)

回答:简而言之,是的