2

I need to convert a double/float angle to the range of [-180,180] by adding or subtracting 360. The remainder function works, but I am not sure why.

x = remainder (x, 360);

Why does this produce a range of [-180,180] and not [0,359.99999...]?

I understand that remainder and mod are the same for positive numbers, but they work differently for negative numbers... I just have not seen a good explanation of what is happening.

I'm happy that this works of course, but I don't really understand why.

Trygve
  • 1,317
  • 10
  • 27

1 Answers1

3

Taken from cppreference:

The IEEE floating-point remainder of the division operation x/y calculated by this function is exactly the value x - n*y, where the value n is the integral value nearest the exact value x/y. When |n-x/y| = ½, the value n is chosen to be even.

In contrast to fmod(), the returned value is not guaranteed to have the same sign as x.

If the returned value is 0, it will have the same sign as x.

What's happening here is the function remainder(x, y) rounds to the nearest integer value, times your y and then subtracts the result from x.

Example:

remainder(160.0f, 360.0f)

result = 160 - round(160.0f / 360.0f) * 360
result = 160 - round(0.44f) * 360
result = 160 - (0 * 360)
result = 160.0f

Example2:

remainder(190.0f, 360.0f)

result = 190 - round(190.0f / 360.0f) * 360
result = 190 - round(0.53f) * 360
result = 190 - (1 * 360)
result = -170.0f

Thus you could end up having negative numbers depending on your input variable.

Community
  • 1
  • 1
DJSchaffner
  • 562
  • 7
  • 22