Java: random integer with non-uniform distribution -
how can create random integer n
in java, between 1
, k
"linear descending distribution", i.e. 1
likely, 2
less likely, 3
less likely, ..., k
least likely, , probabilities descend linearly, this:
i know there dosens of threads on topic already, , apologize making new one, can't seem able create need them. know using import java.util.*;
, code
random r=new random(); int n=r.nextint(k)+1;
creates random integer between 1
, k
, distributed uniformly.
generalization: hints creating arbitrarily distributed integer, i.e. f(n)=some function
, p(n)=f(n)/(f(1)+...+f(k))
), appreciated, example: .
this should give need:
public static int getlinnearrandomnumber(int maxsize){ //get linearly multiplied random number int randommultiplier = maxsize * (maxsize + 1) / 2; random r=new random(); int randomint = r.nextint(randommultiplier); //linearly iterate through possible values find correct 1 int linearrandomnumber = 0; for(int i=maxsize; randomint >= 0; i--){ randomint -= i; linearrandomnumber++; } return linearrandomnumber; }
also, here general solution positive functions (negative functions don't make sense) along range start index stopindex:
public static int getyourpositivefunctionrandomnumber(int startindex, int stopindex) { //generate random number value ranges 0.0 sum of values of yourfunction possible integer return values startindex stopindex. double randommultiplier = 0; (int = startindex; <= stopindex; i++) { randommultiplier += yourfunction(i);//yourfunction(startindex) + yourfunction(startindex + 1) + .. yourfunction(stopindex -1) + yourfunction(stopindex) } random r = new random(); double randomdouble = r.nextdouble() * randommultiplier; //for each possible integer return value, subtract yourfunction value possible return value till below 0. once below 0, return current value. int yourfunctionrandomnumber = startindex; randomdouble = randomdouble - yourfunction(yourfunctionrandomnumber); while (randomdouble >= 0) { yourfunctionrandomnumber++; randomdouble = randomdouble - yourfunction(yourfunctionrandomnumber); } return yourfunctionrandomnumber; }
note: functions may return negative values, 1 method take absolute value of function , apply above solution each yourfunction call.
Comments
Post a Comment