Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

kotlin - Get boolean distributed by a given discrete probability

I currently have a discrete probability that I calculated earlier. I'm getting it like this, so it's just a straightforward double between 0 and 1, which describes the possibility that a certain event will happen. The higher the level, the lower the probability is for this event to actually take place.

val chanceOfLosingDura = 1/(unbreakingLevel+1)

I now need a boolean, and every time my code is called, a new one should be generated. The probability for it to be true should be chanceOfLosingDura.

I know how to basically approach this. I could just get a list of 100 booleans, of which chanceOfLosingDura * 100 will be true, and otherwise false, and then draw a random element of that list. However I'm pretty sure that there's a cleaner way to do this in Kotlin, am I right?

question from:https://stackoverflow.com/questions/65933640/get-boolean-distributed-by-a-given-discrete-probability

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The simplest solution would be to generate a random value between 0 and 1 and check if it's greater than chanceOfLosingDura:

val random = Random(System.currentTimeMillis())
...
val value = random.nextDouble(1.0) > chanceOfLosingDura

It's not 100% accurate, but maybe good enough. When I run it 100000 times for chanceOfLosingDura == 0.9, I got 10008 times true, i.e probability of false was 0.89992


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...