如何與概率例如30%
產生隨機(1
到100
)整數,如果號範圍從(1
到50
)隨機產生整數,並用概率70%
如果號範圍從( 50
至100
)?JAVA:與概率
int integer = new Random().nextInt(100) + 1;
// Probabilities
..... code here ....
我該怎麼做?
如何與概率例如30%
產生隨機(1
到100
)整數,如果號範圍從(1
到50
)隨機產生整數,並用概率70%
如果號範圍從( 50
至100
)?JAVA:與概率
int integer = new Random().nextInt(100) + 1;
// Probabilities
..... code here ....
我該怎麼做?
這是一個方法getRandom()
它返回一個符合您指定的標準的隨機數。它實際上使用0
和9
之間的一個隨機數來確定使用哪個範圍。
public int getRandom() {
Random random = new Random();
int val = random.nextInt(10);
if (val < 3) {
return random.nextInt(50) + 1; // random range 1 to 50
}
else {
return random.nextInt(51) + 50; // random range 50 to 100
}
}
這是一個通用的解決方案,將返回任意數量的事件之一,您可以在其中指定事件的相對權重。權重可能是概率,但他們不必;例如,如果您有三個事件,並且您希望第一個事件的可能性爲20%,第二個30%和第三個50%,則可以在每個事件上調用addEvent
以2,3和5作爲第二參數,或者20,30和50或者0.2,0.3和0.5,或者具有那些比率的任何其他數字組合。對於你的情況,你可以使通用參數爲間隔並添加兩個權重爲3和7(或30和70,或其他)的事件;那麼,當你打電話randomEvent
,並返回與端點m
和n
包容的間隔,那麼你在生成該區間另一個隨機數:
value = m + random.nextInt(n - m + 1);
其中random
是你自己的Random
實例。
class RandomDistribution<T> {
private class Event {
public final T event;
public final double relativeWeight;
public Event(T event, double relativeWeight) {
this.event = event;
this.relativeWeight = relativeWeight;
}
}
private double totalWeight = 0D;
private ArrayList<Event> events = new ArrayList<>();
private Random generator = new Random();
public void addEvent(T event, double relativeWeight) {
events.add(new Event(event, relativeWeight));
totalWeight += relativeWeight;
}
public T randomEvent() {
double random = generator.nextDouble() * totalWeight;
for (Event event : events) {
random -= event.relativeWeight;
if (random < 0D) {
return event.event;
}
}
// It's possible to get here due to rounding errors
return events.get(events.size() - 1).event;
}
}
重複https://stackoverflow.com/questions/20327958/random-number-with-probabilitieshttps://stackoverflow.com/questions/20327958/random-number-with-probabilities編輯:嗯這是奇怪的。 。如果你直接點擊鏈接,它會提供一個404,但它可以通過谷歌https://www.google.com/search?q=questions%2F20327958%2Frandom-number-with-probabilities&oq=questions%2F20327958%2Frandom-number- with-probabilities&aqs = chrome..69i57j69i58j69i60.5166j0j8&sourceid = chrome&es_sm = 91&ie = UTF-8 –
@MichaelJames正確的鏈接是https://stackoverflow.com/questions/20327958/random-number-with-probabilities – Andreas
這是一箇中文網站[用概率隨機生成整數](http://www.360doc.com/content/10/1208/14/2960485_76121195.shtml) –