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.


Vectorized power
#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).


#5

Have there been any updates on this? Particularly, I’m looking for pow(real, vector) (or maybe pow(real, real[]) would be technically more correct).
I thought because exp() seems to work with both vectors and arrays, using any other base would just follow the same rules (and apparently some fields decided that GLMs should have base 2 for the link function).
Thanks.


#6

See: https://github.com/stan-dev/math/pull/603

But it only does pow(vector, vector) so far. I want to wait until it could handle the broadcasting case of pow(real, vector) and pow(vector, real).