gpt4 book ai didi

java - 我的概率/机会系统有什么错误?

转载 作者:行者123 更新时间:2023-12-01 18:35:49 25 4
gpt4 key购买 nike

我目前正在使用机会系统来计算元素。

LootData 是一种对象类型,它存储一个被称为项目的值以及获得该“项目”的机会。

一个项目将包含一个 ItemStack(即项目)以及一个 double(即机会)。

似乎我的数学或我的代码已经关闭,因为一些机会较低的“项目”被更频繁地给出。

// Calculate total chance
double totalChance = 0;
for (LootData item: items)
totalChance += item.getChance();

for (int i = 0; i < numberOfItems; i++) {
// Select a 'random chance' from 0 to total chance
double randomChance = Math.random() * totalChance;

// Check which item the 'random chance' landed on
for (LootData item: items) {
randomChance -= item.getChance();

if (randomChance < 0) {

ItemStack stack = item.getItem().clone();
stack.setAmount((int)(Math.random() * stack.getAmount() + 1));
itemsToGive.add(stack);
break;
}

最佳答案

代码看起来不错,结果也合理。

也许存在转换问题?在不同数字类型之间切换可能会在意外位置截断值。

这是一个示例输出:

Item [  0 ] Freq [   0 ] Odds [ 0.012 ] Proportion [ 0.000 ]
Item [ 1 ] Freq [ 2 ] Odds [ 0.012 ] Proportion [ 0.020 ]
Item [ 2 ] Freq [ 14 ] Odds [ 0.122 ] Proportion [ 0.140 ]
Item [ 3 ] Freq [ 12 ] Odds [ 0.122 ] Proportion [ 0.120 ]
Item [ 4 ] Freq [ 36 ] Odds [ 0.366 ] Proportion [ 0.360 ]
Item [ 5 ] Freq [ 36 ] Odds [ 0.366 ] Proportion [ 0.360 ]

这是我写的算法和测试代码:

public class RandomTest {

public static final int[] lootChance = new int[] { 1, 1, 10, 10, 30, 30 };
public static final int totalLootChance;
static {
int total = 0;
for ( int chance : lootChance ) {
total += chance;
}
totalLootChance = total;
}

public static int lookupItem(double selection) {
for ( int lootNo = 0; lootNo < lootChance.length; lootNo++ ) {
selection -= lootChance[lootNo];
if ( selection < 0 ) {
return lootNo;
}
}
throw new IllegalArgumentException("Selection [ " + selection + " ] out of range [ " + totalLootChance + " ]");
}

public static final int lootRuns = 100;

public static void main(String[] args) {
System.out.printf("Items [ %2d ] Weighed Total [ %3d ]\n", lootChance.length, totalLootChance);
for ( int itemNo = 0; itemNo < lootChance.length; itemNo++) {
System.out.printf(" [ %2d ] [ %3d ]\n", itemNo, lootChance[itemNo]);
}

int[] distribution = new int[ lootChance.length ];

for ( int runNo = 0; runNo < lootRuns; runNo++ ) {
double selection = Math.random() * totalLootChance;
int itemSelection = lookupItem(selection);
distribution[itemSelection]++;

System.out.printf(
"Run [ %3s ] Roll [ %04.2f ] Item [ %2d ]\n",
runNo, selection, itemSelection);
}

for ( int lootNo = 0; lootNo < lootChance.length; lootNo++ ) {
System.out.printf(
"Item [ %2d ] Freq [ %3d ] Odds [ %02.3f ] Proportion [ %02.3f ]\n",
lootNo,
distribution[lootNo],
(((double) lootChance[lootNo]) / totalLootChance),
((double) distribution[lootNo]) / lootRuns);
}
}
}

关于java - 我的概率/机会系统有什么错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60047942/

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