gpt4 book ai didi

java - 根据百分比选择一个值

转载 作者:太空宇宙 更新时间:2023-11-04 12:47:01 25 4
gpt4 key购买 nike

我需要根据选择该值的百分比机会来选择一个值。例如:

  • 时间增量值 a 的 10%
  • 时间增量值 b 的 20%
  • 时间增量值c的30%
  • 时间增量值 d 的 40%

百分比加起来始终恰好为 100%

我遇到过几种解决方案,例如 this one ,但已确定它们不可能是正确的。以下是使用上述解决方案构建的示例程序:

import java.util.Random;

public class Main {

private static Random r = new Random();

public static void main(String[] args) {
final int iterations = 1000000;
System.out.println("Testing percentage based random, " + iterations + " iterations");
int onePercent = 0;
int sixPercent = 0;
int sevenPercent = 0;
int thirtySixPercent = 0;
int fiftyPercent = 0;
// Those values add up to 100% overall
for (int i = 0; i < iterations; i++) {
int random = r.nextInt(100);
if (random < 1) {
onePercent++;
continue;
}
if (random < 6) {
sixPercent++;
continue;
}
if (random < 7) {
sevenPercent++;
continue;
}
if (random < 36) {
thirtySixPercent++;
continue;
}
if (random < 50) {
fiftyPercent++;
continue;
}
// That can't be right because if random > 50 then nothing at all happens
}
System.out.println("One percent happened about " + (onePercent / Float.valueOf(iterations)) * 100 + "% of the time");
System.out.println("Six percent happened about " + (sixPercent / Float.valueOf(iterations)) * 100 + "% of the time");
System.out.println("Seven percent happened about " + (sevenPercent / Float.valueOf(iterations)) * 100 + "% of the time");
System.out.println("Thirty six percent happened about " + (thirtySixPercent / Float.valueOf(iterations)) * 100 + "% of the time");
System.out.println("Fifty percent happened about " + (fiftyPercent / Float.valueOf(iterations)) * 100 + "% of the time");
}
}

输出:

Testing percentage based random, 1000000 iterations
One percent happened about 0.99649996% of the time
Six percent happened about 4.9925% of the time
Seven percent happened about 1.0029999% of the time
Thirty six percent happened about 29.001299% of the time
Fifty percent happened about 14.0191% of the time

预期输出:

Testing percentage based random, 1000000 iterations
One percent happened about 0.99649996% of the time
Six percent happened about 6.9925% of the time
Seven percent happened about 7.0029999% of the time
Thirty six percent happened about 36.001299% of the time
Fifty percent happened about 50.0191% of the time

我相信我需要使用某种算法将百分比转换为从 0 到 99 的范围,以便随机数生成器可以准确地选择一个值。但我想不出如何做到这一点。

最佳答案

您的结果是正确的:

Fifty percent happened about 14.0191% of the time

50 - 36 = 14

Thirty six percent happened about 29.001299% of the time

36 - 7 = 29

Seven percent happened about 1.0029999% of the time

7 - 6 = 1

...

如果您希望总结所有“继续”语句,请删除它们。

关于java - 根据百分比选择一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36213462/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com