Random number with Probabilities

前端 未结 12 2231
醉梦人生
醉梦人生 2020-11-27 02:56

I am wondering what would be the best way (e.g. in Java) to generate random numbers within a particular range where each number has a certain probability to occur or not?

12条回答
  •  囚心锁ツ
    2020-11-27 03:22

    This may be useful to someone, a simple one I did in python. you just have to change the way p and r are written. This one, for instance, projects random values between 0 and 0.1 to 1e-20 to 1e-12.

    import random
    
    def generate_distributed_random():
        p = [1e-20, 1e-12, 1e-10, 1e-08, 1e-04, 1e-02, 1]
        r = [0, 0.1, 0.3, 0.5, 0.7, 0.9, 1]
        val = random.random()
        for i in range(1, len(r)):
            if val <= r[i] and val >= r[i - 1]:
                slope = (p[i] - p[i - 1])/(r[i] - r[i - 1])
                return p[i - 1] + (val - r[i - 1])*slope
    
    
    print(generate_distributed_random())
    

提交回复
热议问题