Take a Chance

Recently (and four years ago when I first wrote the draft for this post in November 2007), I needed a function that had an x in y chance of returning true. Some quick googling turned up nothing (I don’t even know what you would call this). After some trial and error I came up with this:

function chance(x, y)
    // return Math.ceil(Math.random() * y) <= x;
    return Math.random() <= x/y;

Which in my testing behaves as intended. chance(1, 32); has an approximately 3% chance of returning true. chance(99, 100); has an approximately 99% chance of returning true.

Hopefully this will save someone else some unnecessary head-scratching.

Update K.M. points out that Math.random() returns a number between 0 (inclusive) and 1 (exclusive) so the Math.ceil() is unnecessary.

A Treatise on Touch
Past Ats
Shaun Inman
August 24th, 2011 at 12:31 pm