Don’t forget the brackets

I have been helping a user who found some discrepancies between the results from JAGS and OpenBUGS. Such problems always concern me and I give them high priority. In this case, there were several differences in parameterizatino between the JAGS and OpenBUGS models. Among them, the JAGS model included this line:

prec[g] <- 1.0 / sigma[g]*sigma[g]

Most users will recognize the calculation as a transformation from a standard deviation (sigma) to a precision parameter (prec). It is common practice to define a prior on standard deviation and then transform it to the precision parameter required by the dnorm distribution. Unfortunately, this expression is incorrect. To understand why you need to know something about operator precedents.

Like all other languages, operators in JAGS has built-in precedence. For example, multiplications (*) and divisions (/) are carried out before additions (+) and subtractions (-). The multiplication and division operators have the same precedence and when they appear in the same expression they are evaluated from left to right. So in the above expression  JAGS first divides 1.0 by sigma[g] and then multiplies it by sigma[g]. The two operations cancel out so the relation that defines prec[g] is equivalent to

prec[g] <- 1.0

In a small model the consequences of this should be easy to spot. Since the value of sigma[g] has no influence on any other node, its posterior distribution is the same as the prior. Spotting this requires the user to monitor sigma[g] and in a large model with many sigma parameters it might be easy to miss this step.

The solution of course is to put brackets in the expression so that the order of evaluation is clear

prec[g] <- 1.0 /( sigma[g]*sigma[g])

Do not hesitate to do this. Brackets are never harmful (provided you put them in the right place, of course).

The standard-deviation-to-precision transformation is such a common practice that I am now wondering how much code is out there that repeats this simple error. It would be helpful for JAGS to raise some kind of “red flag” to the user in cases such as this.

Advertisements

One thought on “Don’t forget the brackets

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s