5
votes

I am attempting to convert a negative angle (in degrees) to positive. But I am getting a compile error saying:

test.cpp invalid operands of types 'double' and 'int' to binary 'operator%'
test.cpp invalid operands of types 'float' and 'int' to binary 'operator%'

My code:

double to_positive_angle(double angle)
{
   return ((3600000 + angle) % 360);
}

float to_positive_angle(float angle)
{
   return ((3600000 + angle) % 360);
}

Its obviously because I am trying to use the Modulus operator on a Float and Double.

Are the any ways I can successfully convert a negative angle (float) to a positive one (float)? Or ways that I can overcome the modulus compile error?

4
Your angle is in degrees, correct? - Alan
why are you adding 3600000 to the angle? - Alan
He is adding 3600000 because that is a multiple of 360, one rotation, and it will turn most negative angles (>= -3600000) into a positive equivalent angle. - Nathan Day
This is extremely pedantic point but all of the standard libraries dealing with angles use radius not degrees, so I would try to make any code I write use radians as well. I would convert too and from degrees when outputting and inputing only. - Nathan Day
@NathanDay: There are actually lots of reasons to prefer working in degrees. In radians, there is no x such that cos(x)==0 or sin(x)==1, etc. This also means successive rounds around the circle will not give you identical values for sin and cos. With degrees, all of those problems go away. Moreover, degrees are better than the other natural option, sinpi(x) defined as sin(pi*x), because even in that form it's impossible to represent 30 and 60 degree angles exactly (and thus there's no x with sin(x)==0.5, etc.). - R.. GitHub STOP HELPING ICE

4 Answers

5
votes

Okay perhaps I'm a little slow, but I'm not sure why you're using a 3600000.0 constant.

If you're just trying to convert a negative angle to it's positive value, you can just add 360.0 until you get a positive number.

double to_positive_angle(double angle)
{
   angle = fmod(angle, 360);
   while(angle < 0) { //pretty sure this comparison is valid for doubles and floats
     angle += 360.0;
   }

   return angle;
}
14
votes

This version works for all possible inputs, not just ones greater than 3600000, and solves the % issue you were experiencing.

double to_positive_angle(double angle)
{
   angle = fmod(angle, 360);
   if (angle < 0) angle += 360;
   return angle;
}
5
votes

You can't use the modulo operator on floating-point types. You should use fmod for this.

return fmod( 3600000.0 + angle, 360.0 );

Be a little wary of rounding and precision errors you might introduce with the above operation.

0
votes

I think this is the smartest way:

void get_positve_angle(double theta)
{
    return fmod(fmod(theta,360)+360,360);
}