Mathematical Constants in C++

A little-known feature of C++ is that the cmath library actually provides many mathematical constants that you can make use of in your quantitative finance programs.

To include the mathematical constants, you need to use a #define macro called _USE_MATH_DEFINES and add it before importing the cmath library:

#define _USE_MATH_DEFINES
 
#include <cmath>
#include <iostream>
 
int main() { 
  std::cout << M_PI << " " << M_E << " " << M_SQRT2 << endl;
  return 0;
}

There are quite a few constants on offer. See if you can spot the ones that will be useful in quantitative finance:

Mathematical Expression C++ Symbol Decimal Representation
pi M_PI 3.14159265358979323846
pi/2 M_PI_2 1.57079632679489661923
pi/4 M_PI_4 0.785398163397448309616
1/pi M_1_PI 0.318309886183790671538
2/pi M_2_PI 0.636619772367581343076
2/sqrt(pi) M_2_SQRTPI 1.12837916709551257390
sqrt(2) M_SQRT2 1.41421356237309504880
1/sqrt(2) M_SQRT1_2 0.707106781186547524401
e M_E 2.71828182845904523536
log_2(e) M_LOG2E 1.44269504088896340736
log_10(e) M_LOG10E 0.434294481903251827651
log_e(2) M_LN2 0.693147180559945309417
log_e(10) M_LN10 2.30258509299404568402

Note that it is not best practice within C++ to use #defines for mathematical constants! Instead, as an example, you should use const double pi = 3.14159265358979323846;. The #defines are a legacy feature of C.

comments powered by Disqus

Just Getting Started with Quantitative Trading?

3 Reasons to Subscribe to the QuantStart Email List:

No Thanks, I'll Pass For Now

1. Quant Trading Lessons

You'll get instant access to a free 10-part email course packed with hints and tips to help you get started in quantitative trading!

2. All The Latest Content

Every week I'll send you a wrap of all activity on QuantStart so you'll never miss a post again.

3. No Spam

Real, actionable quant trading tips with no nonsense.