Sign in to follow this  

weightedPick random function

Recommended Posts

I found this function really useful except for picking the last element, which is really really hard in comparison with the other elements, because only the number '1' in a random selection between  0 and 1 with double precision floating points can give the last element. Therefore, the probability of obtaining the last element is too low to be useful. 

var test = [0,1,2,3,4,5,6,7,8,9];for(i = 0; i< 1000000; i++){   rnd =;   if(rnd == 9)       console.log(rnd);}
PS:  The way i solved this is by adding a "dummy"(or a placeholder) element in the last place of the array. So, any suggestion for a clean solution?. Thanks in advance.

Share this post

Link to post
Share on other sites

I was thinking this same thing, and problem lies in the weightedPick implementation of using ~~ for flooring the numbers. The solution would be either your dummy entry (workaround) or better would be to use rounding by adding + 0.5 to the algorithm.


Right now it is:


return ary[~~(Math.pow(this.frac(), 2) * (ary.length - 1))];


But this would result a bit better weighting:


return ary[~~(Math.pow(this.frac(), 2) * (ary.length - 1) + 0.5)];

Share this post

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.