`rand()` vs. `rand.()`?

x .= rand() is equivalent to broadcast!(identity, x, rand()), so rand is called only once.

x .= rand.() is equivalent to broadcast!(rand, x). So (in 0.6), rand() is called once for each element of x.

The nice thing about the latter is that you can do vectorized operations with random numbers without requiring a temporary array to fill with rand(n) or rand! first. For example, x .+= y .* rand.() occurs entirely in-place in a single loop, adding a random fraction of each element of y to each element of x. (Or equivalently, you can do @. x += y * rand() in 0.6, allowing you to omit all of the dots.)

8 Likes