2

In C++, the following code:

#include <math.h>
#include <iostream>

int main() {
    std::cout << remainder(-177.14024960054252, 360) << std::endl;
}

Compiled with x86-64 GCC 12.2 (https://godbolt.org/z/43MzbE1ve)

Outputs:

-177.14

However in Python:

np.remainder(-177.14024960054252, 360)
# and
-177.14024960054252 % 360

Both output:

182.85975039945748

According to the numpy docs, np.remainder is doing the IEEE remainder function. According to the C++ docs, remainder is also doing the IEEE remainder function.

Why are these two numbers different?

Tom McLean
  • 5,583
  • 1
  • 11
  • 36

1 Answers1

5

Because np.remainder is not using the IEEE remainder function.

Quote from the docs:

Computes the remainder complementary to the floor_divide function. It is equivalent to the Python modulus operatorx1 % x2 and has the same sign as the divisor x2. The MATLAB function equivalent to np.remainder is mod.

It also has a warning, stating that it is not the same as Python 3.7’s math.remainder and C’s remainder.

This should not be confused with:

Python 3.7’s math.remainder and C’s remainder, which computes the IEEE remainder, which are the complement to round(x1 / x2).

The MATLAB rem function and or the C % operator which is the complement to int(x1 / x2).

For difference between Python's % and C's %, see here.