Search code examples
cfloating-pointtrigonometryradians

Why is atan not producing the correct result?


I have the following small program which reproduces a trig error in my larger project:

#define _USE_MATH_DEFINES
#include <math.h>
#include <stdio.h>

#define R2D(trig_fn, val) trig_fn (val * (180.0 / M_PI))

int main()
{
    printf("%f\n", R2D(atan, 2.5));
    return 0;
}

The expected result of atan(2.5) converted from radians to degrees is 68.1985..., but instead, this program outputs 1.563815, which is nowhere near the correct answer.

I preprocessed this out to a file; the problem isn't in the macro which was my first guess too; the macro expands properly (atan (2.5 * (180.0 / 3.14159265358979323846))).


Solution

  • double atan(double x);
    

    Returns the principal value of the arc tangent of x, expressed in radians.

    The output is in radians, not degrees. You need to convert the result of the function to degrees. The input remains a simple unitless number.

    #define R2D(trig_fn, val) (trig_fn(val) * (180.0 / M_PI))