random probability

fedezack's icon

Hi guys, I'd like using "random", with a range for example of 10, so that in a 80% it produces number 2. how can i do it?
thank you in advance for your answers!

Szrp's icon
Max Patch
Copy patch and select New From Clipboard in Max.

The solution depends on what kind of distribution you want of course, but a simple way in Max would be something like this:

I.e. you start with a list containing all possible numbers, with number repeated more often if you want them to appear more often. For example, if you filled the list with 100 numbers, 80 of them being a "2", then you'd get a "2" 80% of the times of banging that list.

But here's a somewhat more elegant method in javascript:

function bang()
{
var weights = [0.005, 0.05, 0.8, 0.05, 0.02, 0.02, 0.02, 0.02, 0.01, 0.005];
var weightsum = 0;
var randvar = Math.random(); // A random number between 0 and 1

for (i = 0; i
{
if (randvar>weightsum && randvar
{outlet(0, i);return true;}
else
{weightsum += weights[i];}
}
}

P.S. The "weights" array contains the chances of getting each number from 0 to 9, in this case. Here, you'd get "0", with the probability of 0.005, "1" with the probability of 0.05, "2" with the probability of 0.8, etc.

The numbers in this list must always add up to 1. The number of elements in the list determines the range of random numbers it outputs. It gives random numbers between 0 and the number of items in the list - 1.

Bas van der Graaff's icon
Max Patch
Copy patch and select New From Clipboard in Max.

And all the other numbers together make up the other 20%, evenly divided?

andrea agostini's icon

table / itable is the way to go...

say you want 0, 1, 2 to be randomly chosen 10%, 60% and 30% of the times, respectively.
just create a table with size 3 and range 100 (this is just for ease of reading, in fact you can scale the probability as you like), and fill it with 0 10, 1 60, 2 30.
now start banging the table object, and it will yield you the random values with a probability weighted as you need it.
of course, it works with itable too, and you can graphically edit your weights.

aa

fedezack's icon

thanks everybody!!

Peter Castine's icon
Max Patch
Copy patch and select New From Clipboard in Max.

For this particular case, the following is probably the tightest solution:

As always, if you're serious about random numbers, you should take a look at Litter Power.

Peter Castine's icon

PS: The Tutorials in Max4 and earlier had an exercise for building a general "bang here w/prob x%". Not sure where/if they are in Max 5 toots, but worth getting your hands on if you want some examples of how to be more flexible with the factory random objects.