Global constants

What is the best (readable, performant) way to store global constants?

For example I want to store the Boltzmann constant in a central place and then use it across my package.

The compiler would be able to fill this in before running the code so it wouldn’t suffer any performance loss, but what is the best way to do this?

Do you mean across a module? If so, it’s simply this:

module MyPackage

const boltzmann_constant = 1.380649e-23 # joules per kelvin

# The rest of the package code

end

Maximum performance is guaranteed, in the sense that whenever you type boltzmann_constant in the rest of the module, the performance is indistinguishable from literally typing 1.380649e-23 again.

Are you aware of PhysicalConstants.jl and Unitful.jl ?

4 Likes

Sorry, I mean across multiple modules.

For example I have a package like this:

Module1
Module2
Module3

And each of them need the same constants. I guess the best way is to make a fourth module Constants purely for constants and import them directly?

Yes, thanks!

Perhaps Constants · DynamicQuantities.jl would be even better? (I am not really sure how to compare them yet)

Yes, that’ll work.

Well, your initial question was where to put constants - to my understanding, as long as they are defined as const, that doesn’t really matter. Defining them on your own in a separate module, or in each module, or importing them from one of the specialized packages - all that is fine.

Another question was whether your work with “naked” or unitful numbers. For myself it wouldn’t be a question: Since I learned Unitful.jl, I’d never start a physical calculation with “naked” numbers. First, because I can use the data exactly in the units they were measured in - be it °C, Torr, or whatever. Second, because using unitful values helps me catch a substantial proportion of errors.

Now, whether Unitful.jl or DynamicQuantities.jl (or none). The second one is a younger package and I never used it yet. Unitful.jl can cause substantial overhead in certain circumstances, and was in my experience incompatible with some differential equations package (in which case I made all preliminary calculations with unitful values, then converted them to SI using upreferred, and then stripped units before passing them further). DynamicQuantities.jl. might be more compatible.

Now, what’s better for you? - try it, or tell us more about your problem.

1 Like