开发者

Calculating value based on weighted percentage chance

I am writing a program in which I need to get a random value based on weighted chances and am having real difficulty. An example of what I need to do:

a = 50%, b = 30%, c = 1开发者_C百科0%, d = 10%

In this example, I need to be able to get a random value, a,b,c or d, with the value coming back being as 'a' 50% of the time, b 30% of the time, etc...

Many thanks


Assign each value a range of numbers between 0 and 1 based on the chance it should appear. For example, A should be 0 to .5, since it needs a 50% chance. Then, get a random number between 0 and 1. Whichever value's range the random number falls into is the value you get.

A = [0, .5)
B = [.5, .8)
C = [.8, .9)
D = [.9, 1)

Random number is [0,1)

[ = inclusive, ) = exclusive.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜