Question

So I am working with some matlab code converting to c code by hand. I am just wondering if there is a c equivalent to the sind and cosd functions I'm seeing in the matlab code. I guess this returns the answer in degrees rather than the c sin and cos function that gives the result in radians. I guess I could just multiply the result by 180/pi but was just wondering if there was a library function in math.h I'm not seeing. Or even if there is something in the gsl library that does that.

Était-ce utile?

La solution

H2CO3's solution will have catastrophic loss of precision for large arguments due to the imprecision of M_PI. The general, safe version for any argument is:

#define sind(x) (sin(fmod((x),360) * M_PI / 180))

Autres conseils

No, the trigonometric functions in the C standard library all work in radians. But you can easily get away with a macro or an inline function:

#define sind(x) (sin((x) * M_PI / 180))

or

inline double sind(double x)
{
    return sin(x * M_PI / 180);
}

Note that the opposite of the conversion is needed when you want to alter the return value of the function (the so-called inverse or "arcus" functions):

inline double asind(double x)
{
    return asin(x) / M_PI * 180;
}

No, they are not available in C library. You will only find radian value arguments or return values in C library.

Also, note that sind and cosd etc do not return a result in degrees, they take their arguments in degrees. It is asind and acosd that return their results in degrees.

Not in the C library. All trigonometric C library functions take arguments as radian values not degree. As you said you need to perform the conversion yourself or use a dedicated library.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top