Generate Random Weighted value

前端 未结 6 1459
隐瞒了意图╮
隐瞒了意图╮ 2020-12-28 10:19

Edit: I\'ve rewritten the question in hopes that the goal is a little clearer.

This is an extended question to this question here, and I really like

6条回答
  •  别那么骄傲
    2020-12-28 10:28

    First you need to characterize your current random number generator. In the case of PHP, the rand() function returns a nice flat profile - so there's no pre-processing required.

    The remap the output distribution function so the area under it is unity and the range starts at 0. Then calculate its integral. Store the integral (e.g. as an array of values). Then when you need a random number matchnig the profile, first get a random number between 0 and 1 from the built-in generator, then find the Y coordinate on the integral where the X coordinate is the value you generated. Finally, scale the value to the desired range (e.g. if looking for a value between 0 and 10, multiply by 10, if looking for a value between -8 and +8, mutliply by 16 and subtract 8).

    If your random number generator does not generate a flat profile, then the simplest approach would be to convert it to a flat profile using the reverse of the method above.

提交回复
热议问题