I do understand why we have this in standard headers:
#define M_PI 3.14159265358979323846 // pi
However, I don't see much benefit in having these:
#define M_PI_2 1.57079632679489661923 // pi/2
#define M_PI_4 0.785398163397448309616 // pi/4
#define M_1_PI 0.318309886183790671538 // 1/pi
#define M_2_PI 0.636619772367581343076 // 2/pi
Is there any advantage in using these instead of M_PI/2
, M_PI/4
, 1/M_PI
and 2/M_PI
in actual code? (In 2020 and beyond?)
Aren't the spelled-out expressions much more readable?
I'm asking for a couple of reasons really.
Firstly, one day I accidentally mixed up M_PI_2
and M_2_PI
(and maybe even 2 * M_PI
). Took a while to figure out something was wrong, and after that took another while to find out what exactly was the root cause. Still think it's not super obvious what M_PI_2
and M_2_PI
mean, if you are just reading code using them and don't see the definitions. And why should I memorize something like that? So, is it safe to say that using these definitions is actually an anti-pattern that degrades code readability?
Secondly, having these definitions available may still be an issue, e.g. in Windows (Visual C++). Instead of defining all these, I'd prefer to define only M_PI
, and then say M_PI/2
and not M_PI_2
in the code. Is there something I'm missing?
Because 2 and 4 are powers of two, M_PI_2
and M_PI_4
really are redundant and 100% equivalent to M_PI/2
and M_PI/4
. However, M_1_PI
is not necessarily equivalent to 1/M_PI
; the latter has two roundings (approximation of pi, then inexact division) rather than just one (approximation of 1/pi).