Master Baboon The sea of the simulation

21Feb/095

Advanced math functions for AS3

Did you ever need to sample from a Dirichlet distribution in Actionscript 3.0? What about computing a value of the Gamma function? Probably not 😉 In case you did, I wrote a class with a few math methods:

  • a function to sample from multinomial distributions; this is useful if you need to choose randomly from a set of elements, each with a different probability;
  • functions to draw samples from the Dirichlet and Gamma distribution;
  • the Gamma function
  • a factorial function that works even for large values (using the identity n! = Gamma(n+1))
  • other utility functions, e.g. to compute mean and variance of an array, or add two arrays together

You can download the AdvancedMath class here, it includes AsUnit tests.

This is an example of how to use the AdvancedMath class to simulate a rigged dice: the code below throws the dice 1000 times, and keeps a count of how many times one gets the different faces.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import com.masterbaboon.AdvancedMath;

// probability of the faces; 6 is about twice more likely to appear
var p:Array = [0.14, 0.14, 0.14, 0.14, 0.14, 0.3];
           
// count the number of times a face appears
var count:Array = AdvancedMath.zeros(6);
           
// throw dice 1000 times
var face:int;
for (var i:int = 0; i < 1000; i++) {
    face = AdvancedMath.sampleMultinomial(p);
    count[face]++;
}
           
// show how many times we got which face
trace(count);

[ad#adpost]

Facebook Twitter Email
Comments (5) Trackbacks (0)
  1. Hey,

    Thanks for writing this code — I was actually in need of sampling from a Dirichlet in AS 3.0 :)
    I’m writing code to sample a distribution given the entropy in AS 3.0 as well, I can send it to you if you want.

    Also, would you like me to reference you any way in my Flash app or the code?

  2. Hi Gabi! I thought the intersection of people programming in AS3 and people that need to sample a Dirichlet would only contain me, but I’m happy of being in good company. Thanks for contributing the code, if you send it to me I’ll make sure to add it to the library (baboon #AT# masterbaboon #DOT# com). I was playing with the idea of expanding it and making it a project on google code, maybe there are more of us around…
    You don’t need to reference me or the code, but if you do put a node somewhere I won’t complain 😉

  3. Oh wait now that I see where you work I understand 😀 I think we met at some point when you where applying there

  4. Wait, what? we met? when? where? drop me an email about it?

  5. Thanks for that info, been of great help


Leave a comment

No trackbacks yet.