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]

GabiAugust 18th, 2009 - 16:26

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?

masterbaboonAugust 18th, 2009 - 17:34

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 ðŸ˜‰

masterbaboonAugust 18th, 2009 - 17:36

Oh wait now that I see where you work I understand ðŸ˜€ I think we met at some point when you where applying there

AnonymousAugust 19th, 2009 - 09:01

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

StevenJuly 30th, 2010 - 04:10

Thanks for that info, been of great help