Vectorizing power function

performance

#1

How can I avoid using a loop if I have to raise a power to all elements in a vector?

vector[N] x;
vector[N] y;
real a;

y = pow(x, a) // does not work as pow takes only two real numbers
y = x^a // doesn’t work either
y = exp(a * log(x)) // may fail as some x are not always positive.


#2

found an answer here:

https://groups.google.com/forum/#!msg/stan-users/Vpc_kcq0gsY/k8pief7FwxcJ


#3

Glad you found a solution.

In general, loops aren’t a problem in Stan. In your example, having a vectorized statement would only be for convenience; it wouldn’t actually make the code faster in any way.


#4

It would make it faster in the pow(real, vector) because the first parameter is shared and we can cut down on the expression graph size, but there’s no speed gain to be had in the pow(vector, vector) case.

It looks like Rayleigh is done with the pow(vector, vector) versions, but not the broadcasting ones that take pow(real, vector) or pow(vector, real).