Skewing java random number generation toward a certain number

前端 未结 2 2047
陌清茗
陌清茗 2021-01-04 13:29

How, in Java, would you generate a random number but make that random number skewed toward a specific number. For example, I want to generate a number between 1 and 100 inc

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-04 13:46

    Try http://download.oracle.com/javase/6/docs/api/java/util/Random.html#nextGaussian()

    Math.max(1, Math.min(100, (int) 75 + Random.nextGaussian() * stddev)))
    

    Pick a stddev like 10 and play around until you get the distribution you want. There are going to be slightly more at 1 and 100 though than at 2 or 99. If you want to change the rate at which it drops off, you can raise the gaussian to a power.

提交回复
热议问题