JuliaLang/julia — pull request #1036 by kmsquire (2012-07-11 02:06:32+00:00)
Title: Multinomial rand update

Allow rand(d), rand(d, n) to work for Multinomial distribution.

For the Multinomial distribution, one of the parameters is ```n```, the number of trials to be run. When drawing a sample from the distribution, the counts of the various items should add up to ```n```. Currently, only one sample is drawn (as with a Categorical distribution):

```julia
julia> load("base/distributions.jl")

julia> m = Multinomial(10, 3)
Multinomial(10,[0.333333, 0.333333, 0.333333])

julia> rand(m)
3-element Int64 Array:
0
1
0
```

This patch updates ```rand(d)``` to draw ```n``` samples:

```julia

julia> load("base/distributions.jl")

julia> m = Multinomial(10, 3)
Multinomial(10,[0.333333, 0.333333, 0.333333])

julia> rand(m)
3-element Int64 Array:
2
5
3
```

Also, ```rand(d, size)``` throws an error:

```julia

julia> rand(m, 3)
no method convert(Type{Int64},Array{Int64,1})
in method_missing at base.jl:60
in rand! at /home/kmsquire/src/julia/base/distributions.jl:33
in rand at /home/kmsquire/src/julia/base/distributions.jl:37
```

This patch updates ```rand(d, n)``` to allow a scalar ```n```:

```julia

julia> rand(m, 4)
3x4 Int64 Array:
2 3 5 2
3 0 4 2
5 7 1 6
```

Note that rand!(d, Matrix{Int}) previously existed, but
# didn't work with rand(d, n)
# placed the sample output in rows

In contrast, this patch places the sample output in columns. While this choice is somewhat arbitrary, it was motivated by the fact that julia uses column-major indexing.

Some thoughts/questions:
* Most (all?) distributions allow output arrays with arbitrary dimensions. Multinomial is different in that it's default output is a vector. Should we allow arbitrary dimensional outputs? If so, should the count vectors be the first or last dimesion? My preference is first, since we're working with column-major order, although it does get a little confusing. (This is probably why the existing rand!(d, Matrix{Int}) implementation only allowed 2 dimensions, where one was the vector of counts.)

Please comment.

Thanks,
Kevin