用ArrayList重新实现权重随机类

This commit is contained in:
wangyefeng
2024-09-16 17:31:35 +08:00
parent 7e83369205
commit 8586d7f60b
2 changed files with 185 additions and 0 deletions

View File

@@ -0,0 +1,49 @@
package cn.hutool.core.lang;
import cn.hutool.core.util.RandomUtil;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class WeightListPoolTest {
@Test
public void weightRandomTest() {
Map<Integer, Times> timesMap = new HashMap<>();
int size = 100;
double sumWeight = 0.0;
WeightListPool<Integer> pool = new WeightListPool<>(size);
for (int i = 0; i < size; i++) {
double weight = RandomUtil.randomDouble(100);
pool.add(i, weight);
sumWeight += weight;
timesMap.put(i, new Times(weight));
}
double d = 0.0001;// 随机误差
int times = 100000000;// 随机次数
for (int i = 0; i < times; i++) {
timesMap.get(pool.random()).num++;
}
double finalSumWeight = sumWeight;
timesMap.forEach((key, times1) -> {
double expected = times1.weight / finalSumWeight;// 期望概率
double actual = timesMap.get(key).num * 1.0 / times;// 真实随机概率
assertTrue(Math.abs(actual - expected) < d);// 检验随机误差是否在误差范围内
});
}
private static class Times {
int num;
double weight;
public Times(double weight) {
this.weight = weight;
}
}
}