stan-dev / stan

Stan development repository. The master branch contains the current release. The develop branch contains the latest stable development. See the Developer Process Wiki for details.
https://mc-stan.org
BSD 3-Clause "New" or "Revised" License
2.6k stars 370 forks source link

Unexpected behaviour (to me) with declaring multiple transformed data #3307

Closed mhollanders closed 3 months ago

mhollanders commented 3 months ago

Hi,

I was working on a function where I wanted to declare multiple variables as positive_infinity() at the same time in a program called infinity.stan:

transformed data {
  real x, y = positive_infinity();
  print(x);
  print(y);
}

Running this yields the following confusing outcome, where only y is inf but x is nan. Is this expected behaviour?

> mod2<- cmdstan_model("infinity.stan")
Compiling Stan program...

> fit2 <- mod$sample(fixed_param = T)
Running MCMC with 4 sequential chains...

Chain 1 nan 
Chain 1 inf

Thanks!

Matt

WardBrian commented 3 months ago

Yes, this is expected. What you have written is equivalent to

real x;
real y = positive_infinity();

And Stan leaves un-initialized values as NaN

The syntax for declaring multiple variables of the same type at once does not allow initializing all of them to the same value while doing so, but you could write

real x = something(), y = something();

mhollanders commented 3 months ago

Thanks @WardBrian, surprisingly this issue has never caused problems before because I've been doing this for ages. Thanks, and sorry for the non-issue.