No functions for converting between radians and degrees?


Thought it was curious to not see math utilities for converting between radians and degrees in JUCE itself, but the functions for doing so exist in the JavaScriptEngine's MathClass!


An usual (C-style) convenient way to do that is to have both a RAD2DEG and a DEG2RAD floating-point constants, and to multiply with the according one for converting between both. For instance:

float d = r * RAD2DEG;

You might want to use the C++-style option which consists of defining an Angle wrapper class with conversion utility, or create both a Degree and a Radian wrapper structure with implicit conversion methods (or mix all these options…).


Sure, you could do any of those things! The class route sounds like a lot more work to achieve this sort of thing, though.

I would argue that simple global functions would make the code more readable than using constants (which the compiler is very likely to make when optimising the following):

static double radiansToDegrees (double rads) noexcept { return (180.0 / double_Pi) * rads; }
static double degreesToRadians (double degs) noexcept { return (double_Pi / 180.0) * degs; }

static float radiansToDegrees (float rads) noexcept { return (180.0f / float_Pi) * rads; }
static float degreesToRadians (float degs) noexcept { return (float_Pi / 180.0f) * degs; }


Saw my suggestion make it in - cheers, Jules!





/** Converts an angle in degrees to radians. */
template <typename FloatType>
FloatType degreesToRadians (FloatType degrees) noexcept  { return degrees * static_cast<FloatType> (double_Pi / 180.0); }

^ I don't like to look of this... It's going to generate some unintuitive behaviour.

float theta = degreesToRadians(45); // 0

float theta = degreesToRadians(45.f); // 0.785398185

Maybe better to have a separate float and double implementation...



You'd get a compiler warning about the cast from float to int if you call it with an int parameter and assign the result to an int. But yes, point taken, I might change it.


.. but no warning if the result is assigned to a float or double, which it will usually be.  I can't imagine any scenario where I might want radians as an integer!

I think there is some hideous proxy pattern that allows you to return a different value depending on the type it is going to be cast back to. Which shows it is possible to overcomplicate anything in C++.

Nowadays in my code I usually phrase these kind of functions is the other way round e.g. 'radiansFromDegrees(45)' as it saves my mind having to skip backwards momentarily... I think working in ObjC is what did it.

I suppose `45 * RADIANS` would brain-parse most cleanly.