Integer division gives different result for / and %/%

When I run the following little Stan program

data {}

transformed data {
  int NP = 22;
  int d1 = (NP*(NP-1)) %/% 2;
  int d2 = NP*(NP-1) %/% 2;
  int d3 = (NP*(NP-1)) / 2;
  int d4 = NP*(NP-1) / 2;
}

parameters {}

model {
  print([d1,d2,d3,d4]);
}

I get the following printed

[231,220,231,231]

I wold have expected the same result for all four cases, or the same result for d2 and d4. But I’m happy t be told that this result is correct (it’s easy enough to circumvent).

I’m using cmdstan v2.33.1 and cmdstanr. Code to run:

mod$sample(fixed_param = TRUE,
           iter_warmup = 0,
           iter_sampling = 1,
           chains = 1)
1 Like

This is the documented behavior: integer division takes precedence in the order of operations over both multiplication and division.

Huh, while it does appear to be intentional this does seem like it would violate the principle of least surprise.

3 Likes