Non-Uniform Random Number Generator Implementation?

前端 未结 8 2055
北恋
北恋 2021-01-05 19:03

I need a random number generator that picks numbers over a specified range with a programmable mean.

For example, I need to pick numbers between 2 and 14 and I need

相关标签:
8条回答
  • 2021-01-05 19:42

    You haven't said what distribution you are after. Regarding your specific example, a function which produced a uniform distribution between 2 and 8 would satisfy your requirements, strictly as you have written them :)

    0 讨论(0)
  • 2021-01-05 19:43

    If you want a non-uniform distribution of the random number, then you might have to implement some sort of mapping, e.g:

    // returns a number between 0..5 with a custom distribution
    int MyCustomDistribution()
    {
      int r = rand(100); // random number between 0..100
      if (r < 10) return 1;
      if (r < 30) return 2;
      if (r < 42) return 3;
      ...
    }
    
    0 讨论(0)
  • 2021-01-05 19:43

    You can create a non-uniform PRNG from a uniform one. This makes sense, as you can imagine taking a uniform PRNG that returns 0,1,2 and create a new, non-uniform PRNG by returning 0 for values 0,1 and 1 for the value 2.

    There is more to it if you want specific characteristics on the distribution of your new, non-uniform PRNG. This is covered on the Wikipedia page on PRNGs, and the Ziggurat algorithm is specifically mentioned.

    With those clues you should be able to search up some code.

    0 讨论(0)
  • 2021-01-05 19:48

    My first idea would be:

    • generate numbers in the range 0..1
    • scale to the range -9..9 ( x-0.5; x*18)
    • shift range by 5 -> -4 .. 14 (add 5)
    • truncate the range to 2..14 (discard numbers < 2)

    that should give you numbers in the range you want.

    0 讨论(0)
  • 2021-01-05 19:52
    Assign all numbers equal probabilities,
    

    while currentAverage not equal to intendedAverage (whithin possible margin)

     pickedNumber = pick one of the possible numbers (at random, uniform probability, if you pick intendedAverage pick again)
    
     if (pickedNumber is greater than intendedAverage and currentAverage<intendedAverage) or (pickedNumber is less than intendedAverage and currentAverage>intendedAverage)
    
       increase pickedNumber's probability by delta at the expense of all others, conserving sum=100%
    
     else
    
       decrease pickedNumber's probability by delta to the benefit of all others, conserving sum=100%
    
     end if
    
     delta=0.98*delta (the rate of decrease of delta should probably be experimented with)
    

    end while

    0 讨论(0)
  • 2021-01-05 19:53

    Based on the Wikipedia sub-article about non-uniform generators, it would seem you want to apply the output of a uniform pseudorandom number generator to an area distribution that meets the desired mean.

    0 讨论(0)
提交回复
热议问题