Modulus function for real / vector


before I write some code to do this manually, I thought I would double check:

does stan currently support modulus arithmetic for real valued variables?

For example, in R I can write:

5.2 %% 2

And I get an answer of 1.2

The stan operator appears to be %, and only works on ints. Is this correct?


This is correct. To support real numbers (in particular, parameters of the model) we would need to be able to take the derivative with respect to a % b which is undefined when b divides a. We have a few functions with misbehaved derivatives, but not any quite that bad I think

Thanks for the reply.

In my case, I am only using this function to create my predictor features when I come to compute generate quantities.

On the off chance that can point to a more sophisticated solution:

my model uses the angle between two vectors as a feature vector. When model fitting, I can calculate during pre-processing in R.

I am now adding an extensive generated quantities block and will be having to calculate these angular differences “on the fly” in Stan.

my code currently looks like this: (note that the last line is still R,… I am still in the process of working out how to convert this into Stan!)

// angle from item Q[jj-1] to each other item
psi_j = atan2((item_y[t] - item_y[t][Q[jj-1]]), (item_x[t] - item_x[t][Q[jj-1]])) * 180 / pi();

// now subtract the angle from Q[jj-2] and Q[jj-1]
psi_j = psi_j - atan2((item_y[t][Q[jj-1]] - item_y[t][Q[ jj-2]]), (item_x[t][Q[jj-1]] - item_x[t][Q[jj-2]])) * 180 / pi();
// now I want to scale psi_j to go from 0 to pi.
// 0 indicates that we are going forward... both vectors are going in the same direction!
// pi/2 means we have turned a right angle, either left or right.
// pi means that we are doubling back on ourself.
for (tt in 1:n_targets) {
    psi_j[tt] = pmin(abs((psi_j[tt] % 360)), abs((-psi_j[tt] % 360)))/180;