3

I want to use boltzmann constant in my functions. I am using the following code to declare the boltzmann constant

const double boltzmann_constant = 1.3806503 * pow (10,-23);

Will this get calculated at the compile time itself? If now, how should i ensure that it does get calculated at compile time? Any other method to declare the constant?

3
  • 1
    I think it will be compile time in c++0x as it will make use of constexpr Commented Jun 16, 2011 at 7:31
  • ohk.... are c++0x standards still changing? last i read.. there was no guarantee that features would be preserved in the final standard... if constexpr stays in the final feature.. i might as well start using it in my production code.. not exactly in this case but in similar cases? what do you think? Commented Jun 16, 2011 at 16:14
  • I am not sure if math functions will be made constexpr or there will be a seperate set of functions returning constexpr values. But I can't think of why it should not be made so. You might consider asking this as another question. Commented Jun 17, 2011 at 14:51

1 Answer 1

4

The pow() function is very unlikely to be calculated at compile time. However, the operation requested is directly expressible in scientific notation, a standard aspect of floating point numbers:

const double boltzmann_constant = 1.3806503e-23;

For a more complex situation, like sin(M_PI / 3), it can be useful to write a program to calculate and display such values so they can be edited into a program. If you do this, do everyone a favor and include a comment explaining what the constant is:

const double magic_val = 0.8660254037844385965883; // sin(M_PI / 3);
Sign up to request clarification or add additional context in comments.

7 Comments

ohk... thanks... i was not sure about the floating point notation... thank you
0.86602540423628734624386 may not be same as sin(M_PI / 3); due to rounding errors.
@balki: I used a low precision hand calculator originally. I have now updated the value to be accurate (though the value displayed is hardly the point of my answer).
It is not about precision. Its about portablity. Sin(pi/3) will work in any compiler/architecture but 0.8660254037844385965883 may be too precise or less precise. If you are using another compiler which has a better precision and the code relies on this value to be equal to that, there is a potential bug.
@balki: An excellent point! In my 40 or so years working with floating point there has been no notable change how precision works, so I tend to think that 16+ significant digits will always be good enough.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.