Mathematical constants

I looked at the Mathematical Constants section of the functions reference but didn’t see the Euler–Mascheroni constant.

What is best practice if I want to use it? Should I just type 0.57721?

1 Like

We don’t currently have that constant in Stan. It’s available in one of the c++ libraries that we use, so it’s a pretty easy job to expose it. I’ll open an issue in the Math library and we should be able to get it exposed for the next release.

In the interim, you can just define the constant manually in your Stan program. The data type Stan uses for numbers (c++ double) stores values to ~16 decimals. So you can just add a transformed data declaration with the constant given to >= 16 decimals, like so:

transformed data {
  real egamma = 0.57721566490153286;

Then you can just use egamma in your model

stan has the digamma function and this constant is equal to -digamma(1)

in R (since I don’t feel like exposing stan functions)

> options(scipen = -999)
> -digamma(1)
[1] 5.772157e-01

Oh that’s much cleaner, thanks Sean!

Thank you both!
I took a look at the digamma section in the functions reference guide but it didn’t have any example of usage.

I don’t know what “exposing stan functions” means, exactly, but I can use it as below?
real param1 = param2 * -digamma(1);

I don’t know what “exposing stan functions” means, exactly, but I can use it as below?
real param1 = param2 * -digamma(1);

Yep that’s fine. However, you’ll probably want to declare the constant as transformed data, otherwise the -digamma(1) will get recomputed every iteration (and transition), which will slow things down a little.

So at the start of your Stan model, declare:

transformed data {
  real egamma = -digamma(1);

Then in the rest of your model you can use:

real param1 = param2 * egamma;

Thank you :)

Having more constants for users would certainly be a nice thing to have from the math library. There we can make them constexpr to help out optimizations a bit. I have a branch of stan math that cleans some of these up, would be nice to have a few more known ones and expose them via “functions” like pi()

1 Like

If discourse had user tags yours would be “I have a branch for that” at this point haha

I can piggyback off that branch and add the other constants provided in Boost, probably over the next couple days