Search code examples
cmath.h

Why does math.h define pi, pi/2, 2/pi but not 2*pi?


This is a really simple question: Why are there predefined constants for pi, pi/2, pi/4, 1/pi and 2/pi but not for 2*pi? Is there a deeper reason behind it?

This question is not about the whole pi vs tau debate. I am wondering if there is a technical reason for implementing certain constants but not others. I can think of two possibilities:

  1. Avoiding rounding errors.
  2. Avoiding runtime divisions which might be more expensive.

Solution

  • This is just my guess.

    I suppose that these constants are related to the implementations of different functions in the math library:

    ck@c:~/Codes/ref/glibc/math$ grep PI *.c
    s_cacos.c:  __real__ res = (double) M_PI_2 - __real__ y;
    s_cacosf.c:  __real__ res = (float) M_PI_2 - __real__ y;
    s_cacosh.c:                    ? M_PI - M_PI_4 : M_PI_4)
    ...
    s_clogf.c:      __imag__ result = signbit (__real__ x) ? M_PI : 0.0;
    s_clogl.c:      __imag__ result = signbit (__real__ x) ? M_PIl : 0.0;
    ck@c:~/Codes/ref/glibc/math$ 
    

    M_PI, M_PI_2, and M_PI_4 show up quite often but there's no 2.0 * M_PI. So to Hanno's original question, I think MvanGeest is right --- 2π is just not that useful, at least in implementing libm.

    Now about M_PI_2 and M_PI_4, their existences are well justified. The documentation of the GNU C library suggests that "these constants come from the Unix98 standard and were also available in 4.4BSD". Compilers were not that smart back at that time. Typing M_PI/4 instead of M_PI_4 may cause an unnecessary division. Although modern compilers can optimize that away (gcc uses mpfr since 2008 so even rounding is done correctly), using numeric constants is still a more portable way to write high performance code.