Unexpected integer overflow

With the following model (if you can even call it that):

model {
    for(k in 1:10) {
        print(k - 10);
    }
}

The output represents what appears to be integer overflow. I am using cmdstanr_0.0.0.9008 with stan 2.23. Other relevant sessionInfo:

R version 3.6.1 (2019-07-05)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Mojave 10.14.6
Matrix products: default
BLAS:   /Library/Frameworks/R.framework/Versions/3.6/Resources/lib/libRblas.0.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.6/Resources/lib/libRlapack.dylib

To compile and run this I am doing

test <- cmdstan_model("test.stan")
test$optimize()

Thanks,
Dan

1 Like

Hi,

sorry you are having issues with this. This is a known bug that was fixed in 2.24. The index of the loop is of an unsigned type in the generated C++ in 2.23. And since there are no negative numbers in unsigned types -1 becomes max integer.
Issue where we found this: https://github.com/stan-dev/stanc3/issues/536
And PR to fix: https://github.com/stan-dev/stanc3/pull/537

1 Like

Thanks, good to know it’s no longer an issue in 2.24. I was able to work around this in 2.23 by doing - (k - 10).

1 Like

Great. The other workaround is to assign k to an int variable inside the loop and then use thar variable instead of k.