www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Feature request: add degToRad and radToDeg to phobos / tango

reply Spacen Jasset <spacenjasset yahoo.co.uk> writes:
Hello,

I have a suggestion for a small feature. The reason for adding these 
conversions would be to prevent mistakes and a small utilitarian gain.

real degToRad(real deg)
{
     return deg * PI / 180;
}

real radToDeg(real rad)
{
     return (180 * rad) / PI;
}


Or as Derek Parnell sugested (although I don't understand the 
operational difference here, but the top one did originally read float 
instead of real.

enum
{
    fPI_180 = PI / 180.0L;
    f180_PI = 180.0L / PI;
}

T degToRad(T)(T deg)
{
	return cast(T)(cast(real)deg * fPI_180);
}

T radToDeg(T)(T rad)
{
	return cast(T)(cast(real)rad * f180_PI);
}


Perhaps also gradToRad etc. Or gonToRad sice the gon is meant to be the 
proper ISO unit. People don't seem to use Grad much though.
Apr 02 2008
parent Don Clugston <dac nospam.com.au> writes:
Spacen Jasset wrote:
 Hello,
 
 I have a suggestion for a small feature. The reason for adding these 
 conversions would be to prevent mistakes and a small utilitarian gain.
 
 real degToRad(real deg)
 {
     return deg * PI / 180;
 }
 
 real radToDeg(real rad)
 {
     return (180 * rad) / PI;
 }

It's not that simple. The code looks OK, and works OK if rad is less than 2*PI. But once you get to multiple revolutions, you expose the roundoff error in PI. The proper way to deal with this is with sinPi(), cosPi() (they're in Tango, not yet in Phobos) and with modPi() which I haven't yet written, but uses a high-precision value of pi. Standard libraries have a responsibility to not include code which can generate subtle errors. The correct code takes much longer to write. But it's coming.
 
 
 Or as Derek Parnell sugested (although I don't understand the 
 operational difference here, but the top one did originally read float 
 instead of real.
 
 enum
 {
    fPI_180 = PI / 180.0L;
    f180_PI = 180.0L / PI;
 }
 
 T degToRad(T)(T deg)
 {
     return cast(T)(cast(real)deg * fPI_180);
 }
 
 T radToDeg(T)(T rad)
 {
     return cast(T)(cast(real)rad * f180_PI);
 }
 
 
 Perhaps also gradToRad etc. Or gonToRad sice the gon is meant to be the 
 proper ISO unit. People don't seem to use Grad much though.

Apr 02 2008