技术专家Austin Seipp通过分析指出,使用模运算符(r % n)来选择随机对象存在隐藏的数学缺陷1。这种常见做法无法保持底层均匀分布,导致不同选项被选中的概率不相等1。具体来说,从10个均匀分布的输入值中使用r % 3进行选择时,对象1被选中的概率为40%(4个输入),而对象2和3的概率各为30%(3个输入),而非预期的均等33%1。
为解决这一问题,Seipp建议采用更高级的API设计方法1。他推荐使用random_choice()函数接收离散选项及其对应的概率,并采用相对整数权重而非浮点数来实现加权随机选择,例如使用权重4、3、3而非0.4、0.3、0.31。Seipp的团队在Antithesis模糊测试平台中实践了这一改进,通过加权选择来控制测试覆盖率,例如分配88%的测试用例进行小文件上传,各分配4%进行中等、大型和超大文件上传1。Seipp强调,在操作随机变量时需要理解其数学域,因为非线性操作不能保持期望值E[f(X)] = f(E[X])的性质1。他所在的团队已将所有不必要的random_u64()调用替换为加权随机选择1。
Austin Seipp has identified a critical flaw in a common programming practice: using the modulo operator to select random objects from a set 1. When developers apply the expression r % n to choose among n items, the underlying uniform distribution is not preserved, resulting in unequal selection probabilities 1. For example, extracting three options from ten uniformly distributed input values using r % 3 causes the first object to be selected 40 percent of the time (four inputs), while the second and third objects are each chosen only 30 percent of the time—departing significantly from the expected 33 percent probability for each 1.
To address this limitation, Seipp recommends advancing API design through explicit probability distributions and relative integer weights 1. Rather than relying on floating-point probabilities, developers should employ a random_choice() function that accepts discrete options alongside their weights expressed as integers—for instance, weights of 4, 3, and 3 rather than 0.4, 0.3, and 0.3 1. The underlying principle is that non-linear operations on random variables cannot preserve expected values according to the mathematical relationship E[f(X)] = f(E[X]) 1. The Antithesis fuzzy testing platform has implemented this weighted selection approach in practice, controlling test coverage with distributions such as 88 percent small file uploads alongside 4 percent allocations each for medium, large, and extra-large files 1. Seipp's team has removed unnecessary random_u64() calls from their codebase in favor of this weighted random selection methodology 1.
评论
还没有评论,欢迎留下第一条。